@a1hvdy/cc-openclaw 0.23.0 → 0.25.0

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.
Files changed (109) hide show
  1. package/dist/src/channels/telegram/injector.js +71 -0
  2. package/dist/src/channels/telegram/injector.js.map +1 -1
  3. package/dist/src/channels/telegram-mirror/burst-accumulator.d.ts +96 -0
  4. package/dist/src/channels/telegram-mirror/burst-accumulator.js +130 -0
  5. package/dist/src/channels/telegram-mirror/burst-accumulator.js.map +1 -0
  6. package/dist/src/channels/telegram-mirror/callback-mapping.d.ts +61 -0
  7. package/dist/src/channels/telegram-mirror/callback-mapping.js +99 -0
  8. package/dist/src/channels/telegram-mirror/callback-mapping.js.map +1 -0
  9. package/dist/src/channels/telegram-mirror/card-renderer.d.ts +74 -0
  10. package/dist/src/channels/telegram-mirror/card-renderer.js +131 -0
  11. package/dist/src/channels/telegram-mirror/card-renderer.js.map +1 -0
  12. package/dist/src/channels/telegram-mirror/commands.d.ts +142 -0
  13. package/dist/src/channels/telegram-mirror/commands.js +389 -0
  14. package/dist/src/channels/telegram-mirror/commands.js.map +1 -0
  15. package/dist/src/channels/telegram-mirror/compose-buffer.d.ts +71 -0
  16. package/dist/src/channels/telegram-mirror/compose-buffer.js +110 -0
  17. package/dist/src/channels/telegram-mirror/compose-buffer.js.map +1 -0
  18. package/dist/src/channels/telegram-mirror/cost-views.d.ts +58 -0
  19. package/dist/src/channels/telegram-mirror/cost-views.js +121 -0
  20. package/dist/src/channels/telegram-mirror/cost-views.js.map +1 -0
  21. package/dist/src/channels/telegram-mirror/failure/callback-data-overflow.d.ts +21 -0
  22. package/dist/src/channels/telegram-mirror/failure/callback-data-overflow.js +30 -0
  23. package/dist/src/channels/telegram-mirror/failure/callback-data-overflow.js.map +1 -0
  24. package/dist/src/channels/telegram-mirror/failure/gateway-down.d.ts +15 -0
  25. package/dist/src/channels/telegram-mirror/failure/gateway-down.js +27 -0
  26. package/dist/src/channels/telegram-mirror/failure/gateway-down.js.map +1 -0
  27. package/dist/src/channels/telegram-mirror/failure/in-flight-conflict.d.ts +15 -0
  28. package/dist/src/channels/telegram-mirror/failure/in-flight-conflict.js +27 -0
  29. package/dist/src/channels/telegram-mirror/failure/in-flight-conflict.js.map +1 -0
  30. package/dist/src/channels/telegram-mirror/failure/index.d.ts +23 -0
  31. package/dist/src/channels/telegram-mirror/failure/index.js +35 -0
  32. package/dist/src/channels/telegram-mirror/failure/index.js.map +1 -0
  33. package/dist/src/channels/telegram-mirror/failure/model-5xx.d.ts +16 -0
  34. package/dist/src/channels/telegram-mirror/failure/model-5xx.js +24 -0
  35. package/dist/src/channels/telegram-mirror/failure/model-5xx.js.map +1 -0
  36. package/dist/src/channels/telegram-mirror/failure/network-blip.d.ts +17 -0
  37. package/dist/src/channels/telegram-mirror/failure/network-blip.js +25 -0
  38. package/dist/src/channels/telegram-mirror/failure/network-blip.js.map +1 -0
  39. package/dist/src/channels/telegram-mirror/failure/pool-exhausted-fallback.d.ts +15 -0
  40. package/dist/src/channels/telegram-mirror/failure/pool-exhausted-fallback.js +24 -0
  41. package/dist/src/channels/telegram-mirror/failure/pool-exhausted-fallback.js.map +1 -0
  42. package/dist/src/channels/telegram-mirror/failure/rate-limit.d.ts +16 -0
  43. package/dist/src/channels/telegram-mirror/failure/rate-limit.js +26 -0
  44. package/dist/src/channels/telegram-mirror/failure/rate-limit.js.map +1 -0
  45. package/dist/src/channels/telegram-mirror/failure/returning-after-24h.d.ts +14 -0
  46. package/dist/src/channels/telegram-mirror/failure/returning-after-24h.js +33 -0
  47. package/dist/src/channels/telegram-mirror/failure/returning-after-24h.js.map +1 -0
  48. package/dist/src/channels/telegram-mirror/failure/types.d.ts +30 -0
  49. package/dist/src/channels/telegram-mirror/failure/types.js +9 -0
  50. package/dist/src/channels/telegram-mirror/failure/types.js.map +1 -0
  51. package/dist/src/channels/telegram-mirror/index.d.ts +30 -0
  52. package/dist/src/channels/telegram-mirror/index.js +41 -0
  53. package/dist/src/channels/telegram-mirror/index.js.map +1 -0
  54. package/dist/src/channels/telegram-mirror/plan-attachment.d.ts +120 -0
  55. package/dist/src/channels/telegram-mirror/plan-attachment.js +138 -0
  56. package/dist/src/channels/telegram-mirror/plan-attachment.js.map +1 -0
  57. package/dist/src/channels/telegram-mirror/quota-reader.d.ts +41 -0
  58. package/dist/src/channels/telegram-mirror/quota-reader.js +29 -0
  59. package/dist/src/channels/telegram-mirror/quota-reader.js.map +1 -0
  60. package/dist/src/channels/telegram-mirror/sessions-keyboard.d.ts +84 -0
  61. package/dist/src/channels/telegram-mirror/sessions-keyboard.js +113 -0
  62. package/dist/src/channels/telegram-mirror/sessions-keyboard.js.map +1 -0
  63. package/dist/src/channels/telegram-mirror/soak-log.d.ts +98 -0
  64. package/dist/src/channels/telegram-mirror/soak-log.js +136 -0
  65. package/dist/src/channels/telegram-mirror/soak-log.js.map +1 -0
  66. package/dist/src/channels/telegram-mirror/state-machine.d.ts +102 -0
  67. package/dist/src/channels/telegram-mirror/state-machine.js +117 -0
  68. package/dist/src/channels/telegram-mirror/state-machine.js.map +1 -0
  69. package/dist/src/channels/telegram-mirror/sync-commands.d.ts +63 -0
  70. package/dist/src/channels/telegram-mirror/sync-commands.js +51 -0
  71. package/dist/src/channels/telegram-mirror/sync-commands.js.map +1 -0
  72. package/dist/src/channels/telegram-mirror/threshold-watcher.d.ts +54 -0
  73. package/dist/src/channels/telegram-mirror/threshold-watcher.js +77 -0
  74. package/dist/src/channels/telegram-mirror/threshold-watcher.js.map +1 -0
  75. package/dist/src/command-router/cc-handler.js +13 -30
  76. package/dist/src/command-router/cc-handler.js.map +1 -1
  77. package/dist/src/engines/persistent-session.js +5 -0
  78. package/dist/src/engines/persistent-session.js.map +1 -1
  79. package/dist/src/index.js +22 -20
  80. package/dist/src/index.js.map +1 -1
  81. package/dist/src/lib/auto-recovery.js +1 -1
  82. package/dist/src/lib/auto-recovery.js.map +1 -1
  83. package/dist/src/lib/drift-detector.js +1 -1
  84. package/dist/src/lib/drift-detector.js.map +1 -1
  85. package/dist/src/lib/error-renderer.d.ts +23 -0
  86. package/dist/src/lib/error-renderer.js +106 -0
  87. package/dist/src/lib/error-renderer.js.map +1 -0
  88. package/dist/src/lib/perf/speculative-bubble.d.ts +27 -0
  89. package/dist/src/lib/perf/speculative-bubble.js +36 -0
  90. package/dist/src/lib/perf/speculative-bubble.js.map +1 -0
  91. package/dist/src/lib/session-registry.d.ts +66 -0
  92. package/dist/src/lib/session-registry.js +188 -0
  93. package/dist/src/lib/session-registry.js.map +1 -0
  94. package/dist/src/lib/telegram-bot-api.d.ts +100 -0
  95. package/dist/src/lib/telegram-bot-api.js +204 -0
  96. package/dist/src/lib/telegram-bot-api.js.map +1 -0
  97. package/dist/src/openai-compat/openai-compat.d.ts +2 -0
  98. package/dist/src/openai-compat/openai-compat.js +85 -0
  99. package/dist/src/openai-compat/openai-compat.js.map +1 -1
  100. package/dist/src/patches/sysprompt-strip.spec.d.ts +33 -0
  101. package/dist/src/patches/sysprompt-strip.spec.js +53 -0
  102. package/dist/src/patches/sysprompt-strip.spec.js.map +1 -0
  103. package/dist/src/session/session-manager.d.ts +4 -0
  104. package/dist/src/session/session-manager.js +99 -5
  105. package/dist/src/session/session-manager.js.map +1 -1
  106. package/package.json +1 -1
  107. package/dist/src/lib/perf/resident-cli-pool.d.ts +0 -39
  108. package/dist/src/lib/perf/resident-cli-pool.js +0 -60
  109. package/dist/src/lib/perf/resident-cli-pool.js.map +0 -1
@@ -0,0 +1,131 @@
1
+ /**
2
+ * src/channels/telegram-mirror/card-renderer.ts — v0.25.0 M2.
3
+ *
4
+ * Pure-function renderer: Turn (from state-machine.ts) → message body string
5
+ * suitable for sendMessage / editMessageText. Telegram-API HTTP wiring
6
+ * (sendTg / editTg) lands in a later milestone alongside the dispatch path
7
+ * — M2's exit criterion is just "render a single turn (working → done)",
8
+ * which is satisfied by this pure function.
9
+ *
10
+ * Aesthetic: terminal-mimic per ADR-001. Header glyph ("▶" working,
11
+ * "✓" done) + tool call list (each prefixed with status glyph) + assistant
12
+ * text. Compact enough to fit in a single Telegram message bubble.
13
+ *
14
+ * Tests live at tests/channels/telegram-mirror/m2-render-pipeline.test.ts.
15
+ */
16
+ /**
17
+ * Glyph picked per tool-call status. Mirrors terminal "running / done /
18
+ * errored" iconography that A1 already reads in the live Claude Code TUI.
19
+ */
20
+ function toolGlyph(tc) {
21
+ if (tc.isError)
22
+ return '✗';
23
+ if (tc.result !== undefined)
24
+ return '✓';
25
+ return '…';
26
+ }
27
+ /**
28
+ * Render the input argument summary for a tool call. Kept tight — full
29
+ * input is in the result; the mirror line is meant to read at a glance.
30
+ */
31
+ function toolInputSummary(tc) {
32
+ const input = tc.input;
33
+ if (!input || typeof input !== 'object')
34
+ return '';
35
+ // Prefer common single-field shapes used by Bash/Read/Edit/Write.
36
+ const single = typeof input.command === 'string'
37
+ ? input.command
38
+ : typeof input.file_path === 'string'
39
+ ? input.file_path
40
+ : typeof input.path === 'string'
41
+ ? input.path
42
+ : typeof input.url === 'string'
43
+ ? input.url
44
+ : '';
45
+ if (single) {
46
+ return single.length > 60 ? single.slice(0, 57) + '...' : single;
47
+ }
48
+ return '';
49
+ }
50
+ /**
51
+ * Format one tool-call line for inclusion in the rendered card body.
52
+ * "✓ Bash · ls -la"
53
+ * "… Read · src/index.ts"
54
+ * "✗ Edit · …error glyph at left"
55
+ */
56
+ export function renderToolLine(tc) {
57
+ const glyph = toolGlyph(tc);
58
+ const summary = toolInputSummary(tc);
59
+ return summary ? `${glyph} ${tc.name} · ${summary}` : `${glyph} ${tc.name}`;
60
+ }
61
+ /**
62
+ * Render the thinking block (M6). Each line of the thinking text is
63
+ * prefixed with "> " to read as a block quote in plain-text Telegram
64
+ * bubbles — clearly visually distinct from the assistant text below it
65
+ * without depending on MarkdownV2 escapes. Empty thinking returns ''.
66
+ */
67
+ export function renderThinkingBlock(thinkingText) {
68
+ const trimmed = thinkingText.trim();
69
+ if (trimmed.length === 0)
70
+ return '';
71
+ const lines = trimmed.split('\n');
72
+ return ['💭 Thinking', ...lines.map((l) => `> ${l}`)].join('\n');
73
+ }
74
+ /**
75
+ * Render the full turn into a Telegram-safe message body. The mirror keeps
76
+ * a single message per turn that gets edited in place — this function is
77
+ * idempotent for a given turn snapshot and produces the next body string.
78
+ *
79
+ * Body shape (lines separated by \n):
80
+ *
81
+ * ▶ Working ← or "✓ Done" when state==='done'
82
+ * ✓ Bash · ls -la ← one line per tool call, in arrival order
83
+ * … Read · src/x.ts
84
+ * <empty line>
85
+ * 💭 Thinking ← M6, only when thinkingText non-empty
86
+ * > reasoning line 1
87
+ * > reasoning line 2
88
+ * <empty line>
89
+ * <assistant text> ← present only when non-empty;
90
+ * ★ Insight ─ blocks preserved INLINE
91
+ * at their emission position (M6).
92
+ *
93
+ * Lines with no content (e.g. empty tool list, empty assistant text) are
94
+ * omitted entirely so the rendered body never has trailing whitespace.
95
+ */
96
+ export function renderTurn(turn) {
97
+ const header = turn.state === 'done' ? '✓ Done' : '▶ Working';
98
+ const lines = [header];
99
+ if (turn.toolCalls.length > 0) {
100
+ for (const tc of turn.toolCalls) {
101
+ lines.push(renderToolLine(tc));
102
+ }
103
+ }
104
+ // Defensive default — Turn.thinkingText is required by the interface, but
105
+ // some test helpers and pre-M6 fixtures construct Turn-shaped objects
106
+ // without setting it. Treat absent / undefined as empty.
107
+ const thinking = renderThinkingBlock(turn.thinkingText ?? '');
108
+ if (thinking.length > 0) {
109
+ lines.push('');
110
+ lines.push(thinking);
111
+ }
112
+ const text = turn.assistantText.trim();
113
+ if (text.length > 0) {
114
+ lines.push('');
115
+ lines.push(text);
116
+ }
117
+ return lines.join('\n');
118
+ }
119
+ /**
120
+ * Decide whether the current turn snapshot should be sent (first render)
121
+ * or edited (subsequent renders). The dispatcher tracks the (chatId →
122
+ * messageId) map; this function just produces the action shape.
123
+ */
124
+ export function planRenderAction(turn, knownMessageId) {
125
+ const text = renderTurn(turn);
126
+ if (knownMessageId === undefined) {
127
+ return { type: 'send', chatId: turn.chatId, text };
128
+ }
129
+ return { type: 'edit', chatId: turn.chatId, text, messageId: knownMessageId };
130
+ }
131
+ //# sourceMappingURL=card-renderer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"card-renderer.js","sourceRoot":"","sources":["../../../../src/channels/telegram-mirror/card-renderer.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,142 @@
1
+ /**
2
+ * src/channels/telegram-mirror/commands.ts — v0.25.0 M4.
3
+ *
4
+ * Top-7 phone-tier slash commands per PRP §5 M4:
5
+ * /sessions /new <slug> /stop /status /compact /cost /rewind
6
+ *
7
+ * Each handler is a pure function returning a CommandResult — a list of
8
+ * Telegram API actions the dispatch layer consumes. No I/O happens here
9
+ * beyond reading session-registry (which itself isolates I/O behind an
10
+ * env-overridable path for tests).
11
+ *
12
+ * G-2 resolution (2026-05-19): per-message inline keyboards + typed-form
13
+ * — no persistent ReplyKeyboardMarkup. /sessions and /cost have an
14
+ * inline-keyboard form; the rest are text-only.
15
+ *
16
+ * Decision refs:
17
+ * • ADR-003 — slug registry is the canonical source for /sessions, /new,
18
+ * /stop, /status.
19
+ * • ADR-004 — callback_data slots come from the per-handler CallbackMap.
20
+ * • ADR-008 — failure handlers (M12) consume CommandResult.actions[].
21
+ *
22
+ * Out of scope for M4 (per "no premature resolution"):
23
+ * • Actually spawning / killing claude subprocesses (M5+ wiring).
24
+ * • Real quota numbers in /cost — uses QuotaReader stub (M11 wires real).
25
+ * • Threshold notifications / 95% pause button (M11).
26
+ * • Plan attachment via sendDocument (M9).
27
+ */
28
+ import { CallbackMap } from './callback-mapping.js';
29
+ import { type SessionState, type InlineButton } from './sessions-keyboard.js';
30
+ import { type QuotaReader } from './quota-reader.js';
31
+ import type { ComposeBuffer } from './compose-buffer.js';
32
+ /**
33
+ * Discriminated union of Telegram API actions a command may emit.
34
+ * Maps 1:1 to the test mock layer at tests/.../__mocks__/telegram-api.ts.
35
+ */
36
+ export type TelegramAction = {
37
+ type: 'sendMessage';
38
+ chat_id: string | number;
39
+ text: string;
40
+ reply_markup?: {
41
+ inline_keyboard: InlineButton[][];
42
+ };
43
+ parse_mode?: 'MarkdownV2';
44
+ } | {
45
+ type: 'editMessageText';
46
+ chat_id: string | number;
47
+ message_id: number;
48
+ text: string;
49
+ reply_markup?: {
50
+ inline_keyboard: InlineButton[][];
51
+ };
52
+ parse_mode?: 'MarkdownV2';
53
+ } | {
54
+ type: 'sendDocument';
55
+ chat_id: string | number;
56
+ filename: string;
57
+ content: string;
58
+ caption?: string;
59
+ reply_markup?: {
60
+ inline_keyboard: InlineButton[][];
61
+ };
62
+ };
63
+ export interface CommandContext {
64
+ chatId: string | number;
65
+ args: string[];
66
+ callbackMap: CallbackMap;
67
+ /** Optional state lookup for status-rich rows; defaults all entries to 'idle'. */
68
+ stateLookup?: (slug: string) => SessionState;
69
+ /** Optional quota reader for /cost; defaults to stubQuotaReader. */
70
+ quotaReader?: QuotaReader;
71
+ /** Optional clock for deterministic last-activity tests. */
72
+ now?: number;
73
+ /** Required for /compose and /send (M7); other handlers ignore. */
74
+ composeBuffer?: ComposeBuffer;
75
+ }
76
+ export interface CommandResult {
77
+ actions: TelegramAction[];
78
+ /**
79
+ * When the command produces user-message content destined for the
80
+ * engine (currently only /send after /compose), the concatenated
81
+ * payload appears here. M5+ engine bridging consumes this field to
82
+ * feed openai-compat as a single user message. Absent when the command
83
+ * is purely a UI surface (most handlers).
84
+ */
85
+ delivery?: {
86
+ payload: string;
87
+ };
88
+ }
89
+ /**
90
+ * Tiny parser. Telegram slash messages look like "/cmd arg1 arg2" — split
91
+ * on whitespace, drop the leading '/', strip any "@botname" suffix.
92
+ * Returns undefined for non-slash input.
93
+ */
94
+ export interface ParsedSlash {
95
+ cmd: string;
96
+ args: string[];
97
+ }
98
+ export declare function parseSlash(text: string): ParsedSlash | undefined;
99
+ export declare function handleSessions(ctx: CommandContext): CommandResult;
100
+ export declare function handleNew(ctx: CommandContext): CommandResult;
101
+ export declare function handleStop(ctx: CommandContext): CommandResult;
102
+ export declare function handleStatus(ctx: CommandContext): CommandResult;
103
+ export declare function handleCompact(ctx: CommandContext): CommandResult;
104
+ export declare function handleCost(ctx: CommandContext): CommandResult;
105
+ export declare function handleRewind(ctx: CommandContext): CommandResult;
106
+ /**
107
+ * Open a compose session for the chat. M7 — drafts append until /send.
108
+ * Returns a force_reply prompt so Telegram nudges the user into reply mode.
109
+ */
110
+ export declare function handleCompose(ctx: CommandContext): CommandResult;
111
+ /**
112
+ * Commit the active compose buffer. Returns the concatenated payload via
113
+ * CommandResult.delivery for the engine bridge to consume. If no session
114
+ * is active, returns a friendly error message.
115
+ */
116
+ export declare function handleSend(ctx: CommandContext): CommandResult;
117
+ /**
118
+ * Cancel the active compose buffer without sending. Useful when the user
119
+ * starts composing then changes their mind.
120
+ */
121
+ export declare function handleCancel(ctx: CommandContext): CommandResult;
122
+ /**
123
+ * Surface a Y/N inline keyboard so A1 records opened-laptop-today for
124
+ * the soak instrumentation. Idempotency is enforced by SoakLogger
125
+ * downstream — handler always emits the keyboard and lets the callback
126
+ * resolver call recordLaptopCheck().
127
+ */
128
+ export declare function handleSoakCheck(ctx: CommandContext): CommandResult;
129
+ export type CommandHandler = (ctx: CommandContext) => CommandResult;
130
+ export declare const COMMAND_HANDLERS: Record<string, CommandHandler>;
131
+ /**
132
+ * Telegram bot commands list — declarative source for M5's setMyCommands sync.
133
+ */
134
+ export declare const TOP_7_COMMANDS: ReadonlyArray<{
135
+ command: string;
136
+ description: string;
137
+ }>;
138
+ /**
139
+ * Route a parsed slash command to its handler. Returns undefined for
140
+ * unknown commands so the caller can fall back to "unknown command" UX.
141
+ */
142
+ export declare function dispatchCommand(parsed: ParsedSlash, ctxBase: Omit<CommandContext, 'args'>): CommandResult | undefined;
@@ -0,0 +1,389 @@
1
+ /**
2
+ * src/channels/telegram-mirror/commands.ts — v0.25.0 M4.
3
+ *
4
+ * Top-7 phone-tier slash commands per PRP §5 M4:
5
+ * /sessions /new <slug> /stop /status /compact /cost /rewind
6
+ *
7
+ * Each handler is a pure function returning a CommandResult — a list of
8
+ * Telegram API actions the dispatch layer consumes. No I/O happens here
9
+ * beyond reading session-registry (which itself isolates I/O behind an
10
+ * env-overridable path for tests).
11
+ *
12
+ * G-2 resolution (2026-05-19): per-message inline keyboards + typed-form
13
+ * — no persistent ReplyKeyboardMarkup. /sessions and /cost have an
14
+ * inline-keyboard form; the rest are text-only.
15
+ *
16
+ * Decision refs:
17
+ * • ADR-003 — slug registry is the canonical source for /sessions, /new,
18
+ * /stop, /status.
19
+ * • ADR-004 — callback_data slots come from the per-handler CallbackMap.
20
+ * • ADR-008 — failure handlers (M12) consume CommandResult.actions[].
21
+ *
22
+ * Out of scope for M4 (per "no premature resolution"):
23
+ * • Actually spawning / killing claude subprocesses (M5+ wiring).
24
+ * • Real quota numbers in /cost — uses QuotaReader stub (M11 wires real).
25
+ * • Threshold notifications / 95% pause button (M11).
26
+ * • Plan attachment via sendDocument (M9).
27
+ */
28
+ import { register, unregister, list, getBySlug, } from '../../lib/session-registry.js';
29
+ import { buildSessionsKeyboard, formatLastActivity, } from './sessions-keyboard.js';
30
+ import { stubQuotaReader } from './quota-reader.js';
31
+ export function parseSlash(text) {
32
+ const trimmed = text.trim();
33
+ if (!trimmed.startsWith('/'))
34
+ return undefined;
35
+ const tokens = trimmed.slice(1).split(/\s+/).filter((t) => t.length > 0);
36
+ if (tokens.length === 0)
37
+ return undefined;
38
+ const head = tokens[0];
39
+ const cmd = head.includes('@') ? head.split('@')[0] : head;
40
+ return { cmd: cmd.toLowerCase(), args: tokens.slice(1) };
41
+ }
42
+ // ── /sessions ────────────────────────────────────────────────────────────
43
+ function enrichRows(entries, stateLookup) {
44
+ return entries.map((e) => ({
45
+ slug: e.slug,
46
+ sessionName: e.sessionName,
47
+ state: stateLookup(e.slug),
48
+ lastUsedAt: e.lastUsedAt,
49
+ }));
50
+ }
51
+ export function handleSessions(ctx) {
52
+ const entries = list();
53
+ const stateLookup = ctx.stateLookup ?? (() => 'idle');
54
+ const rows = enrichRows(entries, stateLookup);
55
+ const kb = buildSessionsKeyboard({
56
+ rows,
57
+ callbackMap: ctx.callbackMap,
58
+ now: ctx.now,
59
+ });
60
+ const header = entries.length === 0
61
+ ? 'No sessions registered yet. Tap ➕ New to create one.'
62
+ : `Sessions (${entries.length})${kb.pageCount > 1 ? ` · page ${kb.page + 1}/${kb.pageCount}` : ''}`;
63
+ return {
64
+ actions: [
65
+ {
66
+ type: 'sendMessage',
67
+ chat_id: ctx.chatId,
68
+ text: header,
69
+ reply_markup: { inline_keyboard: kb.inline_keyboard },
70
+ },
71
+ ],
72
+ };
73
+ }
74
+ // ── /new <slug> ──────────────────────────────────────────────────────────
75
+ const SLUG_PATTERN = /^[a-z0-9][a-z0-9-_]{0,39}$/i;
76
+ export function handleNew(ctx) {
77
+ const slug = ctx.args[0];
78
+ if (!slug) {
79
+ return {
80
+ actions: [
81
+ {
82
+ type: 'sendMessage',
83
+ chat_id: ctx.chatId,
84
+ text: 'Usage: /new <slug>\nExample: /new cc-openclaw',
85
+ },
86
+ ],
87
+ };
88
+ }
89
+ if (!SLUG_PATTERN.test(slug)) {
90
+ return {
91
+ actions: [
92
+ {
93
+ type: 'sendMessage',
94
+ chat_id: ctx.chatId,
95
+ text: `Invalid slug "${slug}". Use [a-z0-9-_], max 40 chars, starting with [a-z0-9].`,
96
+ },
97
+ ],
98
+ };
99
+ }
100
+ const existing = getBySlug(slug);
101
+ // Session-name comes from the engine; M4 stores a placeholder that M5+ overwrites.
102
+ const sessionName = existing?.sessionName ?? `pending-${slug}-${Date.now()}`;
103
+ register(slug, sessionName);
104
+ return {
105
+ actions: [
106
+ {
107
+ type: 'sendMessage',
108
+ chat_id: ctx.chatId,
109
+ text: existing
110
+ ? `Session "${slug}" already registered — fronted.`
111
+ : `Session "${slug}" registered. Engine wire-up lands in M5.`,
112
+ },
113
+ ],
114
+ };
115
+ }
116
+ // ── /stop ────────────────────────────────────────────────────────────────
117
+ export function handleStop(ctx) {
118
+ const slug = ctx.args[0];
119
+ if (!slug) {
120
+ return {
121
+ actions: [
122
+ {
123
+ type: 'sendMessage',
124
+ chat_id: ctx.chatId,
125
+ text: 'Usage: /stop <slug>',
126
+ },
127
+ ],
128
+ };
129
+ }
130
+ const removed = unregister(slug);
131
+ return {
132
+ actions: [
133
+ {
134
+ type: 'sendMessage',
135
+ chat_id: ctx.chatId,
136
+ text: removed
137
+ ? `Session "${slug}" stopped.`
138
+ : `No registered session named "${slug}".`,
139
+ },
140
+ ],
141
+ };
142
+ }
143
+ // ── /status ──────────────────────────────────────────────────────────────
144
+ export function handleStatus(ctx) {
145
+ const entries = list();
146
+ const stateLookup = ctx.stateLookup ?? (() => 'idle');
147
+ const now = ctx.now ?? Date.now();
148
+ if (entries.length === 0) {
149
+ return {
150
+ actions: [
151
+ {
152
+ type: 'sendMessage',
153
+ chat_id: ctx.chatId,
154
+ text: 'No sessions registered.',
155
+ },
156
+ ],
157
+ };
158
+ }
159
+ const lines = [`Active sessions: ${entries.length}`];
160
+ for (const e of entries) {
161
+ lines.push(`• ${e.slug} (${stateLookup(e.slug)}, ${formatLastActivity(e.lastUsedAt, now)})`);
162
+ }
163
+ return {
164
+ actions: [{ type: 'sendMessage', chat_id: ctx.chatId, text: lines.join('\n') }],
165
+ };
166
+ }
167
+ // ── /compact ─────────────────────────────────────────────────────────────
168
+ export function handleCompact(ctx) {
169
+ // M4: surface the intent. Actual context-compaction wiring runs through
170
+ // the cc-handler module (existing /cc compact path) — bridging the
171
+ // mirror to that handler lands in M5 alongside the rest of the engine
172
+ // integration. Without the bridge, the user sees a clear "queued" state.
173
+ return {
174
+ actions: [
175
+ {
176
+ type: 'sendMessage',
177
+ chat_id: ctx.chatId,
178
+ text: '⏳ Compact queued — engine wire-up lands in M5.',
179
+ },
180
+ ],
181
+ };
182
+ }
183
+ // ── /cost ────────────────────────────────────────────────────────────────
184
+ function formatQuotaSummary(snap) {
185
+ const pct = snap.maxPercent.toFixed(1);
186
+ const burn = snap.weeklyBurn.toFixed(2);
187
+ return `Max 20x: ${pct}% used · Weekly burn: $${burn}`;
188
+ }
189
+ export function handleCost(ctx) {
190
+ const reader = ctx.quotaReader ?? stubQuotaReader;
191
+ const snap = reader.read();
192
+ const summaryText = formatQuotaSummary(snap);
193
+ // Inline detail button — payload tells the callback handler (M11+) which
194
+ // subview to expand: per-day rollup, top sessions, or weekly burn breakdown.
195
+ const detailCb = ctx.callbackMap.create({ action: 'cost-detail' });
196
+ const dailyCb = ctx.callbackMap.create({ action: 'cost-daily' });
197
+ return {
198
+ actions: [
199
+ {
200
+ type: 'sendMessage',
201
+ chat_id: ctx.chatId,
202
+ text: summaryText,
203
+ reply_markup: {
204
+ inline_keyboard: [
205
+ [{ text: '📊 Detail', callback_data: detailCb }],
206
+ [{ text: '📅 Per-day', callback_data: dailyCb }],
207
+ ],
208
+ },
209
+ },
210
+ ],
211
+ };
212
+ }
213
+ // ── /rewind ──────────────────────────────────────────────────────────────
214
+ export function handleRewind(ctx) {
215
+ // M4: queued — actual rewind walks the cc-handler resume path (deferred
216
+ // to M5 with the rest of engine bridging).
217
+ return {
218
+ actions: [
219
+ {
220
+ type: 'sendMessage',
221
+ chat_id: ctx.chatId,
222
+ text: '⏪ Rewind queued — engine wire-up lands in M5.',
223
+ },
224
+ ],
225
+ };
226
+ }
227
+ // ── /compose ─────────────────────────────────────────────────────────────
228
+ /**
229
+ * Open a compose session for the chat. M7 — drafts append until /send.
230
+ * Returns a force_reply prompt so Telegram nudges the user into reply mode.
231
+ */
232
+ export function handleCompose(ctx) {
233
+ if (!ctx.composeBuffer) {
234
+ return {
235
+ actions: [
236
+ {
237
+ type: 'sendMessage',
238
+ chat_id: ctx.chatId,
239
+ text: '⚠️ /compose unavailable — buffer not wired in this context.',
240
+ },
241
+ ],
242
+ };
243
+ }
244
+ ctx.composeBuffer.start(String(ctx.chatId));
245
+ return {
246
+ actions: [
247
+ {
248
+ type: 'sendMessage',
249
+ chat_id: ctx.chatId,
250
+ text: '✍️ Compose mode opened. Send messages; finish with /send (or /cancel to abort).',
251
+ },
252
+ ],
253
+ };
254
+ }
255
+ /**
256
+ * Commit the active compose buffer. Returns the concatenated payload via
257
+ * CommandResult.delivery for the engine bridge to consume. If no session
258
+ * is active, returns a friendly error message.
259
+ */
260
+ export function handleSend(ctx) {
261
+ if (!ctx.composeBuffer) {
262
+ return {
263
+ actions: [
264
+ {
265
+ type: 'sendMessage',
266
+ chat_id: ctx.chatId,
267
+ text: '⚠️ /send unavailable — buffer not wired in this context.',
268
+ },
269
+ ],
270
+ };
271
+ }
272
+ const payload = ctx.composeBuffer.commit(String(ctx.chatId));
273
+ if (payload === undefined) {
274
+ return {
275
+ actions: [
276
+ {
277
+ type: 'sendMessage',
278
+ chat_id: ctx.chatId,
279
+ text: 'No compose session active. Start one with /compose.',
280
+ },
281
+ ],
282
+ };
283
+ }
284
+ // Confirmation surfaces a short preview (≤ 120 chars) so the user sees
285
+ // what was sent. The full payload travels via CommandResult.delivery
286
+ // for M5+ engine bridging.
287
+ const preview = payload.length > 120 ? payload.slice(0, 117) + '...' : payload;
288
+ return {
289
+ actions: [
290
+ {
291
+ type: 'sendMessage',
292
+ chat_id: ctx.chatId,
293
+ text: `📤 Sent (${payload.length} chars): ${preview}`,
294
+ },
295
+ ],
296
+ delivery: { payload },
297
+ };
298
+ }
299
+ /**
300
+ * Cancel the active compose buffer without sending. Useful when the user
301
+ * starts composing then changes their mind.
302
+ */
303
+ export function handleCancel(ctx) {
304
+ if (!ctx.composeBuffer) {
305
+ return {
306
+ actions: [
307
+ {
308
+ type: 'sendMessage',
309
+ chat_id: ctx.chatId,
310
+ text: '⚠️ /cancel unavailable — buffer not wired in this context.',
311
+ },
312
+ ],
313
+ };
314
+ }
315
+ const had = ctx.composeBuffer.cancel(String(ctx.chatId));
316
+ return {
317
+ actions: [
318
+ {
319
+ type: 'sendMessage',
320
+ chat_id: ctx.chatId,
321
+ text: had ? '🚫 Compose cancelled.' : 'No compose session was active.',
322
+ },
323
+ ],
324
+ };
325
+ }
326
+ // ── /soak-check (M14) ────────────────────────────────────────────────────
327
+ /**
328
+ * Surface a Y/N inline keyboard so A1 records opened-laptop-today for
329
+ * the soak instrumentation. Idempotency is enforced by SoakLogger
330
+ * downstream — handler always emits the keyboard and lets the callback
331
+ * resolver call recordLaptopCheck().
332
+ */
333
+ export function handleSoakCheck(ctx) {
334
+ const yesCb = ctx.callbackMap.create({ action: 'soak-check', openedLaptop: true });
335
+ const noCb = ctx.callbackMap.create({ action: 'soak-check', openedLaptop: false });
336
+ return {
337
+ actions: [
338
+ {
339
+ type: 'sendMessage',
340
+ chat_id: ctx.chatId,
341
+ text: 'Opened the laptop today? (one tap per day for v0.25.0 soak)',
342
+ reply_markup: {
343
+ inline_keyboard: [
344
+ [
345
+ { text: '✅ Yes', callback_data: yesCb },
346
+ { text: '❌ No', callback_data: noCb },
347
+ ],
348
+ ],
349
+ },
350
+ },
351
+ ],
352
+ };
353
+ }
354
+ export const COMMAND_HANDLERS = {
355
+ sessions: handleSessions,
356
+ new: handleNew,
357
+ stop: handleStop,
358
+ status: handleStatus,
359
+ compact: handleCompact,
360
+ cost: handleCost,
361
+ rewind: handleRewind,
362
+ compose: handleCompose,
363
+ send: handleSend,
364
+ cancel: handleCancel,
365
+ 'soak-check': handleSoakCheck,
366
+ };
367
+ /**
368
+ * Telegram bot commands list — declarative source for M5's setMyCommands sync.
369
+ */
370
+ export const TOP_7_COMMANDS = [
371
+ { command: 'sessions', description: 'List + switch fronted Claude session' },
372
+ { command: 'new', description: 'Register a new session slug — /new <slug>' },
373
+ { command: 'stop', description: 'Stop a registered session — /stop <slug>' },
374
+ { command: 'status', description: 'Show active sessions and their state' },
375
+ { command: 'compact', description: 'Compact context on the fronted session' },
376
+ { command: 'cost', description: 'Show Max 20x usage + weekly burn' },
377
+ { command: 'rewind', description: 'Rewind the fronted session by one user message' },
378
+ ];
379
+ /**
380
+ * Route a parsed slash command to its handler. Returns undefined for
381
+ * unknown commands so the caller can fall back to "unknown command" UX.
382
+ */
383
+ export function dispatchCommand(parsed, ctxBase) {
384
+ const handler = COMMAND_HANDLERS[parsed.cmd];
385
+ if (!handler)
386
+ return undefined;
387
+ return handler({ ...ctxBase, args: parsed.args });
388
+ }
389
+ //# sourceMappingURL=commands.js.map