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,681 @@
|
|
|
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 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, parseTaskRows, parseTaskDetail, } 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(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 unheard from before /tasks flags it as
|
|
70
|
+
* probably-finished. The notification that ends a task removes the entry
|
|
71
|
+
* outright, so an entry still listed after a long silence usually means that
|
|
72
|
+
* notification 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 renderTasksList(sessionKey, tasks) {
|
|
89
|
+
if (tasks.length === 0) {
|
|
90
|
+
// Cross-pointer: a `Bash(run_in_background=true)` shell can outlive its
|
|
91
|
+
// task entry (npm release scripts, deploys), so the status line's 🔍 counter
|
|
92
|
+
// may show > 0 while /tasks is empty. Surface that here so users know
|
|
93
|
+
// where to look next.
|
|
94
|
+
const claudePid = getPtyProvider().getSessionPid(sessionKey);
|
|
95
|
+
const shellCount = claudePid !== undefined ? getBgProcesses(claudePid).length : 0;
|
|
96
|
+
const b = new EntityText().add('🔄 ').bold('Active background tasks').newline(2).add('None running.');
|
|
97
|
+
if (shellCount > 0) {
|
|
98
|
+
const noun = shellCount === 1 ? 'shell' : 'shells';
|
|
99
|
+
b.newline(2).italic(`🔍 ${shellCount} background ${noun} still running — see /shells.`);
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
message: b.build(),
|
|
103
|
+
keyboard: [[
|
|
104
|
+
{ text: '🔄 Refresh', callback_data: 'tasks:refresh' },
|
|
105
|
+
{ text: '🔎 Ask claude', callback_data: 'tasks:ask' },
|
|
106
|
+
]],
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
const groups = groupTasksForDisplay(tasks);
|
|
110
|
+
const b = new EntityText()
|
|
111
|
+
.add('🔄 ')
|
|
112
|
+
.bold('Active background tasks')
|
|
113
|
+
.add(` (${tasks.length})`)
|
|
114
|
+
.newline(2);
|
|
115
|
+
// Number tasks globally so callback buttons match the listed indices.
|
|
116
|
+
let index = 1;
|
|
117
|
+
const numberedTasks = [];
|
|
118
|
+
for (const group of groups) {
|
|
119
|
+
b.add(`${group.emoji} `).bold(group.label).add(` (${group.tasks.length})`).newline();
|
|
120
|
+
for (const task of group.tasks) {
|
|
121
|
+
const desc = task.description.length > 70
|
|
122
|
+
? task.description.substring(0, 67) + '...'
|
|
123
|
+
: task.description;
|
|
124
|
+
const staleMark = isPossiblyStale(task) ? '⚠️ ' : '';
|
|
125
|
+
b.add(` ${index}. ${staleMark}${desc} · ${formatTaskElapsed(task)}`).newline();
|
|
126
|
+
numberedTasks.push(task);
|
|
127
|
+
index++;
|
|
128
|
+
}
|
|
129
|
+
b.newline();
|
|
130
|
+
}
|
|
131
|
+
b.italic('Tap a number to view details.');
|
|
132
|
+
if (numberedTasks.some(isPossiblyStale)) {
|
|
133
|
+
b.newline().italic('⚠️ no update in a while — may have finished already. ' +
|
|
134
|
+
'Tap 🔎 Ask claude to confirm.');
|
|
135
|
+
}
|
|
136
|
+
const keyboard = [];
|
|
137
|
+
// Telegram inline keyboards render best at 5 buttons per row for short labels.
|
|
138
|
+
const numberRow = [];
|
|
139
|
+
numberedTasks.forEach((task, i) => {
|
|
140
|
+
numberRow.push({ text: String(i + 1), callback_data: `tasks:view:${task.id}` });
|
|
141
|
+
if (numberRow.length === 5 || i === numberedTasks.length - 1) {
|
|
142
|
+
keyboard.push([...numberRow]);
|
|
143
|
+
numberRow.length = 0;
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
keyboard.push([
|
|
147
|
+
{ text: '🔄 Refresh', callback_data: 'tasks:refresh' },
|
|
148
|
+
{ text: '🔎 Ask claude', callback_data: 'tasks:ask' },
|
|
149
|
+
]);
|
|
150
|
+
// The live card is where background work shows as it runs.
|
|
151
|
+
if (hasRunningTasks(sessionKey)) {
|
|
152
|
+
keyboard.push([{ text: '📍 Show live card here', callback_data: 'tasks:card' }]);
|
|
153
|
+
}
|
|
154
|
+
return { message: b.build(), keyboard };
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* `canShowOutput`: there is a live pty to ask, so the detail offers the task's
|
|
158
|
+
* output (see "📄 Output" below). Without one, the output only arrives with
|
|
159
|
+
* the task's notification, which the relay posts when it lands.
|
|
160
|
+
*/
|
|
161
|
+
function renderTaskDetail(task, canShowOutput = false) {
|
|
162
|
+
const groupHint = (() => {
|
|
163
|
+
switch (task.taskType) {
|
|
164
|
+
case 'monitor_mcp': return '📡 Monitor';
|
|
165
|
+
case 'local_bash': return '💻 Shell';
|
|
166
|
+
case 'local_workflow': return '📋 Workflow';
|
|
167
|
+
case 'local_agent':
|
|
168
|
+
case 'remote_agent':
|
|
169
|
+
case undefined: return '🤖 Agent';
|
|
170
|
+
default: return '🔹 Task';
|
|
171
|
+
}
|
|
172
|
+
})();
|
|
173
|
+
const b = new EntityText().add(`${groupHint}: `).bold(task.description).newline();
|
|
174
|
+
/** A `• Label: ` bullet on a line of its own; the caller appends the value. */
|
|
175
|
+
const field = (label) => b.newline().add('• ').bold(`${label}:`).add(' ');
|
|
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 (!canShowOutput && task.taskType !== 'monitor_mcp') {
|
|
184
|
+
b.newline(2).italic('Its output arrives with the result when it finishes.');
|
|
185
|
+
}
|
|
186
|
+
const keyboard = [
|
|
187
|
+
[
|
|
188
|
+
{ text: '← Back to list', callback_data: 'tasks:back' },
|
|
189
|
+
{ text: '🔄 Refresh', callback_data: `tasks:view:${task.id}` },
|
|
190
|
+
],
|
|
191
|
+
];
|
|
192
|
+
if (canShowOutput) {
|
|
193
|
+
keyboard.push([{ text: '📄 Output', callback_data: `tasks:out:${task.id}` }]);
|
|
194
|
+
}
|
|
195
|
+
return { message: b.build(), keyboard };
|
|
196
|
+
}
|
|
197
|
+
/** Whether this chat has a live pty whose `/tasks` overlay can be driven. */
|
|
198
|
+
function hasLivePty(sessionKey) {
|
|
199
|
+
return getPtyProvider().getSessionPid(sessionKey) !== undefined;
|
|
200
|
+
}
|
|
201
|
+
export async function handleTasks(ctx) {
|
|
202
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
203
|
+
if (!keyInfo) {
|
|
204
|
+
await ctx.reply('❌ Could not determine chat context for /tasks.');
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const tasks = taskTracker.getTasks(keyInfo.sessionKey);
|
|
208
|
+
const { message, keyboard } = renderTasksList(keyInfo.sessionKey, tasks);
|
|
209
|
+
await replyFormatted(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
210
|
+
}
|
|
211
|
+
export async function handleTasksCallback(ctx) {
|
|
212
|
+
const data = ctx.callbackQuery?.data;
|
|
213
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
214
|
+
if (!data || !keyInfo) {
|
|
215
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const { sessionKey } = keyInfo;
|
|
219
|
+
if (data === 'tasks:refresh' || data === 'tasks:back') {
|
|
220
|
+
const tasks = taskTracker.getTasks(sessionKey);
|
|
221
|
+
const { message, keyboard } = renderTasksList(sessionKey, tasks);
|
|
222
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
223
|
+
try {
|
|
224
|
+
await editCallbackMessage(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
225
|
+
}
|
|
226
|
+
catch (err) {
|
|
227
|
+
// "message is not modified" is fine — content already up to date.
|
|
228
|
+
const msg = err instanceof Error ? err.message.toLowerCase() : '';
|
|
229
|
+
if (!msg.includes('message is not modified')) {
|
|
230
|
+
console.error('[Tasks] Failed to refresh list:', err);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (data === 'tasks:card') {
|
|
236
|
+
// The card with its log, at the bottom, instead of up in the history.
|
|
237
|
+
const moved = bringCardDown(sessionKey, { withLog: true });
|
|
238
|
+
await ctx.answerCallbackQuery(moved ? {} : { text: 'Nothing running any more.' }).catch(() => { });
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (data === 'tasks:ask') {
|
|
242
|
+
await handleAskClaude(ctx, sessionKey);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (data === 'tasks:claude') {
|
|
246
|
+
await showClaudeView(ctx, sessionKey, { edit: true });
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (data.startsWith('tasks:claude:')) {
|
|
250
|
+
const row = Number.parseInt(data.substring('tasks:claude:'.length), 10);
|
|
251
|
+
if (!Number.isFinite(row) || row < 1) {
|
|
252
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
await showClaudeView(ctx, sessionKey, {
|
|
256
|
+
edit: true,
|
|
257
|
+
pick: (rows) => (row <= rows.length ? row - 1 : undefined),
|
|
258
|
+
refresh: data,
|
|
259
|
+
back: 'tasks:claude',
|
|
260
|
+
});
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (data.startsWith('tasks:out:')) {
|
|
264
|
+
const taskId = data.substring('tasks:out:'.length);
|
|
265
|
+
const task = taskTracker.getTask(sessionKey, taskId);
|
|
266
|
+
await showClaudeView(ctx, sessionKey, {
|
|
267
|
+
edit: true,
|
|
268
|
+
pick: (rows) => (task ? matchTaskRow(task, rows) : undefined),
|
|
269
|
+
unmatchedNote: task
|
|
270
|
+
? "Couldn't tell which of these is that task — tap the one it is."
|
|
271
|
+
: undefined,
|
|
272
|
+
refresh: data,
|
|
273
|
+
back: task ? `tasks:view:${taskId}` : 'tasks:back',
|
|
274
|
+
});
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
if (data.startsWith('tasks:view:')) {
|
|
278
|
+
const taskId = data.substring('tasks:view:'.length);
|
|
279
|
+
const task = taskTracker.getTask(sessionKey, taskId);
|
|
280
|
+
if (!task) {
|
|
281
|
+
// Task finished or was cleared between renders — go back to the list.
|
|
282
|
+
const tasks = taskTracker.getTasks(sessionKey);
|
|
283
|
+
const { message, keyboard } = renderTasksList(sessionKey, tasks);
|
|
284
|
+
await ctx.answerCallbackQuery({ text: 'Task no longer active.' }).catch(() => { });
|
|
285
|
+
try {
|
|
286
|
+
await editCallbackMessage(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
287
|
+
}
|
|
288
|
+
catch { /* ignore */ }
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
const { message, keyboard } = renderTaskDetail(task, hasLivePty(sessionKey));
|
|
292
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
293
|
+
try {
|
|
294
|
+
await editCallbackMessage(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
295
|
+
}
|
|
296
|
+
catch (err) {
|
|
297
|
+
const msg = err instanceof Error ? err.message.toLowerCase() : '';
|
|
298
|
+
if (!msg.includes('message is not modified')) {
|
|
299
|
+
console.error('[Tasks] Failed to render detail:', err);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Test hooks. The predicate is pure, but the render path is where a staleness
|
|
308
|
+
* regression would actually be seen, so both are exposed — and the detail
|
|
309
|
+
* view with them, for its formatting.
|
|
310
|
+
*/
|
|
311
|
+
export const _isPossiblyStale = isPossiblyStale;
|
|
312
|
+
export const _renderTasksList = renderTasksList;
|
|
313
|
+
export const _renderTaskDetail = renderTaskDetail;
|
|
314
|
+
export const _matchTaskRow = matchTaskRow;
|
|
315
|
+
export const _renderClaudeList = renderClaudeList;
|
|
316
|
+
export const _renderClaudeDetail = renderClaudeDetail;
|
|
317
|
+
const DOWN = '\x1b[B';
|
|
318
|
+
const ENTER = '\r';
|
|
319
|
+
/**
|
|
320
|
+
* Open the overlay and, if `pick` names a row of the list it opens on, press
|
|
321
|
+
* ↓ that many times and Enter. The overlay opens straight on the detail when
|
|
322
|
+
* only one task runs, in which case there is nothing to pick.
|
|
323
|
+
*/
|
|
324
|
+
async function readClaudeTasks(sessionKey, pick) {
|
|
325
|
+
const result = await getPtyProvider().runOverlayCommand(sessionKey, '/tasks', (screen) => {
|
|
326
|
+
if (!pick)
|
|
327
|
+
return undefined;
|
|
328
|
+
const overlay = scrapeTasksOverlay(screen);
|
|
329
|
+
if (!overlay)
|
|
330
|
+
return undefined;
|
|
331
|
+
const rows = parseTaskRows(overlay.text);
|
|
332
|
+
const index = rows.length > 0 ? pick(rows) : undefined;
|
|
333
|
+
if (index === undefined)
|
|
334
|
+
return undefined;
|
|
335
|
+
return [...Array(index).fill(DOWN), ENTER];
|
|
336
|
+
});
|
|
337
|
+
if (!result.ok)
|
|
338
|
+
return { kind: 'miss', reason: result.reason };
|
|
339
|
+
const overlay = scrapeTasksOverlay(result.screen);
|
|
340
|
+
if (!overlay)
|
|
341
|
+
return { kind: 'unreadable' };
|
|
342
|
+
if (overlay.empty)
|
|
343
|
+
return { kind: 'empty' };
|
|
344
|
+
const detail = parseTaskDetail(overlay.text);
|
|
345
|
+
if (detail)
|
|
346
|
+
return { kind: 'detail', detail };
|
|
347
|
+
return { kind: 'list', rows: parseTaskRows(overlay.text), text: overlay.text };
|
|
348
|
+
}
|
|
349
|
+
/** Collapse whitespace so a command wrapped by the TUI compares as typed. */
|
|
350
|
+
function squash(text) {
|
|
351
|
+
return text.replace(/\s+/g, ' ').trim();
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* The index of the one row in claude's list that is this task, or undefined
|
|
355
|
+
* when none or several are. A row shows the shell's command, or a description
|
|
356
|
+
* for other kinds, cut short with `…` when long; the task has both, so either
|
|
357
|
+
* may match. Two shells running the same command stay ambiguous on purpose:
|
|
358
|
+
* opening the wrong one's output would read as the right one's.
|
|
359
|
+
*/
|
|
360
|
+
function matchTaskRow(task, rows) {
|
|
361
|
+
const candidates = [task.command, task.description]
|
|
362
|
+
.filter((c) => typeof c === 'string' && c.trim().length > 0)
|
|
363
|
+
.map(squash);
|
|
364
|
+
const hits = [];
|
|
365
|
+
rows.forEach((row, i) => {
|
|
366
|
+
const label = squash(row.label);
|
|
367
|
+
if (!label)
|
|
368
|
+
return;
|
|
369
|
+
const hit = candidates.some((c) => (row.truncated ? c.startsWith(label) : c === label));
|
|
370
|
+
if (hit)
|
|
371
|
+
hits.push(i);
|
|
372
|
+
});
|
|
373
|
+
return hits.length === 1 ? hits[0] : undefined;
|
|
374
|
+
}
|
|
375
|
+
function explainOverlayMiss(reason) {
|
|
376
|
+
switch (reason) {
|
|
377
|
+
case 'turn-active':
|
|
378
|
+
return 'Claude is mid-turn — the TUI keyboard is busy. Try again once it finishes.';
|
|
379
|
+
case 'not-ready':
|
|
380
|
+
return 'The Claude TUI is not at a prompt right now. Try again in a moment.';
|
|
381
|
+
case 'no-session':
|
|
382
|
+
return 'No live Claude session for this chat.';
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/** Every answer below opens with the same heading. */
|
|
386
|
+
function claudeHeading() {
|
|
387
|
+
return new EntityText().add('🔎 ').bold("Claude's background view").newline(2);
|
|
388
|
+
}
|
|
389
|
+
function renderClaudeList(view, nav, note) {
|
|
390
|
+
const b = claudeHeading();
|
|
391
|
+
if (note)
|
|
392
|
+
b.italic(note).newline(2);
|
|
393
|
+
const body = view.text.length > 3000 ? view.text.slice(0, 2997) + '...' : view.text;
|
|
394
|
+
b.pre(body);
|
|
395
|
+
const keyboard = [];
|
|
396
|
+
if (view.rows.length > 0) {
|
|
397
|
+
b.newline().italic('Tap a row number to see its output.');
|
|
398
|
+
let row = [];
|
|
399
|
+
view.rows.forEach((_, i) => {
|
|
400
|
+
row.push({ text: String(i + 1), callback_data: `tasks:claude:${i + 1}` });
|
|
401
|
+
if (row.length === 5 || i === view.rows.length - 1) {
|
|
402
|
+
keyboard.push(row);
|
|
403
|
+
row = [];
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
const last = [{ text: '🔄 Refresh', callback_data: nav.refresh }];
|
|
408
|
+
if (nav.back)
|
|
409
|
+
last.unshift({ text: '← Back', callback_data: nav.back });
|
|
410
|
+
keyboard.push(last);
|
|
411
|
+
return { message: b.build(), keyboard };
|
|
412
|
+
}
|
|
413
|
+
/** The output pane is the point; keep its tail when the whole won't fit. */
|
|
414
|
+
const OUTPUT_MAX_CHARS = 3000;
|
|
415
|
+
function renderClaudeDetail(detail, nav) {
|
|
416
|
+
const b = claudeHeading().bold(detail.title);
|
|
417
|
+
for (const f of detail.fields) {
|
|
418
|
+
b.newline().add('• ').bold(`${f.label}:`).add(' ');
|
|
419
|
+
if (f.label === 'Command')
|
|
420
|
+
b.code(f.value);
|
|
421
|
+
else
|
|
422
|
+
b.add(f.value);
|
|
423
|
+
}
|
|
424
|
+
b.newline(2).bold('Output:').newline();
|
|
425
|
+
if (detail.output === null) {
|
|
426
|
+
b.italic('No output yet.');
|
|
427
|
+
}
|
|
428
|
+
else {
|
|
429
|
+
const out = detail.output.length > OUTPUT_MAX_CHARS
|
|
430
|
+
? '…' + detail.output.slice(-(OUTPUT_MAX_CHARS - 1))
|
|
431
|
+
: detail.output;
|
|
432
|
+
b.pre(out);
|
|
433
|
+
if (detail.note)
|
|
434
|
+
b.newline().italic(detail.note);
|
|
435
|
+
}
|
|
436
|
+
const last = [{ text: '🔄 Refresh', callback_data: nav.refresh }];
|
|
437
|
+
if (nav.back)
|
|
438
|
+
last.unshift({ text: '← Back', callback_data: nav.back });
|
|
439
|
+
return { message: b.build(), keyboard: [last] };
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Read claude's overlay and show what it says — the list with row buttons, a
|
|
443
|
+
* task's detail with its output, or why it couldn't be read. One function so
|
|
444
|
+
* that every entry point (the button under the tracker list, a row number,
|
|
445
|
+
* 📄 Output on a tracked task) renders the same way.
|
|
446
|
+
*/
|
|
447
|
+
async function showClaudeView(ctx, sessionKey, opts) {
|
|
448
|
+
await ctx.answerCallbackQuery({ text: 'Asking claude…' }).catch(() => { });
|
|
449
|
+
const nav = { refresh: opts.refresh ?? 'tasks:claude', back: opts.back };
|
|
450
|
+
const view = await readClaudeTasks(sessionKey, opts.pick);
|
|
451
|
+
let rendered;
|
|
452
|
+
switch (view.kind) {
|
|
453
|
+
case 'detail':
|
|
454
|
+
rendered = renderClaudeDetail(view.detail, nav);
|
|
455
|
+
break;
|
|
456
|
+
case 'list':
|
|
457
|
+
rendered = renderClaudeList(view, nav, opts.pick ? opts.unmatchedNote : undefined);
|
|
458
|
+
break;
|
|
459
|
+
case 'empty': {
|
|
460
|
+
// A code block for one line of "nothing running" is noise. Worth saying
|
|
461
|
+
// out loud though: claude reporting empty while the tracker shows tasks
|
|
462
|
+
// means it is holding entries claude no longer knows about.
|
|
463
|
+
const tracked = taskTracker.getTasks(sessionKey).length;
|
|
464
|
+
const b = claudeHeading().add('Nothing running.');
|
|
465
|
+
if (tracked > 0) {
|
|
466
|
+
b.newline(2).italic(`The ${tracked} tracked task(s) are unknown to claude — likely finished already.`);
|
|
467
|
+
}
|
|
468
|
+
rendered = { message: b.build(), keyboard: [[{ text: '🔄 Refresh', callback_data: nav.refresh }]] };
|
|
469
|
+
break;
|
|
470
|
+
}
|
|
471
|
+
case 'unreadable':
|
|
472
|
+
// The overlay's layout is a Claude Code implementation detail and can
|
|
473
|
+
// move between releases — say so plainly rather than showing a mangled
|
|
474
|
+
// guess.
|
|
475
|
+
rendered = {
|
|
476
|
+
message: claudeHeading()
|
|
477
|
+
.add("Couldn't read the ")
|
|
478
|
+
.code('/tasks')
|
|
479
|
+
.add(' overlay — Claude Code may have changed its layout. The tracked list still works.')
|
|
480
|
+
.build(),
|
|
481
|
+
keyboard: [[{ text: '🔄 Refresh', callback_data: nav.refresh }]],
|
|
482
|
+
};
|
|
483
|
+
break;
|
|
484
|
+
case 'miss':
|
|
485
|
+
rendered = {
|
|
486
|
+
message: claudeHeading().add(explainOverlayMiss(view.reason)).build(),
|
|
487
|
+
keyboard: [[{ text: '🔄 Refresh', callback_data: nav.refresh }]],
|
|
488
|
+
};
|
|
489
|
+
break;
|
|
490
|
+
}
|
|
491
|
+
if (nav.back && view.kind !== 'detail' && view.kind !== 'list') {
|
|
492
|
+
rendered.keyboard[0].unshift({ text: '← Back', callback_data: nav.back });
|
|
493
|
+
}
|
|
494
|
+
const markup = { reply_markup: { inline_keyboard: rendered.keyboard } };
|
|
495
|
+
if (!opts.edit) {
|
|
496
|
+
await replyFormatted(ctx, rendered.message, markup);
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
try {
|
|
500
|
+
await editCallbackMessage(ctx, rendered.message, markup);
|
|
501
|
+
}
|
|
502
|
+
catch (err) {
|
|
503
|
+
const msg = err instanceof Error ? err.message.toLowerCase() : '';
|
|
504
|
+
if (!msg.includes('message is not modified')) {
|
|
505
|
+
console.error("[Tasks] Failed to render claude's view:", err);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
/** The button under the tracker's list: claude's view as a message of its own. */
|
|
510
|
+
async function handleAskClaude(ctx, sessionKey) {
|
|
511
|
+
await showClaudeView(ctx, sessionKey, { edit: false });
|
|
512
|
+
}
|
|
513
|
+
// ── /shells ─────────────────────────────────────────────────────
|
|
514
|
+
// List OS-level child processes of the chat's PTY claude session and offer
|
|
515
|
+
// a one-tap SIGTERM. Complements /tasks (which only sees tracked tasks)
|
|
516
|
+
// and rescues `Bash(run_in_background=true)` shells whose stop condition
|
|
517
|
+
// will never fire.
|
|
518
|
+
const BG_MCP_SERVER_MARKER = 'mcp-server.js';
|
|
519
|
+
function formatBgAge(sec) {
|
|
520
|
+
if (sec < 60)
|
|
521
|
+
return `${sec}s`;
|
|
522
|
+
if (sec < 3600)
|
|
523
|
+
return `${Math.floor(sec / 60)}m`;
|
|
524
|
+
if (sec < 86400) {
|
|
525
|
+
const h = Math.floor(sec / 3600);
|
|
526
|
+
const m = Math.floor((sec % 3600) / 60);
|
|
527
|
+
return m > 0 ? `${h}h${m}m` : `${h}h`;
|
|
528
|
+
}
|
|
529
|
+
return `${Math.floor(sec / 86400)}d`;
|
|
530
|
+
}
|
|
531
|
+
function truncateBgCmd(cmd, max = 150) {
|
|
532
|
+
if (cmd.length <= max)
|
|
533
|
+
return cmd;
|
|
534
|
+
return cmd.substring(0, max - 1) + '…';
|
|
535
|
+
}
|
|
536
|
+
// Claude's `Bash(run_in_background=true)` shells are spawned as
|
|
537
|
+
// <shell> -c "source <snapshot> && setopt … && eval '<USER_CMD>' < /dev/null && pwd -P >| /tmp/…"
|
|
538
|
+
// The wrapper is noise — pull out the real command between `eval '` and the
|
|
539
|
+
// trailing `' < /dev/null`. Returns the original cmd if the pattern doesn't
|
|
540
|
+
// match (e.g. the MCP server, foreign children).
|
|
541
|
+
function unwrapBgCmd(cmd) {
|
|
542
|
+
const evalIdx = cmd.indexOf("eval '");
|
|
543
|
+
if (evalIdx === -1)
|
|
544
|
+
return cmd;
|
|
545
|
+
const start = evalIdx + "eval '".length;
|
|
546
|
+
const tail = cmd.indexOf("' < /dev/null", start);
|
|
547
|
+
if (tail === -1 || tail <= start)
|
|
548
|
+
return cmd;
|
|
549
|
+
return cmd.substring(start, tail);
|
|
550
|
+
}
|
|
551
|
+
export function getBgProcesses(claudePid) {
|
|
552
|
+
const result = [];
|
|
553
|
+
for (const childPid of getDirectChildren(claudePid)) {
|
|
554
|
+
const info = describeProcess(childPid);
|
|
555
|
+
if (!info)
|
|
556
|
+
continue;
|
|
557
|
+
if (info.cmd.includes(BG_MCP_SERVER_MARKER))
|
|
558
|
+
continue;
|
|
559
|
+
result.push(info);
|
|
560
|
+
}
|
|
561
|
+
return result;
|
|
562
|
+
}
|
|
563
|
+
function renderBgList(sessionKey, claudePid, procs) {
|
|
564
|
+
const heading = () => new EntityText().add('🔍 ').bold('Background processes');
|
|
565
|
+
if (claudePid === undefined) {
|
|
566
|
+
return {
|
|
567
|
+
message: heading()
|
|
568
|
+
.newline(2)
|
|
569
|
+
.italic('No live Claude session for this chat.')
|
|
570
|
+
.build(),
|
|
571
|
+
keyboard: [],
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
if (procs.length === 0) {
|
|
575
|
+
// Cross-pointer to /tasks when tracked tasks (agents, monitors) are
|
|
576
|
+
// running but no OS shells are.
|
|
577
|
+
const taskCount = taskTracker.getTasks(sessionKey).length;
|
|
578
|
+
const b = heading().newline(2).add('None running.');
|
|
579
|
+
if (taskCount > 0) {
|
|
580
|
+
const noun = taskCount === 1 ? 'task' : 'tasks';
|
|
581
|
+
b.newline(2).italic(`🔄 ${taskCount} ${noun} still running — see /tasks.`);
|
|
582
|
+
}
|
|
583
|
+
return {
|
|
584
|
+
message: b.build(),
|
|
585
|
+
keyboard: [[{ text: '🔄 Refresh', callback_data: 'shells:refresh' }]],
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
const b = heading().add(` (${procs.length})`).newline(2);
|
|
589
|
+
procs.forEach((p, i) => {
|
|
590
|
+
b.bold(`${i + 1}.`).add(` [${formatBgAge(p.ageSec)}] pid `).code(String(p.pid)).newline();
|
|
591
|
+
b.code(truncateBgCmd(unwrapBgCmd(p.cmd))).newline(2);
|
|
592
|
+
});
|
|
593
|
+
b.italic('Tap a number to SIGTERM that process (and its descendants).');
|
|
594
|
+
const keyboard = [];
|
|
595
|
+
let row = [];
|
|
596
|
+
procs.forEach((p, i) => {
|
|
597
|
+
row.push({ text: `🛑 #${i + 1}`, callback_data: `shells:kill:${p.pid}` });
|
|
598
|
+
if (row.length === 4 || i === procs.length - 1) {
|
|
599
|
+
keyboard.push(row);
|
|
600
|
+
row = [];
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
keyboard.push([
|
|
604
|
+
{ text: '🛑 Kill all', callback_data: 'shells:killall' },
|
|
605
|
+
{ text: '🔄 Refresh', callback_data: 'shells:refresh' },
|
|
606
|
+
]);
|
|
607
|
+
return { message: b.build(), keyboard };
|
|
608
|
+
}
|
|
609
|
+
async function rerenderBg(ctx, sessionKey, claudePid) {
|
|
610
|
+
// Brief grace period so killed processes drop out of /proc before we re-read.
|
|
611
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
612
|
+
const procs = claudePid !== undefined ? getBgProcesses(claudePid) : [];
|
|
613
|
+
const { message, keyboard } = renderBgList(sessionKey, claudePid, procs);
|
|
614
|
+
try {
|
|
615
|
+
await editCallbackMessage(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
616
|
+
}
|
|
617
|
+
catch (err) {
|
|
618
|
+
const msg = err instanceof Error ? err.message.toLowerCase() : '';
|
|
619
|
+
if (!msg.includes('message is not modified')) {
|
|
620
|
+
console.error('[/shells] Failed to refresh list:', err);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
export async function handleShells(ctx) {
|
|
625
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
626
|
+
if (!keyInfo) {
|
|
627
|
+
await ctx.reply('❌ Could not determine chat context for /shells.');
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
const claudePid = getPtyProvider().getSessionPid(keyInfo.sessionKey);
|
|
631
|
+
const procs = claudePid !== undefined ? getBgProcesses(claudePid) : [];
|
|
632
|
+
const { message, keyboard } = renderBgList(keyInfo.sessionKey, claudePid, procs);
|
|
633
|
+
await replyFormatted(ctx, message, { reply_markup: { inline_keyboard: keyboard } });
|
|
634
|
+
}
|
|
635
|
+
export async function handleShellsCallback(ctx) {
|
|
636
|
+
const data = ctx.callbackQuery?.data;
|
|
637
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
638
|
+
if (!data || !keyInfo) {
|
|
639
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
const claudePid = getPtyProvider().getSessionPid(keyInfo.sessionKey);
|
|
643
|
+
if (data === 'shells:refresh') {
|
|
644
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
645
|
+
await rerenderBg(ctx, keyInfo.sessionKey, claudePid);
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
if (data === 'shells:killall') {
|
|
649
|
+
if (claudePid === undefined) {
|
|
650
|
+
await ctx.answerCallbackQuery({ text: 'No active session.' }).catch(() => { });
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
const procs = getBgProcesses(claudePid);
|
|
654
|
+
let total = 0;
|
|
655
|
+
for (const p of procs)
|
|
656
|
+
total += killTree(p.pid);
|
|
657
|
+
await ctx.answerCallbackQuery({ text: `SIGTERM sent to ${total} process(es).` }).catch(() => { });
|
|
658
|
+
await rerenderBg(ctx, keyInfo.sessionKey, claudePid);
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
if (data.startsWith('shells:kill:')) {
|
|
662
|
+
const pid = Number.parseInt(data.substring('shells:kill:'.length), 10);
|
|
663
|
+
if (claudePid === undefined || !Number.isFinite(pid)) {
|
|
664
|
+
await ctx.answerCallbackQuery({ text: 'Unknown target.' }).catch(() => { });
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
// PIDs can be recycled — refuse to signal anything that's no longer a
|
|
668
|
+
// descendant of this chat's claude session.
|
|
669
|
+
if (!isDescendantOf(claudePid, pid)) {
|
|
670
|
+
await ctx.answerCallbackQuery({ text: `PID ${pid} no longer belongs to this session.` }).catch(() => { });
|
|
671
|
+
await rerenderBg(ctx, keyInfo.sessionKey, claudePid);
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
const killed = killTree(pid);
|
|
675
|
+
await ctx.answerCallbackQuery({ text: `SIGTERM sent (${killed} process(es)).` }).catch(() => { });
|
|
676
|
+
await rerenderBg(ctx, keyInfo.sessionKey, claudePid);
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
await ctx.answerCallbackQuery().catch(() => { });
|
|
680
|
+
}
|
|
681
|
+
//# sourceMappingURL=tasks.js.map
|