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,705 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `telecoder init` wizard, free of the terminal and the network: the
|
|
3
|
+
* prompts come through a Prompter and Telegram through a TelegramClient, so the
|
|
4
|
+
* tests drive the whole flow with fakes. commands/init.ts wires up the real ones.
|
|
5
|
+
*
|
|
6
|
+
* The steps: check the machine (doctor's checks), decide what to do with an
|
|
7
|
+
* existing .env, get and check the bot token, find the owner's id by having
|
|
8
|
+
* them message the bot, pick a workspace, two optional
|
|
9
|
+
* features, write the file, and have the bot say hello.
|
|
10
|
+
*
|
|
11
|
+
* Telegram is reached through the proxy the bot would use, when there is one:
|
|
12
|
+
* TELEGRAM_PROXY_URL or the usual proxy variables, from the environment or
|
|
13
|
+
* the .env being edited. One from the environment is written to the .env.
|
|
14
|
+
*
|
|
15
|
+
* Secrets are never printed: not the token, not the Groq key, not a proxy's
|
|
16
|
+
* password, not in errors (telegram.ts redacts those) and not in the summary
|
|
17
|
+
* before writing.
|
|
18
|
+
*/
|
|
19
|
+
import * as fs from 'fs';
|
|
20
|
+
import * as path from 'path';
|
|
21
|
+
import { parse as parseEnv } from 'dotenv';
|
|
22
|
+
import { isWellFormedBotToken, MALFORMED_TOKEN_MESSAGE, REJECTED_TOKEN_MESSAGE } from '../../utils/bot-token.js';
|
|
23
|
+
import { BOT_ICON_FILENAME, botIconJpeg } from '../../utils/bot-icon.js';
|
|
24
|
+
import { parseIdList } from '../../utils/id-list.js';
|
|
25
|
+
import { redactSecrets } from '../../utils/sanitize.js';
|
|
26
|
+
import { findProxy } from '../../utils/telegram-proxy.js';
|
|
27
|
+
import { backupFile, renderEnv, updateEnvText, writeEnvFile } from './env-file.js';
|
|
28
|
+
import { isAbort } from './prompter.js';
|
|
29
|
+
import { TelegramApiError, TelegramNetworkError, } from './telegram.js';
|
|
30
|
+
/** Why the wizard stopped without finishing. The message is for the user. */
|
|
31
|
+
class Stop extends Error {
|
|
32
|
+
code;
|
|
33
|
+
constructor(message, code = 1) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.code = code;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const ICON = { ok: '✓', warn: '!', fail: '✗' };
|
|
39
|
+
/** What the bot answers a /start while the wizard waits for the owner's. */
|
|
40
|
+
export const OWNER_CAPTURED_REPLY = '👋 Got it. Back in your terminal, confirm it\'s you to finish setting up.';
|
|
41
|
+
/** The hello the bot sends at the end: the start command set as code. */
|
|
42
|
+
export function testMessage(startCommand) {
|
|
43
|
+
const before = '✅ TeleCoder is set up. Start it with ';
|
|
44
|
+
return {
|
|
45
|
+
text: `${before}${startCommand}.`,
|
|
46
|
+
// String length is UTF-16 units, which is what Telegram's offsets count.
|
|
47
|
+
entities: [{ type: 'code', offset: before.length, length: startCommand.length }],
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export async function runInit(opts, rawDeps) {
|
|
51
|
+
const deps = { ...rawDeps, prompter: collapseBlankLines(rawDeps.prompter) };
|
|
52
|
+
const p = deps.prompter;
|
|
53
|
+
const interactive = p.interactive && !opts.yes;
|
|
54
|
+
let wrote = false;
|
|
55
|
+
try {
|
|
56
|
+
await wizard(opts, deps, interactive, () => { wrote = true; });
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (isAbort(error)) {
|
|
61
|
+
p.say('');
|
|
62
|
+
p.say(wrote ? 'Cancelled.' : 'Cancelled. Nothing was written.');
|
|
63
|
+
return 130;
|
|
64
|
+
}
|
|
65
|
+
if (error instanceof Stop) {
|
|
66
|
+
if (error.message)
|
|
67
|
+
p.say(error.message);
|
|
68
|
+
return error.code;
|
|
69
|
+
}
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The steps end with a blank line each; when one asked nothing (a flag or a
|
|
75
|
+
* kept value answered it) that would leave a stack of them.
|
|
76
|
+
*/
|
|
77
|
+
function collapseBlankLines(p) {
|
|
78
|
+
let blank = true;
|
|
79
|
+
const answered = (pending) => { blank = false; return pending; };
|
|
80
|
+
return {
|
|
81
|
+
interactive: p.interactive,
|
|
82
|
+
signal: p.signal,
|
|
83
|
+
say: (line = '') => {
|
|
84
|
+
if (line === '' && blank)
|
|
85
|
+
return;
|
|
86
|
+
blank = line === '';
|
|
87
|
+
p.say(line);
|
|
88
|
+
},
|
|
89
|
+
ask: (q, o) => answered(p.ask(q, o)),
|
|
90
|
+
secret: (q) => answered(p.secret(q)),
|
|
91
|
+
confirm: (q, d) => answered(p.confirm(q, d)),
|
|
92
|
+
choose: (q, c, d) => answered(p.choose(q, c, d)),
|
|
93
|
+
runAttached: (cmd, args) => { blank = false; return p.runAttached(cmd, args); },
|
|
94
|
+
close: () => p.close(),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
async function wizard(opts, deps, interactive, markWritten) {
|
|
98
|
+
const p = deps.prompter;
|
|
99
|
+
const startCommand = deps.isCheckout ? 'npm start' : 'telecoder start';
|
|
100
|
+
p.say('TeleCoder setup');
|
|
101
|
+
p.say('');
|
|
102
|
+
// ── 1. The machine ──────────────────────────────────────────
|
|
103
|
+
const pre = await deps.preflight();
|
|
104
|
+
const show = (r) => {
|
|
105
|
+
p.say(`${ICON[r.status]} ${r.label}`);
|
|
106
|
+
for (const line of r.detail ?? [])
|
|
107
|
+
p.say(` ${line}`);
|
|
108
|
+
};
|
|
109
|
+
show(pre.node);
|
|
110
|
+
if (pre.node.status === 'fail')
|
|
111
|
+
throw new Stop('\nInstall a newer Node.js, then run "telecoder init" again.');
|
|
112
|
+
for (const r of pre.claude)
|
|
113
|
+
show(r);
|
|
114
|
+
if (pre.claude[0]?.status === 'fail') {
|
|
115
|
+
throw new Stop('\nTeleCoder drives Claude Code, so it has to be installed first. Then run "telecoder init" again.');
|
|
116
|
+
}
|
|
117
|
+
if (pre.claude[1]?.status === 'fail')
|
|
118
|
+
await offerLogin(deps, interactive);
|
|
119
|
+
const claudeLogin = await stepEnvLogin(deps, interactive, pre.envLogin ?? []);
|
|
120
|
+
for (const r of pre.nodePty)
|
|
121
|
+
show(r);
|
|
122
|
+
const ptyWorks = pre.nodePty.every((r) => r.status === 'ok');
|
|
123
|
+
if (!ptyWorks)
|
|
124
|
+
p.say(' TeleCoder drives Claude Code in a pty, so chats will fail until it loads.');
|
|
125
|
+
p.say('');
|
|
126
|
+
// ── 2. An existing .env ─────────────────────────────────────
|
|
127
|
+
let existing = {};
|
|
128
|
+
let existingText;
|
|
129
|
+
if (fs.existsSync(deps.envPath)) {
|
|
130
|
+
existingText = fs.readFileSync(deps.envPath, 'utf-8');
|
|
131
|
+
if (!interactive) {
|
|
132
|
+
if (!opts.yes) {
|
|
133
|
+
throw new Stop(`${deps.envPath} already exists. Run "telecoder init" in a terminal to edit it, ` +
|
|
134
|
+
'or pass --yes to replace it (the old one is kept as a backup).');
|
|
135
|
+
}
|
|
136
|
+
existingText = undefined;
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
p.say(`There is already a config at ${deps.envPath}.`);
|
|
140
|
+
const choice = await p.choose('What do you want to do?', [
|
|
141
|
+
{ key: 'keep', label: 'Keep it as it is, and stop here' },
|
|
142
|
+
{ key: 'edit', label: 'Go through the setup with its values as the defaults' },
|
|
143
|
+
{ key: 'over', label: 'Start over with a new file' },
|
|
144
|
+
], 'keep');
|
|
145
|
+
if (choice === 'keep')
|
|
146
|
+
throw new Stop(`Kept ${deps.envPath} as it is. "telecoder doctor" checks it.`, 0);
|
|
147
|
+
if (choice === 'edit')
|
|
148
|
+
existing = parseEnv(existingText);
|
|
149
|
+
else
|
|
150
|
+
existingText = undefined;
|
|
151
|
+
}
|
|
152
|
+
const backup = backupFile(deps.envPath, deps.now?.());
|
|
153
|
+
p.say(`Backed up the current file to ${backup}`);
|
|
154
|
+
p.say('');
|
|
155
|
+
}
|
|
156
|
+
const editing = existingText !== undefined;
|
|
157
|
+
// The proxy the bot would use: the environment wins over the file, as it
|
|
158
|
+
// does there.
|
|
159
|
+
const proxy = findProxy((setting) => deps.env[setting] ?? existing[setting]);
|
|
160
|
+
// One that only the shell has is gone when a service starts the bot.
|
|
161
|
+
const saveProxy = proxy !== undefined && deps.env[proxy.setting] !== undefined
|
|
162
|
+
&& existing.TELEGRAM_PROXY_URL !== proxy.url;
|
|
163
|
+
if (proxy) {
|
|
164
|
+
const from = deps.env[proxy.setting] !== undefined ? "your shell's environment" : 'the current .env';
|
|
165
|
+
p.say(`Reaching Telegram through the proxy ${redactSecrets(proxy.url)} (${proxy.setting} in ${from}).`);
|
|
166
|
+
if (saveProxy) {
|
|
167
|
+
p.say(' A service starts TeleCoder outside your shell, so the proxy goes in the .env too, as TELEGRAM_PROXY_URL.');
|
|
168
|
+
}
|
|
169
|
+
p.say('');
|
|
170
|
+
}
|
|
171
|
+
// ── 3. Bot token ────────────────────────────────────────────
|
|
172
|
+
const { token, bot, client } = await stepToken(opts, deps, interactive, editing ? existing.TELEGRAM_BOT_TOKEN : undefined, proxy?.url);
|
|
173
|
+
p.say(`Connected to @${bot.username}`);
|
|
174
|
+
p.say('');
|
|
175
|
+
// ── 4. Owner ────────────────────────────────────────────────
|
|
176
|
+
const owner = await stepOwner(opts, deps, interactive, client, bot, editing ? existing.ALLOWED_USER_IDS : undefined, Boolean(existing.ADMIN_USER_IDS || existing.APPROVER_USER_IDS));
|
|
177
|
+
p.say('');
|
|
178
|
+
// ── 5. Workspace ────────────────────────────────────────────
|
|
179
|
+
const workspace = await stepWorkspace(opts, deps, interactive, editing ? existing.WORKSPACE_DIR : undefined);
|
|
180
|
+
p.say('');
|
|
181
|
+
// ── 6. Optional features ────────────────────────────────────
|
|
182
|
+
const groqKey = await stepVoice(opts, deps, interactive, editing ? existing.GROQ_API_KEY : undefined);
|
|
183
|
+
const icon = await stepIcon(opts, client, bot);
|
|
184
|
+
p.say('');
|
|
185
|
+
// ── 7. Write ────────────────────────────────────────────────
|
|
186
|
+
const values = {
|
|
187
|
+
TELEGRAM_BOT_TOKEN: token,
|
|
188
|
+
ALLOWED_USER_IDS: owner.idList,
|
|
189
|
+
WORKSPACE_DIR: workspace,
|
|
190
|
+
};
|
|
191
|
+
Object.assign(values, claudeLogin);
|
|
192
|
+
if (groqKey)
|
|
193
|
+
values.GROQ_API_KEY = groqKey;
|
|
194
|
+
if (proxy && saveProxy)
|
|
195
|
+
values.TELEGRAM_PROXY_URL = proxy.url;
|
|
196
|
+
p.say(`About to write ${deps.envPath}:`);
|
|
197
|
+
p.say(` Bot @${bot.username} (token hidden)`);
|
|
198
|
+
p.say(` Allowed users ${owner.idList}`);
|
|
199
|
+
p.say(` Workspace ${workspace}`);
|
|
200
|
+
for (const key of Object.keys(claudeLogin))
|
|
201
|
+
p.say(` Claude login ${key}=<hidden>`);
|
|
202
|
+
p.say(` Voice ${groqKey ? 'on (Groq key hidden)' : 'off (run telecoder init again to add it)'}`);
|
|
203
|
+
if (proxy && saveProxy)
|
|
204
|
+
p.say(` Proxy ${redactSecrets(proxy.url)}`);
|
|
205
|
+
if (icon)
|
|
206
|
+
p.say(' Bot picture the TeleCoder icon (--no-icon to skip)');
|
|
207
|
+
if (interactive && !await p.confirm('Write it?', true))
|
|
208
|
+
throw new Stop('Nothing was written.', 1);
|
|
209
|
+
let content;
|
|
210
|
+
if (existingText !== undefined) {
|
|
211
|
+
const updates = {};
|
|
212
|
+
for (const [key, value] of Object.entries(values))
|
|
213
|
+
if (existing[key] !== value)
|
|
214
|
+
updates[key] = value;
|
|
215
|
+
if (!groqKey && existing.GROQ_API_KEY)
|
|
216
|
+
updates.GROQ_API_KEY = undefined;
|
|
217
|
+
content = updateEnvText(existingText, updates);
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
content = renderEnv(values);
|
|
221
|
+
}
|
|
222
|
+
writeEnvFile(deps.envPath, content, { ownDir: deps.ownDir });
|
|
223
|
+
markWritten();
|
|
224
|
+
p.say(`✓ Wrote ${deps.envPath} (readable by you only)`);
|
|
225
|
+
if (owner.otherRoles) {
|
|
226
|
+
p.say('! ADMIN_USER_IDS / APPROVER_USER_IDS are set in this file: check they are still in ALLOWED_USER_IDS.');
|
|
227
|
+
}
|
|
228
|
+
if (icon) {
|
|
229
|
+
try {
|
|
230
|
+
await client.setProfilePhoto(botIconJpeg(), BOT_ICON_FILENAME);
|
|
231
|
+
p.say(`✓ Gave @${bot.username} the TeleCoder icon`);
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
p.say(`! Couldn't set the bot's picture: ${describeTelegramError(error)}`);
|
|
235
|
+
p.say(' The bot works without one. @BotFather can set a picture too: Edit Bot, then Edit Botpic.');
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
// ── 9. Hello, and what next ─────────────────────────────────
|
|
239
|
+
if (!opts.noTestMessage) {
|
|
240
|
+
try {
|
|
241
|
+
const hello = testMessage(startCommand);
|
|
242
|
+
await client.sendMessage(owner.id, hello.text, hello.entities);
|
|
243
|
+
p.say('✓ Sent you a test message on Telegram');
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
p.say(`! Couldn't send you a test message: ${describeTelegramError(error)}`);
|
|
247
|
+
if (error instanceof TelegramApiError && error.code === 403) {
|
|
248
|
+
p.say(` Open https://t.me/${bot.username} and press Start, so the bot is allowed to message you.`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
p.say('');
|
|
253
|
+
p.say('Now:');
|
|
254
|
+
p.say(` ${startCommand.padEnd(18)}run the bot, then message it on Telegram`);
|
|
255
|
+
p.say(` ${'telecoder doctor'.padEnd(18)}check the setup again any time`);
|
|
256
|
+
// A checkout runs under pm2; the service is for npm installs.
|
|
257
|
+
if (interactive && deps.requestService && !deps.isCheckout) {
|
|
258
|
+
const plan = deps.planService ? await deps.planService() : undefined;
|
|
259
|
+
if (plan && !plan.ready) {
|
|
260
|
+
// Nothing to approve: say what stands in the way instead of asking.
|
|
261
|
+
p.say('');
|
|
262
|
+
p.say(plan.manager ? `! telecoder service install would set up ${plan.lines[0]}` : `! ${plan.lines[0]}`);
|
|
263
|
+
for (const line of plan.lines.slice(1))
|
|
264
|
+
p.say(` ${line}`);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
let question = 'Keep it running in the background now (telecoder service install)?';
|
|
268
|
+
if (plan) {
|
|
269
|
+
p.say('');
|
|
270
|
+
p.say(`telecoder service install keeps it running in the background. Here that is ${plan.lines[0]}`);
|
|
271
|
+
for (const line of plan.lines.slice(1))
|
|
272
|
+
p.say(` ${line}`);
|
|
273
|
+
question = `Set up the ${plan.manager === 'launchd' ? 'LaunchAgent' : 'systemd service'} now?`;
|
|
274
|
+
}
|
|
275
|
+
if (await p.confirm(question, true)) {
|
|
276
|
+
deps.requestService();
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
p.say('Next: run `telecoder service install` to keep it running in the background.');
|
|
281
|
+
}
|
|
282
|
+
// ── Steps ─────────────────────────────────────────────────────
|
|
283
|
+
async function offerLogin(deps, interactive) {
|
|
284
|
+
const p = deps.prompter;
|
|
285
|
+
p.say(' TeleCoder answers as your Claude Code login, so it needs one. Either:');
|
|
286
|
+
p.say(' - run "claude auth login" (or "claude", then /login) as the user the bot runs as, or');
|
|
287
|
+
p.say(' - on a machine you won\'t sign in on, run "claude setup-token" and put the token it');
|
|
288
|
+
p.say(' prints in CLAUDE_CODE_OAUTH_TOKEN; or set ANTHROPIC_API_KEY (billed per use).');
|
|
289
|
+
if (!interactive) {
|
|
290
|
+
p.say(' Carrying on: the bot will start without it, but can\'t answer until it has one.');
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (await p.confirm('Log in now? (runs "claude auth login")', true)) {
|
|
294
|
+
const status = p.runAttached(deps.claudeBin, ['auth', 'login']);
|
|
295
|
+
p.say(status === 0 ? '✓ Logged in' : '! The login didn\'t finish; carrying on. Run "claude auth login" later.');
|
|
296
|
+
}
|
|
297
|
+
else {
|
|
298
|
+
p.say(' Carrying on without it.');
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* A login in the shell's environment works for the wizard and for
|
|
303
|
+
* `telecoder start` from this shell, but a service starts without it. Offer
|
|
304
|
+
* to keep the variables in the .env, which the bot loads. The values are
|
|
305
|
+
* never printed.
|
|
306
|
+
*/
|
|
307
|
+
async function stepEnvLogin(deps, interactive, vars) {
|
|
308
|
+
const p = deps.prompter;
|
|
309
|
+
const found = vars.filter((key) => deps.env[key]?.trim());
|
|
310
|
+
if (!found.length)
|
|
311
|
+
return {};
|
|
312
|
+
const names = found.join(' and ');
|
|
313
|
+
p.say(`! Claude Code logs in with ${names} from your shell's environment.`);
|
|
314
|
+
p.say(` When TeleCoder runs as a service, it starts outside your shell and doesn't have ${names}, so Claude Code would be logged out.`);
|
|
315
|
+
p.say(` The wizard can put ${names} in TeleCoder's .env, so TeleCoder always has it.`);
|
|
316
|
+
const save = interactive
|
|
317
|
+
? await p.confirm(`Save ${names} in the .env too (readable by you only)?`, true)
|
|
318
|
+
: true;
|
|
319
|
+
if (!save) {
|
|
320
|
+
p.say(` Not saving it: the bot only logs in where ${names} is set.`);
|
|
321
|
+
return {};
|
|
322
|
+
}
|
|
323
|
+
if (!interactive)
|
|
324
|
+
p.say(` ${names} will go in the .env too (readable by you only), so a service can log in.`);
|
|
325
|
+
return Object.fromEntries(found.map((key) => [key, deps.env[key].trim()]));
|
|
326
|
+
}
|
|
327
|
+
/** Pasted tokens come with stray whitespace or quotes more often than not. */
|
|
328
|
+
export function cleanToken(raw) {
|
|
329
|
+
return raw.trim().replace(/^(['"])(.*)\1$/, '$2').trim();
|
|
330
|
+
}
|
|
331
|
+
async function stepToken(opts, deps, interactive, current, proxyUrl) {
|
|
332
|
+
const p = deps.prompter;
|
|
333
|
+
const check = async (token) => {
|
|
334
|
+
const client = deps.makeClient(token, proxyUrl);
|
|
335
|
+
const bot = await client.getMe();
|
|
336
|
+
return { token, bot, client };
|
|
337
|
+
};
|
|
338
|
+
if (opts.tokenEnv) {
|
|
339
|
+
const token = cleanToken(deps.env[opts.tokenEnv] ?? '');
|
|
340
|
+
if (!token)
|
|
341
|
+
throw new Stop(`--token-env ${opts.tokenEnv}: that environment variable is empty or not set.`);
|
|
342
|
+
if (!isWellFormedBotToken(token))
|
|
343
|
+
throw new Stop(MALFORMED_TOKEN_MESSAGE);
|
|
344
|
+
try {
|
|
345
|
+
return await check(token);
|
|
346
|
+
}
|
|
347
|
+
catch (error) {
|
|
348
|
+
throw new Stop(describeFirstCallError(error));
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
if (!interactive) {
|
|
352
|
+
throw new Stop('No bot token: pass --token-env VAR, naming an environment variable that holds it ' +
|
|
353
|
+
'(not the token itself: arguments show up in ps). Or run "telecoder init" in a terminal.');
|
|
354
|
+
}
|
|
355
|
+
if (current && isWellFormedBotToken(current)) {
|
|
356
|
+
try {
|
|
357
|
+
const found = await check(current);
|
|
358
|
+
if (await p.confirm(`Keep the current token, for @${found.bot.username}?`, true))
|
|
359
|
+
return found;
|
|
360
|
+
}
|
|
361
|
+
catch (error) {
|
|
362
|
+
p.say(`The current token doesn't work: ${describeFirstCallError(error)}`);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
p.say('Bot token. If you don\'t have a bot yet:');
|
|
366
|
+
p.say(' 1. In Telegram, open @BotFather (https://t.me/BotFather) and send /newbot.');
|
|
367
|
+
p.say(' 2. Pick a display name, then a username ending in "bot".');
|
|
368
|
+
p.say(' 3. It replies with a token like 1234567890:AAH…: copy it and paste it here.');
|
|
369
|
+
for (;;) {
|
|
370
|
+
const token = cleanToken(await p.secret('Bot token:'));
|
|
371
|
+
if (!token)
|
|
372
|
+
continue;
|
|
373
|
+
if (!isWellFormedBotToken(token)) {
|
|
374
|
+
p.say(MALFORMED_TOKEN_MESSAGE);
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
for (;;) {
|
|
378
|
+
try {
|
|
379
|
+
return await check(token);
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
p.say(describeFirstCallError(error));
|
|
383
|
+
if (error instanceof TelegramNetworkError && await p.confirm('Try again?', true))
|
|
384
|
+
continue;
|
|
385
|
+
break;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
async function stepOwner(opts, deps, interactive, client, bot, current, hasRoles) {
|
|
391
|
+
const p = deps.prompter;
|
|
392
|
+
// Telegram doesn't deliver updates to getUpdates — or to the bot — while a
|
|
393
|
+
// webhook is set, so look first.
|
|
394
|
+
const webhookOk = await checkWebhook(deps, interactive, client, opts.yes ?? false);
|
|
395
|
+
if (opts.ownerId !== undefined) {
|
|
396
|
+
const id = parseOwnerId(opts.ownerId);
|
|
397
|
+
if (typeof id === 'string')
|
|
398
|
+
throw new Stop(`--owner-id: ${id}`);
|
|
399
|
+
return { id, idList: String(id) };
|
|
400
|
+
}
|
|
401
|
+
if (!interactive) {
|
|
402
|
+
throw new Stop('No owner: pass --owner-id with your numeric Telegram user id. Or run "telecoder init" in a terminal, ' +
|
|
403
|
+
'which finds it when you message the bot.');
|
|
404
|
+
}
|
|
405
|
+
if (current) {
|
|
406
|
+
const parsed = parseIdList('ALLOWED_USER_IDS', current);
|
|
407
|
+
if (parsed.ok && parsed.ids.length && await p.confirm(`Keep the allowed users, ${parsed.ids.join(', ')}?`, true)) {
|
|
408
|
+
return { id: parsed.ids[0], idList: parsed.ids.join(',') };
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
const otherRoles = hasRoles;
|
|
412
|
+
p.say('Who owns this bot: TeleCoder only answers the Telegram accounts you allow.');
|
|
413
|
+
if (webhookOk) {
|
|
414
|
+
const captured = await captureOwner(deps, client, bot);
|
|
415
|
+
if (captured)
|
|
416
|
+
return { id: captured, idList: String(captured), otherRoles };
|
|
417
|
+
}
|
|
418
|
+
for (;;) {
|
|
419
|
+
const answer = await p.ask('Your numeric Telegram user id (message @userinfobot to get it):');
|
|
420
|
+
const id = parseOwnerId(answer);
|
|
421
|
+
if (typeof id === 'number')
|
|
422
|
+
return { id, idList: String(id), otherRoles };
|
|
423
|
+
p.say(id);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
/** A user id, or why it isn't one. */
|
|
427
|
+
export function parseOwnerId(raw) {
|
|
428
|
+
const trimmed = raw.trim();
|
|
429
|
+
if (!trimmed)
|
|
430
|
+
return 'Type the number, like 412345678.';
|
|
431
|
+
const parsed = parseIdList('ALLOWED_USER_IDS', trimmed);
|
|
432
|
+
if (!parsed.ok)
|
|
433
|
+
return parsed.error;
|
|
434
|
+
if (parsed.ids.length !== 1 || parsed.ids[0] <= 0)
|
|
435
|
+
return 'One user id, a positive number like 412345678.';
|
|
436
|
+
return parsed.ids[0];
|
|
437
|
+
}
|
|
438
|
+
async function checkWebhook(deps, interactive, client, yes) {
|
|
439
|
+
const p = deps.prompter;
|
|
440
|
+
let info;
|
|
441
|
+
try {
|
|
442
|
+
info = await client.getWebhookInfo();
|
|
443
|
+
}
|
|
444
|
+
catch (error) {
|
|
445
|
+
p.say(`! Couldn't check the bot's webhook: ${describeTelegramError(error)}`);
|
|
446
|
+
return false;
|
|
447
|
+
}
|
|
448
|
+
if (!info.url)
|
|
449
|
+
return true;
|
|
450
|
+
p.say(`! This bot has a webhook set, to ${redactSecrets(info.url)}: Telegram is sending its messages to`);
|
|
451
|
+
p.say(' another program. TeleCoder fetches them itself, which only works once the webhook is removed.');
|
|
452
|
+
const remove = interactive ? await p.confirm('Remove the webhook?', false) : yes;
|
|
453
|
+
if (!remove) {
|
|
454
|
+
p.say(' Left it in place. TeleCoder won\'t receive messages until it is removed.');
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
try {
|
|
458
|
+
await client.deleteWebhook();
|
|
459
|
+
p.say('✓ Removed the webhook');
|
|
460
|
+
return true;
|
|
461
|
+
}
|
|
462
|
+
catch (error) {
|
|
463
|
+
p.say(`! Couldn't remove it: ${describeTelegramError(error)}`);
|
|
464
|
+
return false;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
function describeUser(user) {
|
|
468
|
+
const name = [user.first_name, user.last_name].filter(Boolean).join(' ') || 'someone';
|
|
469
|
+
return `${name}${user.username ? ` (@${user.username})` : ''}`;
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Wait for the owner to message the bot, and take their id from it. Typing an
|
|
473
|
+
* id instead works at any point. Returns null when nothing usable arrived, for
|
|
474
|
+
* the caller to ask for the id outright.
|
|
475
|
+
*/
|
|
476
|
+
async function captureOwner(deps, client, bot) {
|
|
477
|
+
const p = deps.prompter;
|
|
478
|
+
const waitMs = deps.ownerWaitMs ?? 5 * 60_000;
|
|
479
|
+
const pollTimeout = deps.pollTimeoutSec ?? 30;
|
|
480
|
+
const now = () => (deps.now?.() ?? new Date()).getTime();
|
|
481
|
+
// Whatever is already queued predates this run, and could be anyone's:
|
|
482
|
+
// skip it, so only a message sent from here on counts.
|
|
483
|
+
let offset;
|
|
484
|
+
try {
|
|
485
|
+
const queued = await client.getUpdates({ timeout: 0, signal: p.signal });
|
|
486
|
+
if (queued.length)
|
|
487
|
+
offset = queued[queued.length - 1].update_id + 1;
|
|
488
|
+
}
|
|
489
|
+
catch (error) {
|
|
490
|
+
if (isAbort(error))
|
|
491
|
+
throw error;
|
|
492
|
+
p.say(`! ${describePollError(error)}`);
|
|
493
|
+
return null;
|
|
494
|
+
}
|
|
495
|
+
p.say(`Now open https://t.me/${bot.username} and send /start, from your own account.`);
|
|
496
|
+
p.say('The bot replies there, and this setup then asks you here to confirm it was you.');
|
|
497
|
+
p.say(`Waiting for it, up to ${Math.round(waitMs / 60_000)} minutes. Or type your numeric id and press Enter. Ctrl+C cancels.`);
|
|
498
|
+
const deadline = now() + waitMs;
|
|
499
|
+
let found = null;
|
|
500
|
+
while (found === null && now() < deadline) {
|
|
501
|
+
const stopPoll = new AbortController();
|
|
502
|
+
const stopAsk = new AbortController();
|
|
503
|
+
const poll = (async () => {
|
|
504
|
+
while (now() < deadline) {
|
|
505
|
+
const timeout = Math.max(0, Math.min(pollTimeout, Math.ceil((deadline - now()) / 1000)));
|
|
506
|
+
const updates = await client.getUpdates({
|
|
507
|
+
offset, timeout, signal: AbortSignal.any([p.signal, stopPoll.signal]),
|
|
508
|
+
});
|
|
509
|
+
let candidate;
|
|
510
|
+
let chatId = 0;
|
|
511
|
+
for (const u of updates) {
|
|
512
|
+
offset = u.update_id + 1;
|
|
513
|
+
const m = u.message;
|
|
514
|
+
if (!candidate && m?.from && !m.from.is_bot && m.chat.type === 'private') {
|
|
515
|
+
candidate = m.from;
|
|
516
|
+
chatId = m.chat.id;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
if (candidate) {
|
|
520
|
+
// Otherwise Telegram stays silent and the /start looks lost. Best
|
|
521
|
+
// effort: the answer that counts is the one in the terminal.
|
|
522
|
+
await client.sendMessage(chatId, OWNER_CAPTURED_REPLY).catch(() => { });
|
|
523
|
+
return { kind: 'message', user: candidate };
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return { kind: 'timeout' };
|
|
527
|
+
})();
|
|
528
|
+
const typed = p.ask('>', { signal: stopAsk.signal }).then((text) => ({ kind: 'typed', text }));
|
|
529
|
+
let outcome;
|
|
530
|
+
try {
|
|
531
|
+
outcome = await Promise.race([poll, typed]);
|
|
532
|
+
}
|
|
533
|
+
catch (error) {
|
|
534
|
+
stopPoll.abort();
|
|
535
|
+
stopAsk.abort();
|
|
536
|
+
await Promise.allSettled([poll, typed]);
|
|
537
|
+
if (isAbort(error) || p.signal.aborted)
|
|
538
|
+
throw error;
|
|
539
|
+
p.say(`! ${describePollError(error)}`);
|
|
540
|
+
return null;
|
|
541
|
+
}
|
|
542
|
+
// Whichever lost is cancelled, and its rejection swallowed.
|
|
543
|
+
if (outcome.kind === 'typed')
|
|
544
|
+
stopPoll.abort();
|
|
545
|
+
else
|
|
546
|
+
stopAsk.abort();
|
|
547
|
+
await Promise.allSettled([poll, typed]);
|
|
548
|
+
if (p.signal.aborted)
|
|
549
|
+
throw p.signal.reason;
|
|
550
|
+
if (outcome.kind === 'typed') {
|
|
551
|
+
const id = parseOwnerId(outcome.text);
|
|
552
|
+
if (typeof id === 'number')
|
|
553
|
+
found = id;
|
|
554
|
+
else
|
|
555
|
+
p.say(id);
|
|
556
|
+
}
|
|
557
|
+
else if (outcome.kind === 'message') {
|
|
558
|
+
const user = outcome.user;
|
|
559
|
+
if (await p.confirm(`Is this you: ${describeUser(user)}, id ${user.id}?`, true))
|
|
560
|
+
found = user.id;
|
|
561
|
+
else
|
|
562
|
+
p.say('Waiting for another message. Or type your id.');
|
|
563
|
+
}
|
|
564
|
+
else {
|
|
565
|
+
p.say('No message arrived in time.');
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
// Mark what was read as handled, or the bot's first poll replays the /start.
|
|
570
|
+
if (offset !== undefined) {
|
|
571
|
+
try {
|
|
572
|
+
await client.getUpdates({ offset, timeout: 0 });
|
|
573
|
+
}
|
|
574
|
+
catch {
|
|
575
|
+
// Harmless: the bot answers one /start twice, at worst.
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
return found;
|
|
579
|
+
}
|
|
580
|
+
function describePollError(error) {
|
|
581
|
+
if (error instanceof TelegramApiError && error.code === 409) {
|
|
582
|
+
return 'Something else is already reading this bot\'s messages: probably TeleCoder or another program ' +
|
|
583
|
+
'running with the same token. Stop it, or type your id below.';
|
|
584
|
+
}
|
|
585
|
+
return `Couldn't wait for your message: ${describeTelegramError(error)}`;
|
|
586
|
+
}
|
|
587
|
+
async function stepWorkspace(opts, deps, interactive, current) {
|
|
588
|
+
const p = deps.prompter;
|
|
589
|
+
if (opts.workspace !== undefined) {
|
|
590
|
+
const resolved = resolveDir(opts.workspace, deps.homedir);
|
|
591
|
+
if (typeof resolved !== 'string' || !isDir(resolved))
|
|
592
|
+
throw new Stop(`--workspace: ${opts.workspace} is not a directory.`);
|
|
593
|
+
return resolved;
|
|
594
|
+
}
|
|
595
|
+
const def = current ?? suggestWorkspace(deps.homedir);
|
|
596
|
+
if (!interactive)
|
|
597
|
+
return def;
|
|
598
|
+
p.say('Workspace: the folder your projects are in. /dir picks one of them for Claude to work in,');
|
|
599
|
+
p.say('and admins can fetch files from anywhere inside it with /file.');
|
|
600
|
+
for (;;) {
|
|
601
|
+
const answer = await p.ask('Workspace directory:', { default: tildify(def, deps.homedir) });
|
|
602
|
+
const resolved = resolveDir(answer, deps.homedir);
|
|
603
|
+
if (isDir(resolved))
|
|
604
|
+
return resolved;
|
|
605
|
+
p.say(`${resolved} is not a directory. Create it first, or pick another.`);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
/** ~/projects or the like when there is one, else the home directory. */
|
|
609
|
+
export function suggestWorkspace(homedir, exists = isDir) {
|
|
610
|
+
for (const name of ['projects', 'Projects', 'dev', 'code', 'src', 'repos']) {
|
|
611
|
+
const dir = path.join(homedir, name);
|
|
612
|
+
if (exists(dir))
|
|
613
|
+
return dir;
|
|
614
|
+
}
|
|
615
|
+
return homedir;
|
|
616
|
+
}
|
|
617
|
+
function resolveDir(input, homedir) {
|
|
618
|
+
const trimmed = input.trim();
|
|
619
|
+
const expanded = trimmed === '~' ? homedir : trimmed.startsWith('~/') ? path.join(homedir, trimmed.slice(2)) : trimmed;
|
|
620
|
+
return path.resolve(expanded);
|
|
621
|
+
}
|
|
622
|
+
function tildify(dir, homedir) {
|
|
623
|
+
if (dir === homedir)
|
|
624
|
+
return '~';
|
|
625
|
+
return dir.startsWith(homedir + path.sep) ? `~/${dir.slice(homedir.length + 1)}` : dir;
|
|
626
|
+
}
|
|
627
|
+
function isDir(dir) {
|
|
628
|
+
try {
|
|
629
|
+
return fs.statSync(dir).isDirectory();
|
|
630
|
+
}
|
|
631
|
+
catch {
|
|
632
|
+
return false;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Whether to give the bot the TeleCoder icon. A bot without a picture gets it
|
|
637
|
+
* without being asked: a picture beats a grey initial, the summary says so before
|
|
638
|
+
* anything is written, and --no-icon is there for whoever disagrees. A picture
|
|
639
|
+
* the bot already has is only replaced when --icon asks for it.
|
|
640
|
+
*/
|
|
641
|
+
async function stepIcon(opts, client, bot) {
|
|
642
|
+
if (opts.icon !== undefined)
|
|
643
|
+
return opts.icon;
|
|
644
|
+
try {
|
|
645
|
+
return !await client.hasProfilePhoto(bot.id);
|
|
646
|
+
}
|
|
647
|
+
catch {
|
|
648
|
+
// Can't tell, so leave the picture alone.
|
|
649
|
+
return false;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
async function stepVoice(opts, deps, interactive, current) {
|
|
653
|
+
const p = deps.prompter;
|
|
654
|
+
if (opts.groqKeyEnv) {
|
|
655
|
+
const key = deps.env[opts.groqKeyEnv]?.trim();
|
|
656
|
+
if (!key)
|
|
657
|
+
throw new Stop(`--groq-key-env ${opts.groqKeyEnv}: that environment variable is empty or not set.`);
|
|
658
|
+
return key;
|
|
659
|
+
}
|
|
660
|
+
if (!interactive)
|
|
661
|
+
return current;
|
|
662
|
+
const on = await p.confirm('Optional: transcribe voice notes with Groq Whisper? Needs a Groq API key '
|
|
663
|
+
+ '(https://console.groq.com/keys; it has a free tier). You can turn this on later by running telecoder init again.', Boolean(current));
|
|
664
|
+
if (!on)
|
|
665
|
+
return undefined;
|
|
666
|
+
if (current && await p.confirm('Keep the current Groq key?', true))
|
|
667
|
+
return current;
|
|
668
|
+
for (;;) {
|
|
669
|
+
const key = (await p.secret('Groq API key:')).trim();
|
|
670
|
+
if (key) {
|
|
671
|
+
if (!key.startsWith('gsk_'))
|
|
672
|
+
p.say('! Groq keys usually start with gsk_; using it anyway.');
|
|
673
|
+
return key;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
/** One sentence about a failed Bot API call, in the wording the bot itself uses. */
|
|
678
|
+
export function describeTelegramError(error) {
|
|
679
|
+
if (error instanceof TelegramApiError) {
|
|
680
|
+
if (error.method === 'getMe' && (error.code === 401 || error.code === 404))
|
|
681
|
+
return REJECTED_TOKEN_MESSAGE;
|
|
682
|
+
return `Telegram said: ${error.description}`;
|
|
683
|
+
}
|
|
684
|
+
if (error instanceof TelegramNetworkError) {
|
|
685
|
+
if (error.proxy) {
|
|
686
|
+
return `Couldn't reach api.telegram.org through the proxy ${error.proxy} (${error.message}). ` +
|
|
687
|
+
'Check that the proxy is running and reachable, and try again.';
|
|
688
|
+
}
|
|
689
|
+
return `Couldn't reach api.telegram.org (${error.message}). Check the network connection, and try again.`;
|
|
690
|
+
}
|
|
691
|
+
return redactSecrets(error instanceof Error ? error.message : String(error));
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* The same for the wizard's first call to Telegram, the token check. A
|
|
695
|
+
* network failure there may mean Telegram is blocked on this network, so it
|
|
696
|
+
* names the setting that gets around that, as the bot's own startup check does.
|
|
697
|
+
*/
|
|
698
|
+
export function describeFirstCallError(error) {
|
|
699
|
+
const said = describeTelegramError(error);
|
|
700
|
+
if (!(error instanceof TelegramNetworkError) || error.proxy)
|
|
701
|
+
return said;
|
|
702
|
+
return `${said} If Telegram is blocked on this network, run the wizard with TELEGRAM_PROXY_URL ` +
|
|
703
|
+
'set to an HTTP or HTTPS proxy (e.g. http://127.0.0.1:8080).';
|
|
704
|
+
}
|
|
705
|
+
//# sourceMappingURL=flow.js.map
|