@whzxc/agent-design-gallery 0.6.0 → 0.8.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.
Files changed (41) hide show
  1. package/README.md +12 -1
  2. package/package.json +1 -1
  3. package/public/app.js +38 -10
  4. package/public/arrangement-worker.js +11 -0
  5. package/public/arrangement.js +49 -0
  6. package/public/assets.js +16 -4
  7. package/public/layout.js +29 -13
  8. package/src/cli-output.mjs +258 -0
  9. package/src/cli.mjs +120 -45
  10. package/src/http.mjs +1 -0
  11. package/src/hub/auth.mjs +2 -1
  12. package/src/hub/proxy.mjs +5 -3
  13. package/src/hub/registry.mjs +57 -23
  14. package/src/hub.mjs +36 -21
  15. package/src/lifecycle.mjs +109 -0
  16. package/src/link.mjs +10 -9
  17. package/src/open.mjs +58 -54
  18. package/src/perf.mjs +12 -0
  19. package/src/server.mjs +78 -41
  20. package/src/service.mjs +115 -94
  21. package/src/toolkit/arch-git.mjs +142 -10
  22. package/src/toolkit/arch-overlay.mjs +1 -1
  23. package/src/toolkit/arch.mjs +62 -58
  24. package/src/toolkit/browser.mjs +38 -12
  25. package/src/toolkit/build-store.mjs +11 -3
  26. package/src/toolkit/build-worker.mjs +4 -1
  27. package/src/toolkit/build.mjs +26 -2
  28. package/src/toolkit/commands.mjs +158 -86
  29. package/src/toolkit/compare.mjs +93 -46
  30. package/src/toolkit/config.mjs +23 -20
  31. package/src/toolkit/diff-inputs.mjs +239 -0
  32. package/src/toolkit/diff-policy.mjs +28 -0
  33. package/src/toolkit/diff.mjs +258 -0
  34. package/src/toolkit/migrate.mjs +42 -30
  35. package/src/toolkit/part-diff.mjs +118 -0
  36. package/src/toolkit/part-snapshot.mjs +264 -0
  37. package/src/toolkit/pixel-diff.mjs +103 -0
  38. package/src/toolkit/project.mjs +45 -33
  39. package/src/toolkit/results.mjs +44 -0
  40. package/src/toolkit/runtime.d.ts +2 -1
  41. package/src/toolkit/tokens.mjs +5 -4
package/src/server.mjs CHANGED
@@ -13,8 +13,11 @@ import {
13
13
  import { watch, existsSync } from "node:fs";
14
14
  import path from "node:path";
15
15
  import os from "node:os";
16
+ import { perfSpan } from './perf.mjs';
16
17
 
17
18
  import { createBuildStore } from './toolkit/build-store.mjs';
19
+ import { CliError, asCliError } from './cli-output.mjs';
20
+ import { cleanup } from './toolkit/results.mjs';
18
21
  import { createViewerCache } from './viewer-cache.mjs';
19
22
  import { refreshTypes, archFiles, isSourcePath, readGroups, sourceDirectories } from './toolkit/project.mjs';
20
23
  import { loadConfig } from './toolkit/config.mjs';
@@ -27,7 +30,7 @@ function tokenSourcePath(directory, project) {
27
30
  const base = project.design === directory ? project.root : path.dirname(directory);
28
31
  return path.relative(base, path.join(directory, tokenFile)).split(path.sep).join('/');
29
32
  }
30
- const viewerVersion = Promise.all(['assets.js','layout.js','selection.js'].map(file => readFile(new URL('../public/'+file,import.meta.url)))).then(parts => digest(Buffer.concat(parts)));
33
+ const viewerVersion = Promise.all(['assets.js','layout.js','selection.js','arrangement.js','arrangement-worker.js'].map(file => readFile(new URL('../public/'+file,import.meta.url)))).then(parts => digest(Buffer.concat(parts)));
31
34
  const defaultState = path.join(
32
35
  process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local/state"),
33
36
  "agent-design-gallery",
@@ -39,14 +42,16 @@ export async function startServer({
39
42
  fixtures = null,
40
43
  readOnly = false,
41
44
  instanceId = randomUUID(),
45
+ onDiagnostic, onFatal, watchDirectory = watch,
42
46
  } = {}) {
47
+ const endStartup = perfSpan('viewer-startup');
43
48
  let state = { recent: [], views: {}, selections: {}, theme: "system" };
44
49
  const statePath = path.join(stateDirectory, "state.json");
45
50
  try {
46
51
  state = { ...state, ...JSON.parse(await readFile(statePath, "utf8")) };
47
52
  } catch (e) {
48
53
  if (e.code !== "ENOENT")
49
- throw new Error(`Cannot read preferences: ${e.message}`);
54
+ throw new CliError(e instanceof SyntaxError ? 'STATE_INVALID' : 'IO_FAILED', `Cannot read preferences: ${e.message}`, { cause: e });
50
55
  }
51
56
  let root,
52
57
  tokenSource = null,
@@ -82,6 +87,20 @@ export async function startServer({
82
87
  for (const client of clients)
83
88
  client.write(`data: ${JSON.stringify(data)}\n\n`);
84
89
  };
90
+ const diagnostic = (error, name = null, fallback = 'SOURCE_BUILD_FAILED') => {
91
+ if (error.name === 'AbortError') return;
92
+ const at = error.location ?? error.errors?.[0]?.location ?? error.cause?.errors?.[0]?.location;
93
+ const source = name && activeProject ? (name.endsWith('.mmd') ? name : path.relative(activeProject.root,path.join(root,name)).split(path.sep).join('/')) : null;
94
+ onDiagnostic?.(asCliError(error,fallback),source ? {source,frame:null,theme:null,line:Number.isInteger(at?.line)&&at.line>0?at.line:null,column:Number.isInteger(at?.column)?at.column+1:null} : null);
95
+ };
96
+ const refreshError = error => {
97
+ if (error.name === 'AbortError') return;
98
+ emit({error:error.message}); diagnostic(error,null,'WATCH_FAILED');
99
+ };
100
+ const watcherError = (error,kind) => {
101
+ const failure = new CliError('WATCH_FAILED',`${kind} watcher: ${error.message}`,{cause:error});
102
+ emit({error:failure.message}); onFatal?.(failure);
103
+ };
85
104
  async function closeOverlays() {
86
105
  resettingOverlays = true;
87
106
  try { await Promise.all([...overlayStores.values()].map(async pending=>(await pending).close())); }
@@ -107,7 +126,9 @@ export async function startServer({
107
126
  return [...affected];
108
127
  }
109
128
  async function overlayBuild(name,base) {
110
- const built=await (await overlayStore(base)).get(name);
129
+ let built;
130
+ try { built=await (await overlayStore(base)).get(name); }
131
+ catch(error) { diagnostic(error,name); throw error; }
111
132
  overlayHashes.add(built.hash);frameCounts.set(name,built.frames.length);
112
133
  return built;
113
134
  }
@@ -155,25 +176,25 @@ export async function startServer({
155
176
  archWatcher?.close();archWatcher=null;
156
177
  const directory=project.archDirectory;
157
178
  if(project.design!==base || !directory || !existsSync(directory)) return;
158
- archWatcher=watch(directory,{recursive:true},(_event,filename)=>{
179
+ archWatcher=watchDirectory(directory,{recursive:true},(_event,filename)=>{
159
180
  if(!filename || !/\.(mmd|md)$/.test(String(filename)))return;
160
181
  const file=path.join(directory,String(filename));
161
182
  const dependency=path.relative(base,file).split(path.sep).join('/');
162
183
  const name=path.relative(project.root,file).split(path.sep).join('/');
163
- touched.add(dependency);touched.add(name);invalidateBuilds([dependency,name]).catch(e=>emit({error:e.message}));
164
- clearTimeout(refreshTimer);refreshTimer=setTimeout(()=>refresh().catch(e=>emit({error:e.message})),80);
184
+ touched.add(dependency);touched.add(name);invalidateBuilds([dependency,name]).catch(refreshError);
185
+ clearTimeout(refreshTimer);refreshTimer=setTimeout(()=>refresh().catch(refreshError),80);
165
186
  });
166
- archWatcher.on('error',e=>emit({error:`Architecture watcher: ${e.message}`}));
187
+ archWatcher.on('error',e=>watcherError(e,'Architecture'));
167
188
  }
168
189
  async function openDirectory(input) {
169
190
  let next;
170
191
  try { next = await realpath(path.resolve(input.replace(/^~(?=$|[\\/])/, os.homedir()))); }
171
192
  catch (error) {
172
- if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new Error(`Directory not found: ${input}; choose an existing directory.`);
193
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new CliError('DIRECTORY_NOT_FOUND', `Directory not found: ${input}; choose an existing directory.`, { cause: error });
173
194
  throw error;
174
195
  }
175
196
  if (!(await stat(next)).isDirectory())
176
- throw new Error("Choose a directory containing SVG files.");
197
+ throw new CliError('DIRECTORY_NOT_FOUND', "Choose a directory containing SVG files.");
177
198
  const hasTokens = (await readdir(next)).includes(tokenFile);
178
199
  if (hasTokens && !readOnly) refreshTypes({design:next});
179
200
  const project = await loadConfig(next);
@@ -190,21 +211,21 @@ export async function startServer({
190
211
  if(nextFiles.has(built.path)) {knownBuilds.set(built.path,built);Object.assign(nextFiles.get(built.path),{hash:built.hash,version:built.hash});frameCounts.set(built.path,built.frames.length);}
191
212
  }
192
213
  // Complete discovery before starting the watcher.
193
- const nextWatcher = watch(next, { recursive: true }, (_event, filename) => {
214
+ const nextWatcher = watchDirectory(next, { recursive: true }, (_event, filename) => {
194
215
  if (filename && String(filename).split(path.sep).some(part => part.startsWith("."))) return;
195
216
  if (filename) {
196
217
  const name=String(filename).split(path.sep).join('/');
197
218
  touched.add(name);
198
- invalidateBuilds([name]).catch(e=>emit({error:e.message}));
219
+ invalidateBuilds([name]).catch(refreshError);
199
220
  }
200
221
  clearTimeout(refreshTimer);
201
222
  refreshTimer = setTimeout(
202
- () => refresh().catch((e) => emit({ error: e.message })),
223
+ () => refresh().catch(refreshError),
203
224
  80,
204
225
  );
205
226
  });
206
227
  nextWatcher.on("error", (e) =>
207
- emit({ error: `File watcher: ${e.message}` }),
228
+ watcherError(e,'File'),
208
229
  );
209
230
  watcher?.close();
210
231
  watcher = nextWatcher;
@@ -334,6 +355,7 @@ export async function startServer({
334
355
  result.tokens = [...light].map(([name, value]) => [name, value, dark.get(name) ?? null]);
335
356
  } catch (error) {
336
357
  result.tokenError = error.code ? `Cannot read ${data.tokenSource}.` : error.message;
358
+ diagnostic(new CliError('TOKENS_INVALID',error.message,{cause:error}));
337
359
  }
338
360
  return applyFixtureManifest(result, url.searchParams.get('fixture'));
339
361
  }
@@ -385,8 +407,10 @@ export async function startServer({
385
407
  return applyFixtureManifest(data,url.searchParams.get('fixture'));
386
408
  }
387
409
  async function sourceBuild(name) {
410
+ const endBuild = perfSpan('build', name);
388
411
  let built;
389
- try{built=await buildStore.get(name);}catch(error){if(error.name!=='AbortError')failedSources.add(name);throw error;}
412
+ try{built=await buildStore.get(name);}catch(error){if(error.name!=='AbortError'){failedSources.add(name);diagnostic(error,name);}throw error;}
413
+ finally {endBuild?.();}
390
414
  knownBuilds.set(name,describe(built));dirtyBuilds.delete(name);failedSources.delete(name);frameCounts.set(name,built.frames.length);
391
415
  if(files.has(name))Object.assign(files.get(name),{hash:built.hash,version:built.hash});
392
416
  return built;
@@ -402,7 +426,7 @@ export async function startServer({
402
426
  if (/\.(tsx|mmd)$/.test(name)) {
403
427
  const built=base&&name.endsWith('.mmd')?await overlayBuild(name,base):await sourceBuild(name);
404
428
  const frames = onlyFrame ? built.frames.filter(frame => frame.name === onlyFrame) : built.frames;
405
- if (!frames.length && onlyFrame) throw Error(`Frame ${onlyFrame} does not exist in ${name}.`);
429
+ if (!frames.length && onlyFrame) throw new CliError('FRAME_NOT_FOUND', `Frame ${onlyFrame} does not exist in ${name}.`);
406
430
  return {version:built.hash,imports:built.imports,dependencies:built.dependencies,
407
431
  body:JSON.stringify({format:'tsx',hash:built.hash,css:built.css,imports:built.imports,component:!onlyFrame && name.endsWith('.tsx') && !name.startsWith('surfaces/'),frames})};
408
432
  }
@@ -600,40 +624,53 @@ export async function startServer({
600
624
  });
601
625
  response.end(request.method === "HEAD" ? undefined : content);
602
626
  } catch (error) {
627
+ if (response.destroyed) return;
603
628
  response.writeHead(error.name==='AbortError'?409:400, { "Content-Type": "application/json" });
604
629
  response.end(JSON.stringify({ error: error.message }));
605
630
  }
606
631
  });
607
- if (directory) {
608
- try {
609
- await openDirectory(directory);
610
- } catch (error) {
611
- watcher?.close();archWatcher?.close();
612
- throw error;
632
+ let closePromise;
633
+ const close = () => closePromise ??= (async () => {
634
+ closing = true;
635
+ clearTimeout(refreshTimer);
636
+ let primary;
637
+ for (const step of [
638
+ async () => { watcher?.close(); },
639
+ async () => { archWatcher?.close(); },
640
+ async () => {
641
+ for (const client of clients) client.end();
642
+ const disconnected = server.listening ? new Promise(resolve => server.close(resolve)) : Promise.resolve();
643
+ server.closeAllConnections(); await disconnected;
644
+ },
645
+ async () => { await writes; },
646
+ async () => { await buildStore?.close(); },
647
+ closeOverlays,
648
+ async () => { await viewerCache?.close(); },
649
+ ]) {
650
+ try { await cleanup(step,primary); }
651
+ catch (error) { primary=error; }
613
652
  }
614
- }
653
+ if (primary) throw primary;
654
+ })();
615
655
  try {
616
- await new Promise((resolve, reject) => {
617
- server.once("error", reject);
618
- server.listen(port, "127.0.0.1", resolve);
656
+ if (directory) await openDirectory(directory);
657
+ await new Promise((resolve,reject) => {
658
+ const startupError = error => { server.off('listening',listening); reject(error); };
659
+ const listening = () => {
660
+ server.off('error',startupError);
661
+ server.on('error',error => { if (!closing) onFatal?.(asCliError(error)); });
662
+ resolve();
663
+ };
664
+ server.once('error',startupError);
665
+ server.listen(port,'127.0.0.1',listening);
619
666
  });
620
- } catch (error) {
621
- watcher?.close();archWatcher?.close();
622
- throw error;
667
+ } catch (cause) {
668
+ const primary=asCliError(cause);
669
+ await cleanup(close,primary);
670
+ throw primary;
623
671
  }
624
- const close = async () => {
625
- if (closing) return;
626
- closing = true;
627
- clearTimeout(refreshTimer);
628
- watcher?.close();archWatcher?.close();
629
- for (const c of clients) c.end();
630
- const disconnected = new Promise(resolve => server.close(resolve));
631
- server.closeAllConnections();
632
- await disconnected;
633
- await writes;
634
- await buildStore?.close();await closeOverlays();await viewerCache?.close();
635
- };
636
- return { id: instanceId, directory: root, url: `http://127.0.0.1:${server.address().port}/`, port: server.address().port, close,
672
+ endStartup?.();
673
+ return { id: instanceId, directory: root, stateDirectory:path.resolve(stateDirectory), url: `http://127.0.0.1:${server.address().port}/`, port: server.address().port, close,
637
674
  cacheStats:()=>({builds:buildStore?.stats(),viewer:viewerCache?.stats()}),
638
675
  stats: () => {
639
676
  const entries = [...files.keys()].filter(name => /\.(tsx|mmd)$/.test(name));
package/src/service.mjs CHANGED
@@ -5,6 +5,8 @@ import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { promisify } from 'node:util';
7
7
  import { defaultStateDirectory } from './hub/registry.mjs';
8
+ import { CliError } from './cli-output.mjs';
9
+ import { commandFailure } from './toolkit/results.mjs';
8
10
 
9
11
  export const SERVICE_LABEL = 'org.agent-design-gallery.hub';
10
12
  const execute = promisify(execFile);
@@ -39,58 +41,95 @@ const readOptional = async file => {
39
41
  catch (error) { if (error.code !== 'ENOENT') throw error; return null; }
40
42
  };
41
43
 
44
+ async function job(run, args) {
45
+ try { return await run('/bin/launchctl', args); }
46
+ catch (cause) { throw new CliError('SERVICE_FAILED', cause.message, { cause }); }
47
+ }
48
+ async function loadedJob(run, target) {
49
+ try { return (await run('/bin/launchctl', ['print', target])).stdout; }
50
+ catch (cause) {
51
+ if ([3, 113].includes(cause.code)) return null;
52
+ throw new CliError('SERVICE_FAILED', `Cannot inspect ${SERVICE_LABEL}: ${cause.stderr?.trim() || cause.message}`, { cause });
53
+ }
54
+ }
55
+ function statusData(status, installedPlist, agentFile, stateDirectory) {
56
+ return { label: SERVICE_LABEL, installed: installedPlist !== null, loaded: status !== null,
57
+ state: status?.match(/^\s*state = (.+)$/m)?.[1] ?? null,
58
+ pid: Number(status?.match(/^\s*pid = (\d+)$/m)?.[1]) || null,
59
+ plist: agentFile, stateDirectory,
60
+ logs: { stdout: path.join(stateDirectory, 'service.stdout.log'), stderr: path.join(stateDirectory, 'service.stderr.log') } };
61
+ }
62
+
42
63
  async function migrateService(values, { home, run, nodePath, cliPath, uid, output }) {
43
64
  const oldLabel = 'org.svg-design-gallery.hub';
44
65
  const agents = path.join(home, 'Library', 'LaunchAgents');
45
- const oldAgent = path.join(agents, `${oldLabel}.plist`);
46
- const newAgent = path.join(agents, `${SERVICE_LABEL}.plist`);
66
+ const oldAgent = path.join(agents, `${oldLabel}.plist`), newAgent = path.join(agents, `${SERVICE_LABEL}.plist`);
47
67
  const installed = await readOptional(oldAgent), args = launchArguments(installed);
48
68
  const argument = flag => args.includes(flag) ? args[args.indexOf(flag) + 1] : undefined;
49
69
  const base = process.env.XDG_STATE_HOME || path.join(home, '.local/state');
50
70
  const oldState = path.resolve(argument('--state-dir') ?? path.join(base, 'svg-design-gallery'));
51
71
  const newState = path.resolve(values['state-dir'] ?? path.join(base, 'agent-design-gallery'));
52
- const exists = async file => (await lstat(file).catch(error => { if (error.code !== 'ENOENT') throw error; return null; })) !== null;
53
- if (await exists(newState)) throw Error(`Migration target already exists: ${newState}; move it aside before running adg service migrate.`);
54
- if (await exists(newAgent)) throw Error(`LaunchAgent already exists: ${newAgent}; inspect it before running adg service migrate.`);
55
- if (!(await lstat(oldState)).isDirectory()) throw Error(`Hub state is not a directory: ${oldState}`);
56
- const executable = await realpath(nodePath), entry = await realpath(cliPath);
57
- const port = Number(argument('--port') ?? 4310);
58
- if (!Number.isInteger(port) || port < 1 || port > 65535) throw Error('Invalid port in the old LaunchAgent; correct it before migration.');
59
- const oldKey = await readOptional(path.join(oldState, 'hub.key'));
60
- if (oldKey !== null && !/^(?:sdg|adg)_[a-f0-9]{64}$/.test(oldKey.trim())) throw Error('Invalid hub key file; correct it before migration.');
61
- const domain = `gui/${uid}`, oldTarget = `${domain}/${oldLabel}`;
62
- let loaded = false;
63
- try { await run('/bin/launchctl', ['print', oldTarget]); loaded = true; }
64
- catch (error) { if (![3, 113].includes(error.code)) throw error; }
65
- if (loaded) {
66
- await run('/bin/launchctl', ['bootout', oldTarget]);
67
- output(`Stopped ${oldLabel}`);
68
- }
69
- await mkdir(path.dirname(newState), { recursive: true });
70
- await rename(oldState, newState);
71
- output(`Moved ${oldState} -> ${newState}`);
72
- if (oldKey?.trim().startsWith('sdg_')) {
73
- await writeFile(path.join(newState, 'hub.key'), oldKey.replace('sdg_', 'adg_'), { mode: 0o600 });
74
- output('Updated hub key prefix; use adg serve --print-key when updating browser access.');
75
- }
76
- await mkdir(agents, { recursive: true });
77
- await writeFile(newAgent, renderLaunchAgent({ nodePath: executable, cliPath: entry, stateDirectory: newState, port }));
78
- if (installed !== null) {
79
- await rm(oldAgent);
80
- output(`Removed ${oldAgent}`);
81
- }
82
- output(`Created ${newAgent}`);
83
- await run('/bin/launchctl', ['bootstrap', domain, newAgent]);
84
- output(`Started ${SERVICE_LABEL}`);
85
- output(`Other LaunchAgents referencing ${oldState}:`);
86
- let count = 0;
87
- for (const name of (await readdir(agents)).sort()) {
88
- if (!name.endsWith('.plist') || name === `${SERVICE_LABEL}.plist`) continue;
89
- const file = path.join(agents, name), content = await readFile(file, 'utf8');
90
- if (unxml(content).includes(oldState)) { output(file); count++; }
72
+ const data = { complete: false, from: {label:oldLabel,stateDirectory:oldState,plist:oldAgent},
73
+ to: {label:SERVICE_LABEL,stateDirectory:newState,plist:newAgent}, changes: [], keyPrefixUpdated:false, references:[], service:null };
74
+ const warnings = [];
75
+ try {
76
+ const exists = async file => (await lstat(file).catch(error => { if (error.code !== 'ENOENT') throw error; return null; })) !== null;
77
+ if (await exists(newState)) throw new CliError('MIGRATION_CONFLICT', `Migration target already exists: ${newState}; move it aside before running adg service migrate.`);
78
+ if (await exists(newAgent)) throw new CliError('MIGRATION_CONFLICT', `LaunchAgent already exists: ${newAgent}; inspect it before running adg service migrate.`);
79
+ let oldInfo;
80
+ try { oldInfo = await lstat(oldState); }
81
+ catch (cause) { if (['ENOENT','ENOTDIR'].includes(cause.code)) throw new CliError('DIRECTORY_NOT_FOUND', cause.message, { cause }); throw cause; }
82
+ if (!oldInfo.isDirectory()) throw new CliError('DIRECTORY_NOT_FOUND', `Hub state is not a directory: ${oldState}`);
83
+ const executable = await realpath(nodePath), entry = await realpath(cliPath);
84
+ const port = Number(argument('--port') ?? 4310);
85
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new CliError('STATE_INVALID', 'Invalid port in the old LaunchAgent; correct it before migration.');
86
+ const oldKey = await readOptional(path.join(oldState, 'hub.key'));
87
+ if (oldKey !== null && !/^(?:sdg|adg)_[a-f0-9]{64}$/.test(oldKey.trim())) throw new CliError('STATE_INVALID', 'Invalid hub key file; correct it before migration.');
88
+ const domain = `gui/${uid}`, oldTarget = `${domain}/${oldLabel}`;
89
+ let loaded = false;
90
+ try { await run('/bin/launchctl', ['print', oldTarget]); loaded = true; }
91
+ catch (cause) { if (![3,113].includes(cause.code)) throw new CliError('SERVICE_FAILED', cause.message, { cause }); }
92
+ if (loaded) { await job(run, ['bootout', oldTarget]); output(`Stopped ${oldLabel}`); }
93
+ await mkdir(path.dirname(newState), { recursive:true });
94
+ await rename(oldState,newState);
95
+ data.changes.push({action:'renamed',path:newState,from:oldState});
96
+ output(`Moved ${oldState} -> ${newState}`);
97
+ if (oldKey?.trim().startsWith('sdg_')) {
98
+ await writeFile(path.join(newState,'hub.key'),oldKey.replace('sdg_','adg_'),{mode:0o600});
99
+ data.changes.push({action:'updated',path:path.join(newState,'hub.key'),from:null});
100
+ data.keyPrefixUpdated = true;
101
+ output('Updated hub key prefix; use adg serve --print-key when updating browser access.');
102
+ }
103
+ await mkdir(agents,{recursive:true});
104
+ const plist = renderLaunchAgent({nodePath:executable,cliPath:entry,stateDirectory:newState,port});
105
+ await writeFile(newAgent,plist);
106
+ data.changes.push({action:'created',path:newAgent,from:null});
107
+ if (installed !== null) {
108
+ await rm(oldAgent);
109
+ data.changes.push({action:'deleted',path:oldAgent,from:null});
110
+ output(`Removed ${oldAgent}`);
111
+ }
112
+ output(`Created ${newAgent}`);
113
+ await job(run,['bootstrap',domain,newAgent]);
114
+ output(`Started ${SERVICE_LABEL}`);
115
+ data.service = statusData(await loadedJob(run,`${domain}/${SERVICE_LABEL}`),plist,newAgent,newState);
116
+ output(`Other LaunchAgents referencing ${oldState}:`);
117
+ for (const name of (await readdir(agents)).sort()) {
118
+ if (!name.endsWith('.plist') || name === `${SERVICE_LABEL}.plist`) continue;
119
+ const file=path.join(agents,name),content=await readFile(file,'utf8');
120
+ if (unxml(content).includes(oldState)) {
121
+ data.references.push(file); output(file);
122
+ if (!warnings.length) warnings.push({code:'MIGRATION_REFERENCES_REMAIN',message:`Other LaunchAgents still reference ${oldState}.`,next:[]});
123
+ }
124
+ }
125
+ if (!data.references.length) output('None.');
126
+ data.complete = true;
127
+ return {data,warnings};
128
+ } catch (cause) {
129
+ if (cause instanceof CliError) cause.context.stateDirectory = newState;
130
+ if (!data.changes.length) throw cause;
131
+ throw commandFailure(cause,data,warnings);
91
132
  }
92
- if (!count) output('None.');
93
- return 0;
94
133
  }
95
134
 
96
135
  // Overrides keep launchctl and the user's LaunchAgents directory out of contract checks.
@@ -99,65 +138,47 @@ export async function service(action, values = {}, {
99
138
  nodePath = process.execPath, cliPath = fileURLToPath(new URL('./cli.mjs', import.meta.url)),
100
139
  uid = process.getuid?.(), output = console.log,
101
140
  } = {}) {
102
- if (platform !== 'darwin') throw new Error('adg service is supported only on macOS (LaunchAgent).');
103
- if (!['install', 'uninstall', 'status', 'logs', 'migrate'].includes(action)) {
104
- throw new Error('Expected adg service install|uninstall|status|logs|migrate; run adg service --help.');
105
- }
106
- if (action === 'migrate') return migrateService(values, { home, run, nodePath, cliPath, uid, output });
107
- const agentFile = path.join(home, 'Library', 'LaunchAgents', `${SERVICE_LABEL}.plist`);
108
- let installedPlist = null;
109
- try { installedPlist = await readFile(agentFile, 'utf8'); }
110
- catch (error) { if (error.code !== 'ENOENT') throw error; }
111
- const installedArgs = launchArguments(installedPlist);
112
- const stateFlag = installedArgs.indexOf('--state-dir');
113
- const installedStateDirectory = stateFlag >= 0 ? installedArgs[stateFlag + 1] : undefined;
114
- const stateDirectory = path.resolve(values['state-dir'] ?? (action === 'install' ? undefined : installedStateDirectory) ?? defaultStateDirectory);
115
- const domain = `gui/${uid}`, target = `${domain}/${SERVICE_LABEL}`;
116
- const stdout = path.join(stateDirectory, 'service.stdout.log');
117
- const stderr = path.join(stateDirectory, 'service.stderr.log');
118
- const loaded = async () => {
119
- try { return (await run('/bin/launchctl', ['print', target])).stdout; }
120
- catch (error) {
121
- if ([3, 113].includes(error.code)) return null;
122
- throw new Error(`Cannot inspect ${SERVICE_LABEL}: ${error.stderr?.trim() || error.message}`);
123
- }
124
- };
141
+ if (platform !== 'darwin') throw new CliError('SERVICE_UNSUPPORTED','adg service is supported only on macOS (LaunchAgent).');
142
+ if (!['install','uninstall','status','logs','migrate'].includes(action)) throw new CliError('USAGE_INVALID','Expected adg service install|uninstall|status|logs|migrate; run adg service --help.');
143
+ if (action === 'migrate') return migrateService(values,{home,run,nodePath,cliPath,uid,output});
144
+ const agentFile=path.join(home,'Library','LaunchAgents',`${SERVICE_LABEL}.plist`);
145
+ const installedPlist=await readOptional(agentFile),installedArgs=launchArguments(installedPlist),stateFlag=installedArgs.indexOf('--state-dir');
146
+ const stateDirectory=path.resolve(values['state-dir'] ?? (action === 'install' ? undefined : stateFlag >= 0 ? installedArgs[stateFlag+1] : undefined) ?? defaultStateDirectory);
147
+ const domain=`gui/${uid}`,target=`${domain}/${SERVICE_LABEL}`;
148
+ const stdout=path.join(stateDirectory,'service.stdout.log'),stderr=path.join(stateDirectory,'service.stderr.log');
125
149
  if (action === 'logs') {
126
- for (const file of [stdout, stderr]) {
127
- let content;
128
- try { content = await readFile(file, 'utf8'); }
129
- catch (error) { if (error.code === 'ENOENT') continue; throw error; }
130
- output(`${file}\n${content.trimEnd().split('\n').slice(-200).join('\n')}`);
150
+ const logs=[];
151
+ for (const [stream,file] of [['stdout',stdout],['stderr',stderr]]) {
152
+ const content=await readOptional(file),lines=content?.trimEnd().split('\n').slice(-200) ?? [];
153
+ logs.push({stream,path:file,exists:content!==null,lines:content?.trimEnd() ? lines : []});
154
+ if (!values.json && content !== null) output(`${file}\n${lines.join('\n')}`);
131
155
  }
132
- return 0;
156
+ return {data:{label:SERVICE_LABEL,stateDirectory,logs}};
133
157
  }
134
158
  if (action === 'status') {
135
- const status = await loaded();
136
- output(JSON.stringify({ label: SERVICE_LABEL, installed: installedPlist !== null, loaded: status !== null,
137
- state: status?.match(/^\s*state = (.+)$/m)?.[1] ?? null,
138
- pid: Number(status?.match(/^\s*pid = (\d+)$/m)?.[1]) || null,
139
- plist: agentFile, stateDirectory, logs: { stdout, stderr } }, null, 2));
140
- return 0;
159
+ const data=statusData(await loadedJob(run,target),installedPlist,agentFile,stateDirectory);
160
+ if (!values.json) output(JSON.stringify(data,null,2));
161
+ return {data};
141
162
  }
142
163
  if (action === 'uninstall') {
143
- if (await loaded() !== null) await run('/bin/launchctl', ['bootout', target]);
144
- await rm(agentFile, { force: true });
164
+ if (await loadedJob(run,target) !== null) await job(run,['bootout',target]);
165
+ await rm(agentFile,{force:true});
145
166
  output(`Uninstalled ${SERVICE_LABEL}. State and logs retained in ${stateDirectory}.`);
146
- return 0;
167
+ return {data:{label:SERVICE_LABEL,plist:agentFile,stateDirectory,retained:true}};
147
168
  }
148
- const port = values.port === undefined ? 4310 : Number(values.port);
149
- if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('--port must be an integer from 1 to 65535.');
150
- if (installedPlist !== null) throw new Error(`${SERVICE_LABEL} is already installed; run adg service uninstall before reinstalling.`);
151
- const executable = await realpath(nodePath), entry = await realpath(cliPath);
152
- await mkdir(path.dirname(agentFile), { recursive: true });
153
- await mkdir(stateDirectory, { recursive: true });
154
- await Promise.all([stdout, stderr].map(file => writeFile(file, '', { flag: 'a' })));
155
- await writeFile(agentFile, renderLaunchAgent({ nodePath: executable, cliPath: entry, stateDirectory, port }));
156
- try { await run('/bin/launchctl', ['bootstrap', domain, agentFile]); }
157
- catch (error) {
158
- await rm(agentFile, { force: true });
159
- throw new Error(`Cannot install ${SERVICE_LABEL}: ${error.stderr?.trim() || error.message}`);
169
+ const port=values.port===undefined ? 4310 : Number(values.port);
170
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new CliError('USAGE_INVALID','--port must be an integer from 1 to 65535.');
171
+ if (installedPlist !== null) throw new CliError('SERVICE_ALREADY_INSTALLED',`${SERVICE_LABEL} is already installed; run adg service uninstall before reinstalling.`);
172
+ const executable=await realpath(nodePath),entry=await realpath(cliPath);
173
+ await mkdir(path.dirname(agentFile),{recursive:true});await mkdir(stateDirectory,{recursive:true});
174
+ await Promise.all([stdout,stderr].map(file=>writeFile(file,'',{flag:'a'})));
175
+ const plist=renderLaunchAgent({nodePath:executable,cliPath:entry,stateDirectory,port});
176
+ await writeFile(agentFile,plist);
177
+ try { await run('/bin/launchctl',['bootstrap',domain,agentFile]); }
178
+ catch (cause) {
179
+ await rm(agentFile,{force:true});
180
+ throw new CliError('SERVICE_FAILED',`Cannot install ${SERVICE_LABEL}: ${cause.stderr?.trim() || cause.message}`,{cause});
160
181
  }
161
182
  output(`Installed ${SERVICE_LABEL}. Logs: ${stdout} and ${stderr}.`);
162
- return 0;
183
+ return {data:{service:statusData(await loadedJob(run,target),plist,agentFile,stateDirectory),port}};
163
184
  }