telecoder 0.0.0-stage → 1.3.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.
- package/.env.example +375 -0
- package/CHANGELOG.md +1867 -0
- package/LICENSE +22 -0
- package/README.md +130 -2
- package/dist/audio/transcribe.js +41 -0
- package/dist/bin/mcp-server.js +363 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +573 -0
- package/dist/bot/command-catalog.js +263 -0
- package/dist/bot/deleted-threads.js +103 -0
- package/dist/bot/file-access.js +150 -0
- package/dist/bot/handlers/album.handler.js +128 -0
- package/dist/bot/handlers/branch.handler.js +1096 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +803 -0
- package/dist/bot/handlers/command/all-view.js +33 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/background.js +37 -0
- package/dist/bot/handlers/command/botname.js +76 -0
- package/dist/bot/handlers/command/btw.js +175 -0
- package/dist/bot/handlers/command/cleanup.js +329 -0
- package/dist/bot/handlers/command/model.js +226 -0
- package/dist/bot/handlers/command/prefs-scope.js +362 -0
- package/dist/bot/handlers/command/project.js +458 -0
- package/dist/bot/handlers/command/resume.js +325 -0
- package/dist/bot/handlers/command/session.js +299 -0
- package/dist/bot/handlers/command/settings.js +657 -0
- package/dist/bot/handlers/command/shared.js +207 -0
- package/dist/bot/handlers/command/tasks.js +681 -0
- package/dist/bot/handlers/command/thread.js +128 -0
- package/dist/bot/handlers/command/topic-store.js +74 -0
- package/dist/bot/handlers/command/topic.js +27 -0
- package/dist/bot/handlers/command/usage.js +382 -0
- package/dist/bot/handlers/command-fallback.js +179 -0
- package/dist/bot/handlers/command.handler.js +446 -0
- package/dist/bot/handlers/loop.handler.js +389 -0
- package/dist/bot/handlers/media-fallback.js +126 -0
- package/dist/bot/handlers/message/replies.js +56 -0
- package/dist/bot/handlers/message/shared.js +95 -0
- package/dist/bot/handlers/message/turn-notify.js +135 -0
- package/dist/bot/handlers/message/turn-runner.js +56 -0
- package/dist/bot/handlers/message.handler.js +114 -0
- package/dist/bot/handlers/newbot.handler.js +230 -0
- package/dist/bot/handlers/photo.handler.js +286 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -0
- package/dist/bot/handlers/session-guard.js +78 -0
- package/dist/bot/handlers/suggestion.handler.js +84 -0
- package/dist/bot/handlers/tree.handler.js +480 -0
- package/dist/bot/handlers/view.js +41 -0
- package/dist/bot/handlers/voice.handler.js +147 -0
- package/dist/bot/kept-threads.js +51 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/album-collector.js +69 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +145 -0
- package/dist/bot/middleware/group-role.middleware.js +75 -0
- package/dist/bot/middleware/message-batcher.js +87 -0
- package/dist/bot/middleware/queued-messages.js +1082 -0
- package/dist/bot/middleware/stale-filter.js +9 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/ask-user-form.js +517 -0
- package/dist/claude/ask-user.js +363 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +143 -0
- package/dist/claude/available-commands.js +156 -0
- package/dist/claude/background-hint.js +91 -0
- package/dist/claude/branch-tree.js +393 -0
- package/dist/claude/carry-over.js +25 -0
- package/dist/claude/ccr-shim.js +48 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +117 -0
- package/dist/claude/command-parser.js +206 -0
- package/dist/claude/cost-overlay-scraper.js +134 -0
- package/dist/claude/effort-level.js +5 -0
- package/dist/claude/enabled-plugins.js +52 -0
- package/dist/claude/in-flight-tracker.js +82 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +481 -0
- package/dist/claude/memory-guard.js +400 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +817 -0
- package/dist/claude/model-catalog.js +102 -0
- package/dist/claude/monitor-relay.js +712 -0
- package/dist/claude/native-commands.js +40 -0
- package/dist/claude/pending-branches.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +338 -0
- package/dist/claude/permission-mode.js +152 -0
- package/dist/claude/poll-user.js +51 -0
- package/dist/claude/prewarm.js +70 -0
- package/dist/claude/project-commands.js +69 -0
- package/dist/claude/prompt-hold.js +124 -0
- package/dist/claude/prompt-suggestion-scraper.js +89 -0
- package/dist/claude/pty-idle-reaper.js +96 -0
- package/dist/claude/pty-provider.js +2499 -0
- package/dist/claude/pty-spawn-config.js +343 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/pty-watch.js +201 -0
- package/dist/claude/request-queue.js +107 -0
- package/dist/claude/rewind.js +111 -0
- package/dist/claude/scheduled-runner.js +89 -0
- package/dist/claude/scheduler.js +241 -0
- package/dist/claude/scope-guard.js +279 -0
- package/dist/claude/screen-marks.js +83 -0
- package/dist/claude/screen-render.js +96 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-history.js +288 -0
- package/dist/claude/session-jsonl.js +1067 -0
- package/dist/claude/session-manager.js +216 -0
- package/dist/claude/session-move.js +70 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/shell-mode-gate.js +60 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +252 -0
- package/dist/claude/stage-images.js +62 -0
- package/dist/claude/subagent-tools.js +12 -0
- package/dist/claude/synthetic-ctx.js +51 -0
- package/dist/claude/tasks-overlay-scraper.js +217 -0
- package/dist/claude/thread-judge-haiku.js +88 -0
- package/dist/claude/tip-scraper.js +77 -0
- package/dist/claude/tui-modal.js +746 -0
- package/dist/claude/tui-state.js +456 -0
- package/dist/claude/turn-end.js +105 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/typed-answer.js +104 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +338 -0
- package/dist/cli/commands/help.js +34 -0
- package/dist/cli/commands/init.js +126 -0
- package/dist/cli/commands/service.js +710 -0
- package/dist/cli/commands/start.js +63 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/commands/watch.js +322 -0
- package/dist/cli/dispatch.js +84 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +705 -0
- package/dist/cli/init/prompter.js +124 -0
- package/dist/cli/init/telegram.js +120 -0
- package/dist/cli/service/render.js +212 -0
- package/dist/cli.js +18 -0
- package/dist/config-report.js +107 -0
- package/dist/config.js +525 -0
- package/dist/index.js +443 -0
- package/dist/launcher.js +960 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +142 -0
- package/dist/providers/ccr-provider.js +59 -0
- package/dist/providers/claude-provider.js +10 -0
- package/dist/providers/prefs-sync.js +121 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +128 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/spawn-settings.js +45 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +322 -0
- package/dist/restart-when-idle.js +173 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +161 -0
- package/dist/startup/notices.js +120 -0
- package/dist/startup/shared.js +44 -0
- package/dist/startup/verify-token.js +31 -0
- package/dist/telegram/access-request.js +153 -0
- package/dist/telegram/action-logger.js +522 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +282 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +26 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +96 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1019 -0
- package/dist/telegram/prompt-label.js +148 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +103 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/table-lists.js +56 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +128 -0
- package/dist/telegram/terminal-renderer.js +667 -0
- package/dist/telegram/thread-titles.js +262 -0
- package/dist/telegram/threads-setup.js +117 -0
- package/dist/utils/admins.js +143 -0
- package/dist/utils/agent-timer.js +55 -0
- package/dist/utils/atomic-write.js +24 -0
- package/dist/utils/bot-icon.js +248 -0
- package/dist/utils/bot-token.js +77 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +53 -0
- package/dist/utils/claude-env.js +53 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/download.js +137 -0
- package/dist/utils/exit-codes.js +59 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +78 -0
- package/dist/utils/home-project.js +30 -0
- package/dist/utils/host-stall.js +51 -0
- package/dist/utils/id-list.js +44 -0
- package/dist/utils/idle-restart.js +92 -0
- package/dist/utils/install-mode.js +63 -0
- package/dist/utils/instance-config.js +148 -0
- package/dist/utils/instances.js +95 -0
- package/dist/utils/json-store.js +140 -0
- package/dist/utils/keyed-settings.js +62 -0
- package/dist/utils/legacy-env.js +35 -0
- package/dist/utils/memory-pressure.js +60 -0
- package/dist/utils/npm-version.js +134 -0
- package/dist/utils/prefs-relay.js +107 -0
- package/dist/utils/proc-children.js +102 -0
- package/dist/utils/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +52 -0
- package/dist/utils/respawn-backoff.js +28 -0
- package/dist/utils/sanitize.js +91 -0
- package/dist/utils/session-key.js +37 -0
- package/dist/utils/stale-launcher.js +109 -0
- package/dist/utils/state-dir-migration.js +92 -0
- package/dist/utils/systemd.js +126 -0
- package/dist/utils/telegram-proxy.js +72 -0
- package/dist/utils/uploads-dir.js +27 -0
- package/dist/utils/user-roster.js +275 -0
- package/dist/utils/verbosity.js +118 -0
- package/dist/utils/version-check.js +166 -0
- package/dist/utils/workspace-guard.js +44 -0
- package/dist/worker-restart.js +141 -0
- package/instances.json.example +41 -0
- package/package.json +75 -4
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /threaddelete: delete the thread it's sent in, messages and all, and end
|
|
3
|
+
* the session that belonged to it. Works in a private chat's threads and, for
|
|
4
|
+
* a bot allowed to delete messages there, in a group's forum topics.
|
|
5
|
+
*
|
|
6
|
+
* /threadkeep: mark the thread it's sent in so /threadcleanup leaves it alone, with a 📌
|
|
7
|
+
* in front of its name where the bot names it. `/threadkeep off` takes it off.
|
|
8
|
+
*
|
|
9
|
+
* It answers mid-turn, since stopping that turn is part of the point. The
|
|
10
|
+
* thread goes first and its session after, so a thread Telegram won't delete
|
|
11
|
+
* keeps a session that works.
|
|
12
|
+
*/
|
|
13
|
+
import { GrammyError } from 'grammy';
|
|
14
|
+
import { EntityText } from '../../../telegram/entities.js';
|
|
15
|
+
import { replyFormatted, editCallbackMessage } from '../../../telegram/send.js';
|
|
16
|
+
import { getSessionKeyFromCtx, parseSessionKey } from '../../../utils/session-key.js';
|
|
17
|
+
import { sanitizeError } from '../../../utils/sanitize.js';
|
|
18
|
+
import { forgetThread, isThreadGoneError } from '../../deleted-threads.js';
|
|
19
|
+
import { KEEP_MARK, isThreadKept, setThreadKept } from '../../kept-threads.js';
|
|
20
|
+
import { markThreadName } from '../../../telegram/thread-titles.js';
|
|
21
|
+
import { parseCallback } from './shared.js';
|
|
22
|
+
const SKIP_CONFIRM = new Set(['-y', '--yes', 'yes', 'force']);
|
|
23
|
+
/**
|
|
24
|
+
* Delete the thread, then let its session go. What went wrong, or null. Also
|
|
25
|
+
* what /threadcleanup deletes each thread with.
|
|
26
|
+
*/
|
|
27
|
+
export async function deleteThread(api, sessionKey, why = '/threaddelete') {
|
|
28
|
+
const { chatId, threadId } = parseSessionKey(sessionKey);
|
|
29
|
+
if (threadId === undefined)
|
|
30
|
+
return 'not a thread';
|
|
31
|
+
try {
|
|
32
|
+
await api.deleteForumTopic(chatId, threadId);
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
// Already gone, deleted by hand since the confirmation was sent: let go all the same.
|
|
36
|
+
if (!(err instanceof GrammyError && isThreadGoneError(err.description))) {
|
|
37
|
+
console.error(`[ThreadDelete] Deleting ${sessionKey} failed:`, sanitizeError(err));
|
|
38
|
+
return err instanceof GrammyError ? err.description : 'Telegram refused';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
await forgetThread(api, sessionKey, why);
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
export async function handleThreadDelete(ctx) {
|
|
45
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
46
|
+
if (!keyInfo)
|
|
47
|
+
return;
|
|
48
|
+
const { threadId, sessionKey } = keyInfo;
|
|
49
|
+
if (threadId === undefined) {
|
|
50
|
+
await ctx.reply('ℹ️ Send /threaddelete inside the thread you want to delete.');
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const arg = (ctx.message?.text ?? '').split(' ').slice(1).join(' ').trim().toLowerCase();
|
|
54
|
+
if (SKIP_CONFIRM.has(arg)) {
|
|
55
|
+
const failed = await deleteThread(ctx.api, sessionKey);
|
|
56
|
+
if (failed)
|
|
57
|
+
await ctx.reply(`❌ Couldn't delete this thread: ${failed}`);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const confirm = new EntityText()
|
|
61
|
+
.add('⚠️ ').bold('Delete this thread?')
|
|
62
|
+
.add('\n\nThe thread and all its messages are removed from Telegram, and its Claude session ends. ')
|
|
63
|
+
.add('The conversation itself stays on disk, so ').code('/resume').add(' can still pick it up.\n\n')
|
|
64
|
+
.italic('Telegram can\'t undo this.')
|
|
65
|
+
.add('\n\n💡 Tip: ').code('/threaddelete -y').add(' skips this confirmation.')
|
|
66
|
+
.build();
|
|
67
|
+
await replyFormatted(ctx, confirm, {
|
|
68
|
+
reply_markup: {
|
|
69
|
+
inline_keyboard: [[
|
|
70
|
+
{ text: '🗑️ Yes, delete it', callback_data: 'threaddelete:confirm' },
|
|
71
|
+
{ text: '✗ Cancel', callback_data: 'threaddelete:cancel' },
|
|
72
|
+
]],
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
export async function handleThreadDeleteCallback(ctx) {
|
|
77
|
+
const cb = parseCallback(ctx, 'threaddelete:');
|
|
78
|
+
if (!cb)
|
|
79
|
+
return;
|
|
80
|
+
const { threadId, sessionKey, data } = cb;
|
|
81
|
+
if (data !== 'threaddelete:confirm' || threadId === undefined) {
|
|
82
|
+
await ctx.answerCallbackQuery({ text: 'Kept the thread.' }).catch(() => { });
|
|
83
|
+
await editCallbackMessage(ctx, new EntityText().add('👍 Kept the thread.').build()).catch(() => { });
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const failed = await deleteThread(ctx.api, sessionKey);
|
|
87
|
+
if (failed) {
|
|
88
|
+
await ctx.answerCallbackQuery({ text: 'Couldn\'t delete the thread.' }).catch(() => { });
|
|
89
|
+
await editCallbackMessage(ctx, new EntityText().add(`❌ Couldn't delete this thread: ${failed}`).build()).catch(() => { });
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
await ctx.answerCallbackQuery({ text: 'Thread deleted.' }).catch(() => { });
|
|
93
|
+
}
|
|
94
|
+
const KEEP_OFF = new Set(['off', 'no', 'remove', 'undo']);
|
|
95
|
+
export async function handleThreadKeep(ctx) {
|
|
96
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
97
|
+
if (!keyInfo)
|
|
98
|
+
return;
|
|
99
|
+
const { threadId, sessionKey } = keyInfo;
|
|
100
|
+
if (threadId === undefined) {
|
|
101
|
+
await ctx.reply('ℹ️ Send /threadkeep inside the thread you want to keep.');
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const arg = (ctx.message?.text ?? '').split(' ').slice(1).join(' ').trim().toLowerCase();
|
|
105
|
+
const keep = !KEEP_OFF.has(arg);
|
|
106
|
+
if (!keep) {
|
|
107
|
+
if (!setThreadKept(sessionKey, false)) {
|
|
108
|
+
await replyFormatted(ctx, new EntityText().add('ℹ️ This thread wasn\'t kept, so ').code('/threadcleanup').add(' can already offer it.').build());
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
await markThreadName(sessionKey, KEEP_MARK, false);
|
|
112
|
+
await replyFormatted(ctx, new EntityText().add('👍 Not kept any more: ').code('/threadcleanup').add(' can offer this thread again.').build());
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (isThreadKept(sessionKey)) {
|
|
116
|
+
await replyFormatted(ctx, new EntityText()
|
|
117
|
+
.add('📌 This thread is already kept. ').code('/threadkeep off').add(' lets ').code('/threadcleanup').add(' offer it again.').build());
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
setThreadKept(sessionKey, true);
|
|
121
|
+
const named = await markThreadName(sessionKey, KEEP_MARK, true);
|
|
122
|
+
const text = new EntityText().add('📌 ').bold('Kept.').add(' ').code('/threadcleanup').add(' leaves this thread alone; ')
|
|
123
|
+
.code('/threadkeep off').add(' undoes it.');
|
|
124
|
+
if (named === 'user-named')
|
|
125
|
+
text.newline(2).italic('The thread\'s name is the one you gave it, so it stays as it is, without the 📌.');
|
|
126
|
+
await replyFormatted(ctx, text.build());
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=thread.js.map
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session topic — the state and the mutators.
|
|
3
|
+
*
|
|
4
|
+
* The topic is ephemeral per-session state (persisted only through
|
|
5
|
+
* sessionHistory) that several other command domains read and reset — project
|
|
6
|
+
* switches, /clear, and resume all touch it. It shows in the status line and
|
|
7
|
+
* names the thread; the bot's display name is static (see `/botname`).
|
|
8
|
+
*
|
|
9
|
+
* This module is deliberately kept below the provider layer, so that code
|
|
10
|
+
* under it can read and set the topic without closing an import cycle through
|
|
11
|
+
* the command barrel. Nothing here may import `./shared.js` or anything under
|
|
12
|
+
* `providers/`. The /topic *command* lives in `topic.ts`, which is free to.
|
|
13
|
+
*/
|
|
14
|
+
import * as path from 'path';
|
|
15
|
+
import { sessionManager } from '../../../claude/session-manager.js';
|
|
16
|
+
import { sessionHistory } from '../../../claude/session-history.js';
|
|
17
|
+
import { readLastAiTitle } from '../../../claude/session-jsonl.js';
|
|
18
|
+
import { syncThreadTitle } from '../../../telegram/thread-titles.js';
|
|
19
|
+
import { isHomeProject } from '../../../utils/home-project.js';
|
|
20
|
+
// Per-session topic (ephemeral — not persisted across restarts)
|
|
21
|
+
const sessionTopics = new Map();
|
|
22
|
+
// Per-session timestamp of last setSessionTopic call. Used by the auto-topic
|
|
23
|
+
// reminder hook to skip the per-turn nudge when the topic was just updated.
|
|
24
|
+
const lastTopicSetAt = new Map();
|
|
25
|
+
/**
|
|
26
|
+
* Clear the session topic. Called whenever the conversation context is wiped
|
|
27
|
+
* (clear, reset, project switch).
|
|
28
|
+
*/
|
|
29
|
+
export function clearTopic(sessionKey) {
|
|
30
|
+
setSessionTopic(sessionKey, '');
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Restore the session topic from the saved value (or clear if absent). Called
|
|
34
|
+
* when resuming/continuing a previous conversation.
|
|
35
|
+
*
|
|
36
|
+
* When no persisted topic exists, fall back to Claude Code's `aiTitle` from the
|
|
37
|
+
* session JSONL — better a stale session label than a blank topic line on resume.
|
|
38
|
+
*/
|
|
39
|
+
export function restoreTopic(sessionKey, topic) {
|
|
40
|
+
if (!topic) {
|
|
41
|
+
const session = sessionManager.getSession(sessionKey);
|
|
42
|
+
if (session?.claudeSessionId) {
|
|
43
|
+
topic = readLastAiTitle(session.workingDirectory, session.claudeSessionId);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
setSessionTopic(sessionKey, topic || '');
|
|
47
|
+
}
|
|
48
|
+
/** Set the session topic programmatically (used by the MCP tool and auto-resume). */
|
|
49
|
+
export function setSessionTopic(sessionKey, topic) {
|
|
50
|
+
if (topic) {
|
|
51
|
+
sessionTopics.set(sessionKey, topic);
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
sessionTopics.delete(sessionKey);
|
|
55
|
+
}
|
|
56
|
+
lastTopicSetAt.set(sessionKey, Date.now());
|
|
57
|
+
// Persist so topic survives restarts
|
|
58
|
+
sessionHistory.updateTopic(sessionKey, topic || undefined);
|
|
59
|
+
// In a private chat's thread, the topic is the thread's name too, with the
|
|
60
|
+
// project in front unless it's the one the bot is named after.
|
|
61
|
+
const workingDirectory = sessionManager.getSession(sessionKey)?.workingDirectory;
|
|
62
|
+
const project = workingDirectory && !isHomeProject(workingDirectory) ? path.basename(workingDirectory) : undefined;
|
|
63
|
+
syncThreadTitle(sessionKey, topic, project);
|
|
64
|
+
}
|
|
65
|
+
/** Get the current session topic. */
|
|
66
|
+
export function getSessionTopic(sessionKey) {
|
|
67
|
+
return sessionTopics.get(sessionKey);
|
|
68
|
+
}
|
|
69
|
+
/** Milliseconds since the last setSessionTopic call (or undefined if never). */
|
|
70
|
+
export function getMsSinceTopicSet(sessionKey) {
|
|
71
|
+
const at = lastTopicSetAt.get(sessionKey);
|
|
72
|
+
return at !== undefined ? Date.now() - at : undefined;
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=topic-store.js.map
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The /topic command.
|
|
3
|
+
*
|
|
4
|
+
* The topic state itself lives in `topic-store.ts`, which stays below the
|
|
5
|
+
* provider layer so code under it can read and set the topic without closing
|
|
6
|
+
* an import cycle. This module adds the Telegram command surface on top and
|
|
7
|
+
* re-exports the store so the command barrel's public API is unchanged.
|
|
8
|
+
*/
|
|
9
|
+
import { EntityText } from '../../../telegram/entities.js';
|
|
10
|
+
import { replyFormatted } from '../../../telegram/send.js';
|
|
11
|
+
import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
|
|
12
|
+
import { setSessionTopic } from './topic-store.js';
|
|
13
|
+
export { clearTopic, restoreTopic, setSessionTopic, getSessionTopic, getMsSinceTopicSet, } from './topic-store.js';
|
|
14
|
+
export async function handleTopic(ctx) {
|
|
15
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
16
|
+
if (!keyInfo)
|
|
17
|
+
return;
|
|
18
|
+
const { sessionKey } = keyInfo;
|
|
19
|
+
const text = ctx.message?.text || '';
|
|
20
|
+
const topic = text.split(' ').slice(1).join(' ').trim();
|
|
21
|
+
// Topic lives in the status line, not the Telegram bot name —
|
|
22
|
+
// setSessionTopic updates in-memory + persistent state but the bot's
|
|
23
|
+
// Telegram-side display name doesn't change, so no setMyName call.
|
|
24
|
+
setSessionTopic(sessionKey, topic);
|
|
25
|
+
await replyFormatted(ctx, topic ? new EntityText().add('✅ Topic: ').bold(topic).build() : '✅ Topic cleared');
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=topic.js.map
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/cost` — Claude Code's own cost report, delivered to the chat.
|
|
3
|
+
*
|
|
4
|
+
* What `/cost` reports depends on how the account pays, and the difference
|
|
5
|
+
* decides how much of it TeleCoder can honour:
|
|
6
|
+
*
|
|
7
|
+
* - subscription: the limits view — how much of the session and weekly
|
|
8
|
+
* windows is spent, and when each resets. Account-wide, and the same text
|
|
9
|
+
* `/usage` prints. Asking it in a process that has just spent $0.10
|
|
10
|
+
* returns exactly that view with no session figure in it.
|
|
11
|
+
* - API billing: the session's own totals — dollars, durations, per-model
|
|
12
|
+
* token counts.
|
|
13
|
+
*
|
|
14
|
+
* That second shape is session-scoped, and no probe recovers it. The cost
|
|
15
|
+
* counter lives in the CLI process that spent it: resume the session in a
|
|
16
|
+
* fresh process and it reads zero, because the session log carries no cost
|
|
17
|
+
* field to rebuild it from. So the totals a spawned probe reports are its own,
|
|
18
|
+
* not the conversation's, and `parseCostOutput` says so rather than letting a
|
|
19
|
+
* $0.00 read as this chat having been free.
|
|
20
|
+
*
|
|
21
|
+
* Since the probe is a fresh process either way, it needs no session and no
|
|
22
|
+
* `--resume` — nothing here can append a stray turn to a live conversation,
|
|
23
|
+
* and the command answers before a project is even open.
|
|
24
|
+
*
|
|
25
|
+
* What the probe can't have, the chat's own claude still holds: a live TUI a
|
|
26
|
+
* `/cost` away from drawing exactly those totals, so we ask it too and scrape
|
|
27
|
+
* the Session block off the overlay — the same trick /tasks uses. That is
|
|
28
|
+
* where "Total cost", the durations, the per-model breakdown and the
|
|
29
|
+
* prompt-cache line come from.
|
|
30
|
+
*
|
|
31
|
+
* Two sources, one report, no overlap: the panel's own limits view is left
|
|
32
|
+
* unscraped (it scrolls off the first screenful anyway) and read from the
|
|
33
|
+
* probe, which prints the same numbers in any mode.
|
|
34
|
+
*/
|
|
35
|
+
import { spawn } from 'child_process';
|
|
36
|
+
import * as fs from 'fs';
|
|
37
|
+
import { sessionManager } from '../../../claude/session-manager.js';
|
|
38
|
+
import { scrapeCostSession } from '../../../claude/cost-overlay-scraper.js';
|
|
39
|
+
import { getPtyProvider } from '../../../providers/claude-provider.js';
|
|
40
|
+
import { messageSender } from '../../../telegram/message-sender.js';
|
|
41
|
+
import { getProgressBar } from '../../../utils/format.js';
|
|
42
|
+
import { resolvePtyClaudeBin } from '../../../utils/resolve-claude-bin.js';
|
|
43
|
+
import { sanitizeError } from '../../../utils/sanitize.js';
|
|
44
|
+
import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
|
|
45
|
+
import { getWorkspaceRoot } from '../../../utils/workspace-guard.js';
|
|
46
|
+
/** The probe answers in ~2s; 20s is ten times that. */
|
|
47
|
+
const COST_TIMEOUT_MS = 20_000;
|
|
48
|
+
/** Output cap, standing in for `execFile`'s `maxBuffer`. */
|
|
49
|
+
const MAX_OUTPUT_BYTES = 1024 * 1024;
|
|
50
|
+
/** `Current session: 39% used · resets Aug 31, 5:09pm (UTC)` */
|
|
51
|
+
const LIMIT_RE = /^(.+?):\s*(\d+(?:\.\d+)?)%\s+used\b(?:\s*[·•-]\s*resets\s+(.+?))?$/i;
|
|
52
|
+
/** `Total cost: $0.1234` — the API-billing shape's label/value rows. */
|
|
53
|
+
const TOTALS_RE = /^(Total\s+[^:]+):\s*(.+)$/i;
|
|
54
|
+
/** `Last 24h · 1608 requests · 89 sessions` */
|
|
55
|
+
const PERIOD_RE = /^(Last\s+\S+)(\s*[·•].*)$/i;
|
|
56
|
+
/**
|
|
57
|
+
* Turn the Session block scraped off the live TUI into report lines.
|
|
58
|
+
*
|
|
59
|
+
* Kept close to the panel's own layout — same labels, same order, the
|
|
60
|
+
* per-model rows still nested under `Usage by model` — because this is the
|
|
61
|
+
* half of the report people already know from typing `/cost` in a terminal.
|
|
62
|
+
*/
|
|
63
|
+
function renderSessionBlock(session) {
|
|
64
|
+
const lines = ['**This session**'];
|
|
65
|
+
for (const row of session.rows) {
|
|
66
|
+
if (row.nested) {
|
|
67
|
+
// A model's own line. Two spaces is the least indentation Telegram will
|
|
68
|
+
// render as a nested bullet rather than flatten into its parent.
|
|
69
|
+
lines.push(` - \`${row.label}\`: ${row.value}`);
|
|
70
|
+
}
|
|
71
|
+
else if (row.value) {
|
|
72
|
+
lines.push(`- **${row.label}:** ${row.value}`);
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
// `Usage by model:` and friends — a label whose value is the rows below.
|
|
76
|
+
lines.push(`- **${row.label}:**`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return lines;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Render `claude -p /cost` output as Telegram markdown.
|
|
83
|
+
*
|
|
84
|
+
* `session` is the Session block off the live TUI's `/cost` panel — the real
|
|
85
|
+
* totals for this conversation, when there is a live pty to ask. When we have
|
|
86
|
+
* it, the probe's own `Total ...` rows are dropped rather than printed
|
|
87
|
+
* alongside: they belong to the process that ran the lookup, and two
|
|
88
|
+
* contradicting sets of totals in one message is worse than the one true set.
|
|
89
|
+
*/
|
|
90
|
+
export function parseCostOutput(raw, session) {
|
|
91
|
+
const trimmed = raw.trim();
|
|
92
|
+
if (!trimmed) {
|
|
93
|
+
// The probe failing doesn't make the live totals worthless — they are the
|
|
94
|
+
// part people came for, so show them alone rather than only an error.
|
|
95
|
+
if (session)
|
|
96
|
+
return ['## 💰 Cost & Usage', '', ...renderSessionBlock(session)].join('\n');
|
|
97
|
+
return '⚠️ No cost output received.';
|
|
98
|
+
}
|
|
99
|
+
const body = [];
|
|
100
|
+
let recognised = 0;
|
|
101
|
+
let sawTotals = false;
|
|
102
|
+
/**
|
|
103
|
+
* Inside the probe's own `Usage by model:` section, which the live block
|
|
104
|
+
* supersedes. Its rows are indented, and so are the per-period detail rows
|
|
105
|
+
* further down that we do want, so dropping them takes knowing which
|
|
106
|
+
* heading we are under.
|
|
107
|
+
*/
|
|
108
|
+
let underSupersededModels = false;
|
|
109
|
+
/** Collapse runs of blank lines, and never open a section with one. */
|
|
110
|
+
const pushBlank = () => {
|
|
111
|
+
if (body.length > 0 && body[body.length - 1] !== '')
|
|
112
|
+
body.push('');
|
|
113
|
+
};
|
|
114
|
+
for (const rawLine of trimmed.split('\n')) {
|
|
115
|
+
const line = rawLine.trim();
|
|
116
|
+
// Any unindented line — or a blank one — closes whatever section we were in.
|
|
117
|
+
if (!line || !/^\s/.test(rawLine))
|
|
118
|
+
underSupersededModels = false;
|
|
119
|
+
if (!line) {
|
|
120
|
+
pushBlank();
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const limit = line.match(LIMIT_RE);
|
|
124
|
+
if (limit) {
|
|
125
|
+
const pct = Math.round(Number(limit[2]));
|
|
126
|
+
// "Current session" reads better as "session" once the bar carries the number.
|
|
127
|
+
const label = limit[1].replace(/^current\s+/i, '');
|
|
128
|
+
const resets = limit[3] ? ` — resets ${limit[3]}` : '';
|
|
129
|
+
body.push(`${getProgressBar(pct)} **${pct}%** ${label}${resets}`);
|
|
130
|
+
recognised++;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
const totals = line.match(TOTALS_RE);
|
|
134
|
+
if (totals) {
|
|
135
|
+
// Recognised either way — the line is understood, it is just superseded.
|
|
136
|
+
if (!session) {
|
|
137
|
+
body.push(`- **${totals[1]}:** ${totals[2].trim()}`);
|
|
138
|
+
sawTotals = true;
|
|
139
|
+
}
|
|
140
|
+
recognised++;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const period = line.match(PERIOD_RE);
|
|
144
|
+
if (period) {
|
|
145
|
+
pushBlank();
|
|
146
|
+
body.push(`**${period[1]}**${period[2]}`);
|
|
147
|
+
recognised++;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (/^usage by model:?$/i.test(line)) {
|
|
151
|
+
if (session) {
|
|
152
|
+
underSupersededModels = true;
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
pushBlank();
|
|
156
|
+
body.push('**Usage by model**');
|
|
157
|
+
}
|
|
158
|
+
recognised++;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (/^what's contributing/i.test(line)) {
|
|
162
|
+
pushBlank();
|
|
163
|
+
body.push(`**${line}**`);
|
|
164
|
+
recognised++;
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
// The CLI indents the detail rows under each heading — as bullets they
|
|
168
|
+
// survive Telegram's whitespace collapsing, which would otherwise flatten
|
|
169
|
+
// them into the heading above.
|
|
170
|
+
if (/^\s+\S/.test(rawLine)) {
|
|
171
|
+
if (!underSupersededModels)
|
|
172
|
+
body.push(`- ${line}`);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
// Framing prose ("You are currently using your subscription…", the
|
|
176
|
+
// "Approximate, based on local sessions…" caveat) — kept, because the
|
|
177
|
+
// caveat is the part that says these numbers miss your other machines.
|
|
178
|
+
body.push(`_${line}_`);
|
|
179
|
+
}
|
|
180
|
+
const lines = ['## 💰 Cost & Usage', ''];
|
|
181
|
+
if (session) {
|
|
182
|
+
lines.push(...renderSessionBlock(session), '');
|
|
183
|
+
}
|
|
184
|
+
if (recognised === 0) {
|
|
185
|
+
// A CLI whose wording we don't know. Show what came back rather than
|
|
186
|
+
// dressing up output we failed to understand — as a sentence when that is
|
|
187
|
+
// all it is (older builds answer `/cost` with a single line), as a block
|
|
188
|
+
// when there is a shape worth preserving.
|
|
189
|
+
lines.push(trimmed.includes('\n') ? `\`\`\`\n${trimmed}\n\`\`\`` : `_${trimmed}_`);
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
lines.push(...body);
|
|
193
|
+
}
|
|
194
|
+
if (sawTotals) {
|
|
195
|
+
// These totals belong to the process that just answered, which has done
|
|
196
|
+
// nothing but answer. Left unqualified, an API-billed account reads its
|
|
197
|
+
// $0.00 as a conversation that cost nothing.
|
|
198
|
+
if (lines[lines.length - 1] !== '')
|
|
199
|
+
lines.push('');
|
|
200
|
+
lines.push('_Totals cover this lookup only — Claude Code keeps no per-conversation cost once a turn ends._');
|
|
201
|
+
}
|
|
202
|
+
return lines.join('\n').trimEnd();
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* The CLI to ask: the one the ptys run — the same `claude` the user would type
|
|
206
|
+
* `/cost` into. Spawned fresh with nothing spent in it, so the substance of the
|
|
207
|
+
* answer does not depend on the process. A list, for runClaudeCost, which
|
|
208
|
+
* moves on from a candidate that could not be started.
|
|
209
|
+
*/
|
|
210
|
+
function costExecutables() {
|
|
211
|
+
return [resolvePtyClaudeBin()];
|
|
212
|
+
}
|
|
213
|
+
/** A CLI that never started, as opposed to one that ran and failed. */
|
|
214
|
+
function isSpawnFailure(error) {
|
|
215
|
+
const code = error?.code;
|
|
216
|
+
return code === 'ENOENT' || code === 'EACCES';
|
|
217
|
+
}
|
|
218
|
+
async function runClaudeCost(executables, cwd) {
|
|
219
|
+
let lastError;
|
|
220
|
+
for (const executable of executables) {
|
|
221
|
+
try {
|
|
222
|
+
return await runOne(executable, cwd);
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
// Only a CLI that could not be started is worth retrying elsewhere. One
|
|
226
|
+
// that ran and failed has given its answer, and trying an older copy
|
|
227
|
+
// would just bury the reason.
|
|
228
|
+
if (!isSpawnFailure(error))
|
|
229
|
+
throw error;
|
|
230
|
+
lastError = error;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
throw lastError ?? new Error('No Claude Code CLI found');
|
|
234
|
+
}
|
|
235
|
+
function runOne(executable, cwd) {
|
|
236
|
+
return new Promise((resolve, reject) => {
|
|
237
|
+
// stdin is 'ignore' rather than the pipe `execFile` would hand it: an idle
|
|
238
|
+
// stdin pipe makes the CLI wait three seconds for input that will never
|
|
239
|
+
// arrive, then warn about it on stderr. Closing it up front takes the
|
|
240
|
+
// round trip from ~5.4s to ~2.5s and keeps the warning out of the output.
|
|
241
|
+
const child = spawn(executable, ['-p', '/cost'], {
|
|
242
|
+
cwd,
|
|
243
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
244
|
+
env: process.env,
|
|
245
|
+
});
|
|
246
|
+
let stdout = '';
|
|
247
|
+
let stderr = '';
|
|
248
|
+
let settled = false;
|
|
249
|
+
const finish = (error) => {
|
|
250
|
+
if (settled)
|
|
251
|
+
return;
|
|
252
|
+
settled = true;
|
|
253
|
+
clearTimeout(timer);
|
|
254
|
+
try {
|
|
255
|
+
child.kill('SIGTERM');
|
|
256
|
+
}
|
|
257
|
+
catch { /* already gone */ }
|
|
258
|
+
if (error)
|
|
259
|
+
reject(error);
|
|
260
|
+
else
|
|
261
|
+
resolve((stdout || stderr).trim());
|
|
262
|
+
};
|
|
263
|
+
const timer = setTimeout(() => finish(new Error(`Timed out after ${COST_TIMEOUT_MS / 1000}s`)), COST_TIMEOUT_MS);
|
|
264
|
+
const collect = (into) => (chunk) => {
|
|
265
|
+
const text = chunk.toString('utf-8');
|
|
266
|
+
if (into === 'out')
|
|
267
|
+
stdout += text;
|
|
268
|
+
else
|
|
269
|
+
stderr += text;
|
|
270
|
+
// Standing in for execFile's maxBuffer: take what we have rather than
|
|
271
|
+
// growing without bound if some future build streams into `-p`.
|
|
272
|
+
if (stdout.length + stderr.length > MAX_OUTPUT_BYTES)
|
|
273
|
+
finish(null);
|
|
274
|
+
};
|
|
275
|
+
child.stdout.on('data', collect('out'));
|
|
276
|
+
child.stderr.on('data', collect('err'));
|
|
277
|
+
child.on('error', (error) => finish(error));
|
|
278
|
+
child.on('close', (code) => {
|
|
279
|
+
// A non-zero exit that still printed the report is worth showing; only
|
|
280
|
+
// an exit with nothing to show is an error.
|
|
281
|
+
if (code === 0 || stdout.trim())
|
|
282
|
+
finish(null);
|
|
283
|
+
else
|
|
284
|
+
finish(new Error(stderr.trim() || `claude exited with code ${code}`));
|
|
285
|
+
});
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* A directory the CLI can actually start in.
|
|
290
|
+
*
|
|
291
|
+
* A spawn whose `cwd` does not exist fails as `ENOENT <executable>` — an error
|
|
292
|
+
* that sends you looking for a binary that was never the problem. Falling back
|
|
293
|
+
* costs nothing here: `/cost` reports account-wide numbers, so the working
|
|
294
|
+
* directory only has to be somewhere the process can stand.
|
|
295
|
+
*/
|
|
296
|
+
function resolveSpawnCwd(sessionCwd) {
|
|
297
|
+
for (const candidate of [sessionCwd, getWorkspaceRoot()]) {
|
|
298
|
+
if (candidate && fs.existsSync(candidate))
|
|
299
|
+
return candidate;
|
|
300
|
+
}
|
|
301
|
+
return process.cwd();
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Why the live totals aren't in this report, in the chat's own terms.
|
|
305
|
+
*
|
|
306
|
+
* Every one of these means the report still goes out, carrying the limits view
|
|
307
|
+
* it has always carried. But saying nothing was worse than the missing
|
|
308
|
+
* numbers: a blank where a Session block should be looks like the feature is
|
|
309
|
+
* broken, when three of the four causes clear by themselves.
|
|
310
|
+
*/
|
|
311
|
+
export function explainMissingTotals(reason) {
|
|
312
|
+
switch (reason) {
|
|
313
|
+
case 'turn-active':
|
|
314
|
+
return "This session's totals need the TUI, which is mid-turn — ask again when it finishes.";
|
|
315
|
+
case 'not-ready':
|
|
316
|
+
return "This session's totals need the TUI, which isn't at its prompt — a dialog may be waiting. Ask again in a moment.";
|
|
317
|
+
case 'no-session':
|
|
318
|
+
return "This chat has no live session yet, so there are no totals to read — send a message first.";
|
|
319
|
+
case 'unreadable':
|
|
320
|
+
// The panel is a Claude Code implementation detail and can move between
|
|
321
|
+
// releases. Say that plainly rather than leave a silent gap.
|
|
322
|
+
return "Couldn't read this session's totals — Claude Code may have changed its `/cost` panel.";
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* The chat's own totals, read off the live TUI's `/cost` panel.
|
|
327
|
+
*
|
|
328
|
+
* Best-effort in every failure it can meet: no live session, a
|
|
329
|
+
* turn holding the keyboard, a panel whose layout has moved on. None is worth
|
|
330
|
+
* failing the command over — but each is worth naming, in the log for us and
|
|
331
|
+
* in the report for whoever is looking at the gap.
|
|
332
|
+
*/
|
|
333
|
+
async function readLiveSessionTotals(sessionKey) {
|
|
334
|
+
const miss = (reason) => {
|
|
335
|
+
console.warn(`[Usage] no live session totals for ${sessionKey}: ${reason}`);
|
|
336
|
+
return { session: null, note: explainMissingTotals(reason) };
|
|
337
|
+
};
|
|
338
|
+
try {
|
|
339
|
+
const result = await getPtyProvider().runOverlayCommand(sessionKey, '/cost');
|
|
340
|
+
if (!result.ok)
|
|
341
|
+
return miss(result.reason);
|
|
342
|
+
const session = scrapeCostSession(result.screen);
|
|
343
|
+
return session ? { session, note: null } : miss('unreadable');
|
|
344
|
+
}
|
|
345
|
+
catch (error) {
|
|
346
|
+
console.warn('[Usage] Could not read the live /cost panel:', sanitizeError(error));
|
|
347
|
+
return { session: null, note: explainMissingTotals('unreadable') };
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
export async function handleUsage(ctx) {
|
|
351
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
352
|
+
if (!keyInfo)
|
|
353
|
+
return;
|
|
354
|
+
const { sessionKey } = keyInfo;
|
|
355
|
+
// Deliberately no session guard: limits are account-wide, so the answer is
|
|
356
|
+
// the same — and just as useful — in a chat that has never opened a project.
|
|
357
|
+
const session = sessionManager.getSession(sessionKey);
|
|
358
|
+
const cwd = resolveSpawnCwd(session?.workingDirectory);
|
|
359
|
+
const typing = ctx.replyWithChatAction?.('typing');
|
|
360
|
+
try {
|
|
361
|
+
// Concurrently: the probe is a process launch, the panel is a keystroke
|
|
362
|
+
// into a process already running, and neither waits on the other.
|
|
363
|
+
const [raw, live] = await Promise.all([
|
|
364
|
+
runClaudeCost(costExecutables(), cwd),
|
|
365
|
+
readLiveSessionTotals(sessionKey),
|
|
366
|
+
]);
|
|
367
|
+
await typing?.catch(() => { });
|
|
368
|
+
let report = parseCostOutput(raw, live.session);
|
|
369
|
+
if (live.note)
|
|
370
|
+
report += `\n\n_${live.note}_`;
|
|
371
|
+
await messageSender.sendMessage(ctx, report);
|
|
372
|
+
}
|
|
373
|
+
catch (error) {
|
|
374
|
+
console.error('[Usage] Failed to run /cost:', sanitizeError(error));
|
|
375
|
+
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
376
|
+
const hint = /unknown|unrecognized|command/i.test(message)
|
|
377
|
+
? '\n\nThis Claude Code build may not support `/cost` yet.'
|
|
378
|
+
: '';
|
|
379
|
+
await messageSender.sendMessage(ctx, `❌ Failed to fetch cost: ${message}${hint}`);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
//# sourceMappingURL=usage.js.map
|