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,678 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `telecoder service install|uninstall|status|logs|restart` — run TeleCoder
|
|
3
|
+
* in the background under the machine's own service manager: a systemd user
|
|
4
|
+
* unit on Linux, a LaunchAgent on macOS.
|
|
5
|
+
*
|
|
6
|
+
* An npm install has no botctl script: /restartbot exits (RESTART_EXIT_CODE)
|
|
7
|
+
* and counts on whatever started the bot to start it again. The unit written
|
|
8
|
+
* here does — Restart=always, KeepAlive — and stands down on the config-error
|
|
9
|
+
* code instead (see ../service/render.ts and utils/exit-codes.ts).
|
|
10
|
+
*
|
|
11
|
+
* Everything that touches the machine — files, systemctl, the prompt — comes
|
|
12
|
+
* in through ServiceDeps, so the flows are tested with fakes; the unit text
|
|
13
|
+
* itself is rendered by the pure functions in ../service/render.ts.
|
|
14
|
+
*/
|
|
15
|
+
import { execFile, spawn } from 'child_process';
|
|
16
|
+
import * as fs from 'fs';
|
|
17
|
+
import * as os from 'os';
|
|
18
|
+
import * as path from 'path';
|
|
19
|
+
import * as readline from 'readline';
|
|
20
|
+
import { getConfigHomeInfo } from '../../utils/config-home.js';
|
|
21
|
+
import { detectPackageRunner, getInstallMode, PACKAGE_ROOT, } from '../../utils/install-mode.js';
|
|
22
|
+
import { buildServicePath, DEFAULT_SERVICE_NAME, launchdLabel, lineDiff, normalizeServiceName, renderLaunchdPlist, renderSystemdUnit, systemdUnitName, } from '../service/render.js';
|
|
23
|
+
export function realDeps() {
|
|
24
|
+
return {
|
|
25
|
+
platform: process.platform,
|
|
26
|
+
env: process.env,
|
|
27
|
+
homedir: os.homedir(),
|
|
28
|
+
uid: process.getuid?.() ?? -1,
|
|
29
|
+
username: os.userInfo().username,
|
|
30
|
+
execPath: process.execPath,
|
|
31
|
+
packageRoot: PACKAGE_ROOT,
|
|
32
|
+
installMode: getInstallMode(),
|
|
33
|
+
packageRunner: detectPackageRunner(),
|
|
34
|
+
configHome: getConfigHomeInfo(),
|
|
35
|
+
fs: {
|
|
36
|
+
exists: (p) => fs.existsSync(p),
|
|
37
|
+
readFile: (p) => fs.readFileSync(p, 'utf8'),
|
|
38
|
+
writeFile: (p, content) => fs.writeFileSync(p, content, { mode: 0o644 }),
|
|
39
|
+
mkdirp: (p) => fs.mkdirSync(p, { recursive: true }),
|
|
40
|
+
remove: (p) => fs.rmSync(p, { force: true }),
|
|
41
|
+
realpath: (p) => {
|
|
42
|
+
try {
|
|
43
|
+
return fs.realpathSync(p);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return p;
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
isExecutable: (p) => {
|
|
50
|
+
try {
|
|
51
|
+
const stat = fs.statSync(p);
|
|
52
|
+
return stat.isFile() && (stat.mode & 0o111) !== 0;
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
run: (cmd, args, env) => new Promise((resolve) => {
|
|
60
|
+
execFile(cmd, args, { timeout: 60_000, env }, (error, stdout, stderr) => {
|
|
61
|
+
const code = error ? (typeof error.code === 'number' ? error.code : 127) : 0;
|
|
62
|
+
resolve({ code, stdout: String(stdout), stderr: String(stderr) || (error && !stderr ? error.message : '') });
|
|
63
|
+
});
|
|
64
|
+
}),
|
|
65
|
+
runInherit: (cmd, args, env) => new Promise((resolve) => {
|
|
66
|
+
const child = spawn(cmd, args, { stdio: 'inherit', env });
|
|
67
|
+
child.on('error', () => resolve(127));
|
|
68
|
+
child.on('exit', (code, signal) => resolve(code ?? (signal === 'SIGINT' ? 0 : 1)));
|
|
69
|
+
}),
|
|
70
|
+
ask: async (question, defaultYes) => {
|
|
71
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
72
|
+
return null;
|
|
73
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
74
|
+
try {
|
|
75
|
+
const answer = await new Promise((resolve) => rl.question(`${question} ${defaultYes ? '[Y/n]' : '[y/N]'} `, resolve));
|
|
76
|
+
const a = answer.trim().toLowerCase();
|
|
77
|
+
return a === '' ? defaultYes : a === 'y' || a === 'yes';
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
rl.close();
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const SUBCOMMANDS = ['install', 'uninstall', 'status', 'logs', 'restart'];
|
|
86
|
+
export function parseServiceArgs(args) {
|
|
87
|
+
const options = { name: DEFAULT_SERVICE_NAME, yes: false, fromCheckout: false, dryRun: false, follow: true };
|
|
88
|
+
let sub = null;
|
|
89
|
+
for (let i = 0; i < args.length; i++) {
|
|
90
|
+
const arg = args[i];
|
|
91
|
+
if (arg === '--name' || arg.startsWith('--name=')) {
|
|
92
|
+
const value = arg === '--name' ? args[++i] : arg.slice('--name='.length);
|
|
93
|
+
if (!value)
|
|
94
|
+
return { error: '--name needs a value, e.g. --name telecoder-work' };
|
|
95
|
+
const normalized = normalizeServiceName(value);
|
|
96
|
+
if ('error' in normalized)
|
|
97
|
+
return normalized;
|
|
98
|
+
options.name = normalized.name;
|
|
99
|
+
}
|
|
100
|
+
else if (arg === '--yes' || arg === '-y')
|
|
101
|
+
options.yes = true;
|
|
102
|
+
else if (arg === '--no-linger')
|
|
103
|
+
options.linger = false;
|
|
104
|
+
else if (arg === '--from-checkout')
|
|
105
|
+
options.fromCheckout = true;
|
|
106
|
+
else if (arg === '--dry-run')
|
|
107
|
+
options.dryRun = true;
|
|
108
|
+
else if (arg === '--no-follow')
|
|
109
|
+
options.follow = false;
|
|
110
|
+
else if (!sub && SUBCOMMANDS.includes(arg))
|
|
111
|
+
sub = arg;
|
|
112
|
+
else
|
|
113
|
+
return { error: `Unknown service argument: ${arg}` };
|
|
114
|
+
}
|
|
115
|
+
return { sub, options };
|
|
116
|
+
}
|
|
117
|
+
export function usage() {
|
|
118
|
+
return [
|
|
119
|
+
'Usage: telecoder service <command> [--name <name>]',
|
|
120
|
+
'',
|
|
121
|
+
' install Run TeleCoder in the background, and start it at login/boot',
|
|
122
|
+
' (systemd user unit on Linux, LaunchAgent on macOS)',
|
|
123
|
+
' [--yes] [--no-linger] [--dry-run] [--from-checkout]',
|
|
124
|
+
' status Is it running?',
|
|
125
|
+
' logs Follow its output [--no-follow: print the last 100 lines]',
|
|
126
|
+
' restart Restart it (also after a config error stopped it)',
|
|
127
|
+
' uninstall Stop it and remove the service',
|
|
128
|
+
'',
|
|
129
|
+
'--name picks the unit name (default "telecoder"), for several installs side by side.',
|
|
130
|
+
];
|
|
131
|
+
}
|
|
132
|
+
// ── Locating things ─────────────────────────────────────────────
|
|
133
|
+
/** Where a command is on PATH (the PATH entry, not where its symlink leads), or null. */
|
|
134
|
+
export function findOnPath(name, pathVar, isExecutable) {
|
|
135
|
+
for (const dir of (pathVar ?? '').split(':')) {
|
|
136
|
+
if (!dir || !path.isAbsolute(dir))
|
|
137
|
+
continue;
|
|
138
|
+
const candidate = path.join(dir, name);
|
|
139
|
+
if (isExecutable(candidate))
|
|
140
|
+
return candidate;
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
function extraSearchPath(deps) {
|
|
145
|
+
const dirs = [path.join(deps.homedir, '.local', 'bin'), '/usr/local/bin', '/usr/bin', '/bin'];
|
|
146
|
+
if (deps.platform === 'darwin')
|
|
147
|
+
dirs.unshift('/opt/homebrew/bin');
|
|
148
|
+
return [deps.env.PATH ?? '', ...dirs].join(':');
|
|
149
|
+
}
|
|
150
|
+
const which = (deps, name) => findOnPath(name, extraSearchPath(deps), deps.fs.isExecutable);
|
|
151
|
+
/**
|
|
152
|
+
* The node to put in the unit. process.execPath is already resolved, which
|
|
153
|
+
* for Homebrew is a versioned Cellar path that the next `brew upgrade`
|
|
154
|
+
* deletes; the `node` on PATH that leads to the same binary is the stable
|
|
155
|
+
* name for it.
|
|
156
|
+
*/
|
|
157
|
+
export function chooseNodePath(deps) {
|
|
158
|
+
const onPath = which(deps, 'node');
|
|
159
|
+
if (onPath && deps.fs.realpath(onPath) === deps.fs.realpath(deps.execPath))
|
|
160
|
+
return onPath;
|
|
161
|
+
return deps.execPath;
|
|
162
|
+
}
|
|
163
|
+
/** The env vars carried into the unit: where the config is, never what's in it. */
|
|
164
|
+
function carriedEnv(deps) {
|
|
165
|
+
const env = [];
|
|
166
|
+
if (deps.configHome.source === 'override')
|
|
167
|
+
env.push(['TELECODER_HOME', deps.configHome.dir]);
|
|
168
|
+
for (const suffix of ['ENV_PATH', 'INSTANCES_CONFIG']) {
|
|
169
|
+
const value = deps.env[`TELECODER_${suffix}`] ?? deps.env[`CLAUDEGRAM_${suffix}`];
|
|
170
|
+
if (value?.trim())
|
|
171
|
+
env.push([`TELECODER_${suffix}`, path.resolve(value.trim())]);
|
|
172
|
+
}
|
|
173
|
+
return env;
|
|
174
|
+
}
|
|
175
|
+
/** Work out everything the unit needs, or why there can't be one. */
|
|
176
|
+
export function resolveServiceSpec(deps, options) {
|
|
177
|
+
if (deps.installMode === 'checkout' && !options.fromCheckout) {
|
|
178
|
+
return {
|
|
179
|
+
ok: false,
|
|
180
|
+
lines: [
|
|
181
|
+
`This is a source checkout (${deps.packageRoot}).`,
|
|
182
|
+
'A checkout is usually run with pm2 through scripts/telecoder-botctl.sh, or with',
|
|
183
|
+
'"npm start" — /restartbot and /rebuildbot already know how to work with those.',
|
|
184
|
+
'',
|
|
185
|
+
"To run it as a service instead, pointing at this checkout's dist/:",
|
|
186
|
+
' node dist/cli.js service install --from-checkout',
|
|
187
|
+
'Run it under one or the other, not both: two copies of one bot conflict.',
|
|
188
|
+
],
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
if (deps.installMode === 'package' && deps.packageRunner === 'npx') {
|
|
192
|
+
return {
|
|
193
|
+
ok: false,
|
|
194
|
+
lines: [
|
|
195
|
+
"TeleCoder is running through npx, from npm's cache — a path that can be cleared",
|
|
196
|
+
'at any time, which would leave the service pointing at nothing.',
|
|
197
|
+
'',
|
|
198
|
+
'Install it first, then install the service from that:',
|
|
199
|
+
' npm install -g telecoder',
|
|
200
|
+
' telecoder service install',
|
|
201
|
+
],
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
const cliPath = deps.fs.realpath(path.join(deps.packageRoot, 'dist', 'cli.js'));
|
|
205
|
+
if (!deps.fs.exists(cliPath)) {
|
|
206
|
+
return {
|
|
207
|
+
ok: false,
|
|
208
|
+
lines: deps.installMode === 'checkout'
|
|
209
|
+
? [`${cliPath} doesn't exist yet. Build the checkout first: npm run build`]
|
|
210
|
+
: [`${cliPath} is missing — the install looks broken. Reinstall: npm install -g telecoder`],
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
const home = deps.configHome.dir;
|
|
214
|
+
const hasConfig = ['.env', 'instances.json'].some((f) => deps.fs.exists(path.join(home, f)))
|
|
215
|
+
|| Boolean(deps.env.TELECODER_ENV_PATH || deps.env.CLAUDEGRAM_ENV_PATH);
|
|
216
|
+
if (!hasConfig) {
|
|
217
|
+
return {
|
|
218
|
+
ok: false,
|
|
219
|
+
lines: [
|
|
220
|
+
`No TeleCoder config in ${home} yet, so the service would only fail to start.`,
|
|
221
|
+
'Run "telecoder init" first (or create the .env there), then "telecoder doctor".',
|
|
222
|
+
],
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
const warnings = [];
|
|
226
|
+
const nodePath = chooseNodePath(deps);
|
|
227
|
+
const required = [path.dirname(nodePath)];
|
|
228
|
+
for (const tool of ['claude', 'git', 'ffmpeg']) {
|
|
229
|
+
const found = which(deps, tool);
|
|
230
|
+
if (found)
|
|
231
|
+
required.push(path.dirname(found));
|
|
232
|
+
else if (tool === 'claude')
|
|
233
|
+
warnings.push('The claude CLI is not on your PATH. The bot needs it: install Claude Code, then run this again so the service can find it.');
|
|
234
|
+
else if (tool === 'git')
|
|
235
|
+
warnings.push('git is not on your PATH; Claude will be without it.');
|
|
236
|
+
}
|
|
237
|
+
if (deps.installMode === 'package' && deps.packageRunner === 'local') {
|
|
238
|
+
warnings.push(`TeleCoder is installed in a project's node_modules (${deps.packageRoot}); the service runs it from there.`);
|
|
239
|
+
}
|
|
240
|
+
const platform = deps.platform === 'darwin' ? 'darwin' : 'linux';
|
|
241
|
+
const env = carriedEnv(deps);
|
|
242
|
+
return {
|
|
243
|
+
ok: true,
|
|
244
|
+
warnings,
|
|
245
|
+
notes: env.map(([key, value]) => `The service gets ${key}=${value}, from your environment.`),
|
|
246
|
+
spec: {
|
|
247
|
+
name: options.name,
|
|
248
|
+
nodePath,
|
|
249
|
+
cliPath,
|
|
250
|
+
workingDirectory: home,
|
|
251
|
+
pathEnv: buildServicePath({ required, inherited: deps.env.PATH, platform, keep: (d) => deps.fs.exists(d) }),
|
|
252
|
+
env,
|
|
253
|
+
},
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
// ── systemd ─────────────────────────────────────────────────────
|
|
257
|
+
export function systemdUnitPath(deps, name) {
|
|
258
|
+
const configHome = deps.env.XDG_CONFIG_HOME && path.isAbsolute(deps.env.XDG_CONFIG_HOME)
|
|
259
|
+
? deps.env.XDG_CONFIG_HOME
|
|
260
|
+
: path.join(deps.homedir, '.config');
|
|
261
|
+
return path.join(configHome, 'systemd', 'user', systemdUnitName(name));
|
|
262
|
+
}
|
|
263
|
+
const userRuntimeDir = (uid) => `/run/user/${uid}`;
|
|
264
|
+
/**
|
|
265
|
+
* Under `sudo -u` or `su` there is no XDG_RUNTIME_DIR, so systemctl --user
|
|
266
|
+
* can't find the user's manager even when it is running (a login elsewhere,
|
|
267
|
+
* or lingering). When its bus socket is there, point systemctl at it: the
|
|
268
|
+
* returned deps run every command with XDG_RUNTIME_DIR and
|
|
269
|
+
* DBUS_SESSION_BUS_ADDRESS set. `adopted` is the directory, when it did.
|
|
270
|
+
*/
|
|
271
|
+
export function withUserBus(deps) {
|
|
272
|
+
if (deps.platform !== 'linux' || deps.env.XDG_RUNTIME_DIR || deps.uid < 0)
|
|
273
|
+
return { deps, adopted: null };
|
|
274
|
+
const runtimeDir = userRuntimeDir(deps.uid);
|
|
275
|
+
const bus = `${runtimeDir}/bus`;
|
|
276
|
+
if (!deps.fs.exists(bus))
|
|
277
|
+
return { deps, adopted: null };
|
|
278
|
+
// A DBUS_SESSION_BUS_ADDRESS that came through sudo is the other user's.
|
|
279
|
+
const env = { ...deps.env, XDG_RUNTIME_DIR: runtimeDir, DBUS_SESSION_BUS_ADDRESS: `unix:path=${bus}` };
|
|
280
|
+
return {
|
|
281
|
+
adopted: runtimeDir,
|
|
282
|
+
deps: {
|
|
283
|
+
...deps,
|
|
284
|
+
env,
|
|
285
|
+
run: (cmd, args, e) => deps.run(cmd, args, e ?? env),
|
|
286
|
+
runInherit: (cmd, args, e) => deps.runInherit(cmd, args, e ?? env),
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
/** Why `systemctl --user` can't be used here, or null when it can. */
|
|
291
|
+
export async function systemdUnavailableReason(deps) {
|
|
292
|
+
if (!which(deps, 'systemctl'))
|
|
293
|
+
return { reason: 'systemctl is not installed', userManager: false };
|
|
294
|
+
if (!deps.fs.exists('/run/systemd/system')) {
|
|
295
|
+
return { reason: 'this system was not booted with systemd (a container, or WSL without systemd enabled)', userManager: false };
|
|
296
|
+
}
|
|
297
|
+
if (!deps.env.XDG_RUNTIME_DIR) {
|
|
298
|
+
return {
|
|
299
|
+
reason: `there is no user session here (XDG_RUNTIME_DIR is unset, and no systemd user manager is running for ${deps.username})`,
|
|
300
|
+
userManager: true,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
const probe = await deps.run('systemctl', ['--user', 'show-environment']);
|
|
304
|
+
if (probe.code !== 0) {
|
|
305
|
+
return {
|
|
306
|
+
reason: `the systemd user manager isn't reachable (${firstLine(probe.stderr) || `systemctl exited ${probe.code}`})`,
|
|
307
|
+
userManager: true,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
const firstLine = (text) => text.trim().split('\n')[0] ?? '';
|
|
313
|
+
/** How to get the user's systemd manager running without a login, first in the fallback. */
|
|
314
|
+
async function userManagerFix(deps, name) {
|
|
315
|
+
const user = deps.username;
|
|
316
|
+
const runtimeDir = userRuntimeDir(deps.uid);
|
|
317
|
+
const viaSudo = !deps.env.XDG_RUNTIME_DIR || Boolean(deps.env.SUDO_USER);
|
|
318
|
+
const sudoLines = viaSudo
|
|
319
|
+
? [
|
|
320
|
+
`Under sudo -u, "telecoder service" finds that manager at ${runtimeDir} by itself; other`,
|
|
321
|
+
`systemctl --user commands need XDG_RUNTIME_DIR=${runtimeDir} in front, e.g.`,
|
|
322
|
+
` sudo -u ${user} XDG_RUNTIME_DIR=${runtimeDir} systemctl --user status ${systemdUnitName(name)}`,
|
|
323
|
+
]
|
|
324
|
+
: [];
|
|
325
|
+
if (await lingerEnabled(deps)) {
|
|
326
|
+
return [
|
|
327
|
+
`Lingering is already on for ${user}, so its systemd user manager should be running.`,
|
|
328
|
+
`Check it with "systemctl status user@${deps.uid}.service", then run "telecoder service install" again.`,
|
|
329
|
+
...sudoLines,
|
|
330
|
+
];
|
|
331
|
+
}
|
|
332
|
+
return [
|
|
333
|
+
`To fix it, turn on lingering: it keeps ${user}'s systemd running without a login (and starts it at boot).`,
|
|
334
|
+
` sudo loginctl enable-linger ${user}`,
|
|
335
|
+
'then run "telecoder service install" again.',
|
|
336
|
+
...sudoLines,
|
|
337
|
+
];
|
|
338
|
+
}
|
|
339
|
+
async function systemdFallback(deps, io, unavailable, unitPath, unit, spec) {
|
|
340
|
+
io.err(`Can't install a systemd user service: ${unavailable.reason}.`);
|
|
341
|
+
io.err('');
|
|
342
|
+
if (unavailable.userManager) {
|
|
343
|
+
for (const line of await userManagerFix(deps, spec.name))
|
|
344
|
+
io.err(line);
|
|
345
|
+
io.err('');
|
|
346
|
+
}
|
|
347
|
+
io.err('Or other ways to keep it running:');
|
|
348
|
+
io.err(` - pm2: pm2 start ${spec.cliPath} --name ${spec.name} --interpreter ${spec.nodePath} -- start`);
|
|
349
|
+
io.err(' then "pm2 save" and "pm2 startup" to bring it back after a reboot');
|
|
350
|
+
io.err(' - tmux or screen: run "telecoder start" in a detached session (no restart from chat)');
|
|
351
|
+
io.err(` - by hand, where systemd --user works: save this as ${unitPath}, then`);
|
|
352
|
+
io.err(` systemctl --user daemon-reload && systemctl --user enable --now ${systemdUnitName(spec.name)}`);
|
|
353
|
+
io.err('');
|
|
354
|
+
for (const line of unit.trimEnd().split('\n'))
|
|
355
|
+
io.err(` ${line}`);
|
|
356
|
+
}
|
|
357
|
+
async function lingerEnabled(deps) {
|
|
358
|
+
const result = await deps.run('loginctl', ['show-user', deps.username, '--property=Linger', '--value']);
|
|
359
|
+
return result.code === 0 && result.stdout.trim() === 'yes';
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Compare with what is already there; show the difference and ask before
|
|
363
|
+
* replacing. Returns null when the answer is no.
|
|
364
|
+
*/
|
|
365
|
+
async function checkExisting(deps, io, file, content, yes) {
|
|
366
|
+
if (!deps.fs.exists(file))
|
|
367
|
+
return 'none';
|
|
368
|
+
const current = deps.fs.readFile(file);
|
|
369
|
+
if (current === content)
|
|
370
|
+
return 'same';
|
|
371
|
+
io.out(`${file} already exists and differs:`);
|
|
372
|
+
for (const line of lineDiff(current, content))
|
|
373
|
+
io.out(` ${line}`);
|
|
374
|
+
io.out('');
|
|
375
|
+
const answer = yes ? true : await deps.ask('Replace it?', false);
|
|
376
|
+
if (answer === null) {
|
|
377
|
+
io.err('Not replacing it without asking. Run again in a terminal, or with --yes to replace it.');
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
if (!answer) {
|
|
381
|
+
io.out('Left it as it is.');
|
|
382
|
+
return null;
|
|
383
|
+
}
|
|
384
|
+
return 'replaced';
|
|
385
|
+
}
|
|
386
|
+
async function step(deps, io, cmd, args) {
|
|
387
|
+
const result = await deps.run(cmd, args);
|
|
388
|
+
if (result.code === 0)
|
|
389
|
+
return true;
|
|
390
|
+
io.err(`"${[cmd, ...args].join(' ')}" failed (exit ${result.code}): ${firstLine(result.stderr) || 'no output'}`);
|
|
391
|
+
return false;
|
|
392
|
+
}
|
|
393
|
+
const TWO_COPIES_NOTE = 'If this bot is also running somewhere else (a terminal, pm2), stop that copy: two copies of one bot token fight over its messages.';
|
|
394
|
+
async function installSystemd(deps, io, spec, options) {
|
|
395
|
+
const unitPath = systemdUnitPath(deps, spec.name);
|
|
396
|
+
const unitName = systemdUnitName(spec.name);
|
|
397
|
+
const unit = renderSystemdUnit(spec);
|
|
398
|
+
if (options.dryRun) {
|
|
399
|
+
io.out(`Would write ${unitPath}:`);
|
|
400
|
+
io.out('');
|
|
401
|
+
for (const line of unit.trimEnd().split('\n'))
|
|
402
|
+
io.out(line);
|
|
403
|
+
return 0;
|
|
404
|
+
}
|
|
405
|
+
const unavailable = await systemdUnavailableReason(deps);
|
|
406
|
+
if (unavailable) {
|
|
407
|
+
await systemdFallback(deps, io, unavailable, unitPath, unit, spec);
|
|
408
|
+
return 1;
|
|
409
|
+
}
|
|
410
|
+
const existing = await checkExisting(deps, io, unitPath, unit, options.yes);
|
|
411
|
+
if (existing === null)
|
|
412
|
+
return 1;
|
|
413
|
+
// Ask everything before changing anything.
|
|
414
|
+
let enableLinger = false;
|
|
415
|
+
const lingering = await lingerEnabled(deps);
|
|
416
|
+
if (!lingering && options.linger !== false) {
|
|
417
|
+
io.out('Lingering lets your user services run while you are logged out, and start at boot.');
|
|
418
|
+
const answer = options.yes ? true : await deps.ask(`Enable it for ${deps.username} (loginctl enable-linger)?`, true);
|
|
419
|
+
if (answer === null)
|
|
420
|
+
io.out('Not enabling lingering without asking (--yes would). Until it is on, the bot stops when you log out.');
|
|
421
|
+
enableLinger = answer === true;
|
|
422
|
+
}
|
|
423
|
+
if (existing !== 'same') {
|
|
424
|
+
deps.fs.mkdirp(path.dirname(unitPath));
|
|
425
|
+
deps.fs.writeFile(unitPath, unit);
|
|
426
|
+
io.out(`${existing === 'replaced' ? 'Updated' : 'Wrote'} ${unitPath}`);
|
|
427
|
+
}
|
|
428
|
+
else {
|
|
429
|
+
io.out(`${unitPath} is already up to date.`);
|
|
430
|
+
}
|
|
431
|
+
if (!(await step(deps, io, 'systemctl', ['--user', 'daemon-reload'])))
|
|
432
|
+
return 1;
|
|
433
|
+
if (!(await step(deps, io, 'systemctl', ['--user', 'enable', '--now', unitName]))) {
|
|
434
|
+
io.err(`See why with: telecoder service logs${nameFlag(spec.name)} --no-follow`);
|
|
435
|
+
return 1;
|
|
436
|
+
}
|
|
437
|
+
// enable --now leaves a running bot alone; a changed unit needs a restart to apply.
|
|
438
|
+
if (existing === 'replaced') {
|
|
439
|
+
io.out('Restarting it to apply the change...');
|
|
440
|
+
if (!(await step(deps, io, 'systemctl', ['--user', 'restart', unitName])))
|
|
441
|
+
return 1;
|
|
442
|
+
}
|
|
443
|
+
io.out(`${unitName} is enabled and running.`);
|
|
444
|
+
if (enableLinger) {
|
|
445
|
+
if (await step(deps, io, 'loginctl', ['enable-linger', deps.username])) {
|
|
446
|
+
io.out(`Lingering is on for ${deps.username}: the bot keeps running after logout and starts at boot.`);
|
|
447
|
+
}
|
|
448
|
+
else {
|
|
449
|
+
io.err(`Enable it as root instead: sudo loginctl enable-linger ${deps.username}`);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
else if (lingering) {
|
|
453
|
+
io.out(`Lingering is already on for ${deps.username}: the bot starts at boot.`);
|
|
454
|
+
}
|
|
455
|
+
else {
|
|
456
|
+
io.out(`Lingering is off: the bot runs while you are logged in. "loginctl enable-linger ${deps.username}" changes that.`);
|
|
457
|
+
}
|
|
458
|
+
printNextSteps(io, spec.name);
|
|
459
|
+
return 0;
|
|
460
|
+
}
|
|
461
|
+
const nameFlag = (name) => (name === DEFAULT_SERVICE_NAME ? '' : ` --name ${name}`);
|
|
462
|
+
function printNextSteps(io, name) {
|
|
463
|
+
const flag = nameFlag(name);
|
|
464
|
+
io.out('');
|
|
465
|
+
io.out(TWO_COPIES_NOTE);
|
|
466
|
+
io.out('');
|
|
467
|
+
io.out(` telecoder service status${flag} is it running?`);
|
|
468
|
+
io.out(` telecoder service logs${flag} follow its output`);
|
|
469
|
+
io.out(` telecoder service restart${flag} restart it (/restartbot from chat works too)`);
|
|
470
|
+
io.out(` telecoder service uninstall${flag} stop and remove it`);
|
|
471
|
+
}
|
|
472
|
+
// ── launchd ─────────────────────────────────────────────────────
|
|
473
|
+
export function launchdPaths(deps, name) {
|
|
474
|
+
return {
|
|
475
|
+
plist: path.join(deps.homedir, 'Library', 'LaunchAgents', `${launchdLabel(name)}.plist`),
|
|
476
|
+
logDir: path.join(deps.homedir, 'Library', 'Logs', 'telecoder'),
|
|
477
|
+
logFile: path.join(deps.homedir, 'Library', 'Logs', 'telecoder', `${name}.log`),
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
const launchdDomain = (deps) => `gui/${deps.uid}`;
|
|
481
|
+
const launchdTarget = (deps, name) => `${launchdDomain(deps)}/${launchdLabel(name)}`;
|
|
482
|
+
async function launchdLoaded(deps, name) {
|
|
483
|
+
return (await deps.run('launchctl', ['print', launchdTarget(deps, name)])).code === 0;
|
|
484
|
+
}
|
|
485
|
+
/** bootstrap, or `load -w` on a macOS too old to have it. */
|
|
486
|
+
async function launchdLoad(deps, io, plist) {
|
|
487
|
+
const boot = await deps.run('launchctl', ['bootstrap', launchdDomain(deps), plist]);
|
|
488
|
+
if (boot.code === 0)
|
|
489
|
+
return true;
|
|
490
|
+
const legacy = await deps.run('launchctl', ['load', '-w', plist]);
|
|
491
|
+
if (legacy.code === 0)
|
|
492
|
+
return true;
|
|
493
|
+
io.err(`launchctl couldn't load ${plist}: ${firstLine(boot.stderr) || firstLine(legacy.stderr) || `exit ${boot.code}`}`);
|
|
494
|
+
return false;
|
|
495
|
+
}
|
|
496
|
+
async function launchdUnload(deps, name, plist) {
|
|
497
|
+
const out = await deps.run('launchctl', ['bootout', launchdTarget(deps, name)]);
|
|
498
|
+
if (out.code !== 0)
|
|
499
|
+
await deps.run('launchctl', ['unload', '-w', plist]);
|
|
500
|
+
}
|
|
501
|
+
async function installLaunchd(deps, io, spec, options) {
|
|
502
|
+
const paths = launchdPaths(deps, spec.name);
|
|
503
|
+
const plist = renderLaunchdPlist({ ...spec, logFile: paths.logFile });
|
|
504
|
+
if (options.dryRun) {
|
|
505
|
+
io.out(`Would write ${paths.plist}:`);
|
|
506
|
+
io.out('');
|
|
507
|
+
for (const line of plist.trimEnd().split('\n'))
|
|
508
|
+
io.out(line);
|
|
509
|
+
return 0;
|
|
510
|
+
}
|
|
511
|
+
if (deps.uid === 0) {
|
|
512
|
+
io.err('Run this as the user the bot should run as, not as root: a LaunchAgent belongs to a user session.');
|
|
513
|
+
return 1;
|
|
514
|
+
}
|
|
515
|
+
if (!which(deps, 'launchctl')) {
|
|
516
|
+
io.err('launchctl is not on the PATH, so the LaunchAgent cannot be loaded.');
|
|
517
|
+
return 1;
|
|
518
|
+
}
|
|
519
|
+
const existing = await checkExisting(deps, io, paths.plist, plist, options.yes);
|
|
520
|
+
if (existing === null)
|
|
521
|
+
return 1;
|
|
522
|
+
deps.fs.mkdirp(paths.logDir);
|
|
523
|
+
if (existing !== 'same') {
|
|
524
|
+
deps.fs.mkdirp(path.dirname(paths.plist));
|
|
525
|
+
deps.fs.writeFile(paths.plist, plist);
|
|
526
|
+
io.out(`${existing === 'replaced' ? 'Updated' : 'Wrote'} ${paths.plist}`);
|
|
527
|
+
}
|
|
528
|
+
else {
|
|
529
|
+
io.out(`${paths.plist} is already up to date.`);
|
|
530
|
+
}
|
|
531
|
+
const loaded = await launchdLoaded(deps, spec.name);
|
|
532
|
+
// A loaded agent keeps its old definition until it is unloaded.
|
|
533
|
+
if (loaded && existing === 'replaced')
|
|
534
|
+
await launchdUnload(deps, spec.name, paths.plist);
|
|
535
|
+
if (!loaded || existing === 'replaced') {
|
|
536
|
+
if (!(await launchdLoad(deps, io, paths.plist)))
|
|
537
|
+
return 1;
|
|
538
|
+
}
|
|
539
|
+
io.out(`${launchdLabel(spec.name)} is loaded: it runs now and whenever you log in.`);
|
|
540
|
+
io.out(`Its output goes to ${paths.logFile}.`);
|
|
541
|
+
printNextSteps(io, spec.name);
|
|
542
|
+
return 0;
|
|
543
|
+
}
|
|
544
|
+
// ── Entry points ────────────────────────────────────────────────
|
|
545
|
+
/**
|
|
546
|
+
* Install (or update) the service. Exported for `telecoder init`, which can
|
|
547
|
+
* offer it at the end of a setup.
|
|
548
|
+
*/
|
|
549
|
+
export async function runServiceInstall(opts, givenDeps = realDeps()) {
|
|
550
|
+
const { io } = opts;
|
|
551
|
+
const { deps, adopted } = withUserBus(givenDeps);
|
|
552
|
+
const options = {
|
|
553
|
+
name: DEFAULT_SERVICE_NAME,
|
|
554
|
+
yes: false,
|
|
555
|
+
fromCheckout: false,
|
|
556
|
+
dryRun: false,
|
|
557
|
+
follow: true,
|
|
558
|
+
...Object.fromEntries(Object.entries(opts).filter(([, v]) => v !== undefined)),
|
|
559
|
+
};
|
|
560
|
+
if (deps.platform !== 'linux' && deps.platform !== 'darwin') {
|
|
561
|
+
io.err(`telecoder service supports Linux (systemd) and macOS (launchd), not ${deps.platform}.`);
|
|
562
|
+
io.err('Run "telecoder start" under any supervisor that starts it again when it exits.');
|
|
563
|
+
return 1;
|
|
564
|
+
}
|
|
565
|
+
const resolved = resolveServiceSpec(deps, options);
|
|
566
|
+
if (!resolved.ok) {
|
|
567
|
+
for (const line of resolved.lines)
|
|
568
|
+
io.err(line);
|
|
569
|
+
return 1;
|
|
570
|
+
}
|
|
571
|
+
for (const warning of resolved.warnings)
|
|
572
|
+
io.err(`Warning: ${warning}`);
|
|
573
|
+
for (const note of resolved.notes)
|
|
574
|
+
io.out(note);
|
|
575
|
+
if (adopted && !options.dryRun) {
|
|
576
|
+
io.out(`XDG_RUNTIME_DIR isn't set (sudo -u, say), but ${deps.username}'s systemd user manager is running: using ${adopted}.`);
|
|
577
|
+
}
|
|
578
|
+
return deps.platform === 'darwin'
|
|
579
|
+
? installLaunchd(deps, io, resolved.spec, options)
|
|
580
|
+
: installSystemd(deps, io, resolved.spec, options);
|
|
581
|
+
}
|
|
582
|
+
export async function runServiceUninstall(options, io, deps) {
|
|
583
|
+
if (deps.platform === 'darwin') {
|
|
584
|
+
const paths = launchdPaths(deps, options.name);
|
|
585
|
+
if (!deps.fs.exists(paths.plist)) {
|
|
586
|
+
io.err(`No service named "${options.name}" is installed (${paths.plist} doesn't exist).`);
|
|
587
|
+
return 1;
|
|
588
|
+
}
|
|
589
|
+
await launchdUnload(deps, options.name, paths.plist);
|
|
590
|
+
deps.fs.remove(paths.plist);
|
|
591
|
+
io.out(`Stopped ${launchdLabel(options.name)} and removed ${paths.plist}. Logs stay in ${paths.logDir}.`);
|
|
592
|
+
return 0;
|
|
593
|
+
}
|
|
594
|
+
const unitPath = systemdUnitPath(deps, options.name);
|
|
595
|
+
const unitName = systemdUnitName(options.name);
|
|
596
|
+
if (!deps.fs.exists(unitPath)) {
|
|
597
|
+
io.err(`No service named "${options.name}" is installed (${unitPath} doesn't exist).`);
|
|
598
|
+
return 1;
|
|
599
|
+
}
|
|
600
|
+
const unavailable = await systemdUnavailableReason(deps);
|
|
601
|
+
if (unavailable) {
|
|
602
|
+
io.err(`Can't reach systemd --user: ${unavailable.reason}.`);
|
|
603
|
+
io.err(`Removing ${unitPath} anyway; it was not stopped.`);
|
|
604
|
+
}
|
|
605
|
+
else {
|
|
606
|
+
// Failure here is fine: the unit may never have been loaded.
|
|
607
|
+
await deps.run('systemctl', ['--user', 'disable', '--now', unitName]);
|
|
608
|
+
}
|
|
609
|
+
deps.fs.remove(unitPath);
|
|
610
|
+
if (!unavailable) {
|
|
611
|
+
await deps.run('systemctl', ['--user', 'daemon-reload']);
|
|
612
|
+
await deps.run('systemctl', ['--user', 'reset-failed', unitName]);
|
|
613
|
+
}
|
|
614
|
+
io.out(`Stopped ${unitName} and removed ${unitPath}.`);
|
|
615
|
+
if (!unavailable && (await lingerEnabled(deps))) {
|
|
616
|
+
io.out(`Lingering stays on for ${deps.username}; "loginctl disable-linger ${deps.username}" turns it off if nothing else needs it.`);
|
|
617
|
+
}
|
|
618
|
+
return 0;
|
|
619
|
+
}
|
|
620
|
+
function notInstalled(io, deps, name) {
|
|
621
|
+
const file = deps.platform === 'darwin' ? launchdPaths(deps, name).plist : systemdUnitPath(deps, name);
|
|
622
|
+
if (deps.fs.exists(file))
|
|
623
|
+
return false;
|
|
624
|
+
io.err(`No service named "${name}" is installed. Set one up with: telecoder service install${nameFlag(name)}`);
|
|
625
|
+
return true;
|
|
626
|
+
}
|
|
627
|
+
export async function runServiceCommand(args, io, givenDeps) {
|
|
628
|
+
const deps = withUserBus(givenDeps).deps;
|
|
629
|
+
const parsed = parseServiceArgs(args);
|
|
630
|
+
if ('error' in parsed) {
|
|
631
|
+
io.err(parsed.error);
|
|
632
|
+
for (const line of usage())
|
|
633
|
+
io.err(line);
|
|
634
|
+
return 2;
|
|
635
|
+
}
|
|
636
|
+
const { sub, options } = parsed;
|
|
637
|
+
if (!sub) {
|
|
638
|
+
for (const line of usage())
|
|
639
|
+
io.out(line);
|
|
640
|
+
return 0;
|
|
641
|
+
}
|
|
642
|
+
if (sub === 'install')
|
|
643
|
+
return runServiceInstall({ ...options, io }, givenDeps);
|
|
644
|
+
if (deps.platform !== 'linux' && deps.platform !== 'darwin') {
|
|
645
|
+
io.err(`telecoder service supports Linux (systemd) and macOS (launchd), not ${deps.platform}.`);
|
|
646
|
+
return 1;
|
|
647
|
+
}
|
|
648
|
+
if (sub === 'uninstall')
|
|
649
|
+
return runServiceUninstall(options, io, deps);
|
|
650
|
+
if (notInstalled(io, deps, options.name))
|
|
651
|
+
return 1;
|
|
652
|
+
if (deps.platform === 'darwin') {
|
|
653
|
+
const target = launchdTarget(deps, options.name);
|
|
654
|
+
if (sub === 'status')
|
|
655
|
+
return deps.runInherit('launchctl', ['print', target]);
|
|
656
|
+
if (sub === 'restart')
|
|
657
|
+
return (await step(deps, io, 'launchctl', ['kickstart', '-k', target])) ? 0 : 1;
|
|
658
|
+
const { logFile } = launchdPaths(deps, options.name);
|
|
659
|
+
return deps.runInherit('tail', ['-n', '100', ...(options.follow ? ['-F'] : []), logFile]);
|
|
660
|
+
}
|
|
661
|
+
const unitName = systemdUnitName(options.name);
|
|
662
|
+
if (sub === 'status')
|
|
663
|
+
return deps.runInherit('systemctl', ['--user', 'status', unitName, '--no-pager']);
|
|
664
|
+
if (sub === 'logs') {
|
|
665
|
+
return deps.runInherit('journalctl', ['--user', '-u', unitName, '-n', '100', options.follow ? '-f' : '--no-pager']);
|
|
666
|
+
}
|
|
667
|
+
// restart: reset-failed first, or a unit that hit its start limit (or
|
|
668
|
+
// stopped on a config error) refuses to start again.
|
|
669
|
+
await deps.run('systemctl', ['--user', 'reset-failed', unitName]);
|
|
670
|
+
if (!(await step(deps, io, 'systemctl', ['--user', 'restart', unitName])))
|
|
671
|
+
return 1;
|
|
672
|
+
io.out(`Restarted ${unitName}.`);
|
|
673
|
+
return 0;
|
|
674
|
+
}
|
|
675
|
+
export async function run(args, io) {
|
|
676
|
+
return runServiceCommand(args, io, realDeps());
|
|
677
|
+
}
|
|
678
|
+
//# sourceMappingURL=service.js.map
|