paris-immersion 0.1.7 → 0.1.9

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.
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `paris daemon <install|uninstall|status>` — gerencia o serviço persistente
3
+ * do `paris serve` (o agente que o terminal embutido do curso espelha). O
4
+ * instalador chama `install`; o `paris logout` chama `uninstall`.
5
+ */
6
+ export declare function daemonCommand(action: string): Promise<void>;
@@ -0,0 +1,35 @@
1
+ import { installDaemon, uninstallDaemon, daemonStatus } from '../lib/daemon.js';
2
+ import { c } from '../lib/colors.js';
3
+ /**
4
+ * `paris daemon <install|uninstall|status>` — gerencia o serviço persistente
5
+ * do `paris serve` (o agente que o terminal embutido do curso espelha). O
6
+ * instalador chama `install`; o `paris logout` chama `uninstall`.
7
+ */
8
+ export async function daemonCommand(action) {
9
+ const act = (action || '').toLowerCase();
10
+ if (act === 'install') {
11
+ try {
12
+ const { mechanism } = await installDaemon();
13
+ console.log(c.green(`✓ paris serve instalado como serviço (${mechanism}).`));
14
+ console.log(c.dim(' Sobe sozinho no login e reinicia se cair — o terminal do curso conecta sempre.'));
15
+ }
16
+ catch (err) {
17
+ console.log(c.yellow(`! Não consegui instalar o serviço: ${err instanceof Error ? err.message : String(err)}`));
18
+ console.log(c.dim(' Você ainda pode rodar `paris serve` num terminal manualmente.'));
19
+ process.exitCode = 1;
20
+ }
21
+ return;
22
+ }
23
+ if (act === 'uninstall') {
24
+ await uninstallDaemon();
25
+ console.log(c.green('✓ Serviço do paris serve removido.'));
26
+ return;
27
+ }
28
+ if (act === 'status') {
29
+ const on = await daemonStatus();
30
+ console.log(on ? c.green('● paris serve: serviço ativo') : c.dim('○ paris serve: serviço não instalado'));
31
+ return;
32
+ }
33
+ console.log(c.yellow("Uso: paris daemon <install|uninstall|status>"));
34
+ process.exitCode = 1;
35
+ }
@@ -1,8 +1,12 @@
1
1
  import { apiAuthFetch } from '../lib/api.js';
2
2
  import { deleteCredentials, readCredentials } from '../lib/credentials.js';
3
+ import { uninstallDaemon } from '../lib/daemon.js';
3
4
  import { c } from '../lib/colors.js';
4
5
  export async function logoutCommand() {
5
6
  const creds = await readCredentials();
7
+ // Remove o serviço persistente do paris serve (best-effort) — não faz sentido
8
+ // o agente seguir subindo no login depois que o aluno saiu.
9
+ await uninstallDaemon();
6
10
  if (!creds) {
7
11
  console.log(c.dim('Nenhuma sessão local pra encerrar.'));
8
12
  return;
@@ -38,9 +38,19 @@ export interface ServeHandle {
38
38
  close: () => void;
39
39
  }
40
40
  /**
41
- * Spawn the coached pty (`claude '/tostudy'` inside the provisioned workspace).
42
- * Shared by the local ws server and the relay agent. Throws if node-pty can't
43
- * load/spawn — callers report it on their channel.
41
+ * Descobre o slash-command do tutor pra injetar no kickoff. O `@tostudy-ai/cli`
42
+ * instala o comando com nome ESPECÍFICO do curso (`.claude/commands/tostudy-<slug>.md`),
43
+ * NÃO `/tostudy` — então cravar `/tostudy` dava "Unknown command: /tostudy" e o
44
+ * curso não iniciava. Aqui varremos `.claude/commands/tostudy*.md` e usamos o
45
+ * comando real; com vários cursos, casamos com o `slug` ativo do
46
+ * `.tostudy/workspace.json`. Override explícito via PARIS_COACH_KICKOFF.
47
+ * Fallback `/tostudy` (legado / antes do `tostudy` instalar o comando).
48
+ */
49
+ export declare function resolveKickoff(cwd: string): string;
50
+ /**
51
+ * Spawn the coached pty (`claude '/tostudy-<curso>'` inside the provisioned
52
+ * workspace). Shared by the local ws server and the relay agent. Throws if
53
+ * node-pty can't load/spawn — callers report it on their channel.
44
54
  */
45
55
  export declare function spawnCoachPty(cwd: string): IPty;
46
56
  /**
@@ -1,6 +1,6 @@
1
1
  import { WebSocketServer } from 'ws';
2
2
  import { createRequire } from 'node:module';
3
- import { promises as fs, chmodSync, existsSync, statSync } from 'node:fs';
3
+ import { promises as fs, chmodSync, existsSync, statSync, readdirSync, readFileSync } from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { readCredentials } from '../lib/credentials.js';
6
6
  import { ensureWorkspace } from './install.js';
@@ -69,20 +69,60 @@ const DEFAULT_ALLOWED_ORIGINS = [
69
69
  // `/tostudy` roda o curso real direto. Override com PARIS_COACH_KICKOFF se uma
70
70
  // turma precisar de outro entrypoint (ex.: o tutor-paris `get_course` como
71
71
  // fallback quando não há curso ToStudy configurado).
72
- const COACH_KICKOFF = process.env.PARIS_COACH_KICKOFF || '/tostudy';
73
72
  /**
74
- * Spawn the coached pty (`claude '/tostudy'` inside the provisioned workspace).
75
- * Shared by the local ws server and the relay agent. Throws if node-pty can't
76
- * load/spawn — callers report it on their channel.
73
+ * Descobre o slash-command do tutor pra injetar no kickoff. O `@tostudy-ai/cli`
74
+ * instala o comando com nome ESPECÍFICO do curso (`.claude/commands/tostudy-<slug>.md`),
75
+ * NÃO `/tostudy` — então cravar `/tostudy` dava "Unknown command: /tostudy" e o
76
+ * curso não iniciava. Aqui varremos `.claude/commands/tostudy*.md` e usamos o
77
+ * comando real; com vários cursos, casamos com o `slug` ativo do
78
+ * `.tostudy/workspace.json`. Override explícito via PARIS_COACH_KICKOFF.
79
+ * Fallback `/tostudy` (legado / antes do `tostudy` instalar o comando).
80
+ */
81
+ export function resolveKickoff(cwd) {
82
+ const override = process.env.PARIS_COACH_KICKOFF;
83
+ if (override)
84
+ return override;
85
+ try {
86
+ const cmdDir = path.join(cwd, '.claude', 'commands');
87
+ const files = readdirSync(cmdDir).filter((f) => /^tostudy.*\.md$/i.test(f));
88
+ if (files.length === 0)
89
+ return '/tostudy';
90
+ let chosen = files.sort()[0];
91
+ if (files.length > 1) {
92
+ try {
93
+ const ws = JSON.parse(readFileSync(path.join(cwd, '.tostudy', 'workspace.json'), 'utf8'));
94
+ const slug = ws.slug?.toLowerCase();
95
+ if (slug) {
96
+ const match = files.find((f) => f.toLowerCase() === `tostudy-${slug}.md`) ??
97
+ files.find((f) => f.toLowerCase().includes(slug));
98
+ if (match)
99
+ chosen = match;
100
+ }
101
+ }
102
+ catch {
103
+ /* sem workspace.json legível — usa o primeiro */
104
+ }
105
+ }
106
+ return '/' + chosen.replace(/\.md$/i, '');
107
+ }
108
+ catch {
109
+ return '/tostudy';
110
+ }
111
+ }
112
+ /**
113
+ * Spawn the coached pty (`claude '/tostudy-<curso>'` inside the provisioned
114
+ * workspace). Shared by the local ws server and the relay agent. Throws if
115
+ * node-pty can't load/spawn — callers report it on their channel.
77
116
  */
78
117
  export function spawnCoachPty(cwd) {
79
118
  const req = createRequire(import.meta.url);
80
119
  ensureSpawnHelperExecutable(req);
81
120
  const ptyMod = req('node-pty');
121
+ const kickoff = resolveKickoff(cwd);
82
122
  const shell = process.env.SHELL || (process.platform === 'win32' ? 'powershell.exe' : 'bash');
83
123
  const shellArgs = process.platform === 'win32'
84
- ? ['-NoLogo', '-Command', `claude "${COACH_KICKOFF.replace(/"/g, '`"')}"`]
85
- : ['-l', '-c', `claude '${COACH_KICKOFF.replace(/'/g, `'\\''`)}'`];
124
+ ? ['-NoLogo', '-Command', `claude "${kickoff.replace(/"/g, '`"')}"`]
125
+ : ['-l', '-c', `claude '${kickoff.replace(/'/g, `'\\''`)}'`];
86
126
  return ptyMod.spawn(shell, shellArgs, {
87
127
  name: 'xterm-color',
88
128
  cols: 80,
package/dist/index.js CHANGED
@@ -9,10 +9,11 @@ import { reopenCommand } from './commands/reopen.js';
9
9
  import { graduateCommand } from './commands/graduate.js';
10
10
  import { logoutCommand } from './commands/logout.js';
11
11
  import { serveCommand } from './commands/serve.js';
12
+ import { daemonCommand } from './commands/daemon.js';
12
13
  const program = new Command()
13
14
  .name('paris')
14
15
  .description('Paris Immersion — CLI do aluno (login, workspace, tarefas)')
15
- .version('0.1.7');
16
+ .version('0.1.9');
16
17
  program
17
18
  .command('login')
18
19
  .description('Autenticar com sua conta Paris (device-code OR --token direto)')
@@ -56,6 +57,10 @@ program
56
57
  .description('Sobe WS local (ws://localhost:31000) para o terminal embarcado do onboarding')
57
58
  .option('--port <port>', 'Porta do WebSocket', '31000')
58
59
  .action(serveCommand);
60
+ program
61
+ .command('daemon <action>')
62
+ .description('Serviço persistente do paris serve (install | uninstall | status)')
63
+ .action(daemonCommand);
59
64
  program.parseAsync().catch((err) => {
60
65
  console.error('\n[paris] erro:', err?.message ?? err);
61
66
  process.exit(1);
@@ -0,0 +1,6 @@
1
+ export declare function installDaemon(): Promise<{
2
+ mechanism: string;
3
+ }>;
4
+ /** Best-effort — nunca lança (usado no logout, não pode travar). */
5
+ export declare function uninstallDaemon(): Promise<void>;
6
+ export declare function daemonStatus(): Promise<boolean>;
@@ -0,0 +1,246 @@
1
+ /**
2
+ * paris-serve como serviço persistente — pra que o terminal embutido do
3
+ * onboarding SEMPRE tenha um agente pareável, sem o aluno rodar nada e sem
4
+ * engasgo após reboot/crash. Leve: o serve só mantém uma conexão wss com o
5
+ * relay; o Claude só é spawnado quando um viewer (a página do curso) conecta.
6
+ *
7
+ * - macOS → LaunchAgent (~/Library/LaunchAgents) com RunAtLoad + KeepAlive.
8
+ * - Windows→ Scheduled Task AtLogOn (oculta, via .vbs) com restart-on-failure.
9
+ * - Linux → systemd --user service (Restart=always); senão erro amigável.
10
+ *
11
+ * Removido por `paris logout` (uninstallDaemon) ou `paris daemon uninstall`.
12
+ */
13
+ import { promises as fs } from 'node:fs';
14
+ import fsSync from 'node:fs';
15
+ import { homedir, platform } from 'node:os';
16
+ import path from 'node:path';
17
+ import { execFile } from 'node:child_process';
18
+ import { promisify } from 'node:util';
19
+ import { readCredentials } from './credentials.js';
20
+ const execFileAsync = promisify(execFile);
21
+ const LABEL = 'ai.parisgroup.serve';
22
+ const WIN_TASK = 'ParisServe';
23
+ function parisDir() {
24
+ return path.join(homedir(), '.paris');
25
+ }
26
+ function serveLog() {
27
+ return path.join(parisDir(), 'serve.log');
28
+ }
29
+ /** Caminhos absolutos que o launchd/Task precisam pra rodar `paris serve`. */
30
+ function resolveRun() {
31
+ const node = process.execPath;
32
+ let entry = process.argv[1] || '';
33
+ try {
34
+ entry = fsSync.realpathSync(entry);
35
+ }
36
+ catch {
37
+ /* mantém argv[1] */
38
+ }
39
+ return { node, entry };
40
+ }
41
+ async function resolveApiUrl() {
42
+ if (process.env.PARIS_API_URL)
43
+ return process.env.PARIS_API_URL;
44
+ const creds = await readCredentials();
45
+ return creds?.api_url ?? undefined;
46
+ }
47
+ function escapeXml(s) {
48
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
49
+ }
50
+ // ─── macOS (launchd) ──────────────────────────────────────────────────────
51
+ function plistPath() {
52
+ return path.join(homedir(), 'Library', 'LaunchAgents', `${LABEL}.plist`);
53
+ }
54
+ function buildPlist(node, entry, apiUrl, pathEnv) {
55
+ const env = [
56
+ apiUrl ? ` <key>PARIS_API_URL</key><string>${escapeXml(apiUrl)}</string>` : '',
57
+ ` <key>PATH</key><string>${escapeXml(pathEnv)}</string>`,
58
+ ]
59
+ .filter(Boolean)
60
+ .join('\n');
61
+ return `<?xml version="1.0" encoding="UTF-8"?>
62
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
63
+ <plist version="1.0">
64
+ <dict>
65
+ <key>Label</key><string>${LABEL}</string>
66
+ <key>ProgramArguments</key>
67
+ <array>
68
+ <string>${escapeXml(node)}</string>
69
+ <string>${escapeXml(entry)}</string>
70
+ <string>serve</string>
71
+ </array>
72
+ <key>EnvironmentVariables</key>
73
+ <dict>
74
+ ${env}
75
+ </dict>
76
+ <key>RunAtLoad</key><true/>
77
+ <key>KeepAlive</key><true/>
78
+ <key>ThrottleInterval</key><integer>10</integer>
79
+ <key>ProcessType</key><string>Background</string>
80
+ <key>StandardOutPath</key><string>${escapeXml(serveLog())}</string>
81
+ <key>StandardErrorPath</key><string>${escapeXml(serveLog())}</string>
82
+ </dict>
83
+ </plist>
84
+ `;
85
+ }
86
+ function guiDomain() {
87
+ const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
88
+ return `gui/${uid}`;
89
+ }
90
+ async function installDarwin() {
91
+ const { node, entry } = resolveRun();
92
+ const apiUrl = await resolveApiUrl();
93
+ const pathEnv = process.env.PATH || '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin';
94
+ await fs.mkdir(parisDir(), { recursive: true, mode: 0o700 });
95
+ await fs.mkdir(path.dirname(plistPath()), { recursive: true });
96
+ const p = plistPath();
97
+ await fs.writeFile(p, buildPlist(node, entry, apiUrl, pathEnv));
98
+ const domain = guiDomain();
99
+ await execFileAsync('launchctl', ['bootout', `${domain}/${LABEL}`]).catch(() => { });
100
+ try {
101
+ await execFileAsync('launchctl', ['bootstrap', domain, p]);
102
+ }
103
+ catch {
104
+ // launchctl mais antigo / edge — caminho clássico.
105
+ await execFileAsync('launchctl', ['unload', p]).catch(() => { });
106
+ await execFileAsync('launchctl', ['load', '-w', p]);
107
+ }
108
+ await execFileAsync('launchctl', ['kickstart', '-k', `${domain}/${LABEL}`]).catch(() => { });
109
+ }
110
+ async function uninstallDarwin() {
111
+ const p = plistPath();
112
+ await execFileAsync('launchctl', ['bootout', `${guiDomain()}/${LABEL}`]).catch(() => { });
113
+ await execFileAsync('launchctl', ['unload', p]).catch(() => { });
114
+ await fs.rm(p, { force: true }).catch(() => { });
115
+ }
116
+ async function statusDarwin() {
117
+ try {
118
+ const { stdout } = await execFileAsync('launchctl', ['list']);
119
+ return stdout.includes(LABEL);
120
+ }
121
+ catch {
122
+ return false;
123
+ }
124
+ }
125
+ // ─── Windows (Scheduled Task, oculto via .vbs) ──────────────────────────────
126
+ async function installWin32() {
127
+ const { node, entry } = resolveRun();
128
+ const apiUrl = await resolveApiUrl();
129
+ await fs.mkdir(parisDir(), { recursive: true });
130
+ const log = serveLog();
131
+ const cmdPath = path.join(parisDir(), 'serve-daemon.cmd');
132
+ const vbsPath = path.join(parisDir(), 'serve-daemon.vbs');
133
+ const cmd = `@echo off\r\n` +
134
+ (apiUrl ? `set "PARIS_API_URL=${apiUrl}"\r\n` : '') +
135
+ `"${node}" "${entry}" serve >> "${log}" 2>&1\r\n`;
136
+ await fs.writeFile(cmdPath, cmd);
137
+ // .vbs roda o .cmd com janela 0 (oculta) — evita o flash do console no logon.
138
+ await fs.writeFile(vbsPath, `CreateObject("Wscript.Shell").Run "cmd /c ""${cmdPath}""", 0, False\r\n`);
139
+ const ps = [
140
+ `$a = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument '"${vbsPath}"'`,
141
+ `$t = New-ScheduledTaskTrigger -AtLogOn`,
142
+ `$s = New-ScheduledTaskSettingsSet -Hidden -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1)`,
143
+ `Register-ScheduledTask -TaskName '${WIN_TASK}' -Action $a -Trigger $t -Settings $s -Force | Out-Null`,
144
+ `Start-ScheduledTask -TaskName '${WIN_TASK}'`,
145
+ ].join('; ');
146
+ await execFileAsync('powershell', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', ps]);
147
+ }
148
+ async function uninstallWin32() {
149
+ await execFileAsync('powershell', [
150
+ '-NoProfile',
151
+ '-Command',
152
+ `Unregister-ScheduledTask -TaskName '${WIN_TASK}' -Confirm:$false`,
153
+ ]).catch(() => { });
154
+ }
155
+ async function statusWin32() {
156
+ try {
157
+ await execFileAsync('schtasks', ['/Query', '/TN', WIN_TASK]);
158
+ return true;
159
+ }
160
+ catch {
161
+ return false;
162
+ }
163
+ }
164
+ // ─── Linux (systemd --user) ────────────────────────────────────────────────
165
+ function unitPath() {
166
+ return path.join(homedir(), '.config', 'systemd', 'user', 'paris-serve.service');
167
+ }
168
+ async function installLinux() {
169
+ const { node, entry } = resolveRun();
170
+ const apiUrl = await resolveApiUrl();
171
+ await fs.mkdir(path.dirname(unitPath()), { recursive: true });
172
+ const unit = `[Unit]
173
+ Description=Paris Immersion serve (agente do terminal embutido)
174
+ After=network-online.target
175
+
176
+ [Service]
177
+ ExecStart=${node} ${entry} serve
178
+ Restart=always
179
+ RestartSec=5
180
+ ${apiUrl ? `Environment=PARIS_API_URL=${apiUrl}\n` : ''}Environment=PATH=${process.env.PATH || '/usr/local/bin:/usr/bin:/bin'}
181
+
182
+ [Install]
183
+ WantedBy=default.target
184
+ `;
185
+ await fs.writeFile(unitPath(), unit);
186
+ await execFileAsync('systemctl', ['--user', 'daemon-reload']).catch(() => { });
187
+ await execFileAsync('systemctl', ['--user', 'enable', '--now', 'paris-serve.service']);
188
+ }
189
+ async function uninstallLinux() {
190
+ await execFileAsync('systemctl', ['--user', 'disable', '--now', 'paris-serve.service']).catch(() => { });
191
+ await fs.rm(unitPath(), { force: true }).catch(() => { });
192
+ await execFileAsync('systemctl', ['--user', 'daemon-reload']).catch(() => { });
193
+ }
194
+ async function statusLinux() {
195
+ try {
196
+ const { stdout } = await execFileAsync('systemctl', ['--user', 'is-active', 'paris-serve.service']);
197
+ return stdout.trim() === 'active';
198
+ }
199
+ catch {
200
+ return false;
201
+ }
202
+ }
203
+ // ─── API pública ────────────────────────────────────────────────────────────
204
+ export async function installDaemon() {
205
+ switch (platform()) {
206
+ case 'darwin':
207
+ await installDarwin();
208
+ return { mechanism: 'launchd LaunchAgent (RunAtLoad + KeepAlive)' };
209
+ case 'win32':
210
+ await installWin32();
211
+ return { mechanism: 'Scheduled Task AtLogOn (oculta, restart-on-failure)' };
212
+ case 'linux':
213
+ await installLinux();
214
+ return { mechanism: 'systemd --user (Restart=always)' };
215
+ default:
216
+ throw new Error(`plataforma não suportada para daemon: ${platform()}`);
217
+ }
218
+ }
219
+ /** Best-effort — nunca lança (usado no logout, não pode travar). */
220
+ export async function uninstallDaemon() {
221
+ try {
222
+ switch (platform()) {
223
+ case 'darwin':
224
+ return await uninstallDarwin();
225
+ case 'win32':
226
+ return await uninstallWin32();
227
+ case 'linux':
228
+ return await uninstallLinux();
229
+ }
230
+ }
231
+ catch {
232
+ /* best-effort */
233
+ }
234
+ }
235
+ export async function daemonStatus() {
236
+ switch (platform()) {
237
+ case 'darwin':
238
+ return statusDarwin();
239
+ case 'win32':
240
+ return statusWin32();
241
+ case 'linux':
242
+ return statusLinux();
243
+ default:
244
+ return false;
245
+ }
246
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paris-immersion",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "Paris Immersion CLI — login, install workspace, status, task control. Para alunos das imersões da Paris Group.",
5
5
  "homepage": "https://parisgroup.ai",
6
6
  "repository": {