@commonlyai/cli 0.1.31 → 0.1.32

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,8 +1,8 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.31",
3
+ "version": "0.1.32",
4
4
  "license": "Apache-2.0",
5
- "description": "The Commonly CLI \u2014 connect agents, manage pods, iterate fast",
5
+ "description": "The Commonly CLI connect agents, manage pods, iterate fast",
6
6
  "type": "module",
7
7
  "main": "./src/index.js",
8
8
  "bin": {
@@ -6,10 +6,20 @@
6
6
  * later slices; this command never reads an agent runtime credential.
7
7
  */
8
8
 
9
- import { hostname } from 'os';
9
+ import { hostname, homedir } from 'os';
10
+ import { spawn } from 'child_process';
11
+ import { existsSync, mkdirSync, openSync } from 'fs';
12
+ import { join } from 'path';
10
13
  import { createClient } from '../lib/api.js';
11
14
  import { getToken, resolveInstanceUrl } from '../lib/config.js';
12
15
  import { loadDaemonRecord, saveDaemonRecord } from '../lib/daemon-store.js';
16
+ import {
17
+ createDaemonSupervisor,
18
+ DEFAULT_HEARTBEAT_MS,
19
+ DEFAULT_POLL_MS,
20
+ } from '../lib/daemon-supervisor.js';
21
+ import { loadAgentToken, saveAgentToken } from './agent.js';
22
+ import { getAdapter } from '../lib/adapters/index.js';
13
23
 
14
24
  const requireDaemonRecord = () => {
15
25
  const record = loadDaemonRecord();
@@ -80,6 +90,20 @@ export const getDaemonMachineStatus = async ({ client }) => {
80
90
  return response?.machine || null;
81
91
  };
82
92
 
93
+ // The adapter names a binary on THIS machine — the one fact the server cannot
94
+ // know (same reasoning as `agent run`'s env bootstrap). A server-declared
95
+ // preference is honored when that CLI is installed; otherwise probe the known
96
+ // ones in order.
97
+ export const resolveAdapterForRuntime = async (runtime, registry = { getAdapter }) => {
98
+ const candidates = [runtime?.adapter, 'claude', 'codex'].filter(Boolean);
99
+ for (const name of candidates) {
100
+ const adapter = registry.getAdapter(name);
101
+ // eslint-disable-next-line no-await-in-loop
102
+ if (adapter && await adapter.detect()) return name;
103
+ }
104
+ return null;
105
+ };
106
+
83
107
  export const registerDaemon = (program) => {
84
108
  const daemon = program.command('daemon').description('Manage the local Commonly daemon');
85
109
 
@@ -147,6 +171,58 @@ Examples:
147
171
  }
148
172
  });
149
173
 
174
+ // ── run (ADR-026 Phase 2, slice 2) ────────────────────────────────────────
175
+ daemon
176
+ .command('run')
177
+ .description('Run the resident supervisor: adopt requested agents, keep bound agents running, report per-agent state')
178
+ .option('--poll <ms>', 'Work-list poll interval in ms', String(DEFAULT_POLL_MS))
179
+ .option('--heartbeat <ms>', 'Heartbeat interval in ms', String(DEFAULT_HEARTBEAT_MS))
180
+ .action(async (opts) => {
181
+ try {
182
+ const record = requireDaemonRecord();
183
+ const client = createClient({ instance: record.instanceUrl, token: record.daemonToken });
184
+ const logsDir = join(homedir(), '.commonly', 'logs', 'daemon');
185
+ if (!existsSync(logsDir)) mkdirSync(logsDir, { recursive: true });
186
+ const stampLog = (line) => console.log(`${new Date().toISOString()} ${line}`);
187
+
188
+ const supervisor = createDaemonSupervisor({
189
+ record,
190
+ client,
191
+ // One child per agent, logging to its own file. The child is the
192
+ // ordinary `commonly agent run <name>` — the daemon is its
193
+ // supervisor, never its replacement (D6).
194
+ spawnChild: (agentName) => {
195
+ const out = openSync(join(logsDir, `${agentName}.log`), 'a');
196
+ return spawn(process.execPath, [process.argv[1], 'agent', 'run', agentName], {
197
+ stdio: ['ignore', out, out],
198
+ });
199
+ },
200
+ loadToken: loadAgentToken,
201
+ saveToken: saveAgentToken,
202
+ resolveAdapter: (runtime) => resolveAdapterForRuntime(runtime),
203
+ log: stampLog,
204
+ });
205
+
206
+ stampLog(`daemon supervising for ${record.machineName} — poll ${opts.poll}ms, heartbeat ${opts.heartbeat}ms (ctrl+c to stop)`);
207
+ await supervisor.tick();
208
+ await supervisor.heartbeat();
209
+ const pollTimer = setInterval(() => supervisor.tick(), Number(opts.poll) || DEFAULT_POLL_MS);
210
+ const heartbeatTimer = setInterval(() => supervisor.heartbeat(), Number(opts.heartbeat) || DEFAULT_HEARTBEAT_MS);
211
+ const shutdown = () => {
212
+ stampLog('daemon stopping — terminating supervised agents');
213
+ clearInterval(pollTimer);
214
+ clearInterval(heartbeatTimer);
215
+ supervisor.stop();
216
+ process.exit(0);
217
+ };
218
+ process.on('SIGINT', shutdown);
219
+ process.on('SIGTERM', shutdown);
220
+ } catch (error) {
221
+ console.error(`Daemon run failed: ${error.message}`);
222
+ process.exitCode = 1;
223
+ }
224
+ });
225
+
150
226
  daemon
151
227
  .command('status')
152
228
  .description('Show the server-derived liveness of this machine')
@@ -0,0 +1,211 @@
1
+ /**
2
+ * ADR-026 Phase 2, slice 2: the resident supervision loop behind
3
+ * `commonly daemon run`.
4
+ *
5
+ * The server's work list (GET /api/agent-binding/assigned) is the source of
6
+ * truth (D2): a row `requested` gets adopted (the D3 CAS — the server refuses
7
+ * the loser of a race cleanly), a row `bound` gets provisioned (token file)
8
+ * and supervised (a `commonly agent run <name>` child), and a supervised
9
+ * agent that leaves the list gets stopped. Per-agent state rides every
10
+ * machine heartbeat (D5).
11
+ *
12
+ * D6 discipline: a replacement child is only ever scheduled from the previous
13
+ * child's 'exit' event — there is no code path that spawns a second runner
14
+ * for an agent whose child has not exited.
15
+ *
16
+ * All side effects (client, spawn, token file I/O, adapter detection, timers)
17
+ * are injected so the loop's decisions are testable without processes.
18
+ */
19
+
20
+ export const DEFAULT_POLL_MS = 30_000;
21
+ export const DEFAULT_HEARTBEAT_MS = 30_000;
22
+ export const BACKOFF_BASE_MS = 5_000;
23
+ export const BACKOFF_MAX_MS = 60_000;
24
+
25
+ export const backoffMs = (restarts) => Math.min(
26
+ BACKOFF_MAX_MS,
27
+ BACKOFF_BASE_MS * 2 ** Math.max(0, Math.min(restarts, 10)),
28
+ );
29
+
30
+ const identityKey = (agentName, instanceId) => `${agentName} ${instanceId || 'default'}`;
31
+
32
+ export const createDaemonSupervisor = ({
33
+ record,
34
+ client,
35
+ spawnChild, // (agentName) => child emitting 'exit'; must expose .kill()
36
+ loadToken, // (agentName) => token record | null
37
+ saveToken, // (agentName, record) => void
38
+ resolveAdapter, // async (runtime) => adapter name for THIS machine
39
+ log = () => {},
40
+ setTimeoutFn = setTimeout,
41
+ clearTimeoutFn = clearTimeout,
42
+ }) => {
43
+ // key → { agentName, instanceId, child, state, restarts, backoffTimer, desired }
44
+ const seats = new Map();
45
+ let stopped = false;
46
+
47
+ const agentStates = () => Array.from(seats.values()).map((s) => ({
48
+ agentName: s.agentName,
49
+ instanceId: s.instanceId,
50
+ state: s.state,
51
+ restarts: s.restarts,
52
+ }));
53
+
54
+ const startChild = (seat) => {
55
+ if (stopped || !seat.desired || seat.child) return;
56
+ seat.child = spawnChild(seat.agentName);
57
+ seat.state = 'running';
58
+ log(`[${seat.agentName}] supervising (restarts so far: ${seat.restarts})`);
59
+ seat.child.on('exit', (code) => {
60
+ seat.child = null;
61
+ if (stopped || !seat.desired) {
62
+ seat.state = 'stopped';
63
+ return;
64
+ }
65
+ seat.state = code === 0 ? 'stopped' : 'crashed';
66
+ seat.restarts += 1;
67
+ const delay = backoffMs(seat.restarts - 1);
68
+ log(`[${seat.agentName}] exited (code ${code}) — respawn in ${Math.round(delay / 1000)}s`);
69
+ seat.backoffTimer = setTimeoutFn(() => {
70
+ seat.backoffTimer = null;
71
+ startChild(seat);
72
+ }, delay);
73
+ });
74
+ };
75
+
76
+ const stopSeat = (seat) => {
77
+ seat.desired = false;
78
+ if (seat.backoffTimer) {
79
+ clearTimeoutFn(seat.backoffTimer);
80
+ seat.backoffTimer = null;
81
+ }
82
+ if (seat.child) {
83
+ log(`[${seat.agentName}] no longer assigned here — stopping`);
84
+ seat.child.kill('SIGTERM');
85
+ } else {
86
+ seat.state = 'stopped';
87
+ }
88
+ };
89
+
90
+ // Ensure ~/.commonly/tokens/<name>.json exists so `agent run` can boot.
91
+ // The mint refuses to clobber an existing token (409 token_exists); the
92
+ // binding to THIS machine is the owner's explicit takeover choice (D3), so
93
+ // that refusal is answered with rotate:true — loudly.
94
+ const ensureToken = async (row) => {
95
+ if (loadToken(row.agentName)) return true;
96
+ const body = { agentName: row.agentName, instanceId: row.instanceId };
97
+ let minted;
98
+ try {
99
+ minted = await client.post('/api/agent-binding/runtime-token', body);
100
+ } catch (error) {
101
+ if (error?.status === 409 && error?.body?.code === 'token_exists') {
102
+ log(`[${row.agentName}] a runtime token exists elsewhere — rotating it to this machine (the old token stops working)`);
103
+ try {
104
+ minted = await client.post('/api/agent-binding/runtime-token', { ...body, rotate: true });
105
+ } catch (rotateError) {
106
+ log(`[${row.agentName}] token rotation failed: ${rotateError.message}`);
107
+ return false;
108
+ }
109
+ } else {
110
+ log(`[${row.agentName}] token mint failed: ${error.message}`);
111
+ return false;
112
+ }
113
+ }
114
+ if (!minted?.token) {
115
+ log(`[${row.agentName}] mint returned no token — skipping`);
116
+ return false;
117
+ }
118
+ const adapter = await resolveAdapter(row.runtime || null);
119
+ if (!adapter) {
120
+ log(`[${row.agentName}] no usable CLI adapter on this machine — install claude or codex, or attach manually`);
121
+ return false;
122
+ }
123
+ saveToken(row.agentName, {
124
+ agentName: row.agentName,
125
+ instanceId: row.instanceId,
126
+ runtimeToken: minted.token,
127
+ instanceUrl: record.instanceUrl,
128
+ podId: row.podIds?.[0] || null,
129
+ adapter,
130
+ });
131
+ log(`[${row.agentName}] provisioned runtime token (adapter: ${adapter})`);
132
+ return true;
133
+ };
134
+
135
+ const tick = async () => {
136
+ if (stopped) return;
137
+ let assigned;
138
+ try {
139
+ assigned = await client.get('/api/agent-binding/assigned');
140
+ } catch (error) {
141
+ log(`work-list fetch failed: ${error.message}`);
142
+ return;
143
+ }
144
+ const rows = Array.isArray(assigned?.agents) ? assigned.agents : [];
145
+
146
+ const bound = [];
147
+ for (const row of rows) {
148
+ if (row.state === 'requested') {
149
+ try {
150
+ // eslint-disable-next-line no-await-in-loop
151
+ await client.post('/api/agent-binding/adopt', {
152
+ agentName: row.agentName, instanceId: row.instanceId,
153
+ });
154
+ log(`[${row.agentName}] adopted onto this machine`);
155
+ bound.push(row);
156
+ } catch (error) {
157
+ // A clean CAS refusal (409) means another machine won — drop it.
158
+ log(`[${row.agentName}] adopt refused: ${error.message}`);
159
+ }
160
+ } else {
161
+ bound.push(row);
162
+ }
163
+ }
164
+
165
+ const desiredKeys = new Set();
166
+ for (const row of bound) {
167
+ const key = identityKey(row.agentName, row.instanceId);
168
+ desiredKeys.add(key);
169
+ let seat = seats.get(key);
170
+ if (!seat) {
171
+ seat = {
172
+ agentName: row.agentName,
173
+ instanceId: row.instanceId || 'default',
174
+ child: null,
175
+ state: 'stopped',
176
+ restarts: 0,
177
+ backoffTimer: null,
178
+ desired: true,
179
+ };
180
+ seats.set(key, seat);
181
+ }
182
+ seat.desired = true;
183
+ if (!seat.child && !seat.backoffTimer) {
184
+ // eslint-disable-next-line no-await-in-loop
185
+ if (await ensureToken(row)) startChild(seat);
186
+ }
187
+ }
188
+
189
+ for (const [key, seat] of seats) {
190
+ if (!desiredKeys.has(key) && seat.desired) stopSeat(seat);
191
+ }
192
+ };
193
+
194
+ const heartbeat = async () => {
195
+ if (stopped) return;
196
+ try {
197
+ await client.post(`/api/machines/${record.machineDbId}/heartbeat`, { agents: agentStates() });
198
+ } catch (error) {
199
+ log(`heartbeat failed: ${error.message}`);
200
+ }
201
+ };
202
+
203
+ const stop = () => {
204
+ stopped = true;
205
+ for (const seat of seats.values()) stopSeat(seat);
206
+ };
207
+
208
+ return {
209
+ tick, heartbeat, stop, agentStates,
210
+ };
211
+ };