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,597 @@
|
|
|
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. Keeps the PTY-mode buckets
|
|
95
|
+
* identical to the SDK-mode ones so the command renders the same either way.
|
|
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()) {
|
|
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.handleEvent(sessionKey, {
|
|
190
|
+
type: 'started',
|
|
191
|
+
taskId: toolUseId,
|
|
192
|
+
toolUseId,
|
|
193
|
+
description,
|
|
194
|
+
taskType: TASK_TYPE_BY_KIND[kind],
|
|
195
|
+
// Everything routed through this relay is backgrounded by definition —
|
|
196
|
+
// that's the property that made it need a relay in the first place.
|
|
197
|
+
isBackgrounded: true,
|
|
198
|
+
startedAt,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
noteTaskArmed(sessionKey, kind, description, toolUseId, startedAt);
|
|
202
|
+
}
|
|
203
|
+
export function markTurnStart(sessionKey) {
|
|
204
|
+
const state = states.get(sessionKey);
|
|
205
|
+
if (state) {
|
|
206
|
+
// A turn claude started itself may not be read to the end yet, or not
|
|
207
|
+
// closed. What it wrote goes out now, ahead of this turn, instead of
|
|
208
|
+
// being skipped as this turn's. Without a status line, even if the log
|
|
209
|
+
// turns out to have closed it: this turn is under way and ends with one.
|
|
210
|
+
drain(state, false);
|
|
211
|
+
void sendReply(state);
|
|
212
|
+
state.postedInTurn = false;
|
|
213
|
+
state.inTurn = true;
|
|
214
|
+
state.selfTurnOpen = false;
|
|
215
|
+
}
|
|
216
|
+
// The user's own message has just buried any card left over from the
|
|
217
|
+
// previous quiet window; start a fresh one rather than going on editing
|
|
218
|
+
// where nobody is looking.
|
|
219
|
+
sealCard(sessionKey);
|
|
220
|
+
}
|
|
221
|
+
export function markTurnEnd(sessionKey) {
|
|
222
|
+
const state = states.get(sessionKey);
|
|
223
|
+
if (!state)
|
|
224
|
+
return;
|
|
225
|
+
// Drain any pending JSONL writes while inTurn is still true so terminal
|
|
226
|
+
// task-notifications that landed during the turn get edit-in-place
|
|
227
|
+
// treatment before the cursor jumps forward.
|
|
228
|
+
drain(state);
|
|
229
|
+
state.inTurn = false;
|
|
230
|
+
// Snap to current end so the user-turn's own assistant text doesn't get
|
|
231
|
+
// sent again as a reply — the turn pipeline already delivered it.
|
|
232
|
+
const filePath = sessionJsonlPath(state.cwd, state.claudeSessionId);
|
|
233
|
+
try {
|
|
234
|
+
state.jsonlPosition = fs.statSync(filePath).size;
|
|
235
|
+
}
|
|
236
|
+
catch { /* file gone or unreadable; next change event will rediscover */ }
|
|
237
|
+
// The turn pipeline posts its reply as soon as this returns, so whatever
|
|
238
|
+
// is on the card is about to be buried. Seal it — with the completions
|
|
239
|
+
// drained above already on it.
|
|
240
|
+
sealCard(sessionKey);
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Bring the chat up to date ahead of something a tool posts in a turn claude
|
|
244
|
+
* started itself — a question, a file. Nothing streams such a turn, so what
|
|
245
|
+
* it has written so far goes out first, and the card is sealed: both stay
|
|
246
|
+
* above the post, and what the turn writes after it lands below rather than
|
|
247
|
+
* on a card the post has buried.
|
|
248
|
+
*/
|
|
249
|
+
export async function settleBeforePost(sessionKey) {
|
|
250
|
+
const state = states.get(sessionKey);
|
|
251
|
+
if (state && !state.inTurn) {
|
|
252
|
+
drain(state);
|
|
253
|
+
// The post counts as the turn's, with or without prose ahead of it.
|
|
254
|
+
state.postedInTurn = true;
|
|
255
|
+
await sendReply(state);
|
|
256
|
+
}
|
|
257
|
+
sealCard(sessionKey);
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* A turn claude started itself has just been interrupted. The log can't be left
|
|
261
|
+
* to say so: an Esc that lands before any output writes no record at all, so
|
|
262
|
+
* going by the log alone would leave the turn open until the next one of ours.
|
|
263
|
+
*/
|
|
264
|
+
export function markSelfTurnInterrupted(sessionKey) {
|
|
265
|
+
const state = states.get(sessionKey);
|
|
266
|
+
if (!state || state.inTurn)
|
|
267
|
+
return;
|
|
268
|
+
drain(state);
|
|
269
|
+
state.selfTurnOpen = false;
|
|
270
|
+
void sendReply(state);
|
|
271
|
+
// Cut short rather than closed, and by someone looking at the chat.
|
|
272
|
+
state.postedInTurn = false;
|
|
273
|
+
}
|
|
274
|
+
/** The sessions to look at: the one asked about, or all of them. */
|
|
275
|
+
function statesFor(sessionKey) {
|
|
276
|
+
if (sessionKey === undefined)
|
|
277
|
+
return [...states.values()];
|
|
278
|
+
const state = states.get(sessionKey);
|
|
279
|
+
return state ? [state] : [];
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Whether a turn claude started itself is still going, or its reply hasn't
|
|
283
|
+
* been handed on yet. Nothing in the request queue knows about such a turn.
|
|
284
|
+
*/
|
|
285
|
+
export function hasSelfStartedTurn(sessionKey) {
|
|
286
|
+
return statesFor(sessionKey).some((state) => state.selfTurnOpen || state.reply.length > 0);
|
|
287
|
+
}
|
|
288
|
+
/** Resolves once every reply already handed on is in its chat. */
|
|
289
|
+
export async function whenRepliesSent(sessionKey) {
|
|
290
|
+
await Promise.all(statesFor(sessionKey).map((state) => state.replySent));
|
|
291
|
+
}
|
|
292
|
+
export function teardown(sessionKey) {
|
|
293
|
+
const state = states.get(sessionKey);
|
|
294
|
+
if (!state)
|
|
295
|
+
return;
|
|
296
|
+
stopWatcher(state);
|
|
297
|
+
// A turn claude started itself and never got to close — it crashed, or was
|
|
298
|
+
// cleared or restarted mid-turn. What it wrote is still the user's to read.
|
|
299
|
+
// No status line under it: the session it would describe is going away.
|
|
300
|
+
drain(state, false);
|
|
301
|
+
void sendReply(state);
|
|
302
|
+
states.delete(sessionKey);
|
|
303
|
+
clearCard(sessionKey);
|
|
304
|
+
// This relay owns the PTY-side tracker entries, and teardown is PTY-only
|
|
305
|
+
// (_cleanupSession is its sole caller). Drop them with the session so a
|
|
306
|
+
// respawned one doesn't inherit tasks that died with the old process.
|
|
307
|
+
taskTracker.clear(sessionKey);
|
|
308
|
+
}
|
|
309
|
+
function startWatching(state) {
|
|
310
|
+
const filePath = sessionJsonlPath(state.cwd, state.claudeSessionId);
|
|
311
|
+
try {
|
|
312
|
+
state.jsonlPosition = fs.statSync(filePath).size;
|
|
313
|
+
}
|
|
314
|
+
catch {
|
|
315
|
+
state.jsonlPosition = 0;
|
|
316
|
+
}
|
|
317
|
+
try {
|
|
318
|
+
state.watcher = fs.watch(filePath, { persistent: false }, () => {
|
|
319
|
+
// fs.watch can fire repeatedly for a single append (rename + change
|
|
320
|
+
// on some platforms). Coalesce so we don't read partial JSON lines.
|
|
321
|
+
if (state.pendingRead)
|
|
322
|
+
return;
|
|
323
|
+
state.pendingRead = setTimeout(() => {
|
|
324
|
+
state.pendingRead = null;
|
|
325
|
+
handleChange(state);
|
|
326
|
+
}, COALESCE_MS);
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
catch (err) {
|
|
330
|
+
console.error(`[Monitor] failed to watch JSONL for ${state.sessionKey}:`, err);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function stopWatcher(state) {
|
|
334
|
+
if (state.watcher) {
|
|
335
|
+
try {
|
|
336
|
+
state.watcher.close();
|
|
337
|
+
}
|
|
338
|
+
catch { /* already gone */ }
|
|
339
|
+
state.watcher = null;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Read now whatever the watcher has been told about but not read yet.
|
|
344
|
+
* Cancels the coalesce timer so it doesn't fire later with the position
|
|
345
|
+
* already past the data.
|
|
346
|
+
*
|
|
347
|
+
* `closes` is whether a turn found closed in what's read still ends with the
|
|
348
|
+
* status line. Not when the caller is ending the relay's part itself.
|
|
349
|
+
*/
|
|
350
|
+
function drain(state, closes = true) {
|
|
351
|
+
if (state.pendingRead) {
|
|
352
|
+
clearTimeout(state.pendingRead);
|
|
353
|
+
state.pendingRead = null;
|
|
354
|
+
}
|
|
355
|
+
handleChange(state, closes);
|
|
356
|
+
}
|
|
357
|
+
function handleChange(state, closes = true) {
|
|
358
|
+
const filePath = sessionJsonlPath(state.cwd, state.claudeSessionId);
|
|
359
|
+
let size;
|
|
360
|
+
try {
|
|
361
|
+
size = fs.statSync(filePath).size;
|
|
362
|
+
}
|
|
363
|
+
catch {
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
if (size <= state.jsonlPosition)
|
|
367
|
+
return;
|
|
368
|
+
let chunk;
|
|
369
|
+
try {
|
|
370
|
+
const fd = fs.openSync(filePath, 'r');
|
|
371
|
+
const buf = Buffer.alloc(size - state.jsonlPosition);
|
|
372
|
+
fs.readSync(fd, buf, 0, buf.length, state.jsonlPosition);
|
|
373
|
+
fs.closeSync(fd);
|
|
374
|
+
chunk = buf.toString('utf-8');
|
|
375
|
+
}
|
|
376
|
+
catch (err) {
|
|
377
|
+
console.error('[Monitor] read failed:', err);
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
state.jsonlPosition = size;
|
|
381
|
+
for (const line of chunk.split('\n')) {
|
|
382
|
+
const trimmed = line.trim();
|
|
383
|
+
if (!trimmed)
|
|
384
|
+
continue;
|
|
385
|
+
let rec;
|
|
386
|
+
try {
|
|
387
|
+
rec = JSON.parse(trimmed);
|
|
388
|
+
}
|
|
389
|
+
catch {
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if (!rec || typeof rec !== 'object')
|
|
393
|
+
continue;
|
|
394
|
+
const typed = rec;
|
|
395
|
+
if (typed.type === 'user') {
|
|
396
|
+
// Filed as a user record, but it ends a turn rather than starting one.
|
|
397
|
+
if (isInterruptRecord(typed)) {
|
|
398
|
+
if (!state.inTurn) {
|
|
399
|
+
state.selfTurnOpen = false;
|
|
400
|
+
void sendReply(state);
|
|
401
|
+
state.postedInTurn = false;
|
|
402
|
+
}
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
if (!state.inTurn)
|
|
406
|
+
state.selfTurnOpen = true;
|
|
407
|
+
const notif = parseTaskNotification(typed);
|
|
408
|
+
if (notif) {
|
|
409
|
+
// Terminal notifications (status set + matching armed entry) always
|
|
410
|
+
// get edit-in-place treatment, even during an active user-turn.
|
|
411
|
+
// A backgrounded task can complete at any moment; without this, a
|
|
412
|
+
// completion that lands mid-turn would leave the armed message stuck
|
|
413
|
+
// on "in progress" forever — markTurnEnd would snap the JSONL cursor
|
|
414
|
+
// past the notification and the watcher would never revisit it.
|
|
415
|
+
if (notif.status && notif.toolUseId && state.armedTasks.has(notif.toolUseId)) {
|
|
416
|
+
handleTerminalNotification(state, notif);
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
// Non-terminal event notifications stay gated on !inTurn — during a
|
|
420
|
+
// user-turn the turn pipeline owns the model's response, and the
|
|
421
|
+
// watcher must not race it.
|
|
422
|
+
if (state.inTurn)
|
|
423
|
+
continue;
|
|
424
|
+
postMonitorEvent(state.sessionKey, notif);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
else if (typed.type === 'attachment') {
|
|
428
|
+
// A task that finishes while claude is mid-turn never gets the user
|
|
429
|
+
// record above; its completion only arrives folded into that turn. Left
|
|
430
|
+
// unread, the task stays "running" in the footer and /tasks for the rest
|
|
431
|
+
// of the session. Only the completion is taken from here — the model's
|
|
432
|
+
// reply to it belongs to the turn that absorbed it.
|
|
433
|
+
const notif = parseAbsorbedNotification(typed.attachment);
|
|
434
|
+
if (notif?.status && notif.toolUseId && state.armedTasks.has(notif.toolUseId)) {
|
|
435
|
+
handleTerminalNotification(state, notif);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
else if (typed.type === 'assistant') {
|
|
439
|
+
// Assistant text during an active turn belongs to the turn pipeline.
|
|
440
|
+
if (state.inTurn)
|
|
441
|
+
continue;
|
|
442
|
+
const text = extractAssistantText(typed.message?.content);
|
|
443
|
+
if (text)
|
|
444
|
+
state.reply.push(text);
|
|
445
|
+
}
|
|
446
|
+
else if (typed.type === 'system' && typed.subtype === 'turn_duration') {
|
|
447
|
+
// Claude Code closes every turn with this record — the ones it starts
|
|
448
|
+
// itself too, and one cut short by an API error as well.
|
|
449
|
+
if (!state.inTurn) {
|
|
450
|
+
state.selfTurnOpen = false;
|
|
451
|
+
void sendReply(state, closes);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Send what claude has written in a turn it started itself, the way the turn
|
|
458
|
+
* pipeline sends a reply: whole, split across messages only where Telegram
|
|
459
|
+
* needs it, with an Instant View link when it runs long. Joined as
|
|
460
|
+
* readLastAssistantTurnText joins a turn's text records.
|
|
461
|
+
*
|
|
462
|
+
* `turnClosed` is for the send that follows claude closing the turn. A turn
|
|
463
|
+
* that put anything in the chat then ends as one of ours does, with the status
|
|
464
|
+
* line under it. A send for any other reason gets none: the turn is still
|
|
465
|
+
* going, or was cut short, or a turn of ours is taking over and will end with
|
|
466
|
+
* its own.
|
|
467
|
+
*
|
|
468
|
+
* Resolves once all of it is in the chat, so a tool can post below it.
|
|
469
|
+
*/
|
|
470
|
+
function sendReply(state, turnClosed = false) {
|
|
471
|
+
const text = state.reply.join('\n\n');
|
|
472
|
+
state.reply = [];
|
|
473
|
+
if (text)
|
|
474
|
+
state.postedInTurn = true;
|
|
475
|
+
const closes = turnClosed && state.postedInTurn;
|
|
476
|
+
if (turnClosed)
|
|
477
|
+
state.postedInTurn = false;
|
|
478
|
+
if (!text && !closes)
|
|
479
|
+
return state.replySent;
|
|
480
|
+
// What the card shows happened before this. Sealed, the card stays above
|
|
481
|
+
// it, and whatever happens next starts a fresh card below.
|
|
482
|
+
sealCard(state.sessionKey);
|
|
483
|
+
const { sessionKey } = state;
|
|
484
|
+
state.replySent = state.replySent.then(async () => {
|
|
485
|
+
if (text)
|
|
486
|
+
await postReply(sessionKey, text);
|
|
487
|
+
if (closes)
|
|
488
|
+
await postStatusLine(sessionKey);
|
|
489
|
+
});
|
|
490
|
+
return state.replySent;
|
|
491
|
+
}
|
|
492
|
+
async function postReply(sessionKey, text) {
|
|
493
|
+
if (!botRef)
|
|
494
|
+
return;
|
|
495
|
+
const ctx = buildSyntheticCtx({ api: botRef.api, sessionKey, syntheticText: '' });
|
|
496
|
+
try {
|
|
497
|
+
// Imported lazily, as mcp-bridge does: this module is loaded from
|
|
498
|
+
// pty-provider at module scope, where every eager edge is a chance to
|
|
499
|
+
// close a cycle back through it.
|
|
500
|
+
const { messageSender } = await import('../telegram/message-sender.js');
|
|
501
|
+
await messageSender.sendMessage(ctx, text);
|
|
502
|
+
}
|
|
503
|
+
catch (err) {
|
|
504
|
+
console.error('[Monitor] reply send failed:', err instanceof Error ? err.message : err);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
/** Close a turn claude started itself the way the turn pipeline closes one of ours. */
|
|
508
|
+
async function postStatusLine(sessionKey) {
|
|
509
|
+
if (!botRef)
|
|
510
|
+
return;
|
|
511
|
+
const ctx = buildSyntheticCtx({ api: botRef.api, sessionKey, syntheticText: '' });
|
|
512
|
+
try {
|
|
513
|
+
// Lazy like the import above, and with more reason: the handler layer
|
|
514
|
+
// imports the provider that loads this module.
|
|
515
|
+
const { closeSelfStartedTurn } = await import('../bot/handlers/message/turn-notify.js');
|
|
516
|
+
await closeSelfStartedTurn(ctx, sessionKey);
|
|
517
|
+
}
|
|
518
|
+
catch (err) {
|
|
519
|
+
console.error('[Monitor] status line send failed:', err instanceof Error ? err.message : err);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
function extractAssistantText(content) {
|
|
523
|
+
if (typeof content === 'string')
|
|
524
|
+
return content.trim();
|
|
525
|
+
if (!Array.isArray(content))
|
|
526
|
+
return '';
|
|
527
|
+
return content
|
|
528
|
+
.filter((b) => !!b && typeof b === 'object' && b.type === 'text' && typeof b.text === 'string')
|
|
529
|
+
.map((b) => b.text.trim())
|
|
530
|
+
.filter((t) => t.length > 0)
|
|
531
|
+
.join('\n\n');
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Relay claude's PushNotification tool to Telegram. The native tool fires
|
|
535
|
+
* an OS-level notification on the bot host (no real user is sitting there)
|
|
536
|
+
* so the only useful surface is Telegram. Called from PreToolUse and treated
|
|
537
|
+
* independently of the JSONL watcher — push notifications are single-shot
|
|
538
|
+
* and don't need turn-end pairing.
|
|
539
|
+
*/
|
|
540
|
+
export function relayPushNotification(sessionKey, message) {
|
|
541
|
+
if (!botRef)
|
|
542
|
+
return;
|
|
543
|
+
const trimmed = message.trim();
|
|
544
|
+
if (!trimmed)
|
|
545
|
+
return;
|
|
546
|
+
const { chatId, threadId } = parseSessionKey(sessionKey);
|
|
547
|
+
const threadOpts = threadId !== undefined ? { message_thread_id: threadId } : {};
|
|
548
|
+
const preview = trimmed.length > 500 ? trimmed.slice(0, 497) + '...' : trimmed;
|
|
549
|
+
sendFormatted(chatId, threadOpts, `🔔 ${preview}`, 'push').catch(() => { });
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Called when a task-notification's status indicates the task is done.
|
|
553
|
+
* Retires the task from the card's running list and records how it ended.
|
|
554
|
+
*
|
|
555
|
+
* Whether that gets the user's attention is the card's call: a failure is
|
|
556
|
+
* urgent enough to re-post immediately, a task that ran past the notification
|
|
557
|
+
* threshold is worth a ping if the card has been sitting a while, and a quick
|
|
558
|
+
* success just folds into the card silently.
|
|
559
|
+
*
|
|
560
|
+
* Returns true when the notification was consumed as a completion; the caller
|
|
561
|
+
* then skips the monitor-event path so we don't double-report.
|
|
562
|
+
*/
|
|
563
|
+
function handleTerminalNotification(state, notif) {
|
|
564
|
+
const armed = state.armedTasks.get(notif.toolUseId);
|
|
565
|
+
if (!armed)
|
|
566
|
+
return false;
|
|
567
|
+
state.armedTasks.delete(notif.toolUseId);
|
|
568
|
+
// Retire the tracker entry before any chat I/O, mirroring the SDK path's
|
|
569
|
+
// remove-after-notification. /tasks filters to running/pending, so dropping
|
|
570
|
+
// it outright is equivalent to recording a terminal status.
|
|
571
|
+
taskTracker.remove(state.sessionKey, notif.toolUseId);
|
|
572
|
+
const elapsedMs = Date.now() - armed.startedAt;
|
|
573
|
+
const isError = notif.status === 'failed' || notif.status === 'killed';
|
|
574
|
+
const longRunning = elapsedMs >= config.NOTIFICATION_THRESHOLD_SECONDS * 1000;
|
|
575
|
+
noteTaskFinished(state.sessionKey, notif.toolUseId, { kind: armed.kind, description: armed.description, status: notif.status, elapsedMs }, { notify: isError || longRunning, urgent: isError });
|
|
576
|
+
return true;
|
|
577
|
+
}
|
|
578
|
+
function stripSummaryPrefix(summary) {
|
|
579
|
+
// Claude code formats summaries as `Monitor event: "<desc>"` — strip the
|
|
580
|
+
// boilerplate so the header isn't redundant with the "📡 Monitor" prefix.
|
|
581
|
+
return summary.replace(/^Monitor event:\s*/i, '').replace(/^"(.*)"$/, '$1').trim();
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Put a monitor firing on the card as it lands. What claude says about it is
|
|
585
|
+
* its turn's reply, sent when the turn closes.
|
|
586
|
+
*/
|
|
587
|
+
function postMonitorEvent(sessionKey, notif) {
|
|
588
|
+
const summary = notif.summary ? stripSummaryPrefix(notif.summary) : '';
|
|
589
|
+
// The footer under a running turn's status line shows it too, beside
|
|
590
|
+
// the task it came from.
|
|
591
|
+
taskTracker.noteUpdate(sessionKey, notif.toolUseId, summary || notif.event.split('\n')[0]);
|
|
592
|
+
// A monitor firing is the whole reason the user armed it, so it always
|
|
593
|
+
// wants the user's attention — the card decides whether that means a fresh
|
|
594
|
+
// message or a silent edit onto one it posted moments ago.
|
|
595
|
+
noteMonitorEvent(sessionKey, summary, notif.event, { notify: true });
|
|
596
|
+
}
|
|
597
|
+
//# sourceMappingURL=monitor-relay.js.map
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pending-fork storage. When a user forks a conversation from Bot A to Bot B,
|
|
3
|
+
* Bot A writes the truncated transcript here keyed by Bot B's id. Bot B picks
|
|
4
|
+
* it up on the next user message and offers accept/decline.
|
|
5
|
+
*
|
|
6
|
+
* File: ~/.telecoder/pending-forks-<targetBotId>.json
|
|
7
|
+
* Structure: { users: { [userId]: PendingFork } } — keyed by the Telegram
|
|
8
|
+
* user id, not the chatId, because each bot has its own private DM with the
|
|
9
|
+
* user (different chatId per bot). Routing by user id lets a fork from a
|
|
10
|
+
* DM with Bot A land in the DM with Bot B without either side knowing the
|
|
11
|
+
* other's chatId. The target bot's chat resolves when the user actually
|
|
12
|
+
* messages it — wherever they message from, that's where the offer shows up.
|
|
13
|
+
*
|
|
14
|
+
* Cross-bot handoff is via the shared `~/.telecoder/` dir on disk — every
|
|
15
|
+
* worker on this machine can read/write any bot's file. The target worker
|
|
16
|
+
* doesn't get a live notification; it polls on each incoming user message.
|
|
17
|
+
*/
|
|
18
|
+
import * as path from 'path';
|
|
19
|
+
import { z } from 'zod';
|
|
20
|
+
import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
|
|
21
|
+
const HISTORY_DIR = getStateDir();
|
|
22
|
+
const pendingForkSchema = z.object({
|
|
23
|
+
fromBotName: z.string(),
|
|
24
|
+
fromBotId: z.string(),
|
|
25
|
+
/** Source chat the fork was created in — informational, not used for routing. */
|
|
26
|
+
fromChatId: z.number().optional(),
|
|
27
|
+
projectPath: z.string(),
|
|
28
|
+
// The truncated JSONL content, inline. JSONL is small (<1 MB even for very
|
|
29
|
+
// long conversations) so inlining is cheaper than a separate file with its
|
|
30
|
+
// own lifecycle.
|
|
31
|
+
jsonl: z.string(),
|
|
32
|
+
topic: z.string().optional(),
|
|
33
|
+
assistantPreview: z.string().optional(),
|
|
34
|
+
createdAt: z.string(),
|
|
35
|
+
/** Set to true once the target bot has proactively notified the user. The
|
|
36
|
+
* lazy in-message path still works regardless; this flag just prevents
|
|
37
|
+
* the proactive watcher from spamming on every file change / restart. */
|
|
38
|
+
offered: z.boolean().optional(),
|
|
39
|
+
});
|
|
40
|
+
const fileSchema = z.object({
|
|
41
|
+
users: z.record(z.string(), pendingForkSchema),
|
|
42
|
+
});
|
|
43
|
+
function pathFor(botId) {
|
|
44
|
+
return path.join(HISTORY_DIR, `pending-forks-${botId}.json`);
|
|
45
|
+
}
|
|
46
|
+
function loadFile(botId) {
|
|
47
|
+
return readJsonFile(pathFor(botId), fileSchema, 'PendingForks') ?? { users: {} };
|
|
48
|
+
}
|
|
49
|
+
// rethrow: callers confirm "Forked." to the user immediately after writing, so
|
|
50
|
+
// a swallowed failure would report a handoff that never landed on disk.
|
|
51
|
+
function saveFile(botId, data) {
|
|
52
|
+
ensureStateDir(HISTORY_DIR, 'PendingForks');
|
|
53
|
+
writeJsonFile(pathFor(botId), data, 'PendingForks', { rethrow: true });
|
|
54
|
+
}
|
|
55
|
+
/** Write a pending fork to the target bot's file, replacing any existing one for this user. */
|
|
56
|
+
export function putPendingFork(targetBotId, userId, fork) {
|
|
57
|
+
const data = loadFile(targetBotId);
|
|
58
|
+
data.users[String(userId)] = fork;
|
|
59
|
+
saveFile(targetBotId, data);
|
|
60
|
+
}
|
|
61
|
+
/** Read the pending fork for this (target bot, user), if any. */
|
|
62
|
+
export function getPendingFork(targetBotId, userId) {
|
|
63
|
+
const data = loadFile(targetBotId);
|
|
64
|
+
return data.users[String(userId)];
|
|
65
|
+
}
|
|
66
|
+
/** Remove the pending fork for this (target bot, user). No-op if missing. */
|
|
67
|
+
export function removePendingFork(targetBotId, userId) {
|
|
68
|
+
const data = loadFile(targetBotId);
|
|
69
|
+
if (!(String(userId) in data.users))
|
|
70
|
+
return;
|
|
71
|
+
delete data.users[String(userId)];
|
|
72
|
+
saveFile(targetBotId, data);
|
|
73
|
+
}
|
|
74
|
+
/** Flag a fork as already-offered so the proactive watcher won't re-send it. */
|
|
75
|
+
export function markForkOffered(targetBotId, userId) {
|
|
76
|
+
const data = loadFile(targetBotId);
|
|
77
|
+
const entry = data.users[String(userId)];
|
|
78
|
+
if (!entry)
|
|
79
|
+
return;
|
|
80
|
+
if (entry.offered)
|
|
81
|
+
return;
|
|
82
|
+
data.users[String(userId)] = { ...entry, offered: true };
|
|
83
|
+
saveFile(targetBotId, data);
|
|
84
|
+
}
|
|
85
|
+
/** Return all pending forks for a bot, keyed by userId (string). */
|
|
86
|
+
export function listPendingForks(targetBotId) {
|
|
87
|
+
return loadFile(targetBotId).users;
|
|
88
|
+
}
|
|
89
|
+
/** Path that contains pending forks for this bot — useful for file watching. */
|
|
90
|
+
export function pendingForksPathFor(targetBotId) {
|
|
91
|
+
return pathFor(targetBotId);
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=pending-forks.js.map
|