@myvillage/cli 1.86.0 → 1.88.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myvillage/cli",
3
- "version": "1.86.0",
3
+ "version": "1.88.0",
4
4
  "description": "MyVillageOS CLI for community developers",
5
5
  "type": "module",
6
6
  "bin": {
@@ -522,6 +522,11 @@ Guidelines:
522
522
  // Send server-side heartbeat
523
523
  if (config.man?.agent_id) {
524
524
  try {
525
+ // Fleet fencing: when this agent was launched under a runner lease,
526
+ // report the machine + lease epoch so the server can reject us (409
527
+ // LEASE_LOST) if another machine has taken over. Absent otherwise.
528
+ const machineId = process.env.MYVILLAGE_MACHINE_ID;
529
+ const leaseEpoch = process.env.MYVILLAGE_LEASE_EPOCH;
525
530
  await postAgentHeartbeat(config.man.agent_id, {
526
531
  postsCreated: activity.postsCreated,
527
532
  commentsCreated: activity.commentsCreated,
@@ -531,13 +536,21 @@ Guidelines:
531
536
  tokensUsed: result.usage?.totalTokens || 0,
532
537
  durationMs: Date.now() - loopStart,
533
538
  activitySummary: { feedItemsRead, mentionsFound },
539
+ ...(machineId ? { machineId } : {}),
540
+ ...(leaseEpoch !== undefined ? { leaseEpoch: Number(leaseEpoch) } : {}),
534
541
  });
535
542
  } catch (err) {
536
543
  if (isPausedResponse(err)) throw new AgentPausedError();
544
+ if (isLeaseLostResponse(err)) throw new LeaseLostError();
537
545
  logActivity(agentDir, { type: 'error', error: 'Failed to send server heartbeat' });
538
546
  }
539
547
  }
540
548
  } catch (err) {
549
+ if (err instanceof LeaseLostError) {
550
+ logActivity(agentDir, { type: 'lease_lost', message: err.message });
551
+ console.log('\n[MyVillage] Lease lost — another machine now owns this agent. Exiting.\n');
552
+ break;
553
+ }
541
554
  if (err instanceof AgentPausedError) {
542
555
  logActivity(agentDir, { type: 'agent_paused', message: err.message });
543
556
  console.log('\n[MyVillage] This agent has been paused by an admin. Exiting.\n');
@@ -730,6 +743,18 @@ function isPausedResponse(err) {
730
743
  return err?.response?.status === 409 && err?.response?.data?.code === 'AGENT_PAUSED';
731
744
  }
732
745
 
746
+ class LeaseLostError extends Error {
747
+ constructor(message = 'Lease lost — another machine now owns this agent') {
748
+ super(message);
749
+ this.name = 'LeaseLostError';
750
+ this.code = 'LEASE_LOST';
751
+ }
752
+ }
753
+
754
+ function isLeaseLostResponse(err) {
755
+ return err?.response?.status === 409 && err?.response?.data?.code === 'LEASE_LOST';
756
+ }
757
+
733
758
  // Pull up to 5 pending tasks and claim the first one we can win the race for.
734
759
  // Returns the claimed task or null. Errors are swallowed and logged — the loop
735
760
  // should keep running on transient backend issues. A pause response (409
@@ -0,0 +1,314 @@
1
+ /**
2
+ * Headless fleet runner.
3
+ *
4
+ * One per machine (Raspberry Pi, DGX Spark, office Mac, or Studio in-process).
5
+ * Registers the machine, then loops: heartbeat (renew leases + report observed
6
+ * + pull assignments) → reconcile local agent daemons to match. Single-active is
7
+ * enforced by the control-plane lease; this runner only starts an agent after it
8
+ * acquires the lease, and stops+releases anything it holds that is no longer
9
+ * assigned-and-running here.
10
+ *
11
+ * Auth model: the runner authenticates as a machine with a `machine:runner` API
12
+ * key sent as `x-api-key`. That key is normally provisioned automatically — on
13
+ * first start the runner registers using the signed-in user's OAuth token and
14
+ * the control plane mints + returns a machine-scoped credential, which is saved
15
+ * to ~/.myvillage/runner.json (0600) and reused thereafter. So a machine that
16
+ * has run `myvillage login` (or Studio) never needs a hand-made key; supplying
17
+ * MYVILLAGE_MACHINE_KEY / --key stays supported for unattended provisioning.
18
+ * Spawned agent daemons still use the owner's OAuth token from
19
+ * ~/.myvillage/credentials.json.
20
+ */
21
+ import os from 'os';
22
+ import fs from 'fs';
23
+ import path from 'path';
24
+ import { getConfig } from '../utils/config.js';
25
+ import { getAccessToken } from '../utils/auth.js';
26
+ import { listLocalAgents, readAgentConfig } from '../utils/local-agent.js';
27
+ import { startDaemon, stopDaemon, isDaemonRunning, getDaemonInfo } from './daemon.js';
28
+
29
+ const RUNNER_STATE_FILE = path.join(os.homedir(), '.myvillage', 'runner.json');
30
+ const DEFAULT_HEARTBEAT_MS = 20_000;
31
+ const LEASE_TTL_SECONDS = 90;
32
+
33
+ function log(msg, extra) {
34
+ const line = `[runner] ${new Date().toISOString()} ${msg}`;
35
+ if (extra !== undefined) console.log(line, extra);
36
+ else console.log(line);
37
+ }
38
+
39
+ function collectMetadata() {
40
+ return {
41
+ hostname: os.hostname(),
42
+ loadavg: os.loadavg(),
43
+ totalmem: os.totalmem(),
44
+ freemem: os.freemem(),
45
+ cpus: os.cpus().length,
46
+ uptimeSec: Math.round(os.uptime()),
47
+ };
48
+ }
49
+
50
+ function persistRunnerState(state) {
51
+ try {
52
+ fs.mkdirSync(path.dirname(RUNNER_STATE_FILE), { recursive: true });
53
+ // 0600: the file holds this machine's credential.
54
+ fs.writeFileSync(RUNNER_STATE_FILE, JSON.stringify(state, null, 2), { mode: 0o600 });
55
+ try { fs.chmodSync(RUNNER_STATE_FILE, 0o600); } catch { /* best-effort */ }
56
+ } catch { /* best-effort */ }
57
+ }
58
+
59
+ export function readRunnerState() {
60
+ try {
61
+ return JSON.parse(fs.readFileSync(RUNNER_STATE_FILE, 'utf8'));
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+
67
+ // ── Control-plane client (machine principal via x-api-key) ───────────────────
68
+
69
+ function makeClient(machineKey, machineId) {
70
+ const { networkBaseUrl } = getConfig();
71
+ return async function cp(pathname, { method = 'GET', body } = {}) {
72
+ const headers = { 'Content-Type': 'application/json', 'x-api-key': machineKey };
73
+ if (machineId) headers['X-Machine-Id'] = machineId;
74
+ return request(networkBaseUrl, pathname, method, body, headers);
75
+ };
76
+ }
77
+
78
+ /**
79
+ * One-shot client authenticated as the signed-in *user* (OAuth bearer). Used
80
+ * only to register a machine and receive its minted credential.
81
+ */
82
+ function makeUserClient() {
83
+ const { networkBaseUrl } = getConfig();
84
+ const token = getAccessToken();
85
+ if (!token) return null;
86
+ return async function cp(pathname, { method = 'GET', body } = {}) {
87
+ const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };
88
+ return request(networkBaseUrl, pathname, method, body, headers);
89
+ };
90
+ }
91
+
92
+ async function request(networkBaseUrl, pathname, method, body, headers) {
93
+ const res = await fetch(`${networkBaseUrl}${pathname}`, {
94
+ method,
95
+ headers,
96
+ body: body ? JSON.stringify(body) : undefined,
97
+ });
98
+ const text = await res.text();
99
+ let json;
100
+ try { json = text ? JSON.parse(text) : {}; } catch { json = { raw: text }; }
101
+ return { status: res.status, ok: res.ok, json };
102
+ }
103
+
104
+ // ── Local agent indexing ─────────────────────────────────────────────────────
105
+
106
+ // Map control-plane agentProfileId -> local agent { name, config } via the
107
+ // `man.agent_id` binding in each local agent.config.yaml.
108
+ function indexLocalAgentsByProfileId() {
109
+ const map = new Map();
110
+ for (const a of listLocalAgents()) {
111
+ let cfg;
112
+ try { cfg = readAgentConfig(a.name); } catch { continue; }
113
+ const profileId = cfg?.man?.agent_id;
114
+ if (profileId) map.set(profileId, { name: a.name, config: cfg });
115
+ }
116
+ return map;
117
+ }
118
+
119
+ function startAgent(name, config, machineId, leaseEpoch) {
120
+ const token = getAccessToken();
121
+ if (token) process.env.MYVILLAGE_ACCESS_TOKEN = token;
122
+ if (config.man?.agent_id) process.env.MYVILLAGE_AGENT_ID = config.man.agent_id;
123
+ if (config.man?.village_agent_id) process.env.MYVILLAGE_VILLAGE_AGENT_ID = config.man.village_agent_id;
124
+ process.env.MYVILLAGE_MACHINE_ID = machineId;
125
+ process.env.MYVILLAGE_LEASE_EPOCH = String(leaseEpoch);
126
+ const pid = startDaemon(name);
127
+ // Clear the per-agent fencing vars so they don't bleed into the next spawn.
128
+ delete process.env.MYVILLAGE_LEASE_EPOCH;
129
+ return pid;
130
+ }
131
+
132
+ // ── Registration + reconcile ─────────────────────────────────────────────────
133
+
134
+ async function register(cp, opts) {
135
+ const body = {
136
+ name: opts.name || os.hostname(),
137
+ kind: opts.kind,
138
+ platform: process.platform,
139
+ arch: process.arch,
140
+ agentVersion: opts.agentVersion,
141
+ capacity: opts.capacity,
142
+ metadata: collectMetadata(),
143
+ };
144
+ const { ok, status, json } = await cp('/machines', { method: 'POST', body });
145
+ if (!ok) throw new Error(`register failed (${status}): ${JSON.stringify(json)}`);
146
+ // machineKey is present only on the user-auth path (minted once, server-side).
147
+ return { machineId: json.data.id, machineKey: json.data.machineKey ?? null };
148
+ }
149
+
150
+ /**
151
+ * Resolve this machine's credential without asking a human for one:
152
+ * 1. an explicit --key / MYVILLAGE_MACHINE_KEY (unattended provisioning)
153
+ * 2. the credential saved on a previous start (~/.myvillage/runner.json)
154
+ * 3. otherwise register as the signed-in user; the control plane mints one
155
+ *
156
+ * Returns { machineId, machineKey }.
157
+ */
158
+ async function resolveMachineIdentity(opts) {
159
+ const explicitKey = opts.machineKey || process.env.MYVILLAGE_MACHINE_KEY || null;
160
+ const saved = readRunnerState();
161
+
162
+ if (explicitKey) {
163
+ const { machineId } = await register(makeClient(explicitKey, null), opts);
164
+ persistRunnerState({
165
+ machineId,
166
+ machineKey: explicitKey,
167
+ name: opts.name || os.hostname(),
168
+ registeredAt: new Date().toISOString(),
169
+ });
170
+ return { machineId, machineKey: explicitKey };
171
+ }
172
+
173
+ if (saved?.machineKey) {
174
+ // Re-register with the stored credential so name/metadata/version refresh.
175
+ const { machineId } = await register(makeClient(saved.machineKey, null), opts);
176
+ persistRunnerState({ ...saved, machineId, name: opts.name || saved.name, registeredAt: new Date().toISOString() });
177
+ return { machineId, machineKey: saved.machineKey };
178
+ }
179
+
180
+ const userClient = makeUserClient();
181
+ if (!userClient) {
182
+ throw new Error(
183
+ 'Not signed in. Run `myvillage login` on this machine (or pass --key with a machine:runner API key).',
184
+ );
185
+ }
186
+ const { machineId, machineKey } = await register(userClient, opts);
187
+ if (!machineKey) {
188
+ throw new Error('The control plane did not return a machine credential. Update the backend and retry.');
189
+ }
190
+ persistRunnerState({
191
+ machineId,
192
+ machineKey,
193
+ name: opts.name || os.hostname(),
194
+ registeredAt: new Date().toISOString(),
195
+ });
196
+ return { machineId, machineKey };
197
+ }
198
+
199
+ async function reconcileOnce(ctx) {
200
+ const observed = [];
201
+ for (const [profileId, lease] of ctx.leases) {
202
+ observed.push({
203
+ agentProfileId: profileId,
204
+ observedState: isDaemonRunning(lease.name) ? 'RUNNING' : 'STOPPED',
205
+ pid: getDaemonInfo(lease.name)?.pid ?? null,
206
+ });
207
+ }
208
+
209
+ const hb = await ctx.cp(`/machines/${ctx.machineId}/heartbeat`, {
210
+ method: 'POST',
211
+ body: { status: 'ONLINE', metadata: collectMetadata(), agentVersion: ctx.agentVersion, agents: observed },
212
+ });
213
+ if (!hb.ok) {
214
+ log(`heartbeat failed (${hb.status})`, hb.json?.error);
215
+ return;
216
+ }
217
+ const assignments = hb.json.data.assignments || [];
218
+ const local = indexLocalAgentsByProfileId();
219
+
220
+ const desiredRunning = assignments.filter((a) => a.desiredState === 'RUNNING');
221
+ const desiredIds = new Set(desiredRunning.map((a) => a.agentProfileId));
222
+
223
+ // Adopt agents already running under our ownership after a runner restart.
224
+ for (const a of assignments) {
225
+ if (
226
+ a.ownerMachineId === ctx.machineId &&
227
+ !ctx.leases.has(a.agentProfileId) &&
228
+ local.has(a.agentProfileId) &&
229
+ isDaemonRunning(local.get(a.agentProfileId).name)
230
+ ) {
231
+ ctx.leases.set(a.agentProfileId, { name: local.get(a.agentProfileId).name, epoch: a.leaseEpoch });
232
+ log(`adopted running agent ${local.get(a.agentProfileId).name} (epoch ${a.leaseEpoch})`);
233
+ }
234
+ }
235
+
236
+ // Start desired-running agents we don't yet own+run here.
237
+ for (const a of desiredRunning) {
238
+ const entry = local.get(a.agentProfileId);
239
+ if (!entry) {
240
+ log(`assigned agent ${a.handle || a.agentProfileId} has no local config on this machine — skipping (provision it first)`);
241
+ continue;
242
+ }
243
+ if (ctx.leases.has(a.agentProfileId) && isDaemonRunning(entry.name)) continue;
244
+
245
+ const lease = await ctx.cp(`/agents/${a.agentProfileId}/lease`, {
246
+ method: 'POST',
247
+ body: { action: 'acquire', ttlSeconds: LEASE_TTL_SECONDS },
248
+ });
249
+ if (!lease.ok) {
250
+ log(`could not acquire lease for ${entry.name} (${lease.json?.code || lease.status}) — held elsewhere, will retry`);
251
+ continue;
252
+ }
253
+ const epoch = lease.json.data.leaseEpoch;
254
+ const pid = startAgent(entry.name, entry.config, ctx.machineId, epoch);
255
+ ctx.leases.set(a.agentProfileId, { name: entry.name, epoch });
256
+ log(`started ${entry.name} (pid ${pid}, epoch ${epoch})`);
257
+ }
258
+
259
+ // Stop + release anything we hold that is no longer desired-running here.
260
+ for (const [profileId, lease] of [...ctx.leases]) {
261
+ if (desiredIds.has(profileId)) continue;
262
+ try { stopDaemon(lease.name); } catch { /* best-effort */ }
263
+ await ctx.cp(`/agents/${profileId}/lease`, { method: 'POST', body: { action: 'release' } });
264
+ ctx.leases.delete(profileId);
265
+ log(`stopped + released ${lease.name} (no longer assigned here)`);
266
+ }
267
+ }
268
+
269
+ function sleep(ms, signal) {
270
+ return new Promise((resolve) => {
271
+ const t = setTimeout(resolve, ms);
272
+ if (signal) signal.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });
273
+ });
274
+ }
275
+
276
+ export async function runRunner(opts = {}) {
277
+ log(`registering machine "${opts.name || os.hostname()}" (${process.platform}/${process.arch})…`);
278
+ const { machineId, machineKey } = await resolveMachineIdentity(opts);
279
+ log(`registered as machine ${machineId}`);
280
+
281
+ // Record our pid so Studio (or `runner status`) can tell whether this
282
+ // machine's runner is alive, and stop it. Cleared on exit.
283
+ const markRunning = (pid) => {
284
+ const s = readRunnerState() || {};
285
+ persistRunnerState({ ...s, pid, startedAt: pid ? new Date().toISOString() : undefined });
286
+ };
287
+ markRunning(process.pid);
288
+ const clearPid = () => { try { markRunning(null); } catch { /* best-effort */ } };
289
+ process.on('exit', clearPid);
290
+
291
+ const ctx = {
292
+ cp: makeClient(machineKey, machineId),
293
+ machineId,
294
+ agentVersion: opts.agentVersion,
295
+ leases: new Map(),
296
+ };
297
+
298
+ const controller = new AbortController();
299
+ const shutdown = () => { log('shutting down (agents keep running; leases will expire for failover)'); controller.abort(); };
300
+ process.on('SIGTERM', shutdown);
301
+ process.on('SIGINT', shutdown);
302
+
303
+ const intervalMs = opts.intervalMs || DEFAULT_HEARTBEAT_MS;
304
+ log(`reconcile loop every ${Math.round(intervalMs / 1000)}s (lease TTL ${LEASE_TTL_SECONDS}s)`);
305
+ while (!controller.signal.aborted) {
306
+ try {
307
+ await reconcileOnce(ctx);
308
+ } catch (err) {
309
+ log('reconcile error', err?.message || err);
310
+ }
311
+ if (!controller.signal.aborted) await sleep(intervalMs, controller.signal);
312
+ }
313
+ log('runner stopped');
314
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `myvillage runner` — headless fleet runner commands.
3
+ */
4
+ import { createRequire } from 'module';
5
+ import { runRunner, readRunnerState } from '../agent-runtime/runner.js';
6
+
7
+ function getCliVersion() {
8
+ try {
9
+ const require = createRequire(import.meta.url);
10
+ return require('../../package.json').version;
11
+ } catch {
12
+ return undefined;
13
+ }
14
+ }
15
+
16
+ export async function runnerStartCommand(options = {}) {
17
+ try {
18
+ await runRunner({
19
+ name: options.name,
20
+ kind: options.kind ? String(options.kind).toUpperCase() : undefined,
21
+ capacity: options.capacity ? parseInt(options.capacity, 10) : undefined,
22
+ intervalMs: options.interval ? parseInt(options.interval, 10) * 1000 : undefined,
23
+ machineKey: options.key,
24
+ agentVersion: getCliVersion(),
25
+ });
26
+ } catch (err) {
27
+ console.error(`[runner] ${err.message}`);
28
+ process.exit(1);
29
+ }
30
+ }
31
+
32
+ export function runnerStatusCommand() {
33
+ const state = readRunnerState();
34
+ if (!state) {
35
+ console.log('No runner has registered on this machine yet. Run `myvillage runner start`.');
36
+ return;
37
+ }
38
+ console.log(`Machine: ${state.name} (${state.machineId})`);
39
+ console.log(`Registered: ${state.registeredAt}`);
40
+ }
package/src/index.js CHANGED
@@ -72,6 +72,7 @@ import {
72
72
  agentRememberCommand,
73
73
  agentRecipesListCommand,
74
74
  } from './commands/agent-local.js';
75
+ import { runnerStartCommand, runnerStatusCommand } from './commands/runner.js';
75
76
  import {
76
77
  agentRegisterClientCommand,
77
78
  agentListClientsCommand,
@@ -993,5 +994,23 @@ export function run() {
993
994
  .option('--json', 'Output raw JSON')
994
995
  .action(modelPredictCommand);
995
996
 
997
+ // ── Fleet runner ───────────────────────────────────────
998
+ const runnerCmd = program
999
+ .command('runner')
1000
+ .description('Fleet runner: register this machine and run its assigned agents');
1001
+ runnerCmd
1002
+ .command('start')
1003
+ .description('Register this machine and run agents assigned to it')
1004
+ .option('--name <name>', 'Machine name (default: hostname)')
1005
+ .option('--kind <kind>', 'Machine kind: laptop|mac|pi|spark|cloud|other')
1006
+ .option('--capacity <n>', 'Soft cap on concurrently-run agents')
1007
+ .option('--interval <sec>', 'Reconcile/heartbeat interval in seconds (default 20)')
1008
+ .option('--key <apiKey>', 'machine:runner API key (or set MYVILLAGE_MACHINE_KEY)')
1009
+ .action(runnerStartCommand);
1010
+ runnerCmd
1011
+ .command('status')
1012
+ .description("Show this machine's runner registration")
1013
+ .action(runnerStatusCommand);
1014
+
996
1015
  program.parse();
997
1016
  }