@commonlyai/cli 0.1.142 → 0.1.147

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.142",
3
+ "version": "0.1.147",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -174,7 +174,7 @@ live.
174
174
 
175
175
  | what you produced | where it belongs |
176
176
  |---|---|
177
- | a review of a pull request | `gh pr review` — approve, or request changes |
177
+ | a review of a pull request | review on the pull request, not only in chat |
178
178
  | a decision with a lasting consequence | an ADR in `docs/adr/` |
179
179
  | an idea nobody is building yet | the idea register |
180
180
  | a bug or a piece of work | a GitHub issue |
@@ -183,8 +183,7 @@ live.
183
183
  This matters most for reviews. Excellent review reasoning posted as a pod
184
184
  message does not gate anything and cannot be acted on by someone reading the
185
185
  pull request — the merge button does not know the conversation happened. If you
186
- reviewed something and it is not ready, **say so on the pull request** with
187
- `gh pr review --request-changes`, not only in chat.
186
+ reviewed something, say so on the pull request, not only in chat.
188
187
 
189
188
  When you approve, say what you verified AND what you could not. An unqualified
190
189
  approval on something you did not check is worse than a partial one, because it
@@ -13,7 +13,10 @@ import {
13
13
  } from 'fs';
14
14
  import { createClient } from '../lib/api.js';
15
15
  import { getToken, resolveInstanceUrl } from '../lib/config.js';
16
- import { loadDaemonRecord, removeDaemonRecord, saveDaemonRecord } from '../lib/daemon-store.js';
16
+ import {
17
+ clearDaemonStop, loadDaemonRecord, loadDaemonStop, removeDaemonRecord,
18
+ saveDaemonRecord, saveDaemonStop,
19
+ } from '../lib/daemon-store.js';
17
20
  import {
18
21
  createDaemonSupervisor,
19
22
  DEFAULT_HEARTBEAT_MS,
@@ -117,21 +120,73 @@ export const heartbeatDaemonMachine = async ({ client, record }) => (
117
120
  client.post(`/api/machines/${record.machineDbId}/heartbeat`)
118
121
  );
119
122
 
120
- export const getDaemonMachineStatus = async ({ client }) => {
123
+ export const getDaemonMachineStatus = async ({ client, record }) => {
121
124
  const response = await client.get('/api/machines/me');
122
- return response?.machine || null;
125
+ const machine = response?.machine;
126
+ if (!machine || typeof machine !== 'object' || Array.isArray(machine)
127
+ || !machine.id || !machine.machineId
128
+ || (record && (machine.id !== record.machineDbId || machine.machineId !== record.machineId))) {
129
+ throw new Error('Unexpected daemon status response; local credential kept.');
130
+ }
131
+ return machine;
132
+ };
133
+
134
+ const isRevokedDaemonKey = (error) => error?.status === 401 && [
135
+ 'Daemon token revoked or unknown',
136
+ 'Machine access revoked',
137
+ ].includes(error?.body?.message);
138
+
139
+ const isMissingDaemonMachine = (error) => error?.status === 404
140
+ && error?.body?.message === 'Machine not found';
141
+
142
+ const storedDaemonState = async (client, record) => {
143
+ try {
144
+ await getDaemonMachineStatus({ client, record });
145
+ return 'active';
146
+ } catch (error) {
147
+ if (isRevokedDaemonKey(error)) return 'revoked';
148
+ if (isMissingDaemonMachine(error)) return 'missing';
149
+ throw error;
150
+ }
123
151
  };
124
152
 
125
- // Revoke remotely before unlinking locally. A failed network call must leave
126
- // the bearer record intact so the operator can retry rather than orphaning a
127
- // year-long daemon credential they can no longer address from the CLI.
128
- export const unregisterDaemonMachine = async ({ client, record, remove = removeDaemonRecord }) => {
153
+ export const daemonStatusErrorMessage = (error) => (isRevokedDaemonKey(error)
154
+ ? "This computer's old key was revoked. Run: commonly daemon register"
155
+ : isMissingDaemonMachine(error)
156
+ ? 'This computer is no longer registered. Run: commonly daemon register'
157
+ : `Daemon status failed: ${error.message}`);
158
+
159
+ // Keep the old record until a new registration is securely persisted. A
160
+ // network failure or a still-live daemon key must never silently mint another.
161
+ export const allowRevokedDaemonReplacement = async ({ existing, client }) => {
162
+ if (!existing) return null;
163
+ const state = await storedDaemonState(client, existing);
164
+ if (state === 'active') {
165
+ throw new Error(`A local daemon is already registered for ${existing.machineName}. Run: commonly daemon status`);
166
+ }
167
+ return state;
168
+ };
169
+
170
+ // Revoke remotely before unlinking locally. An owner-session 401/403 is not
171
+ // proof of revocation: check the stored daemon key before discarding it.
172
+ export const unregisterDaemonMachine = async ({
173
+ client, daemonClient, record, remove = removeDaemonRecord,
174
+ }) => {
175
+ let removedRemotely = true;
129
176
  try {
130
177
  await client.del(`/api/machines/${record.machineDbId}`);
131
178
  } catch (error) {
132
- if (error?.status !== 404) throw error;
179
+ if (isMissingDaemonMachine(error)) {
180
+ removedRemotely = false;
181
+ } else if ([401, 403].includes(error?.status) && daemonClient) {
182
+ if (await storedDaemonState(daemonClient, record) === 'active') throw error;
183
+ removedRemotely = false;
184
+ } else {
185
+ throw error;
186
+ }
133
187
  }
134
188
  remove();
189
+ return { removedRemotely };
135
190
  };
136
191
 
137
192
  // The adapter names a binary on THIS machine — the one fact the server cannot
@@ -173,7 +228,13 @@ Examples:
173
228
  try {
174
229
  const existing = loadDaemonRecord();
175
230
  if (existing) {
176
- throw new Error(`A local daemon is already registered for ${existing.machineName}. Run: commonly daemon status`);
231
+ const state = await allowRevokedDaemonReplacement({
232
+ existing,
233
+ client: createClient({ instance: existing.instanceUrl, token: existing.daemonToken }),
234
+ });
235
+ console.log(state === 'revoked'
236
+ ? "This computer's old key was revoked; registering it again."
237
+ : 'This computer is no longer registered; registering it again.');
177
238
  }
178
239
  const instanceUrl = resolveInstanceUrl(opts.instance);
179
240
  const client = createClient({ instance: instanceUrl, token: requireUserToken(opts.instance || instanceUrl) });
@@ -182,6 +243,7 @@ Examples:
182
243
  instanceUrl,
183
244
  name: String(opts.name || hostname()).trim(),
184
245
  });
246
+ clearDaemonStop();
185
247
  console.log(`Registered ${machine.name}. Daemon credential stored securely.`);
186
248
 
187
249
  try {
@@ -195,6 +257,9 @@ Examples:
195
257
  console.error('Retry with: commonly daemon heartbeat');
196
258
  process.exitCode = 1;
197
259
  }
260
+ if (existing && existsSync(servicePaths(process.platform, homedir()).file)) {
261
+ console.log('Restart the installed daemon to use the new key: commonly daemon restart');
262
+ }
198
263
  } catch (error) {
199
264
  console.error(`Daemon registration failed: ${error.message}`);
200
265
  process.exitCode = 1;
@@ -211,8 +276,14 @@ Examples:
211
276
  instance: record.instanceUrl,
212
277
  token: requireUserToken(record.instanceUrl),
213
278
  });
214
- await unregisterDaemonMachine({ client, record });
215
- console.log(`Unregistered ${record.machineName} and removed its local daemon credential.`);
279
+ const { removedRemotely } = await unregisterDaemonMachine({
280
+ client,
281
+ daemonClient: createClient({ instance: record.instanceUrl, token: record.daemonToken }),
282
+ record,
283
+ });
284
+ console.log(removedRemotely
285
+ ? `Unregistered ${record.machineName} and removed its local daemon credential.`
286
+ : `Removed ${record.machineName}'s local daemon credential. Server access was already revoked or the machine was removed.`);
216
287
  } catch (error) {
217
288
  console.error(`Daemon unregister failed: ${error.message}`);
218
289
  process.exitCode = 1;
@@ -343,8 +414,23 @@ Examples:
343
414
  .option('--heartbeat <ms>', 'Heartbeat interval in ms', String(DEFAULT_HEARTBEAT_MS))
344
415
  .option('--foreground', 'Keep the supervisor attached to this terminal (default for direct invocation)')
345
416
  .action(async (opts) => {
417
+ let record;
346
418
  try {
347
- const record = requireDaemonRecord();
419
+ const terminal = loadDaemonStop();
420
+ if (terminal) {
421
+ console.error('Daemon stopped: no valid local registration. Run: commonly daemon register');
422
+ process.exitCode = process.platform === 'darwin' ? 0 : terminal.exitCode;
423
+ return;
424
+ }
425
+ record = requireDaemonRecord();
426
+ const stopped = loadDaemonStop(record);
427
+ if (stopped) {
428
+ console.error("Daemon stopped: this computer's key was revoked. Run: commonly daemon register");
429
+ // launchd restarts the first nonzero terminal exit once; a saved
430
+ // verdict makes that second invocation successful and ends the loop.
431
+ process.exitCode = process.platform === 'darwin' ? 0 : stopped.exitCode;
432
+ return;
433
+ }
348
434
  const client = createClient({ instance: record.instanceUrl, token: record.daemonToken });
349
435
  const logsDir = daemonLogsDir();
350
436
  if (!existsSync(logsDir)) mkdirSync(logsDir, { recursive: true });
@@ -365,9 +451,34 @@ Examples:
365
451
  stampLog(`WARNING: ${name} is not set in this environment — a seat whose adapter needs it will fail to start. Export it and re-run: commonly daemon install (docs/agents/daemon-service-environment.md)`);
366
452
  }
367
453
 
368
- const supervisor = createDaemonSupervisor({
454
+ let pollTimer;
455
+ let heartbeatTimer;
456
+ let supervisor;
457
+ let terminalEnded = false;
458
+ const terminalAuth = (error) => isRevokedDaemonKey(error)
459
+ || isMissingDaemonMachine(error);
460
+ const onTerminalAuthError = () => {
461
+ terminalEnded = true;
462
+ let saved = false;
463
+ try {
464
+ saveDaemonStop(record, 77);
465
+ saved = true;
466
+ } catch (error) {
467
+ stampLog(`could not save revoked-machine stop marker: ${error.message}`);
468
+ }
469
+ stampLog("machine key revoked; stopping supervised agents. Run: commonly daemon register");
470
+ clearInterval(pollTimer);
471
+ clearInterval(heartbeatTimer);
472
+ supervisor.stop();
473
+ // Without the marker launchd would restart forever. A successful
474
+ // exit parks it on macOS; systemd honors 77 directly.
475
+ process.exitCode = saved || process.platform !== 'darwin' ? 77 : 0;
476
+ };
477
+ supervisor = createDaemonSupervisor({
369
478
  record,
370
479
  client,
480
+ isTerminalAuthError: terminalAuth,
481
+ onTerminalAuthError,
371
482
  // One child per agent, logging to its own file. The child is the
372
483
  // ordinary `commonly agent run <name>` — the daemon is its
373
484
  // supervisor, never its replacement (D6).
@@ -396,9 +507,20 @@ Examples:
396
507
 
397
508
  stampLog(`daemon supervising for ${record.machineName} — poll ${opts.poll}ms, heartbeat ${opts.heartbeat}ms (ctrl+c to stop)`);
398
509
  await supervisor.tick();
510
+ if (terminalEnded) return;
399
511
  await supervisor.heartbeat();
400
- const pollTimer = setInterval(() => supervisor.tick(), Number(opts.poll) || DEFAULT_POLL_MS);
401
- const heartbeatTimer = setInterval(() => supervisor.heartbeat(), Number(opts.heartbeat) || DEFAULT_HEARTBEAT_MS);
512
+ if (terminalEnded) return;
513
+ const runtimeFailure = (error) => {
514
+ if (terminalEnded) return;
515
+ terminalEnded = true;
516
+ stampLog(`daemon runtime failed: ${error.message}`);
517
+ clearInterval(pollTimer);
518
+ clearInterval(heartbeatTimer);
519
+ supervisor.stop();
520
+ process.exitCode = 75;
521
+ };
522
+ pollTimer = setInterval(() => { void supervisor.tick().catch(runtimeFailure); }, Number(opts.poll) || DEFAULT_POLL_MS);
523
+ heartbeatTimer = setInterval(() => { void supervisor.heartbeat().catch(runtimeFailure); }, Number(opts.heartbeat) || DEFAULT_HEARTBEAT_MS);
402
524
  const shutdown = () => {
403
525
  stampLog('daemon stopping — terminating supervised agents');
404
526
  clearInterval(pollTimer);
@@ -410,7 +532,19 @@ Examples:
410
532
  process.on('SIGTERM', shutdown);
411
533
  } catch (error) {
412
534
  console.error(`Daemon run failed: ${error.message}`);
413
- process.exitCode = 1;
535
+ const badConfig = !record || error.message.startsWith('Daemon credential file');
536
+ if (badConfig) {
537
+ try {
538
+ saveDaemonStop(record || { machineDbId: 'unregistered' }, 78);
539
+ } catch (markerError) {
540
+ console.error(`Could not save daemon stop marker: ${markerError.message}`);
541
+ if (process.platform === 'darwin') {
542
+ process.exitCode = 0;
543
+ return;
544
+ }
545
+ }
546
+ }
547
+ process.exitCode = badConfig ? 78 : 75;
414
548
  }
415
549
  });
416
550
 
@@ -423,11 +557,8 @@ Examples:
423
557
  const record = requireDaemonRecord();
424
558
  const machine = await getDaemonMachineStatus({
425
559
  client: createClient({ instance: record.instanceUrl, token: record.daemonToken }),
560
+ record,
426
561
  });
427
- if (!machine) {
428
- console.log(`${record.machineName}: no longer registered on the server.`);
429
- return;
430
- }
431
562
  const lastSeen = machine.lastSeenAt ? new Date(machine.lastSeenAt).toLocaleString() : 'never';
432
563
  console.log(`${machine.name}: ${machine.status} (last heartbeat: ${lastSeen})`);
433
564
  if (opts.verbose) {
@@ -442,7 +573,7 @@ Examples:
442
573
  }
443
574
  }
444
575
  } catch (error) {
445
- console.error(`Daemon status failed: ${error.message}`);
576
+ console.error(daemonStatusErrorMessage(error));
446
577
  process.exitCode = 1;
447
578
  }
448
579
  });
@@ -1,8 +1,7 @@
1
1
  /**
2
2
  * ADR-026 D1: install-once service registration for the resident daemon.
3
3
  *
4
- * macOS gets a launchd LaunchAgent (KeepAlive — launchd itself restarts a
5
- * dead daemon), Linux a systemd user unit (Restart=always). Both run the
4
+ * macOS gets a launchd LaunchAgent, Linux a systemd user unit. Both run the
6
5
  * exact interpreter + CLI entry that executed `daemon install`, resolved at
7
6
  * install time — a PATH lookup at boot would race version managers and
8
7
  * silently run a different install than the one the user tested.
@@ -165,7 +164,10 @@ ${plistEnvPairs(providerEnv)}\t</dict>
165
164
  \t<key>RunAtLoad</key>
166
165
  \t<true/>
167
166
  \t<key>KeepAlive</key>
168
- \t<true/>
167
+ \t<dict>
168
+ \t\t<key>SuccessfulExit</key>
169
+ \t\t<false/>
170
+ \t</dict>
169
171
  \t<key>StandardOutPath</key>
170
172
  \t<string>${xmlEscape(daemonLogPath(home))}</string>
171
173
  \t<key>StandardErrorPath</key>
@@ -185,6 +187,7 @@ After=network-online.target
185
187
  [Service]
186
188
  ExecStart=${nodePath} ${cliPath} daemon run --foreground
187
189
  Restart=always
190
+ RestartPreventExitStatus=77 78
188
191
  RestartSec=5
189
192
  Environment=PATH=${childPath(nodePath)}${providerLines}
190
193
 
@@ -21,6 +21,35 @@ import { join } from 'path';
21
21
 
22
22
  const daemonDir = () => join(homedir(), '.commonly', 'daemon');
23
23
  export const daemonRecordPath = () => join(daemonDir(), 'machine.json');
24
+ export const daemonStopPath = () => join(daemonDir(), 'stopped.json');
25
+
26
+ // A terminal machine-key verdict survives launchd's one unavoidable restart.
27
+ // It contains no bearer; registration clears it only after the new key is safe.
28
+ export const loadDaemonStop = (record = { machineDbId: 'unregistered' }) => {
29
+ const path = daemonStopPath();
30
+ if (!existsSync(path)) return null;
31
+ const value = JSON.parse(readFileSync(path, 'utf8'));
32
+ return value.machineDbId === record.machineDbId ? value : null;
33
+ };
34
+
35
+ export const saveDaemonStop = (record, exitCode) => {
36
+ const dir = daemonDir();
37
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
38
+ chmodSync(dir, 0o700);
39
+ const path = daemonStopPath();
40
+ const tmp = `${path}.${process.pid}.tmp`;
41
+ try {
42
+ writeFileSync(tmp, `${JSON.stringify({ machineDbId: record.machineDbId, exitCode })}\n`, { mode: 0o600, flag: 'wx' });
43
+ renameSync(tmp, path);
44
+ } catch (error) {
45
+ if (existsSync(tmp)) unlinkSync(tmp);
46
+ throw error;
47
+ }
48
+ };
49
+
50
+ export const clearDaemonStop = () => {
51
+ if (existsSync(daemonStopPath())) unlinkSync(daemonStopPath());
52
+ };
24
53
 
25
54
  const validateRecord = (record) => {
26
55
  if (!record
@@ -33,6 +33,14 @@ export const DEFAULT_POLL_MS = 30_000;
33
33
  export const DEFAULT_HEARTBEAT_MS = 30_000;
34
34
  export const BACKOFF_BASE_MS = 5_000;
35
35
  export const BACKOFF_MAX_MS = 60_000;
36
+ export const MAX_CONCURRENT_AGENT_STARTS = 3;
37
+ export const AGENT_START_WINDOW_MS = 5_000;
38
+ export const RECONNECT_MAX_MS = 60_000;
39
+
40
+ export const reconnectDelayMs = (failures, random = Math.random) => {
41
+ const ceiling = Math.min(RECONNECT_MAX_MS, 1_000 * 2 ** Math.min(failures, 6));
42
+ return Math.floor(1_000 + random() * (ceiling - 1_000));
43
+ };
36
44
 
37
45
  const workspacePathFor = (environment) => {
38
46
  const declared = environment?.workspace?.path;
@@ -59,12 +67,35 @@ export const createDaemonSupervisor = ({
59
67
  resolveAdapter, // async (runtime) => adapter name for THIS machine
60
68
  persistState = () => {}, // (agentStates) => void; must not persist secrets
61
69
  log = () => {},
70
+ isTerminalAuthError = () => false,
71
+ onTerminalAuthError = () => {},
72
+ now = Date.now,
73
+ random = Math.random,
62
74
  setTimeoutFn = setTimeout,
63
75
  clearTimeoutFn = clearTimeout,
64
76
  }) => {
65
77
  // key → { agentName, instanceId, child, state, restarts, backoffTimer, desired }
66
78
  const seats = new Map();
67
79
  let stopped = false;
80
+ let reconnectFailures = 0;
81
+ let reconnectAfter = 0;
82
+ const recentStarts = [];
83
+
84
+ const connectionFailure = (error, label) => {
85
+ if (isTerminalAuthError(error)) {
86
+ stopped = true;
87
+ onTerminalAuthError(error);
88
+ return;
89
+ }
90
+ reconnectFailures += 1;
91
+ reconnectAfter = now() + reconnectDelayMs(reconnectFailures, random);
92
+ log(`${label}: ${error.message}; reconnect after ${Math.round((reconnectAfter - now()) / 1000)}s`);
93
+ };
94
+
95
+ const connectionRestored = () => {
96
+ reconnectFailures = 0;
97
+ reconnectAfter = 0;
98
+ };
68
99
 
69
100
  const persist = () => {
70
101
  try {
@@ -90,7 +121,19 @@ export const createDaemonSupervisor = ({
90
121
  }));
91
122
 
92
123
  const startChild = (seat) => {
93
- if (stopped || !seat.desired || seat.child) return;
124
+ if (stopped || !seat.desired || seat.child || seat.startDelayTimer) return;
125
+ const at = now();
126
+ while (recentStarts.length && recentStarts[0] + AGENT_START_WINDOW_MS <= at) {
127
+ recentStarts.shift();
128
+ }
129
+ if (recentStarts.length >= MAX_CONCURRENT_AGENT_STARTS) {
130
+ seat.startDelayTimer = setTimeoutFn(() => {
131
+ seat.startDelayTimer = null;
132
+ startChild(seat);
133
+ }, Math.max(1, recentStarts[0] + AGENT_START_WINDOW_MS - at));
134
+ return;
135
+ }
136
+ recentStarts.push(at);
94
137
  seat.child = spawnChild(seat.agentName);
95
138
  seat.state = 'running';
96
139
  seat.pid = Number.isInteger(seat.child?.pid) ? seat.child.pid : null;
@@ -121,6 +164,10 @@ export const createDaemonSupervisor = ({
121
164
 
122
165
  const stopSeat = (seat) => {
123
166
  seat.desired = false;
167
+ if (seat.startDelayTimer) {
168
+ clearTimeoutFn(seat.startDelayTimer);
169
+ seat.startDelayTimer = null;
170
+ }
124
171
  if (seat.backoffTimer) {
125
172
  clearTimeoutFn(seat.backoffTimer);
126
173
  seat.backoffTimer = null;
@@ -411,14 +458,15 @@ export const createDaemonSupervisor = ({
411
458
  };
412
459
 
413
460
  const tick = async () => {
414
- if (stopped) return;
461
+ if (stopped || now() < reconnectAfter) return;
415
462
  let assigned;
416
463
  try {
417
464
  assigned = await client.get('/api/agent-binding/assigned');
418
465
  } catch (error) {
419
- log(`work-list fetch failed: ${error.message}`);
466
+ connectionFailure(error, 'work-list fetch failed');
420
467
  return;
421
468
  }
469
+ connectionRestored();
422
470
  const rows = Array.isArray(assigned?.agents) ? assigned.agents : [];
423
471
 
424
472
  const bound = [];
@@ -453,6 +501,7 @@ export const createDaemonSupervisor = ({
453
501
  state: 'stopped',
454
502
  restarts: 0,
455
503
  backoffTimer: null,
504
+ startDelayTimer: null,
456
505
  desired: true,
457
506
  adapter: null,
458
507
  model: null,
@@ -501,11 +550,12 @@ export const createDaemonSupervisor = ({
501
550
  };
502
551
 
503
552
  const heartbeat = async () => {
504
- if (stopped) return;
553
+ if (stopped || now() < reconnectAfter) return;
505
554
  try {
506
555
  await client.post(`/api/machines/${record.machineDbId}/heartbeat`, { agents: agentStates() });
556
+ connectionRestored();
507
557
  } catch (error) {
508
- log(`heartbeat failed: ${error.message}`);
558
+ connectionFailure(error, 'heartbeat failed');
509
559
  }
510
560
  };
511
561