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,712 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import { sessionJsonlPath } from './session-jsonl.js';
|
|
3
|
+
import { isSubagentTool } from './subagent-tools.js';
|
|
4
|
+
import { buildSyntheticCtx } from './synthetic-ctx.js';
|
|
5
|
+
import { parseSessionKey } from '../utils/session-key.js';
|
|
6
|
+
import { sendMarkdown } from '../telegram/send.js';
|
|
7
|
+
import { taskTracker } from '../telegram/task-tracker.js';
|
|
8
|
+
import { setBackgroundCardBot, noteTaskArmed, noteTaskFinished, noteMonitorEvent, sealCard, clearCard, } from '../telegram/background-activity-card.js';
|
|
9
|
+
import { config } from '../config.js';
|
|
10
|
+
function parseTaskNotification(rec) {
|
|
11
|
+
// origin.kind is the cleanest discriminator when the field is present;
|
|
12
|
+
// fall back to scanning for the wrapper tag in older records that don't
|
|
13
|
+
// carry it.
|
|
14
|
+
const isNotif = rec.origin?.kind === 'task-notification';
|
|
15
|
+
const content = rec.message?.content;
|
|
16
|
+
let text;
|
|
17
|
+
if (typeof content === 'string') {
|
|
18
|
+
text = content;
|
|
19
|
+
}
|
|
20
|
+
else if (Array.isArray(content)) {
|
|
21
|
+
const textBlock = content.find((b) => !!b && typeof b === 'object'
|
|
22
|
+
&& b.type === 'text'
|
|
23
|
+
&& typeof b.text === 'string');
|
|
24
|
+
if (!textBlock)
|
|
25
|
+
return null;
|
|
26
|
+
text = textBlock.text;
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
if (!isNotif && !text.includes('<task-notification>'))
|
|
32
|
+
return null;
|
|
33
|
+
const taskIdMatch = text.match(/<task-id>([^<]*)<\/task-id>/);
|
|
34
|
+
const toolUseIdMatch = text.match(/<tool-use-id>([^<]*)<\/tool-use-id>/);
|
|
35
|
+
const statusMatch = text.match(/<status>([^<]*)<\/status>/);
|
|
36
|
+
const summaryMatch = text.match(/<summary>([\s\S]*?)<\/summary>/);
|
|
37
|
+
const eventMatch = text.match(/<event>([\s\S]*?)<\/event>/);
|
|
38
|
+
return {
|
|
39
|
+
taskId: taskIdMatch?.[1].trim() ?? '',
|
|
40
|
+
toolUseId: toolUseIdMatch?.[1].trim() ?? '',
|
|
41
|
+
status: statusMatch?.[1].trim() ?? '',
|
|
42
|
+
summary: summaryMatch?.[1].trim() ?? '',
|
|
43
|
+
event: eventMatch?.[1].trim() ?? '',
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Claude Code's record of an Esc that landed once a turn had output. A turn that's
|
|
48
|
+
* interrupted doesn't get the `turn_duration` record that closes every other
|
|
49
|
+
* turn, and left unrecognised this one would look like a turn opening.
|
|
50
|
+
*/
|
|
51
|
+
function isInterruptRecord(rec) {
|
|
52
|
+
const content = rec.message?.content;
|
|
53
|
+
const blocks = Array.isArray(content) ? content : [content];
|
|
54
|
+
return blocks.some((block) => {
|
|
55
|
+
const text = typeof block === 'string' ? block : block?.text;
|
|
56
|
+
return typeof text === 'string' && text.startsWith('[Request interrupted by user');
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* A task-notification claude delivered into a turn that was already running.
|
|
61
|
+
* It gets no user record of its own: the queue logs it as removed with reason
|
|
62
|
+
* `absorbed_mid_turn`, and the turn carries it as a `queued_command`
|
|
63
|
+
* attachment.
|
|
64
|
+
*/
|
|
65
|
+
function parseAbsorbedNotification(attachment) {
|
|
66
|
+
if (attachment?.type !== 'queued_command')
|
|
67
|
+
return null;
|
|
68
|
+
return parseTaskNotification({ origin: attachment.origin, message: { content: attachment.prompt } });
|
|
69
|
+
}
|
|
70
|
+
const states = new Map();
|
|
71
|
+
let botRef = null;
|
|
72
|
+
/**
|
|
73
|
+
* Send a relay message, its markdown converted to entities (split if long;
|
|
74
|
+
* a part Telegram refuses the formatting of goes out as plain text). Mirrors
|
|
75
|
+
* the turn pipeline in messageSender.sendMessage so monitor/push messages
|
|
76
|
+
* render bold, code, links, etc.
|
|
77
|
+
*/
|
|
78
|
+
async function sendFormatted(chatId, threadOpts, text, context) {
|
|
79
|
+
if (!botRef)
|
|
80
|
+
return;
|
|
81
|
+
try {
|
|
82
|
+
await sendMarkdown(botRef.api, chatId, text, threadOpts);
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
console.error(`[Monitor] send failed (${context}):`, err instanceof Error ? err.message : err);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const COALESCE_MS = 200;
|
|
89
|
+
export function setMonitorRelayBot(bot) {
|
|
90
|
+
botRef = bot;
|
|
91
|
+
setBackgroundCardBot(bot);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Kind → the `taskType` string /tasks groups on: Claude Code's own names for
|
|
95
|
+
* the kinds of task.
|
|
96
|
+
*/
|
|
97
|
+
const TASK_TYPE_BY_KIND = {
|
|
98
|
+
monitor: 'monitor_mcp',
|
|
99
|
+
bash_background: 'local_bash',
|
|
100
|
+
subagent: 'local_agent',
|
|
101
|
+
workflow: 'local_workflow',
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* Which tool calls are backgrounded — i.e. PostToolUse fires almost at once,
|
|
105
|
+
* the user-turn returns, and the real outcome arrives later as a
|
|
106
|
+
* task-notification. Returns null for everything synchronous.
|
|
107
|
+
*
|
|
108
|
+
* A tool missing from this list is invisible twice over: its completion never
|
|
109
|
+
* reaches Telegram, and it never appears in /tasks. Add new backgrounded
|
|
110
|
+
* tools here.
|
|
111
|
+
*/
|
|
112
|
+
export function classifyAsyncTool(toolName, toolInput) {
|
|
113
|
+
if (toolName === 'Monitor')
|
|
114
|
+
return 'monitor';
|
|
115
|
+
// Bash is only async on the explicit opt-in; the common case is synchronous.
|
|
116
|
+
if (toolName === 'Bash')
|
|
117
|
+
return toolInput.run_in_background === true ? 'bash_background' : null;
|
|
118
|
+
if (toolName === 'Workflow')
|
|
119
|
+
return 'workflow';
|
|
120
|
+
if (isSubagentTool(toolName))
|
|
121
|
+
return 'subagent';
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* A plain Bash call claude moved to the background partway through. A command
|
|
126
|
+
* that runs into the 10-minute foreground cap isn't killed: the call returns
|
|
127
|
+
* with a `backgroundTaskId`, and the command finishes later the way a
|
|
128
|
+
* run_in_background one does, with a task-notification. classifyAsyncTool saw
|
|
129
|
+
* an ordinary call at PreToolUse, so only the response tells.
|
|
130
|
+
*/
|
|
131
|
+
export function movedToBackground(toolName, toolInput, toolResponse) {
|
|
132
|
+
if (toolName !== 'Bash' || classifyAsyncTool(toolName, toolInput) !== null)
|
|
133
|
+
return false;
|
|
134
|
+
return !!toolResponse && typeof toolResponse === 'object'
|
|
135
|
+
&& typeof toolResponse.backgroundTaskId === 'string';
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Register that an async tool was invoked (see classifyAsyncTool). Arms the
|
|
139
|
+
* JSONL watcher on first call per session so future task-notifications and
|
|
140
|
+
* their assistant responses get relayed to Telegram, and records the task
|
|
141
|
+
* with `taskTracker` so /tasks and the footer counters can see it.
|
|
142
|
+
*
|
|
143
|
+
* Idempotent — multiple async tool calls in one session share one watcher.
|
|
144
|
+
*
|
|
145
|
+
* `startedAt` is for a task that was already running when it was armed — see
|
|
146
|
+
* movedToBackground.
|
|
147
|
+
*/
|
|
148
|
+
export function onAsyncToolArmed(kind, sessionKey, cwd, claudeSessionId, description, toolUseId, startedAt = Date.now(), command) {
|
|
149
|
+
let state = states.get(sessionKey);
|
|
150
|
+
if (!state) {
|
|
151
|
+
state = {
|
|
152
|
+
sessionKey,
|
|
153
|
+
cwd,
|
|
154
|
+
claudeSessionId,
|
|
155
|
+
jsonlPosition: 0,
|
|
156
|
+
watcher: null,
|
|
157
|
+
inTurn: true,
|
|
158
|
+
selfTurnOpen: false,
|
|
159
|
+
pendingRead: null,
|
|
160
|
+
reply: [],
|
|
161
|
+
replySent: Promise.resolve(),
|
|
162
|
+
postedInTurn: false,
|
|
163
|
+
armedTasks: new Map(),
|
|
164
|
+
};
|
|
165
|
+
states.set(sessionKey, state);
|
|
166
|
+
startWatching(state);
|
|
167
|
+
}
|
|
168
|
+
// claudeSessionId can change if the session was reset between turns;
|
|
169
|
+
// refresh so the watcher tracks the correct log on the next arm.
|
|
170
|
+
if (state.claudeSessionId !== claudeSessionId) {
|
|
171
|
+
state.claudeSessionId = claudeSessionId;
|
|
172
|
+
stopWatcher(state);
|
|
173
|
+
startWatching(state);
|
|
174
|
+
}
|
|
175
|
+
// Register before the Telegram round-trip, not after it. These entries are
|
|
176
|
+
// what /tasks and the footer counters read, so a failed sendMessage must
|
|
177
|
+
// not render a live background task invisible.
|
|
178
|
+
//
|
|
179
|
+
// A task without a tool_use_id is untrackable rather than merely unposted:
|
|
180
|
+
// the terminal task-notification identifies itself by that id, so there'd
|
|
181
|
+
// be nothing to match the completion against and the entry would leak as a
|
|
182
|
+
// permanently-"running" ghost. Relay it to chat, but don't track it.
|
|
183
|
+
if (toolUseId) {
|
|
184
|
+
state.armedTasks.set(toolUseId, {
|
|
185
|
+
kind,
|
|
186
|
+
description,
|
|
187
|
+
startedAt,
|
|
188
|
+
});
|
|
189
|
+
taskTracker.start(sessionKey, {
|
|
190
|
+
taskId: toolUseId,
|
|
191
|
+
toolUseId,
|
|
192
|
+
description,
|
|
193
|
+
...(command !== undefined ? { command } : {}),
|
|
194
|
+
taskType: TASK_TYPE_BY_KIND[kind],
|
|
195
|
+
startedAt,
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
noteTaskArmed(sessionKey, kind, description, toolUseId, startedAt);
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* The launching call has returned claude's own id for a backgrounded task
|
|
202
|
+
* (`backgroundTaskId` in a Bash response). Remember it: TaskStop names the
|
|
203
|
+
* task by that id, and the tool_use_id everything else is keyed by is not in
|
|
204
|
+
* its input.
|
|
205
|
+
*/
|
|
206
|
+
export function noteClaudeTaskId(sessionKey, toolUseId, claudeTaskId) {
|
|
207
|
+
const armed = states.get(sessionKey)?.armedTasks.get(toolUseId);
|
|
208
|
+
if (armed)
|
|
209
|
+
armed.claudeTaskId = claudeTaskId;
|
|
210
|
+
taskTracker.setClaudeTaskId(sessionKey, toolUseId, claudeTaskId);
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Claude called TaskStop on a task. The task is killed, but claude writes no
|
|
214
|
+
* task-notification for a task it stopped itself, so the completion path
|
|
215
|
+
* never fires and the entry would stay "running" until the bot restarts, the
|
|
216
|
+
* footer saying so under every reply. Retire it here instead, as stopped.
|
|
217
|
+
*
|
|
218
|
+
* Returns false for a task this relay never armed (one claude started between
|
|
219
|
+
* turns, or before the last restart), which has nothing to retire.
|
|
220
|
+
*/
|
|
221
|
+
export function onTaskStopped(sessionKey, claudeTaskId) {
|
|
222
|
+
const state = states.get(sessionKey);
|
|
223
|
+
if (!state)
|
|
224
|
+
return false;
|
|
225
|
+
const entry = [...state.armedTasks].find(([, armed]) => armed.claudeTaskId === claudeTaskId);
|
|
226
|
+
if (!entry)
|
|
227
|
+
return false;
|
|
228
|
+
const [toolUseId, armed] = entry;
|
|
229
|
+
state.armedTasks.delete(toolUseId);
|
|
230
|
+
taskTracker.remove(sessionKey, toolUseId);
|
|
231
|
+
noteTaskFinished(sessionKey, toolUseId, { kind: armed.kind, description: armed.description, status: 'stopped', elapsedMs: Date.now() - armed.startedAt });
|
|
232
|
+
return true;
|
|
233
|
+
}
|
|
234
|
+
export function markTurnStart(sessionKey) {
|
|
235
|
+
const state = states.get(sessionKey);
|
|
236
|
+
if (state) {
|
|
237
|
+
// A turn claude started itself may not be read to the end yet, or not
|
|
238
|
+
// closed. What it wrote goes out now, ahead of this turn, instead of
|
|
239
|
+
// being skipped as this turn's. Without a status line, even if the log
|
|
240
|
+
// turns out to have closed it: this turn is under way and ends with one.
|
|
241
|
+
drain(state, false);
|
|
242
|
+
void sendReply(state);
|
|
243
|
+
state.postedInTurn = false;
|
|
244
|
+
state.inTurn = true;
|
|
245
|
+
state.selfTurnOpen = false;
|
|
246
|
+
}
|
|
247
|
+
// The user's own message has just buried any card left over from the
|
|
248
|
+
// previous quiet window; start a fresh one rather than going on editing
|
|
249
|
+
// where nobody is looking.
|
|
250
|
+
sealCard(sessionKey);
|
|
251
|
+
}
|
|
252
|
+
export function markTurnEnd(sessionKey) {
|
|
253
|
+
const state = states.get(sessionKey);
|
|
254
|
+
if (!state)
|
|
255
|
+
return;
|
|
256
|
+
// Drain any pending JSONL writes while inTurn is still true so terminal
|
|
257
|
+
// task-notifications that landed during the turn get edit-in-place
|
|
258
|
+
// treatment before the cursor jumps forward.
|
|
259
|
+
drain(state);
|
|
260
|
+
state.inTurn = false;
|
|
261
|
+
// Snap to current end so the user-turn's own assistant text doesn't get
|
|
262
|
+
// sent again as a reply — the turn pipeline already delivered it.
|
|
263
|
+
const filePath = sessionJsonlPath(state.cwd, state.claudeSessionId);
|
|
264
|
+
try {
|
|
265
|
+
state.jsonlPosition = fs.statSync(filePath).size;
|
|
266
|
+
}
|
|
267
|
+
catch { /* file gone or unreadable; next change event will rediscover */ }
|
|
268
|
+
// The turn pipeline posts its reply as soon as this returns, so whatever
|
|
269
|
+
// is on the card is about to be buried. Seal it — with the completions
|
|
270
|
+
// drained above already on it.
|
|
271
|
+
sealCard(sessionKey);
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Bring the chat up to date ahead of something a tool posts in a turn claude
|
|
275
|
+
* started itself — a question, a file. Nothing streams such a turn, so what
|
|
276
|
+
* it has written so far goes out first, and the card is sealed: both stay
|
|
277
|
+
* above the post, and what the turn writes after it lands below rather than
|
|
278
|
+
* on a card the post has buried.
|
|
279
|
+
*/
|
|
280
|
+
export async function settleBeforePost(sessionKey) {
|
|
281
|
+
const state = states.get(sessionKey);
|
|
282
|
+
if (state && !state.inTurn) {
|
|
283
|
+
drain(state);
|
|
284
|
+
// The post counts as the turn's, with or without prose ahead of it.
|
|
285
|
+
state.postedInTurn = true;
|
|
286
|
+
await sendReply(state);
|
|
287
|
+
}
|
|
288
|
+
sealCard(sessionKey);
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* A turn claude started itself has just been interrupted. The log can't be left
|
|
292
|
+
* to say so: an Esc that lands before any output writes no record at all, so
|
|
293
|
+
* going by the log alone would leave the turn open until the next one of ours.
|
|
294
|
+
*/
|
|
295
|
+
export function markSelfTurnInterrupted(sessionKey) {
|
|
296
|
+
const state = states.get(sessionKey);
|
|
297
|
+
if (!state || state.inTurn)
|
|
298
|
+
return;
|
|
299
|
+
drain(state);
|
|
300
|
+
state.selfTurnOpen = false;
|
|
301
|
+
void sendReply(state);
|
|
302
|
+
// Cut short rather than closed, and by someone looking at the chat.
|
|
303
|
+
state.postedInTurn = false;
|
|
304
|
+
}
|
|
305
|
+
/** The sessions to look at: the one asked about, or all of them. */
|
|
306
|
+
function statesFor(sessionKey) {
|
|
307
|
+
if (sessionKey === undefined)
|
|
308
|
+
return [...states.values()];
|
|
309
|
+
const state = states.get(sessionKey);
|
|
310
|
+
return state ? [state] : [];
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Whether a turn claude started itself is still going, or its reply hasn't
|
|
314
|
+
* been handed on yet. Nothing in the request queue knows about such a turn.
|
|
315
|
+
*/
|
|
316
|
+
export function hasSelfStartedTurn(sessionKey) {
|
|
317
|
+
return statesFor(sessionKey).some((state) => state.selfTurnOpen || state.reply.length > 0);
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* How long claude must sit at its prompt, with its log not growing, before a
|
|
321
|
+
* turn it started itself counts as over though the log never closed it.
|
|
322
|
+
*/
|
|
323
|
+
export const STALE_SELF_TURN_MS = 2 * 60_000;
|
|
324
|
+
/** Per open self-started turn: since when claude was seen idle at its prompt, and the log's size then. */
|
|
325
|
+
const atPromptSince = new Map();
|
|
326
|
+
/**
|
|
327
|
+
* Close the turns claude started itself that are plainly over, though nothing
|
|
328
|
+
* in the log closed them. A turn opens on a record the watcher reads and only
|
|
329
|
+
* a record closes it, so any record that opens one by mistake, with no turn
|
|
330
|
+
* behind it, holds it open until the bot restarts: /botrebuild's "when idle"
|
|
331
|
+
* waits on it, the idle reaper spares its claude, and a message waits behind
|
|
332
|
+
* it. Idle compaction did that on 11-23, and two bots sat "answering a
|
|
333
|
+
* background task" for two days.
|
|
334
|
+
*
|
|
335
|
+
* So a self-started turn whose claude has sat at its input box, generating
|
|
336
|
+
* nothing and asking nothing, with the log not growing, for STALE_SELF_TURN_MS
|
|
337
|
+
* is closed here, and whatever it wrote goes out. Called every so often with
|
|
338
|
+
* a check of claude's screen; returns the sessions it closed.
|
|
339
|
+
*/
|
|
340
|
+
export function closeStaleSelfTurns(isAtPrompt, now = Date.now()) {
|
|
341
|
+
for (const key of atPromptSince.keys()) {
|
|
342
|
+
if (!states.get(key)?.selfTurnOpen)
|
|
343
|
+
atPromptSince.delete(key);
|
|
344
|
+
}
|
|
345
|
+
const closed = [];
|
|
346
|
+
for (const state of states.values()) {
|
|
347
|
+
if (!state.selfTurnOpen || state.inTurn)
|
|
348
|
+
continue;
|
|
349
|
+
const key = state.sessionKey;
|
|
350
|
+
if (!isAtPrompt(key)) {
|
|
351
|
+
atPromptSince.delete(key);
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
let logSize;
|
|
355
|
+
try {
|
|
356
|
+
logSize = fs.statSync(sessionJsonlPath(state.cwd, state.claudeSessionId)).size;
|
|
357
|
+
}
|
|
358
|
+
catch {
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
const seen = atPromptSince.get(key);
|
|
362
|
+
if (!seen || seen.logSize !== logSize) {
|
|
363
|
+
atPromptSince.set(key, { since: now, logSize });
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
if (now - seen.since < STALE_SELF_TURN_MS)
|
|
367
|
+
continue;
|
|
368
|
+
atPromptSince.delete(key);
|
|
369
|
+
// Whatever the watcher hasn't read yet first: a close in there ends the
|
|
370
|
+
// turn the ordinary way.
|
|
371
|
+
drain(state);
|
|
372
|
+
if (!state.selfTurnOpen)
|
|
373
|
+
continue;
|
|
374
|
+
console.warn(`[Monitor] ${key}: closing a turn claude started itself that the log never closed — `
|
|
375
|
+
+ `claude has sat at its prompt for ${Math.round((now - seen.since) / 1000)}s`);
|
|
376
|
+
state.selfTurnOpen = false;
|
|
377
|
+
void sendReply(state, true);
|
|
378
|
+
closed.push(key);
|
|
379
|
+
}
|
|
380
|
+
return closed;
|
|
381
|
+
}
|
|
382
|
+
/** Resolves once every reply already handed on is in its chat. */
|
|
383
|
+
export async function whenRepliesSent(sessionKey) {
|
|
384
|
+
await Promise.all(statesFor(sessionKey).map((state) => state.replySent));
|
|
385
|
+
}
|
|
386
|
+
export function teardown(sessionKey) {
|
|
387
|
+
const state = states.get(sessionKey);
|
|
388
|
+
if (!state)
|
|
389
|
+
return;
|
|
390
|
+
stopWatcher(state);
|
|
391
|
+
// A turn claude started itself and never got to close — it crashed, or was
|
|
392
|
+
// cleared or restarted mid-turn. What it wrote is still the user's to read.
|
|
393
|
+
// No status line under it: the session it would describe is going away.
|
|
394
|
+
drain(state, false);
|
|
395
|
+
void sendReply(state);
|
|
396
|
+
states.delete(sessionKey);
|
|
397
|
+
clearCard(sessionKey);
|
|
398
|
+
// This relay owns the tracker entries (_cleanupSession is teardown's sole
|
|
399
|
+
// caller). Drop them with the session so a respawned one doesn't inherit
|
|
400
|
+
// tasks that died with the old process.
|
|
401
|
+
taskTracker.clear(sessionKey);
|
|
402
|
+
}
|
|
403
|
+
function startWatching(state) {
|
|
404
|
+
const filePath = sessionJsonlPath(state.cwd, state.claudeSessionId);
|
|
405
|
+
try {
|
|
406
|
+
state.jsonlPosition = fs.statSync(filePath).size;
|
|
407
|
+
}
|
|
408
|
+
catch {
|
|
409
|
+
state.jsonlPosition = 0;
|
|
410
|
+
}
|
|
411
|
+
try {
|
|
412
|
+
state.watcher = fs.watch(filePath, { persistent: false }, () => {
|
|
413
|
+
// fs.watch can fire repeatedly for a single append (rename + change
|
|
414
|
+
// on some platforms). Coalesce so we don't read partial JSON lines.
|
|
415
|
+
if (state.pendingRead)
|
|
416
|
+
return;
|
|
417
|
+
state.pendingRead = setTimeout(() => {
|
|
418
|
+
state.pendingRead = null;
|
|
419
|
+
handleChange(state);
|
|
420
|
+
}, COALESCE_MS);
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
catch (err) {
|
|
424
|
+
console.error(`[Monitor] failed to watch JSONL for ${state.sessionKey}:`, err);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Watch the session's log in its new directory: Claude Code's /cd moved it
|
|
429
|
+
* there (session-move.ts). What was appended in between isn't read again.
|
|
430
|
+
*/
|
|
431
|
+
export function onSessionMoved(sessionKey, cwd) {
|
|
432
|
+
const state = states.get(sessionKey);
|
|
433
|
+
if (!state || state.cwd === cwd)
|
|
434
|
+
return;
|
|
435
|
+
state.cwd = cwd;
|
|
436
|
+
stopWatcher(state);
|
|
437
|
+
startWatching(state);
|
|
438
|
+
}
|
|
439
|
+
function stopWatcher(state) {
|
|
440
|
+
if (state.watcher) {
|
|
441
|
+
try {
|
|
442
|
+
state.watcher.close();
|
|
443
|
+
}
|
|
444
|
+
catch { /* already gone */ }
|
|
445
|
+
state.watcher = null;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Read now whatever the watcher has been told about but not read yet.
|
|
450
|
+
* Cancels the coalesce timer so it doesn't fire later with the position
|
|
451
|
+
* already past the data.
|
|
452
|
+
*
|
|
453
|
+
* `closes` is whether a turn found closed in what's read still ends with the
|
|
454
|
+
* status line. Not when the caller is ending the relay's part itself.
|
|
455
|
+
*/
|
|
456
|
+
function drain(state, closes = true) {
|
|
457
|
+
if (state.pendingRead) {
|
|
458
|
+
clearTimeout(state.pendingRead);
|
|
459
|
+
state.pendingRead = null;
|
|
460
|
+
}
|
|
461
|
+
handleChange(state, closes);
|
|
462
|
+
}
|
|
463
|
+
function handleChange(state, closes = true) {
|
|
464
|
+
const filePath = sessionJsonlPath(state.cwd, state.claudeSessionId);
|
|
465
|
+
let size;
|
|
466
|
+
try {
|
|
467
|
+
size = fs.statSync(filePath).size;
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
if (size <= state.jsonlPosition)
|
|
473
|
+
return;
|
|
474
|
+
let chunk;
|
|
475
|
+
try {
|
|
476
|
+
const fd = fs.openSync(filePath, 'r');
|
|
477
|
+
const buf = Buffer.alloc(size - state.jsonlPosition);
|
|
478
|
+
fs.readSync(fd, buf, 0, buf.length, state.jsonlPosition);
|
|
479
|
+
fs.closeSync(fd);
|
|
480
|
+
chunk = buf.toString('utf-8');
|
|
481
|
+
}
|
|
482
|
+
catch (err) {
|
|
483
|
+
console.error('[Monitor] read failed:', err);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
state.jsonlPosition = size;
|
|
487
|
+
for (const line of chunk.split('\n')) {
|
|
488
|
+
const trimmed = line.trim();
|
|
489
|
+
if (!trimmed)
|
|
490
|
+
continue;
|
|
491
|
+
let rec;
|
|
492
|
+
try {
|
|
493
|
+
rec = JSON.parse(trimmed);
|
|
494
|
+
}
|
|
495
|
+
catch {
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
if (!rec || typeof rec !== 'object')
|
|
499
|
+
continue;
|
|
500
|
+
const typed = rec;
|
|
501
|
+
if (typed.type === 'user') {
|
|
502
|
+
// Filed as a user record, but it ends a turn rather than starting one.
|
|
503
|
+
if (isInterruptRecord(typed)) {
|
|
504
|
+
if (!state.inTurn) {
|
|
505
|
+
state.selfTurnOpen = false;
|
|
506
|
+
void sendReply(state);
|
|
507
|
+
state.postedInTurn = false;
|
|
508
|
+
}
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
// The summary a compaction leaves, filed as a user record too. When
|
|
512
|
+
// claude compacts an idle session by itself ("Compacted while idle")
|
|
513
|
+
// no turn follows, so nothing would ever close one opened here.
|
|
514
|
+
if (typed.isCompactSummary)
|
|
515
|
+
continue;
|
|
516
|
+
if (!state.inTurn)
|
|
517
|
+
state.selfTurnOpen = true;
|
|
518
|
+
const notif = parseTaskNotification(typed);
|
|
519
|
+
if (notif) {
|
|
520
|
+
// Terminal notifications (status set + matching armed entry) always
|
|
521
|
+
// get edit-in-place treatment, even during an active user-turn.
|
|
522
|
+
// A backgrounded task can complete at any moment; without this, a
|
|
523
|
+
// completion that lands mid-turn would leave the armed message stuck
|
|
524
|
+
// on "in progress" forever — markTurnEnd would snap the JSONL cursor
|
|
525
|
+
// past the notification and the watcher would never revisit it.
|
|
526
|
+
if (notif.status && notif.toolUseId && state.armedTasks.has(notif.toolUseId)) {
|
|
527
|
+
handleTerminalNotification(state, notif);
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
// Non-terminal event notifications stay gated on !inTurn — during a
|
|
531
|
+
// user-turn the turn pipeline owns the model's response, and the
|
|
532
|
+
// watcher must not race it.
|
|
533
|
+
if (state.inTurn)
|
|
534
|
+
continue;
|
|
535
|
+
postMonitorEvent(state.sessionKey, notif);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
else if (typed.type === 'attachment') {
|
|
539
|
+
// A task that finishes while claude is mid-turn never gets the user
|
|
540
|
+
// record above; its completion only arrives folded into that turn. Left
|
|
541
|
+
// unread, the task stays "running" in the footer and /tasks for the rest
|
|
542
|
+
// of the session. Only the completion is taken from here — the model's
|
|
543
|
+
// reply to it belongs to the turn that absorbed it.
|
|
544
|
+
const notif = parseAbsorbedNotification(typed.attachment);
|
|
545
|
+
if (notif?.status && notif.toolUseId && state.armedTasks.has(notif.toolUseId)) {
|
|
546
|
+
handleTerminalNotification(state, notif);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
else if (typed.type === 'assistant') {
|
|
550
|
+
// Assistant text during an active turn belongs to the turn pipeline.
|
|
551
|
+
if (state.inTurn)
|
|
552
|
+
continue;
|
|
553
|
+
const text = extractAssistantText(typed.message?.content);
|
|
554
|
+
if (text)
|
|
555
|
+
state.reply.push(text);
|
|
556
|
+
}
|
|
557
|
+
else if (typed.type === 'system' && typed.subtype === 'turn_duration') {
|
|
558
|
+
// Claude Code closes every turn with this record — the ones it starts
|
|
559
|
+
// itself too, and one cut short by an API error as well.
|
|
560
|
+
if (!state.inTurn) {
|
|
561
|
+
state.selfTurnOpen = false;
|
|
562
|
+
void sendReply(state, closes);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Send what claude has written in a turn it started itself, the way the turn
|
|
569
|
+
* pipeline sends a reply: whole, split across messages only where Telegram
|
|
570
|
+
* needs it, with an Instant View link when it runs long. Joined as
|
|
571
|
+
* readLastAssistantTurnText joins a turn's text records.
|
|
572
|
+
*
|
|
573
|
+
* `turnClosed` is for the send that follows claude closing the turn. A turn
|
|
574
|
+
* that put anything in the chat then ends as one of ours does, with the status
|
|
575
|
+
* line under it. A send for any other reason gets none: the turn is still
|
|
576
|
+
* going, or was cut short, or a turn of ours is taking over and will end with
|
|
577
|
+
* its own.
|
|
578
|
+
*
|
|
579
|
+
* Resolves once all of it is in the chat, so a tool can post below it.
|
|
580
|
+
*/
|
|
581
|
+
function sendReply(state, turnClosed = false) {
|
|
582
|
+
const text = state.reply.join('\n\n');
|
|
583
|
+
state.reply = [];
|
|
584
|
+
if (text)
|
|
585
|
+
state.postedInTurn = true;
|
|
586
|
+
const closes = turnClosed && state.postedInTurn;
|
|
587
|
+
if (turnClosed)
|
|
588
|
+
state.postedInTurn = false;
|
|
589
|
+
if (!text && !closes)
|
|
590
|
+
return state.replySent;
|
|
591
|
+
// What the card shows happened before this. Sealed, the card stays above
|
|
592
|
+
// it, and whatever happens next starts a fresh card below.
|
|
593
|
+
sealCard(state.sessionKey);
|
|
594
|
+
const { sessionKey } = state;
|
|
595
|
+
state.replySent = state.replySent.then(async () => {
|
|
596
|
+
if (text)
|
|
597
|
+
await postReply(sessionKey, text);
|
|
598
|
+
if (closes)
|
|
599
|
+
await postStatusLine(sessionKey);
|
|
600
|
+
});
|
|
601
|
+
return state.replySent;
|
|
602
|
+
}
|
|
603
|
+
async function postReply(sessionKey, text) {
|
|
604
|
+
if (!botRef)
|
|
605
|
+
return;
|
|
606
|
+
const ctx = buildSyntheticCtx({ api: botRef.api, sessionKey, syntheticText: '' });
|
|
607
|
+
try {
|
|
608
|
+
// Imported lazily, as mcp-bridge does: this module is loaded from
|
|
609
|
+
// pty-provider at module scope, where every eager edge is a chance to
|
|
610
|
+
// close a cycle back through it.
|
|
611
|
+
const { messageSender } = await import('../telegram/message-sender.js');
|
|
612
|
+
const lastMessageId = await messageSender.sendMessage(ctx, text);
|
|
613
|
+
// A reply like any other, so it branches like any other: the button goes
|
|
614
|
+
// under its last message, as the turn pipeline puts it under a reply of
|
|
615
|
+
// TeleCoder's.
|
|
616
|
+
await messageSender.attachBranchButton(ctx, sessionKey, lastMessageId);
|
|
617
|
+
}
|
|
618
|
+
catch (err) {
|
|
619
|
+
console.error('[Monitor] reply send failed:', err instanceof Error ? err.message : err);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
/** Close a turn claude started itself the way the turn pipeline closes one of ours. */
|
|
623
|
+
async function postStatusLine(sessionKey) {
|
|
624
|
+
if (!botRef)
|
|
625
|
+
return;
|
|
626
|
+
const ctx = buildSyntheticCtx({ api: botRef.api, sessionKey, syntheticText: '' });
|
|
627
|
+
try {
|
|
628
|
+
// Lazy like the import above, and with more reason: the handler layer
|
|
629
|
+
// imports the provider that loads this module.
|
|
630
|
+
const { closeSelfStartedTurn } = await import('../bot/handlers/message/turn-notify.js');
|
|
631
|
+
await closeSelfStartedTurn(ctx, sessionKey);
|
|
632
|
+
}
|
|
633
|
+
catch (err) {
|
|
634
|
+
console.error('[Monitor] status line send failed:', err instanceof Error ? err.message : err);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
function extractAssistantText(content) {
|
|
638
|
+
if (typeof content === 'string')
|
|
639
|
+
return content.trim();
|
|
640
|
+
if (!Array.isArray(content))
|
|
641
|
+
return '';
|
|
642
|
+
return content
|
|
643
|
+
.filter((b) => !!b && typeof b === 'object' && b.type === 'text' && typeof b.text === 'string')
|
|
644
|
+
.map((b) => b.text.trim())
|
|
645
|
+
.filter((t) => t.length > 0)
|
|
646
|
+
.join('\n\n');
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Relay claude's PushNotification tool to Telegram. The native tool fires
|
|
650
|
+
* an OS-level notification on the bot host (no real user is sitting there)
|
|
651
|
+
* so the only useful surface is Telegram. Called from PreToolUse and treated
|
|
652
|
+
* independently of the JSONL watcher — push notifications are single-shot
|
|
653
|
+
* and don't need turn-end pairing.
|
|
654
|
+
*/
|
|
655
|
+
export function relayPushNotification(sessionKey, message) {
|
|
656
|
+
if (!botRef)
|
|
657
|
+
return;
|
|
658
|
+
const trimmed = message.trim();
|
|
659
|
+
if (!trimmed)
|
|
660
|
+
return;
|
|
661
|
+
const { chatId, threadId } = parseSessionKey(sessionKey);
|
|
662
|
+
const threadOpts = threadId !== undefined ? { message_thread_id: threadId } : {};
|
|
663
|
+
const preview = trimmed.length > 500 ? trimmed.slice(0, 497) + '...' : trimmed;
|
|
664
|
+
sendFormatted(chatId, threadOpts, `🔔 ${preview}`, 'push').catch(() => { });
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Called when a task-notification's status indicates the task is done.
|
|
668
|
+
* Retires the task from the card's running list and records how it ended.
|
|
669
|
+
*
|
|
670
|
+
* Whether that gets the user's attention is the card's call: a failure is
|
|
671
|
+
* urgent enough to re-post immediately, a task that ran past the notification
|
|
672
|
+
* threshold is worth a ping if the card has been sitting a while, and a quick
|
|
673
|
+
* success just folds into the card silently.
|
|
674
|
+
*
|
|
675
|
+
* Returns true when the notification was consumed as a completion; the caller
|
|
676
|
+
* then skips the monitor-event path so we don't double-report.
|
|
677
|
+
*/
|
|
678
|
+
function handleTerminalNotification(state, notif) {
|
|
679
|
+
const armed = state.armedTasks.get(notif.toolUseId);
|
|
680
|
+
if (!armed)
|
|
681
|
+
return false;
|
|
682
|
+
state.armedTasks.delete(notif.toolUseId);
|
|
683
|
+
// Retire the tracker entry before any chat I/O. /tasks filters to
|
|
684
|
+
// running/pending, so dropping it outright is equivalent to recording a
|
|
685
|
+
// terminal status.
|
|
686
|
+
taskTracker.remove(state.sessionKey, notif.toolUseId);
|
|
687
|
+
const elapsedMs = Date.now() - armed.startedAt;
|
|
688
|
+
const isError = notif.status === 'failed' || notif.status === 'killed';
|
|
689
|
+
const longRunning = elapsedMs >= config.NOTIFICATION_THRESHOLD_SECONDS * 1000;
|
|
690
|
+
noteTaskFinished(state.sessionKey, notif.toolUseId, { kind: armed.kind, description: armed.description, status: notif.status, elapsedMs }, { notify: isError || longRunning, urgent: isError });
|
|
691
|
+
return true;
|
|
692
|
+
}
|
|
693
|
+
function stripSummaryPrefix(summary) {
|
|
694
|
+
// Claude code formats summaries as `Monitor event: "<desc>"` — strip the
|
|
695
|
+
// boilerplate so the header isn't redundant with the "📡 Monitor" prefix.
|
|
696
|
+
return summary.replace(/^Monitor event:\s*/i, '').replace(/^"(.*)"$/, '$1').trim();
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Put a monitor firing on the card as it lands. What claude says about it is
|
|
700
|
+
* its turn's reply, sent when the turn closes.
|
|
701
|
+
*/
|
|
702
|
+
function postMonitorEvent(sessionKey, notif) {
|
|
703
|
+
const summary = notif.summary ? stripSummaryPrefix(notif.summary) : '';
|
|
704
|
+
// The footer under a running turn's status line shows it too, beside
|
|
705
|
+
// the task it came from.
|
|
706
|
+
taskTracker.noteUpdate(sessionKey, notif.toolUseId, summary || notif.event.split('\n')[0]);
|
|
707
|
+
// A monitor firing is the whole reason the user armed it, so it always
|
|
708
|
+
// wants the user's attention — the card decides whether that means a fresh
|
|
709
|
+
// message or a silent edit onto one it posted moments ago.
|
|
710
|
+
noteMonitorEvent(sessionKey, summary, notif.event, { notify: true });
|
|
711
|
+
}
|
|
712
|
+
//# sourceMappingURL=monitor-relay.js.map
|