telecoder 0.0.0-stage → 1.2.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 +363 -0
- package/CHANGELOG.md +1186 -0
- package/LICENSE +22 -0
- package/README.md +126 -2
- package/dist/audio/transcribe.js +50 -0
- package/dist/bin/mcp-server.js +378 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +592 -0
- package/dist/bot/file-access.js +141 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +827 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/btw.js +224 -0
- package/dist/bot/handlers/command/cost.js +409 -0
- package/dist/bot/handlers/command/media.js +197 -0
- package/dist/bot/handlers/command/model.js +305 -0
- package/dist/bot/handlers/command/prefs-scope.js +197 -0
- package/dist/bot/handlers/command/project.js +536 -0
- package/dist/bot/handlers/command/resume.js +321 -0
- package/dist/bot/handlers/command/session.js +438 -0
- package/dist/bot/handlers/command/settings.js +1012 -0
- package/dist/bot/handlers/command/shared.js +210 -0
- package/dist/bot/handlers/command/streaming-mode.js +16 -0
- package/dist/bot/handlers/command/tasks.js +513 -0
- package/dist/bot/handlers/command/topic-store.js +113 -0
- package/dist/bot/handlers/command/topic.js +80 -0
- package/dist/bot/handlers/command.handler.js +772 -0
- package/dist/bot/handlers/fork.handler.js +1109 -0
- package/dist/bot/handlers/media-fallback.js +121 -0
- package/dist/bot/handlers/message/replies.js +133 -0
- package/dist/bot/handlers/message/shared.js +117 -0
- package/dist/bot/handlers/message/throttle.js +49 -0
- package/dist/bot/handlers/message/turn-notify.js +169 -0
- package/dist/bot/handlers/message/turn-runner.js +141 -0
- package/dist/bot/handlers/message.handler.js +107 -0
- package/dist/bot/handlers/newbot.handler.js +221 -0
- package/dist/bot/handlers/photo.handler.js +327 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -0
- package/dist/bot/handlers/schedule.handler.js +303 -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 +209 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +139 -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 +971 -0
- package/dist/bot/middleware/stale-filter.js +31 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/agent-watchdog.js +162 -0
- package/dist/claude/agent.js +1458 -0
- package/dist/claude/ask-user.js +295 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +126 -0
- package/dist/claude/available-commands.js +153 -0
- package/dist/claude/carry-over.js +27 -0
- package/dist/claude/ccr-shim.js +46 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +121 -0
- package/dist/claude/command-parser.js +200 -0
- package/dist/claude/cost-overlay-scraper.js +129 -0
- package/dist/claude/enabled-plugins.js +56 -0
- package/dist/claude/fork-tree.js +393 -0
- package/dist/claude/held-query.js +190 -0
- package/dist/claude/in-flight-tracker.js +61 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +453 -0
- package/dist/claude/mcp-tools.js +354 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +450 -0
- package/dist/claude/model-catalog.js +85 -0
- package/dist/claude/monitor-relay.js +597 -0
- package/dist/claude/pending-forks.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +337 -0
- package/dist/claude/permission-mode.js +178 -0
- package/dist/claude/poll-user.js +51 -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-provider.js +2214 -0
- package/dist/claude/pty-spawn-config.js +296 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/request-queue.js +135 -0
- package/dist/claude/scheduled-runner.js +91 -0
- package/dist/claude/scheduler.js +237 -0
- package/dist/claude/scope-guard.js +274 -0
- package/dist/claude/sdk-permission-gate.js +77 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-cost.js +41 -0
- package/dist/claude/session-history.js +286 -0
- package/dist/claude/session-jsonl.js +920 -0
- package/dist/claude/session-manager.js +195 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +249 -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/system-prompt.js +162 -0
- package/dist/claude/tasks-overlay-scraper.js +94 -0
- package/dist/claude/tip-scraper.js +78 -0
- package/dist/claude/tui-modal.js +501 -0
- package/dist/claude/tui-state.js +384 -0
- package/dist/claude/turn-end.js +91 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +305 -0
- package/dist/cli/commands/help.js +25 -0
- package/dist/cli/commands/init.js +123 -0
- package/dist/cli/commands/service.js +678 -0
- package/dist/cli/commands/start.js +53 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/dispatch.js +79 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +638 -0
- package/dist/cli/init/prompter.js +116 -0
- package/dist/cli/init/telegram.js +94 -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 +500 -0
- package/dist/index.js +367 -0
- package/dist/launcher.js +933 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +149 -0
- package/dist/providers/ccr-provider.js +60 -0
- package/dist/providers/claude-provider.js +63 -0
- package/dist/providers/prefs-sync.js +164 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +127 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/sdk-provider.js +37 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +214 -0
- package/dist/restart-when-idle.js +153 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +173 -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 +684 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +336 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +27 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +57 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1287 -0
- package/dist/telegram/prompt-label.js +142 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +105 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +209 -0
- package/dist/telegram/telegraph-settings.js +31 -0
- package/dist/telegram/telegraph.js +453 -0
- package/dist/telegram/terminal-renderer.js +671 -0
- package/dist/telegram/terminal-settings.js +25 -0
- package/dist/telegram/thread-titles.js +190 -0
- package/dist/telegram/threads-setup.js +117 -0
- package/dist/tts/tts-settings.js +62 -0
- package/dist/tts/tts.js +245 -0
- package/dist/tts/voice-reply.js +78 -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-token.js +74 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +50 -0
- package/dist/utils/claude-env.js +54 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/debug-agent.js +117 -0
- package/dist/utils/debug-watchdog.js +121 -0
- package/dist/utils/download.js +111 -0
- package/dist/utils/exit-codes.js +48 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +81 -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/npm-version.js +134 -0
- package/dist/utils/prefs-relay.js +107 -0
- package/dist/utils/proc-children.js +102 -0
- package/dist/utils/project-data-dir.js +33 -0
- package/dist/utils/reasoning-summary.js +12 -0
- package/dist/utils/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +63 -0
- package/dist/utils/respawn-backoff.js +19 -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/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 +76 -4
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /tasks and /shells — inspecting what the agent is running.
|
|
3
|
+
*
|
|
4
|
+
* Grouped because both are read-only views over live process state with the
|
|
5
|
+
* same list/detail inline-keyboard shape: /tasks over the SDK task tracker,
|
|
6
|
+
* /shells over the pty's real child processes.
|
|
7
|
+
*/
|
|
8
|
+
import { EntityText } from '../../../telegram/entities.js';
|
|
9
|
+
import { replyFormatted, editCallbackMessage } from '../../../telegram/send.js';
|
|
10
|
+
import { taskTracker } from '../../../telegram/task-tracker.js';
|
|
11
|
+
import { getPtyProvider } from '../../../providers/claude-provider.js';
|
|
12
|
+
import { scrapeTasksOverlay } from '../../../claude/tasks-overlay-scraper.js';
|
|
13
|
+
import { bringCardDown, hasRunningTasks } from '../../../telegram/background-activity-card.js';
|
|
14
|
+
import { getDirectChildren, describeProcess, isDescendantOf, killTree, } from '../../../utils/proc-children.js';
|
|
15
|
+
import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
|
|
16
|
+
function groupTasksForDisplay(tasks) {
|
|
17
|
+
const monitors = [];
|
|
18
|
+
const shells = [];
|
|
19
|
+
const agents = [];
|
|
20
|
+
const workflows = [];
|
|
21
|
+
const other = [];
|
|
22
|
+
for (const task of tasks) {
|
|
23
|
+
switch (task.taskType) {
|
|
24
|
+
case 'monitor_mcp':
|
|
25
|
+
monitors.push(task);
|
|
26
|
+
break;
|
|
27
|
+
case 'local_bash':
|
|
28
|
+
shells.push(task);
|
|
29
|
+
break;
|
|
30
|
+
case 'local_workflow':
|
|
31
|
+
workflows.push(task);
|
|
32
|
+
break;
|
|
33
|
+
case 'local_agent':
|
|
34
|
+
case 'remote_agent':
|
|
35
|
+
case undefined:
|
|
36
|
+
agents.push(task);
|
|
37
|
+
break;
|
|
38
|
+
default:
|
|
39
|
+
other.push(task);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const groups = [];
|
|
43
|
+
if (agents.length)
|
|
44
|
+
groups.push({ emoji: '🤖', label: 'Agents', tasks: agents });
|
|
45
|
+
if (monitors.length)
|
|
46
|
+
groups.push({ emoji: '📡', label: 'Monitors', tasks: monitors });
|
|
47
|
+
if (shells.length)
|
|
48
|
+
groups.push({ emoji: '💻', label: 'Shells', tasks: shells });
|
|
49
|
+
if (workflows.length)
|
|
50
|
+
groups.push({ emoji: '📋', label: 'Workflows', tasks: workflows });
|
|
51
|
+
if (other.length)
|
|
52
|
+
groups.push({ emoji: '🔹', label: 'Other', tasks: other });
|
|
53
|
+
return groups;
|
|
54
|
+
}
|
|
55
|
+
function formatDuration(ms) {
|
|
56
|
+
const seconds = Math.floor(ms / 1000);
|
|
57
|
+
if (seconds < 60)
|
|
58
|
+
return `${seconds}s`;
|
|
59
|
+
const minutes = Math.floor(seconds / 60);
|
|
60
|
+
return `${minutes}m ${seconds % 60}s`;
|
|
61
|
+
}
|
|
62
|
+
function formatTaskElapsed(task) {
|
|
63
|
+
return formatDuration((task.endedAt ?? Date.now()) - task.startedAt);
|
|
64
|
+
}
|
|
65
|
+
function formatTaskSilence(task) {
|
|
66
|
+
return formatDuration(Date.now() - task.lastActivityAt);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* How long a task may go without any SDK event before /tasks flags it as
|
|
70
|
+
* probably-finished. A completion `notification` removes the entry outright,
|
|
71
|
+
* so an entry still listed after a long silence usually means that event
|
|
72
|
+
* never arrived (restart mid-task, dropped notification).
|
|
73
|
+
*
|
|
74
|
+
* Deliberately generous: this only annotates, never hides, but a false
|
|
75
|
+
* positive on a slow-but-live agent is still noise.
|
|
76
|
+
*/
|
|
77
|
+
const STALE_AFTER_MS = 15 * 60 * 1000;
|
|
78
|
+
/**
|
|
79
|
+
* Monitors are exempt. An armed monitor waiting for its first event is
|
|
80
|
+
* *supposed* to sit silent for hours, so inactivity carries no signal about
|
|
81
|
+
* whether it's still alive — flagging them would mark every idle monitor.
|
|
82
|
+
*/
|
|
83
|
+
function isPossiblyStale(task) {
|
|
84
|
+
if (task.taskType === 'monitor_mcp')
|
|
85
|
+
return false;
|
|
86
|
+
return Date.now() - task.lastActivityAt > STALE_AFTER_MS;
|
|
87
|
+
}
|
|
88
|
+
function getActiveTasks(sessionKey) {
|
|
89
|
+
return taskTracker.getTasks(sessionKey).filter(t => t.status === 'running' || t.status === 'pending');
|
|
90
|
+
}
|
|
91
|
+
function renderTasksList(sessionKey, tasks) {
|
|
92
|
+
if (tasks.length === 0) {
|
|
93
|
+
// Cross-pointer: a `Bash(run_in_background=true)` shell can outlive its SDK
|
|
94
|
+
// task entry (npm release scripts, deploys), so the statusline's 🔍 counter
|
|
95
|
+
// may show > 0 while /tasks is empty. Surface that here so users know
|
|
96
|
+
// where to look next.
|
|
97
|
+
const claudePid = getPtyProvider().getSessionPid(sessionKey);
|
|
98
|
+
const shellCount = claudePid !== undefined ? getBgProcesses(claudePid).length : 0;
|
|
99
|
+
const b = new EntityText().add('🔄 ').bold('Active background tasks').newline(2).add('None running.');
|
|
100
|
+
if (shellCount > 0) {
|
|
101
|
+
const noun = shellCount === 1 ? 'shell' : 'shells';
|
|
102
|
+
b.newline(2).italic(`🔍 ${shellCount} background ${noun} still running — see /shells.`);
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
message: b.build(),
|
|
106
|
+
keyboard: [[
|
|
107
|
+
{ text: '🔄 Refresh', callback_data: 'tasks:refresh' },
|
|
108
|
+
{ text: '🔎 Ask claude', callback_data: 'tasks:ask' },
|
|
109
|
+
]],
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const groups = groupTasksForDisplay(tasks);
|
|
113
|
+
const b = new EntityText()
|
|
114
|
+
.add('🔄 ')
|
|
115
|
+
.bold('Active background tasks')
|
|
116
|
+
.add(` (${tasks.length})`)
|
|
117
|
+
.newline(2);
|
|
118
|
+
// Number tasks globally so callback buttons match the listed indices.
|
|
119
|
+
let index = 1;
|
|
120
|
+
const numberedTasks = [];
|
|
121
|
+
for (const group of groups) {
|
|
122
|
+
b.add(`${group.emoji} `).bold(group.label).add(` (${group.tasks.length})`).newline();
|
|
123
|
+
for (const task of group.tasks) {
|
|
124
|
+
const desc = task.description.length > 70
|
|
125
|
+
? task.description.substring(0, 67) + '...'
|
|
126
|
+
: task.description;
|
|
127
|
+
const staleMark = isPossiblyStale(task) ? '⚠️ ' : '';
|
|
128
|
+
b.add(` ${index}. ${staleMark}${desc} · ${formatTaskElapsed(task)}`).newline();
|
|
129
|
+
numberedTasks.push(task);
|
|
130
|
+
index++;
|
|
131
|
+
}
|
|
132
|
+
b.newline();
|
|
133
|
+
}
|
|
134
|
+
b.italic('Tap a number to view details.');
|
|
135
|
+
if (numberedTasks.some(isPossiblyStale)) {
|
|
136
|
+
b.newline().italic('⚠️ no update in a while — may have finished already. ' +
|
|
137
|
+
'Tap 🔎 Ask claude to confirm.');
|
|
138
|
+
}
|
|
139
|
+
const keyboard = [];
|
|
140
|
+
// Telegram inline keyboards render best at 5 buttons per row for short labels.
|
|
141
|
+
const numberRow = [];
|
|
142
|
+
numberedTasks.forEach((task, i) => {
|
|
143
|
+
numberRow.push({ text: String(i + 1), callback_data: `tasks:view:${task.id}` });
|
|
144
|
+
if (numberRow.length === 5 || i === numberedTasks.length - 1) {
|
|
145
|
+
keyboard.push([...numberRow]);
|
|
146
|
+
numberRow.length = 0;
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
keyboard.push([
|
|
150
|
+
{ text: '🔄 Refresh', callback_data: 'tasks:refresh' },
|
|
151
|
+
{ text: '🔎 Ask claude', callback_data: 'tasks:ask' },
|
|
152
|
+
]);
|
|
153
|
+
// PTY-only: the live card is how that mode shows background work.
|
|
154
|
+
if (hasRunningTasks(sessionKey)) {
|
|
155
|
+
keyboard.push([{ text: '📍 Show live card here', callback_data: 'tasks:card' }]);
|
|
156
|
+
}
|
|
157
|
+
return { message: b.build(), keyboard };
|
|
158
|
+
}
|
|
159
|
+
function renderTaskDetail(task) {
|
|
160
|
+
const groupHint = (() => {
|
|
161
|
+
switch (task.taskType) {
|
|
162
|
+
case 'monitor_mcp': return '📡 Monitor';
|
|
163
|
+
case 'local_bash': return '💻 Shell';
|
|
164
|
+
case 'local_workflow': return '📋 Workflow';
|
|
165
|
+
case 'local_agent':
|
|
166
|
+
case 'remote_agent':
|
|
167
|
+
case undefined: return '🤖 Agent';
|
|
168
|
+
default: return '🔹 Task';
|
|
169
|
+
}
|
|
170
|
+
})();
|
|
171
|
+
const b = new EntityText().add(`${groupHint}: `).bold(task.description).newline();
|
|
172
|
+
/** A `• Label: ` bullet on a line of its own; the caller appends the value. */
|
|
173
|
+
const field = (label) => b.newline().add('• ').bold(`${label}:`).add(' ');
|
|
174
|
+
field('Status').add(task.status);
|
|
175
|
+
field('Backgrounded').add(task.isBackgrounded ? 'yes' : 'no');
|
|
176
|
+
field('Started').add(`${formatTaskElapsed(task)} ago`);
|
|
177
|
+
if (isPossiblyStale(task)) {
|
|
178
|
+
field('Last update').add(`${formatTaskSilence(task)} ago ⚠️`);
|
|
179
|
+
}
|
|
180
|
+
if (task.taskType) {
|
|
181
|
+
field('Type').code(task.taskType);
|
|
182
|
+
}
|
|
183
|
+
if (task.lastProgress?.lastToolName) {
|
|
184
|
+
field('Last tool').code(task.lastProgress.lastToolName);
|
|
185
|
+
}
|
|
186
|
+
if (task.lastProgress?.usage) {
|
|
187
|
+
const u = task.lastProgress.usage;
|
|
188
|
+
field('Tokens').add(`${u.totalTokens} · `).bold('Tool uses:').add(` ${u.toolUses}`);
|
|
189
|
+
}
|
|
190
|
+
if (task.lastProgress?.summary) {
|
|
191
|
+
const summary = task.lastProgress.summary.length > 300
|
|
192
|
+
? task.lastProgress.summary.substring(0, 297) + '...'
|
|
193
|
+
: task.lastProgress.summary;
|
|
194
|
+
b.newline(2).bold('Latest progress:').newline().quote(summary);
|
|
195
|
+
}
|
|
196
|
+
if (task.error) {
|
|
197
|
+
b.newline(2).add(`⚠️ ${task.error}`);
|
|
198
|
+
}
|
|
199
|
+
return {
|
|
200
|
+
message: b.build(),
|
|
201
|
+
keyboard: [
|
|
202
|
+
[
|
|
203
|
+
{ text: '← Back to list', callback_data: 'tasks:back' },
|
|
204
|
+
{ text: '🔄 Refresh', callback_data: `tasks:view:${task.id}` },
|
|
205
|
+
],
|
|
206
|
+
],
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
export async function handleTasks(ctx) {
|
|
210
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
211
|
+
if (!keyInfo) {
|
|
212
|
+
await ctx.reply('❌ Could not determine chat context for /tasks.');
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
const tasks = getActiveTasks(keyInfo.sessionKey);
|
|
216
|
+
const { message, keyboard } = renderTasksList(keyInfo.sessionKey, tasks);
|
|
217
|
+
await replyFormatted(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
218
|
+
}
|
|
219
|
+
export async function handleTasksCallback(ctx) {
|
|
220
|
+
const data = ctx.callbackQuery?.data;
|
|
221
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
222
|
+
if (!data || !keyInfo) {
|
|
223
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const { sessionKey } = keyInfo;
|
|
227
|
+
if (data === 'tasks:refresh' || data === 'tasks:back') {
|
|
228
|
+
const tasks = getActiveTasks(sessionKey);
|
|
229
|
+
const { message, keyboard } = renderTasksList(sessionKey, tasks);
|
|
230
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
231
|
+
try {
|
|
232
|
+
await editCallbackMessage(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
233
|
+
}
|
|
234
|
+
catch (err) {
|
|
235
|
+
// "message is not modified" is fine — content already up to date.
|
|
236
|
+
const msg = err instanceof Error ? err.message.toLowerCase() : '';
|
|
237
|
+
if (!msg.includes('message is not modified')) {
|
|
238
|
+
console.error('[Tasks] Failed to refresh list:', err);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (data === 'tasks:card') {
|
|
244
|
+
// The card with its log, at the bottom, instead of up in the history.
|
|
245
|
+
const moved = bringCardDown(sessionKey, { withLog: true });
|
|
246
|
+
await ctx.answerCallbackQuery(moved ? {} : { text: 'Nothing running any more.' }).catch(() => { });
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (data === 'tasks:ask') {
|
|
250
|
+
await handleAskClaude(ctx, sessionKey);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (data.startsWith('tasks:view:')) {
|
|
254
|
+
const taskId = data.substring('tasks:view:'.length);
|
|
255
|
+
const task = taskTracker.getTask(sessionKey, taskId);
|
|
256
|
+
if (!task) {
|
|
257
|
+
// Task finished or was cleared between renders — go back to the list.
|
|
258
|
+
const tasks = getActiveTasks(sessionKey);
|
|
259
|
+
const { message, keyboard } = renderTasksList(sessionKey, tasks);
|
|
260
|
+
await ctx.answerCallbackQuery({ text: 'Task no longer active.' }).catch(() => { });
|
|
261
|
+
try {
|
|
262
|
+
await editCallbackMessage(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
263
|
+
}
|
|
264
|
+
catch { /* ignore */ }
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const { message, keyboard } = renderTaskDetail(task);
|
|
268
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
269
|
+
try {
|
|
270
|
+
await editCallbackMessage(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
271
|
+
}
|
|
272
|
+
catch (err) {
|
|
273
|
+
const msg = err instanceof Error ? err.message.toLowerCase() : '';
|
|
274
|
+
if (!msg.includes('message is not modified')) {
|
|
275
|
+
console.error('[Tasks] Failed to render detail:', err);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Test hooks. The predicate is pure, but the render path is where a staleness
|
|
284
|
+
* regression would actually be seen, so both are exposed — and the detail
|
|
285
|
+
* view with them, for its formatting.
|
|
286
|
+
*/
|
|
287
|
+
export const _isPossiblyStale = isPossiblyStale;
|
|
288
|
+
export const _renderTasksList = renderTasksList;
|
|
289
|
+
export const _renderTaskDetail = renderTaskDetail;
|
|
290
|
+
// ---------------------------------------------------------------------------
|
|
291
|
+
// "🔎 Ask claude" — relay claude's own /tasks overlay
|
|
292
|
+
// ---------------------------------------------------------------------------
|
|
293
|
+
/**
|
|
294
|
+
* The tracker above is reconstructed from tool-arm and task-notification
|
|
295
|
+
* events, so it only knows about work TeleCoder saw start. Claude's own
|
|
296
|
+
* `/tasks` overlay is the live process's view: it also covers shells claude
|
|
297
|
+
* backgrounded on its own initiative, and everything armed before the last bot
|
|
298
|
+
* restart (relay state doesn't persist). This button asks it directly.
|
|
299
|
+
*
|
|
300
|
+
* PTY-only — there is no TUI to drive in SDK mode, where the tracker is fed
|
|
301
|
+
* from the event stream and is already authoritative.
|
|
302
|
+
*/
|
|
303
|
+
async function handleAskClaude(ctx, sessionKey) {
|
|
304
|
+
await ctx.answerCallbackQuery({ text: 'Asking claude…' }).catch(() => { });
|
|
305
|
+
// Every answer below opens with the same heading.
|
|
306
|
+
const view = () => new EntityText().add('🔎 ').bold("Claude's background view").newline(2);
|
|
307
|
+
const result = await getPtyProvider().runOverlayCommand(sessionKey, '/tasks');
|
|
308
|
+
if (!result.ok) {
|
|
309
|
+
const reason = result.reason === 'turn-active'
|
|
310
|
+
? 'Claude is mid-turn — the TUI keyboard is busy. Try again once it finishes.'
|
|
311
|
+
: result.reason === 'not-ready'
|
|
312
|
+
? 'The Claude TUI is not at a prompt right now. Try again in a moment.'
|
|
313
|
+
: 'No active PTY session for this chat. In SDK mode the list above is already authoritative.';
|
|
314
|
+
await replyFormatted(ctx, view().add(reason).build());
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
const overlay = scrapeTasksOverlay(result.screen);
|
|
318
|
+
if (!overlay) {
|
|
319
|
+
// The overlay's layout is a Claude Code implementation detail and can move
|
|
320
|
+
// between releases — say so plainly rather than showing a mangled guess.
|
|
321
|
+
await replyFormatted(ctx, view()
|
|
322
|
+
.add("Couldn't read the ")
|
|
323
|
+
.code('/tasks')
|
|
324
|
+
.add(' overlay — Claude Code may have changed its layout. The list above still works.')
|
|
325
|
+
.build());
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (overlay.empty) {
|
|
329
|
+
// A code block for one line of "nothing running" is noise. Worth saying
|
|
330
|
+
// out loud though: claude reporting empty while the list above shows
|
|
331
|
+
// tasks means our tracker is holding entries claude no longer knows about.
|
|
332
|
+
const tracked = getActiveTasks(sessionKey).length;
|
|
333
|
+
const b = view().add('Nothing running.');
|
|
334
|
+
if (tracked > 0) {
|
|
335
|
+
b.newline(2).italic(`The ${tracked} task(s) listed above are unknown to claude — likely finished already.`);
|
|
336
|
+
}
|
|
337
|
+
await replyFormatted(ctx, b.build());
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
const body = overlay.text.length > 3000 ? overlay.text.slice(0, 2997) + '...' : overlay.text;
|
|
341
|
+
await replyFormatted(ctx, view().pre(body).build());
|
|
342
|
+
}
|
|
343
|
+
// ── /shells ─────────────────────────────────────────────────────
|
|
344
|
+
// List OS-level child processes of the chat's PTY claude session and offer
|
|
345
|
+
// a one-tap SIGTERM. Complements /tasks (which only sees SDK-tracked tasks)
|
|
346
|
+
// and rescues `Bash(run_in_background=true)` shells whose stop condition
|
|
347
|
+
// will never fire.
|
|
348
|
+
const BG_MCP_SERVER_MARKER = 'mcp-server.js';
|
|
349
|
+
function formatBgAge(sec) {
|
|
350
|
+
if (sec < 60)
|
|
351
|
+
return `${sec}s`;
|
|
352
|
+
if (sec < 3600)
|
|
353
|
+
return `${Math.floor(sec / 60)}m`;
|
|
354
|
+
if (sec < 86400) {
|
|
355
|
+
const h = Math.floor(sec / 3600);
|
|
356
|
+
const m = Math.floor((sec % 3600) / 60);
|
|
357
|
+
return m > 0 ? `${h}h${m}m` : `${h}h`;
|
|
358
|
+
}
|
|
359
|
+
return `${Math.floor(sec / 86400)}d`;
|
|
360
|
+
}
|
|
361
|
+
function truncateBgCmd(cmd, max = 150) {
|
|
362
|
+
if (cmd.length <= max)
|
|
363
|
+
return cmd;
|
|
364
|
+
return cmd.substring(0, max - 1) + '…';
|
|
365
|
+
}
|
|
366
|
+
// Claude's `Bash(run_in_background=true)` shells are spawned as
|
|
367
|
+
// <shell> -c "source <snapshot> && setopt … && eval '<USER_CMD>' < /dev/null && pwd -P >| /tmp/…"
|
|
368
|
+
// The wrapper is noise — pull out the real command between `eval '` and the
|
|
369
|
+
// trailing `' < /dev/null`. Returns the original cmd if the pattern doesn't
|
|
370
|
+
// match (e.g. the MCP server, foreign children).
|
|
371
|
+
function unwrapBgCmd(cmd) {
|
|
372
|
+
const evalIdx = cmd.indexOf("eval '");
|
|
373
|
+
if (evalIdx === -1)
|
|
374
|
+
return cmd;
|
|
375
|
+
const start = evalIdx + "eval '".length;
|
|
376
|
+
const tail = cmd.indexOf("' < /dev/null", start);
|
|
377
|
+
if (tail === -1 || tail <= start)
|
|
378
|
+
return cmd;
|
|
379
|
+
return cmd.substring(start, tail);
|
|
380
|
+
}
|
|
381
|
+
export function getBgProcesses(claudePid) {
|
|
382
|
+
const result = [];
|
|
383
|
+
for (const childPid of getDirectChildren(claudePid)) {
|
|
384
|
+
const info = describeProcess(childPid);
|
|
385
|
+
if (!info)
|
|
386
|
+
continue;
|
|
387
|
+
if (info.cmd.includes(BG_MCP_SERVER_MARKER))
|
|
388
|
+
continue;
|
|
389
|
+
result.push(info);
|
|
390
|
+
}
|
|
391
|
+
return result;
|
|
392
|
+
}
|
|
393
|
+
function renderBgList(sessionKey, claudePid, procs) {
|
|
394
|
+
const heading = () => new EntityText().add('🔍 ').bold('Background processes');
|
|
395
|
+
if (claudePid === undefined) {
|
|
396
|
+
return {
|
|
397
|
+
message: heading()
|
|
398
|
+
.newline(2)
|
|
399
|
+
.italic('No active PTY session for this chat.')
|
|
400
|
+
.newline(2)
|
|
401
|
+
.add('In SDK mode, use /tasks to inspect tracked background tasks.')
|
|
402
|
+
.build(),
|
|
403
|
+
keyboard: [],
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
if (procs.length === 0) {
|
|
407
|
+
// Cross-pointer to /tasks when SDK-tracked tasks (agents, monitors) are
|
|
408
|
+
// running but no OS shells are.
|
|
409
|
+
const taskCount = getActiveTasks(sessionKey).length;
|
|
410
|
+
const b = heading().newline(2).add('None running.');
|
|
411
|
+
if (taskCount > 0) {
|
|
412
|
+
const noun = taskCount === 1 ? 'task' : 'tasks';
|
|
413
|
+
b.newline(2).italic(`🔄 ${taskCount} SDK ${noun} still running — see /tasks.`);
|
|
414
|
+
}
|
|
415
|
+
return {
|
|
416
|
+
message: b.build(),
|
|
417
|
+
keyboard: [[{ text: '🔄 Refresh', callback_data: 'shells:refresh' }]],
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
const b = heading().add(` (${procs.length})`).newline(2);
|
|
421
|
+
procs.forEach((p, i) => {
|
|
422
|
+
b.bold(`${i + 1}.`).add(` [${formatBgAge(p.ageSec)}] pid `).code(String(p.pid)).newline();
|
|
423
|
+
b.code(truncateBgCmd(unwrapBgCmd(p.cmd))).newline(2);
|
|
424
|
+
});
|
|
425
|
+
b.italic('Tap a number to SIGTERM that process (and its descendants).');
|
|
426
|
+
const keyboard = [];
|
|
427
|
+
let row = [];
|
|
428
|
+
procs.forEach((p, i) => {
|
|
429
|
+
row.push({ text: `🛑 #${i + 1}`, callback_data: `shells:kill:${p.pid}` });
|
|
430
|
+
if (row.length === 4 || i === procs.length - 1) {
|
|
431
|
+
keyboard.push(row);
|
|
432
|
+
row = [];
|
|
433
|
+
}
|
|
434
|
+
});
|
|
435
|
+
keyboard.push([
|
|
436
|
+
{ text: '🛑 Kill all', callback_data: 'shells:killall' },
|
|
437
|
+
{ text: '🔄 Refresh', callback_data: 'shells:refresh' },
|
|
438
|
+
]);
|
|
439
|
+
return { message: b.build(), keyboard };
|
|
440
|
+
}
|
|
441
|
+
async function rerenderBg(ctx, sessionKey, claudePid) {
|
|
442
|
+
// Brief grace period so killed processes drop out of /proc before we re-read.
|
|
443
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
444
|
+
const procs = claudePid !== undefined ? getBgProcesses(claudePid) : [];
|
|
445
|
+
const { message, keyboard } = renderBgList(sessionKey, claudePid, procs);
|
|
446
|
+
try {
|
|
447
|
+
await editCallbackMessage(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
448
|
+
}
|
|
449
|
+
catch (err) {
|
|
450
|
+
const msg = err instanceof Error ? err.message.toLowerCase() : '';
|
|
451
|
+
if (!msg.includes('message is not modified')) {
|
|
452
|
+
console.error('[/shells] Failed to refresh list:', err);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
export async function handleShells(ctx) {
|
|
457
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
458
|
+
if (!keyInfo) {
|
|
459
|
+
await ctx.reply('❌ Could not determine chat context for /shells.');
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
const claudePid = getPtyProvider().getSessionPid(keyInfo.sessionKey);
|
|
463
|
+
const procs = claudePid !== undefined ? getBgProcesses(claudePid) : [];
|
|
464
|
+
const { message, keyboard } = renderBgList(keyInfo.sessionKey, claudePid, procs);
|
|
465
|
+
await replyFormatted(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
466
|
+
}
|
|
467
|
+
export async function handleShellsCallback(ctx) {
|
|
468
|
+
const data = ctx.callbackQuery?.data;
|
|
469
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
470
|
+
if (!data || !keyInfo) {
|
|
471
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
const claudePid = getPtyProvider().getSessionPid(keyInfo.sessionKey);
|
|
475
|
+
if (data === 'shells:refresh') {
|
|
476
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
477
|
+
await rerenderBg(ctx, keyInfo.sessionKey, claudePid);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
if (data === 'shells:killall') {
|
|
481
|
+
if (claudePid === undefined) {
|
|
482
|
+
await ctx.answerCallbackQuery({ text: 'No active session.' }).catch(() => { });
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
const procs = getBgProcesses(claudePid);
|
|
486
|
+
let total = 0;
|
|
487
|
+
for (const p of procs)
|
|
488
|
+
total += killTree(p.pid);
|
|
489
|
+
await ctx.answerCallbackQuery({ text: `SIGTERM sent to ${total} process(es).` }).catch(() => { });
|
|
490
|
+
await rerenderBg(ctx, keyInfo.sessionKey, claudePid);
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
if (data.startsWith('shells:kill:')) {
|
|
494
|
+
const pid = Number.parseInt(data.substring('shells:kill:'.length), 10);
|
|
495
|
+
if (claudePid === undefined || !Number.isFinite(pid)) {
|
|
496
|
+
await ctx.answerCallbackQuery({ text: 'Unknown target.' }).catch(() => { });
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
// PIDs can be recycled — refuse to signal anything that's no longer a
|
|
500
|
+
// descendant of this chat's claude session.
|
|
501
|
+
if (!isDescendantOf(claudePid, pid)) {
|
|
502
|
+
await ctx.answerCallbackQuery({ text: `PID ${pid} no longer belongs to this session.` }).catch(() => { });
|
|
503
|
+
await rerenderBg(ctx, keyInfo.sessionKey, claudePid);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
const killed = killTree(pid);
|
|
507
|
+
await ctx.answerCallbackQuery({ text: `SIGTERM sent (${killed} process(es)).` }).catch(() => { });
|
|
508
|
+
await rerenderBg(ctx, keyInfo.sessionKey, claudePid);
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
512
|
+
}
|
|
513
|
+
//# sourceMappingURL=tasks.js.map
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session topic and Telegram bot display name — 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.
|
|
7
|
+
*
|
|
8
|
+
* This module is deliberately kept below the provider layer: `agent.ts` and
|
|
9
|
+
* `mcp-tools.ts` both need to read and set the topic, and importing it from
|
|
10
|
+
* the command barrel closed an import cycle (barrel -> command/shared.ts ->
|
|
11
|
+
* claude-provider -> sdk-provider -> agent -> back to the barrel). Nothing
|
|
12
|
+
* here may import `./shared.js` or anything under `providers/`. The /topic and
|
|
13
|
+
* /botname *commands* live in `topic.ts`, which is free to.
|
|
14
|
+
*/
|
|
15
|
+
import * as path from 'path';
|
|
16
|
+
import { config } from '../../../config.js';
|
|
17
|
+
import { sessionManager } from '../../../claude/session-manager.js';
|
|
18
|
+
import { sessionHistory } from '../../../claude/session-history.js';
|
|
19
|
+
import { readLastAiTitle } from '../../../claude/session-jsonl.js';
|
|
20
|
+
import { isBotNameEnabled, rateLimitedSetMyName, notifyBotNameBlock, } from '../../../telegram/botname-settings.js';
|
|
21
|
+
import { syncThreadTitle } from '../../../telegram/thread-titles.js';
|
|
22
|
+
import { isHomeProject } from '../../../utils/home-project.js';
|
|
23
|
+
// Per-session topic (ephemeral — not persisted across restarts)
|
|
24
|
+
const sessionTopics = new Map();
|
|
25
|
+
// Per-session timestamp of last setSessionTopic call. Used by the auto-topic
|
|
26
|
+
// reminder hook to skip the per-turn nudge when the topic was just updated.
|
|
27
|
+
const lastTopicSetAt = new Map();
|
|
28
|
+
/** Build the bot display name from base name and project. Topic now lives in the status line. */
|
|
29
|
+
export function buildBotDisplayName(sessionKey) {
|
|
30
|
+
const session = sessionManager.getSession(sessionKey);
|
|
31
|
+
// A bot made for one project already carries it in its name.
|
|
32
|
+
const project = session?.workingDirectory && !isHomeProject(session.workingDirectory)
|
|
33
|
+
? path.basename(session.workingDirectory)
|
|
34
|
+
: '';
|
|
35
|
+
const parts = [config.BOT_NAME];
|
|
36
|
+
if (project)
|
|
37
|
+
parts.push(project);
|
|
38
|
+
return parts.join(' — ').slice(0, 64);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Push a display name to Telegram (rate-limited) and surface any block notice.
|
|
42
|
+
* Swallows errors — a failed name update should never break the calling flow.
|
|
43
|
+
* `context` is used only for the debug log so failures are attributable.
|
|
44
|
+
*/
|
|
45
|
+
export async function pushBotName(ctx, name, context) {
|
|
46
|
+
try {
|
|
47
|
+
const result = await rateLimitedSetMyName(ctx.api, (n) => ctx.api.setMyName(n), name);
|
|
48
|
+
await notifyBotNameBlock(ctx, result);
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
console.debug(`[Bot] Failed to set bot name (${context}):`, err instanceof Error ? err.message : err);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Clear the session topic and refresh the bot display name accordingly.
|
|
56
|
+
* Called whenever the conversation context is wiped (clear, reset, project switch).
|
|
57
|
+
*/
|
|
58
|
+
export async function clearTopicAndRefreshBotName(ctx, sessionKey) {
|
|
59
|
+
setSessionTopic(sessionKey, '');
|
|
60
|
+
if (!isBotNameEnabled(sessionKey))
|
|
61
|
+
return;
|
|
62
|
+
await pushBotName(ctx, buildBotDisplayName(sessionKey), 'topic clear');
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Restore the session topic from the saved value (or clear if absent) and refresh
|
|
66
|
+
* the bot display name. Called when resuming/continuing a previous conversation.
|
|
67
|
+
*
|
|
68
|
+
* When no persisted topic exists, fall back to Claude Code's `aiTitle` from the
|
|
69
|
+
* session JSONL — better a stale session label than a blank topic line on resume.
|
|
70
|
+
*/
|
|
71
|
+
export async function restoreTopicAndRefreshBotName(ctx, sessionKey, topic) {
|
|
72
|
+
if (!topic) {
|
|
73
|
+
const session = sessionManager.getSession(sessionKey);
|
|
74
|
+
if (session?.claudeSessionId) {
|
|
75
|
+
topic = readLastAiTitle(session.workingDirectory, session.claudeSessionId);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
setSessionTopic(sessionKey, topic || '');
|
|
79
|
+
if (!isBotNameEnabled(sessionKey))
|
|
80
|
+
return;
|
|
81
|
+
await pushBotName(ctx, buildBotDisplayName(sessionKey), 'topic restore');
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Set the session topic programmatically (used by MCP tool and auto-resume).
|
|
85
|
+
* Returns the new display name string.
|
|
86
|
+
*/
|
|
87
|
+
export function setSessionTopic(sessionKey, topic) {
|
|
88
|
+
if (topic) {
|
|
89
|
+
sessionTopics.set(sessionKey, topic);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
sessionTopics.delete(sessionKey);
|
|
93
|
+
}
|
|
94
|
+
lastTopicSetAt.set(sessionKey, Date.now());
|
|
95
|
+
// Persist so topic survives restarts
|
|
96
|
+
sessionHistory.updateTopic(sessionKey, topic || undefined);
|
|
97
|
+
// In a private chat's thread, the topic is the thread's name too, with the
|
|
98
|
+
// project in front unless it's the one the bot is named after.
|
|
99
|
+
const workingDirectory = sessionManager.getSession(sessionKey)?.workingDirectory;
|
|
100
|
+
const project = workingDirectory && !isHomeProject(workingDirectory) ? path.basename(workingDirectory) : undefined;
|
|
101
|
+
syncThreadTitle(sessionKey, topic, project);
|
|
102
|
+
return buildBotDisplayName(sessionKey);
|
|
103
|
+
}
|
|
104
|
+
/** Get the current session topic. */
|
|
105
|
+
export function getSessionTopic(sessionKey) {
|
|
106
|
+
return sessionTopics.get(sessionKey);
|
|
107
|
+
}
|
|
108
|
+
/** Milliseconds since the last setSessionTopic call (or undefined if never). */
|
|
109
|
+
export function getMsSinceTopicSet(sessionKey) {
|
|
110
|
+
const at = lastTopicSetAt.get(sessionKey);
|
|
111
|
+
return at !== undefined ? Date.now() - at : undefined;
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=topic-store.js.map
|