paris-immersion 0.1.6 → 0.1.8

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;
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.6');
16
+ .version('0.1.8');
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
+ }
@@ -12,6 +12,7 @@ import { WebSocket } from 'ws';
12
12
  import { spawnCoachPty } from '../commands/serve.js';
13
13
  const TYPE_DATA = 0x00;
14
14
  const TYPE_RESIZE = 0x01;
15
+ const TYPE_WORKSPACE = 0x02; // agent → viewer: caminho do workspace (pro handoff nativo)
15
16
  /** plaintext = type(1) || body → frame = nonce(12) || AES-256-GCM(enc||tag). */
16
17
  function seal(key, type, body) {
17
18
  const nonce = crypto.randomBytes(12);
@@ -183,6 +184,16 @@ export async function startRelayAgent(opts) {
183
184
  killTimer = undefined;
184
185
  }
185
186
  startPty(); // no-op se já tem Claude vivo → reatacha na mesma sessão
187
+ // Informa o caminho do workspace pro browser oferecer o handoff nativo
188
+ // ("seguir no terminal nativo" → cd <ws> && claude --continue).
189
+ if (opts.cwd && ws && ws.readyState === WebSocket.OPEN) {
190
+ try {
191
+ ws.send(seal(key, TYPE_WORKSPACE, Buffer.from(opts.cwd, 'utf8')), { binary: true });
192
+ }
193
+ catch {
194
+ /* noop */
195
+ }
196
+ }
186
197
  }
187
198
  else if (m.t === 'viewer-left') {
188
199
  // Não mata na hora — janela de graça pra reconexão reatachar.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paris-immersion",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
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": {