@agentage/cli 0.52.1 → 0.54.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 (56) hide show
  1. package/README.md +9 -11
  2. package/dist/commands/daemon/daemon.d.ts +5 -3
  3. package/dist/commands/daemon/daemon.js +45 -10
  4. package/dist/commands/daemon/installer.d.ts +4 -0
  5. package/dist/commands/daemon/installer.js +32 -8
  6. package/dist/commands/daemon/run.d.ts +3 -0
  7. package/dist/commands/daemon/run.js +11 -1
  8. package/dist/commands/extension/build.js +5 -3
  9. package/dist/commands/extension/configure.js +2 -1
  10. package/dist/commands/extension/create-install.js +3 -2
  11. package/dist/commands/extension/install-once.d.ts +2 -0
  12. package/dist/commands/extension/install-once.js +5 -5
  13. package/dist/commands/extension/install-spec.d.ts +7 -0
  14. package/dist/commands/extension/install-spec.js +33 -0
  15. package/dist/commands/extension/lifecycle.d.ts +1 -4
  16. package/dist/commands/extension/lifecycle.js +8 -32
  17. package/dist/commands/extension/package-build.d.ts +11 -1
  18. package/dist/commands/extension/package-build.js +53 -17
  19. package/dist/commands/extension/release-guard.d.ts +8 -1
  20. package/dist/commands/extension/release-guard.js +39 -16
  21. package/dist/commands/extension/release.js +35 -19
  22. package/dist/commands/extension/setup-install.js +48 -23
  23. package/dist/commands/extension/setup-marker.d.ts +6 -0
  24. package/dist/commands/extension/setup-marker.js +23 -0
  25. package/dist/commands/extension/up-build.d.ts +17 -0
  26. package/dist/commands/extension/up-build.js +71 -0
  27. package/dist/commands/extension/up-commands.js +11 -10
  28. package/dist/commands/extension/up-local.d.ts +15 -12
  29. package/dist/commands/extension/up-local.js +61 -60
  30. package/dist/commands/extension/up-reload.d.ts +30 -0
  31. package/dist/commands/extension/up-reload.js +115 -0
  32. package/dist/commands/extension/up-run.d.ts +9 -11
  33. package/dist/commands/extension/up-run.js +132 -50
  34. package/dist/commands/extension/up-watch.d.ts +23 -0
  35. package/dist/commands/extension/up-watch.js +81 -0
  36. package/dist/commands/extension/up.d.ts +5 -3
  37. package/dist/commands/extension/up.js +48 -25
  38. package/dist/core/installer/version-spec.d.ts +2 -0
  39. package/dist/core/installer/version-spec.js +5 -0
  40. package/dist/core/loader/manifest.d.ts +2 -1
  41. package/dist/core/loader/manifest.js +13 -8
  42. package/dist/lib/daemon/daemon-client.js +16 -11
  43. package/dist/lib/daemon/daemon-file.d.ts +2 -0
  44. package/dist/lib/daemon/daemon-file.js +4 -0
  45. package/dist/lib/daemon/daemon-health.d.ts +5 -0
  46. package/dist/lib/daemon/daemon-health.js +27 -2
  47. package/dist/lib/daemon/daemon-probe.d.ts +10 -5
  48. package/dist/lib/daemon/daemon-probe.js +8 -2
  49. package/dist/lib/daemon/host-client.d.ts +17 -2
  50. package/dist/lib/daemon/host-client.js +42 -12
  51. package/dist/lib/fs/file-lock.js +6 -0
  52. package/dist/lib/json-output.js +7 -5
  53. package/dist/lib/proc/start-time.d.ts +10 -0
  54. package/dist/lib/proc/start-time.js +46 -0
  55. package/dist/program-deps.js +3 -1
  56. package/package.json +2 -2
@@ -1,23 +1,19 @@
1
- import { createServer } from 'node:http';
2
1
  import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
3
2
  import { join, resolve } from 'node:path';
4
- import { isPid } from '../../lib/daemon/daemon-file.js';
3
+ import { isMark, markOf, proven, stopProven } from '../../lib/proc/start-time.js';
4
+ import { withFileLock } from '../../lib/fs/file-lock.js';
5
5
  import { isRecord, readJson, writeTextAtomic } from '../../lib/fs/json-file.js';
6
- import { CliError, messageOf } from '../../lib/json-output.js';
6
+ import { CliError } from '../../lib/json-output.js';
7
7
  import { waitFor } from '../../lib/wait.js';
8
- // D7: a local up takes the first free port from here; the daemon keeps 4243.
9
- export const UP_FROM = 4244;
10
8
  // The kit's own folder in a working copy (`.agentage/`, ignored by the template).
11
9
  const LOCAL = '.agentage';
12
10
  export const recordPath = (dir) => join(resolve(dir), LOCAL, 'up.json');
13
- export const dataDirOf = (dir) => join(resolve(dir), LOCAL, 'data');
14
11
  const isUpRecord = (value) => isRecord(value) &&
15
- isPid(value['pid']) &&
16
- Number.isInteger(value['port']) &&
17
- value['port'] >= 1024 &&
18
- value['port'] <= 65535 &&
12
+ isMark(value['up']) &&
13
+ typeof value['nonce'] === 'string' &&
19
14
  typeof value['id'] === 'string' &&
20
- typeof value['instance'] === 'string';
15
+ typeof value['added'] === 'boolean' &&
16
+ (value['tsc'] === undefined || isMark(value['tsc']));
21
17
  export const readRecord = (dir) => readJson(recordPath(dir), isUpRecord);
22
18
  // The run state stays out of git: `.agentage/` goes into the folder's .gitignore when missing.
23
19
  export const ignoreLocal = (dir) => {
@@ -36,59 +32,64 @@ export const writeRecord = (dir, record) => {
36
32
  writeTextAtomic(recordPath(dir), `${JSON.stringify(record)}\n`);
37
33
  };
38
34
  export const removeRecord = (dir) => rmSync(recordPath(dir), { force: true });
39
- const bind = (handler, port) => new Promise((done, fail) => {
40
- const server = createServer(handler);
41
- server.once('error', (err) => err.code === 'EADDRINUSE' ? done(null) : fail(err));
42
- server.listen(port, '127.0.0.1', () => done(server));
43
- });
44
- // D7: the first port from 4244 that binds; a port taken meanwhile is skipped, not fatal.
45
- export const listenFrom = async (handler, from = UP_FROM) => {
46
- for (let port = from; port < from + 100; port += 1) {
47
- const server = await bind(handler, port);
48
- if (server)
49
- return server;
50
- }
51
- throw new CliError('port_in_use', `no free port from ${from} to ${from + 99}`);
35
+ // A tsc that outlived its up (killed hard): stopped only when proven to be that tsc.
36
+ export const stopOrphan = (record) => {
37
+ if (!record?.tsc || proven(record.up))
38
+ return;
39
+ if (stopProven(record.tsc))
40
+ console.error(`stopped the tsc watch (pid ${record.tsc.pid}) of an up that ended`);
52
41
  };
53
- export const portOf = (server) => server.address().port;
54
- // The record's extension answers on its port when /health names the same id and instance.
55
- export const answerOf = async (record, timeoutMs = 2_000) => {
56
- const res = await fetch(`http://127.0.0.1:${record.port}/health`, {
57
- signal: AbortSignal.timeout(timeoutMs),
58
- }).catch(() => null);
59
- if (!res)
60
- return 'none';
61
- const body = (await res.json().catch(() => null));
62
- const same = body?.data?.extension === record.id && body.data.instance === record.instance;
63
- return same ? 'ours' : 'other';
42
+ // A live up of the folder is refused; a record of an up that ended keeps only its `added`.
43
+ export const refuseRunning = (dir) => {
44
+ const record = readRecord(dir);
45
+ if (!record || !proven(record.up) || record.up.pid === process.pid)
46
+ return (stopOrphan(record), record);
47
+ throw new CliError('already_running', `extension up runs for ${dir} (pid ${record.up.pid}): agentage extension down`);
64
48
  };
65
- // Resolves on the first SIGINT or SIGTERM, then releases both.
66
- export const untilSignal = () => new Promise((done) => {
67
- const on = (signal) => {
68
- process.off('SIGINT', on);
69
- process.off('SIGTERM', on);
70
- done(signal);
49
+ // A closed terminal (SIGHUP) stops as Ctrl-C does: the watch goes, the row stays for the next up.
50
+ const STOPS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
51
+ // This up: pid and start time; where the start time cannot be read (Windows) it is never proven.
52
+ export const selfMark = () => markOf(process.pid) ?? { pid: process.pid, started: 'unknown' };
53
+ // Two ups of one folder at once: the check and the claim are one step under the record's lock.
54
+ export const claimFolder = (dir, nonce, id) => withFileLock(recordPath(dir), () => {
55
+ const before = refuseRunning(dir);
56
+ writeRecord(dir, { up: selfMark(), nonce, id, added: before?.added === true });
57
+ return before;
58
+ });
59
+ // A record that is no longer this up's (down ran, or a second up took it) stops the start; locked as down is.
60
+ export const rewriteRecord = (dir, record) => withFileLock(recordPath(dir), () => {
61
+ if (readRecord(dir)?.nonce !== record.nonce)
62
+ throw new CliError('cancelled', `the record of this up for ${dir} changed while it started (extension down, or another up)`);
63
+ writeRecord(dir, record);
64
+ });
65
+ // Ends on a signal (the row stays), a removed or rewritten record (`down`) or a dead watch.
66
+ export const untilStopped = (dir, nonce, ended, everyMs = 300) => new Promise((done) => {
67
+ const on = STOPS.map((name) => [name, () => finish(name)]);
68
+ const finish = (why) => {
69
+ clearInterval(timer);
70
+ for (const [name, handler] of on)
71
+ process.off(name, handler);
72
+ done(why);
71
73
  };
72
- process.once('SIGINT', on);
73
- process.once('SIGTERM', on);
74
+ const timer = setInterval(() => readRecord(dir)?.nonce === nonce || finish('down'), everyMs);
75
+ for (const [name, handler] of on)
76
+ process.once(name, handler);
77
+ void ended.then(finish);
74
78
  });
75
- const gone = (record, timeoutMs) => waitFor(async () => (await answerOf(record, 500)) === 'none', timeoutMs);
76
- // Signals the recorded pid only when its port answers as that extension; else the record is stale.
79
+ // Removing the record is the stop: the up of that pid sees it and exits; no up is signalled.
77
80
  export const stopLocal = async (dir, timeoutMs = 10_000) => {
78
- const record = readRecord(dir);
81
+ const record = await withFileLock(recordPath(dir), () => {
82
+ const found = readRecord(dir);
83
+ if (found)
84
+ removeRecord(dir);
85
+ return found;
86
+ });
79
87
  if (!record)
80
- return 'none';
81
- if ((await answerOf(record)) !== 'ours')
82
- return (removeRecord(dir), 'stale');
83
- try {
84
- process.kill(record.pid, 'SIGTERM');
85
- }
86
- catch (err) {
87
- const why = messageOf(err);
88
- throw new CliError('stop_failed', `cannot stop extension up (pid ${record.pid}): ${why}`);
89
- }
90
- if (!(await gone(record, timeoutMs)))
91
- throw new CliError('stop_failed', `extension up (pid ${record.pid}) did not stop`);
92
- removeRecord(dir);
93
- return 'stopped';
88
+ return { down: 'none', record };
89
+ if (!proven(record.up))
90
+ return (stopOrphan(record), { down: 'stale', record });
91
+ if (!(await waitFor(() => !proven(record.up), timeoutMs)))
92
+ throw new CliError('stop_failed', `extension up (pid ${record.up.pid}) did not stop`);
93
+ stopOrphan(record);
94
+ return { down: 'stopped', record };
94
95
  };
@@ -0,0 +1,30 @@
1
+ import { type HostClient } from '../../lib/daemon/host-client.js';
2
+ import { type Code } from '../../lib/json-output.js';
3
+ import { type Npm } from './package-build.js';
4
+ import { type UpMode } from './up-build.js';
5
+ import { type Stoppable, type TscBuilt } from './up-watch.js';
6
+ export interface Run {
7
+ dir: string;
8
+ id: string;
9
+ host: HostClient;
10
+ npm: Npm;
11
+ fatal?: (why: string, code?: Code) => void;
12
+ failed?: number;
13
+ builtAt?: number;
14
+ }
15
+ export declare const editedSince: (dir: string, since?: number) => boolean;
16
+ export declare const RELOAD_STRIKES = 3;
17
+ type Task = () => Promise<void>;
18
+ export declare const lane: () => ((task: Task) => Promise<void>);
19
+ export declare const reload: (run: Run, since: number) => Promise<void>;
20
+ export declare const stageAndReload: (run: Run) => Promise<void>;
21
+ export declare const tscReloads: (run: Run, inLane: (task: Task) => Promise<void>) => {
22
+ onChange: () => undefined;
23
+ onBuilt: ({ errors, ms, first }: TscBuilt) => void;
24
+ };
25
+ export interface Watch {
26
+ watchers: Stoppable[];
27
+ tscPid?: number;
28
+ }
29
+ export declare const startWatch: (run: Run, mode: UpMode, onDied: (why: string) => void) => Watch;
30
+ export {};
@@ -0,0 +1,115 @@
1
+ import { cpSync, existsSync, readdirSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import {} from '../../lib/daemon/host-client.js';
4
+ import { messageOf } from '../../lib/json-output.js';
5
+ import {} from './package-build.js';
6
+ import { NEXT, stagedBuild } from './up-build.js';
7
+ import { coalesced, runRest, watchFolder, watchTsc, } from './up-watch.js';
8
+ // A save between the start of the running build and the end of the first watch build.
9
+ export const editedSince = (dir, since) => {
10
+ const src = join(dir, 'src');
11
+ if (since === undefined || !existsSync(src))
12
+ return false;
13
+ return readdirSync(src, { recursive: true, withFileTypes: true }).some((f) => f.isFile() && statSync(join(f.parentPath, f.name)).mtimeMs >= since);
14
+ };
15
+ // A daemon that refuses the call three times in a row will not take the next save either.
16
+ export const RELOAD_STRIKES = 3;
17
+ const failedReload = (run, why) => {
18
+ console.error(`reload ${run.id} failed: ${why}`);
19
+ run.failed = (run.failed ?? 0) + 1;
20
+ if (run.failed >= RELOAD_STRIKES)
21
+ run.fatal?.(`the reload failed ${run.failed} times in a row`, 'daemon_unavailable');
22
+ };
23
+ // One lane for every write into dist.next and every reload: two of them never overlap.
24
+ export const lane = () => {
25
+ let tail = Promise.resolve();
26
+ return (task) => {
27
+ const next = tail.then(task);
28
+ tail = next.catch(() => undefined);
29
+ return next;
30
+ };
31
+ };
32
+ // One line per reload: reloaded and the time, or the daemon's refusal (the last good build runs).
33
+ export const reload = async (run, since) => {
34
+ const { host, id } = run;
35
+ const answer = await host.reload(id).catch((err) => ({ error: messageOf(err) }));
36
+ const ms = Date.now() - since;
37
+ if ('error' in answer)
38
+ return failedReload(run, answer.error);
39
+ run.failed = 0;
40
+ if (answer.reloaded)
41
+ return console.log(`reload ${id} reloaded: true in ${ms} ms`);
42
+ console.log(`reload ${id} reloaded: false, refused: ${answer.refused ?? 'no reason'} (${ms} ms)`);
43
+ console.log(` ${id} the last good build runs`);
44
+ };
45
+ // npm or the script's own tool cannot run (127: command not found): no later save builds either.
46
+ const MISSING = /did not start|exited 127$/;
47
+ // A build that fails prints the compiler's words (its own stderr) and sends no reload.
48
+ export const stageAndReload = async (run) => {
49
+ const since = Date.now();
50
+ try {
51
+ await stagedBuild(run.dir, run.npm);
52
+ }
53
+ catch (err) {
54
+ console.error(`build failed, no reload: ${messageOf(err)}`);
55
+ if (MISSING.test(messageOf(err)))
56
+ run.fatal?.('the build tool is missing (npm ci installs it)');
57
+ return;
58
+ }
59
+ await reload(run, since);
60
+ };
61
+ // D17: a change under src/ui runs the widget bundle into dist/ui; the daemon serves no ui yet.
62
+ const bundleUi = async (run, rest) => {
63
+ const since = Date.now();
64
+ if (!(await runRest(run.dir, rest)))
65
+ return console.error('ui the bundle failed');
66
+ cpSync(join(run.dir, 'dist', 'ui'), join(run.dir, NEXT, 'ui'), { recursive: true, force: true });
67
+ console.log(`ui bundled into dist/ui in ${Date.now() - since} ms (no reload)`);
68
+ };
69
+ // A reload only after a clean tsc build, never during one; a build during a reload gives one more.
70
+ export const tscReloads = (run, inLane) => {
71
+ const state = { building: false, pending: false, since: 0 };
72
+ const go = coalesced(() => inLane(async () => {
73
+ if (state.building || !state.pending)
74
+ return;
75
+ state.pending = false;
76
+ await reload(run, state.since);
77
+ }));
78
+ const onBuilt = ({ errors, ms, first }) => {
79
+ state.building = false;
80
+ if (errors > 0)
81
+ console.error(`build ${errors} error(s), no reload`);
82
+ // The first watch build is the running one, unless a save came in while it built.
83
+ const changed = !first || editedSince(run.dir, run.builtAt);
84
+ if (errors === 0 && changed)
85
+ Object.assign(state, { pending: true, since: Date.now() - ms });
86
+ if (state.pending)
87
+ void go();
88
+ };
89
+ return { onChange: () => void (state.building = true), onBuilt };
90
+ };
91
+ const watchWithTsc = (run, mode, onDied) => {
92
+ const inLane = lane();
93
+ const tsc = watchTsc(run.dir, mode, { ...tscReloads(run, inLane), onDied });
94
+ if (!mode.rest)
95
+ return { watchers: [tsc], tscPid: tsc.pid };
96
+ const rest = mode.rest;
97
+ const bundle = coalesced(() => inLane(() => bundleUi(run, rest)));
98
+ const ui = watchFolder(join(run.dir, 'src', 'ui'), bundle);
99
+ return { watchers: [tsc, ui], tscPid: tsc.pid };
100
+ };
101
+ export const startWatch = (run, mode, onDied) => {
102
+ if (mode.kind === 'tsc')
103
+ return watchWithTsc(run, mode, onDied);
104
+ if (!mode.script)
105
+ console.error('watch no build script: a change in src/ is not built');
106
+ if (!existsSync(join(run.dir, 'src')))
107
+ console.error('watch no src/ folder: nothing to watch');
108
+ if (!mode.script)
109
+ return { watchers: [] };
110
+ return {
111
+ watchers: [
112
+ watchFolder(join(run.dir, 'src'), coalesced(() => stageAndReload(run))),
113
+ ],
114
+ };
115
+ };
@@ -1,15 +1,13 @@
1
- import type * as KitHostModule from '@agentage/extension/host';
2
- import type { HostedExtension, HostOptions } from '@agentage/extension/host';
3
- import { type PackageBuild } from './package-build.js';
4
- export interface KitHost {
5
- host: (dir: string, opts: HostOptions) => Promise<HostedExtension>;
6
- }
7
- type KitModule = Pick<typeof KitHostModule, 'hostExtension'>;
8
- export declare const loadKitHost: (load?: () => Promise<KitModule>) => Promise<KitHost>;
1
+ import { type HostClient } from '../../lib/daemon/host-client.js';
2
+ import { type Npm, type PackageBuild } from './package-build.js';
9
3
  export interface LocalUpDeps {
10
4
  build: (dir: string) => Promise<PackageBuild>;
11
- kit: () => Promise<KitHost>;
12
- stopped: () => Promise<string>;
5
+ daemon: () => Promise<{
6
+ port: number;
7
+ host: HostClient;
8
+ }>;
9
+ npm: Npm;
10
+ stopped: (dir: string, nonce: string, ended: Promise<string>) => Promise<string>;
13
11
  }
14
12
  export declare const localUpDeps: LocalUpDeps;
15
13
  export interface LocalUp {
@@ -17,7 +15,7 @@ export interface LocalUp {
17
15
  version: string;
18
16
  url: string;
19
17
  port: number;
18
+ added: boolean;
20
19
  stoppedBy: string;
21
20
  }
22
21
  export declare const runLocalUp: (folder?: string, deps?: LocalUpDeps, json?: boolean) => Promise<LocalUp>;
23
- export {};
@@ -1,27 +1,33 @@
1
- import {} from 'node:http';
1
+ import { randomUUID } from 'node:crypto';
2
+ import { markOf } from '../../lib/proc/start-time.js';
2
3
  import { resolve } from 'node:path';
4
+ import { isRecord } from '../../lib/fs/json-file.js';
5
+ import { ensureDaemon } from '../../lib/daemon/daemon-client.js';
6
+ import { hostClient } from '../../lib/daemon/host-client.js';
3
7
  import { setExit } from '../../lib/exit-code.js';
4
8
  import { CliError } from '../../lib/json-output.js';
9
+ import { folderRow, installFolder } from './install-once.js';
5
10
  import { loadKitTool } from './kit-tool.js';
6
- import { buildPackage } from './package-build.js';
7
- import { answerOf, dataDirOf, listenFrom, portOf, readRecord, removeRecord, untilSignal, writeRecord, } from './up-local.js';
8
- export const loadKitHost = async (load = () => import('@agentage/extension/host')) => {
9
- const kit = await load();
10
- return { host: (dir, opts) => kit.hostExtension(dir, { ...opts, localOnly: true }) };
11
- };
11
+ import { buildPackage, npmIn, packageOf } from './package-build.js';
12
+ import { removeStage, seedNext, upModeOf } from './up-build.js';
13
+ import { claimFolder, rewriteRecord, selfMark, untilStopped } from './up-local.js';
14
+ import { stageAndReload, startWatch } from './up-reload.js';
12
15
  export const localUpDeps = {
13
16
  build: (dir) => buildPackage(dir),
14
- kit: () => loadKitHost(),
15
- stopped: untilSignal,
17
+ daemon: async () => {
18
+ const port = await ensureDaemon();
19
+ return { port, host: hostClient(port) };
20
+ },
21
+ npm: npmIn,
22
+ stopped: (dir, nonce, ended) => untilStopped(dir, nonce, ended),
16
23
  };
17
- const refuseRunning = async (dir) => {
18
- const record = readRecord(dir);
19
- if (!record)
20
- return;
21
- if ((await answerOf(record)) !== 'ours')
22
- return removeRecord(dir);
23
- const at = `http://127.0.0.1:${record.port}`;
24
- throw new CliError('already_running', `extension up runs for ${dir} on ${at}: extension down`);
24
+ // Checked before the daemon starts: a folder that is no extension package starts nothing.
25
+ const idOf = (dir) => {
26
+ const agentage = packageOf(dir)['agentage'];
27
+ const id = isRecord(agentage) ? agentage['id'] : undefined;
28
+ if (typeof id !== 'string')
29
+ throw new CliError('invalid_argument', `${dir}: no agentage.id`);
30
+ return id;
25
31
  };
26
32
  // Problems do not stop a local run; they are printed, as `extension build` would refuse them.
27
33
  const warnProblems = async ({ report }) => {
@@ -30,46 +36,122 @@ const warnProblems = async ({ report }) => {
30
36
  for (const text of (await loadKitTool()).checkLines(report))
31
37
  console.error(`check ${text}`);
32
38
  };
33
- const serve = (hosted) => listenFrom(hosted.app);
34
- const close = async (server, hosted, dir) => {
35
- server?.closeAllConnections();
36
- await Promise.all([server && new Promise((done) => server.close(done)), hosted.stop()]);
37
- removeRecord(dir);
38
- };
39
39
  // Ready: the line, and with --json one JSON line on stdout before the envelope at exit.
40
- const ready = (hosted, url, port, json) => {
41
- console.log(`up ${hosted.id} ${hosted.version} on ${url} (Ctrl-C stops it)`);
42
- const line = { ready: true, id: hosted.id, version: hosted.version, url, port };
40
+ const ready = (up, json) => {
41
+ console.log(`up ${up.id} ${up.version} on ${up.url} (watching src/; Ctrl-C stops)`);
42
+ const line = { ready: true, id: up.id, version: up.version, url: up.url, port: up.port };
43
43
  if (json)
44
44
  process.stdout.write(`${JSON.stringify(line)}\n`);
45
45
  };
46
- const runHosted = async (dir, hosted, deps, json) => {
47
- let server = null;
46
+ const stopLine = (id, stoppedBy, added) => {
47
+ if (stoppedBy === 'down')
48
+ return console.log(`stopped watching ${id} (extension down)`);
49
+ console.log(`stopped watching ${id} (${stoppedBy}); the daemon still runs it`);
50
+ if (added)
51
+ console.log(` agentage extension down removes it (its data stays)`);
52
+ };
53
+ // The first build: in the folder while no child runs it (a create or an earlier up), else staged.
54
+ const firstBuild = async (run, mode, build) => {
55
+ if (!(await folderRow(run.host, run.id, run.dir))) {
56
+ await warnProblems(await build(run.dir));
57
+ return seedNext(run.dir);
58
+ }
59
+ seedNext(run.dir);
60
+ if (mode.kind === 'tsc' || mode.script)
61
+ await stageAndReload(run);
62
+ };
63
+ // A watch that ends by itself, a missing build tool or a reload that keeps failing stops up.
64
+ const deathOf = () => {
65
+ let died = () => undefined;
66
+ let reason = '';
67
+ let code = 'build_failed';
68
+ const ended = new Promise((done) => (died = done));
69
+ const onDied = (why, as = 'build_failed') => {
70
+ if (reason)
71
+ return;
72
+ [reason, code] = [why, as];
73
+ console.error(`watch ${why}; extension up stops (run it again)`);
74
+ died('watch died');
75
+ };
76
+ const failure = () => new CliError(code, `extension up stopped: ${reason}`);
77
+ return { ended, onDied, failure, died: () => reason !== '' };
78
+ };
79
+ // Ctrl-C is 130 and a closed terminal 129; a watch that died fails, so --json gives the error.
80
+ const exitFor = (stoppedBy, failure) => {
81
+ if (stoppedBy === 'SIGINT')
82
+ setExit(130);
83
+ if (stoppedBy === 'SIGHUP')
84
+ setExit(129);
85
+ if (stoppedBy === 'watch died')
86
+ throw failure();
87
+ };
88
+ // D12: build, the folder as a daemon row, a watch that builds to dist.next and reloads that child.
89
+ export const runLocalUp = async (folder = '.', deps = localUpDeps, json = false) => {
90
+ const dir = resolve(folder);
91
+ const id = idOf(dir);
92
+ const nonce = randomUUID();
93
+ const before = await claimFolder(dir, nonce, id);
94
+ const { port, host } = await deps.daemon();
95
+ const run = { dir, id, host, npm: deps.npm };
96
+ const mode = upModeOf(dir);
97
+ // A stage of an earlier up may hold an old package.json: the first staged build copies it again.
98
+ removeStage(dir);
48
99
  try {
49
- server = await serve(hosted);
50
- const port = portOf(server);
51
- const { instance } = (await hosted.health()).data;
52
- writeRecord(dir, { pid: process.pid, port, id: hosted.id, instance });
53
- const url = `http://127.0.0.1:${port}/api/${hosted.id}/`;
54
- ready(hosted, url, port, json);
55
- const stoppedBy = await deps.stopped();
56
- return { id: hosted.id, version: hosted.version, url, port, stoppedBy };
100
+ return await upAndWatch(run, mode, deps, { port, json, before, nonce });
57
101
  }
58
102
  finally {
59
- await close(server, hosted, dir);
103
+ removeStage(dir);
60
104
  }
61
105
  };
62
- // D7: the working copy in this terminal, on the next free port from 4244, until Ctrl-C (exit 130).
63
- export const runLocalUp = async (folder = '.', deps = localUpDeps, json = false) => {
64
- const dir = resolve(folder);
65
- await refuseRunning(dir);
66
- await warnProblems(await deps.build(dir));
67
- delete process.env['AGENTAGE_TOKEN'];
68
- const kit = await deps.kit();
69
- const hosted = await kit.host(dir, { dataDir: dataDirOf(dir) });
70
- const done = await runHosted(dir, hosted, deps, json);
71
- console.log(`stopped ${done.id} (${done.stoppedBy})`);
72
- if (done.stoppedBy === 'SIGINT')
73
- setExit(130);
74
- return done;
106
+ // The fatal channel is wired before the first build: a second up with no build tool stops too.
107
+ const upAndWatch = async (run, mode, deps, ctx) => {
108
+ const death = deathOf();
109
+ run.fatal = death.onDied;
110
+ run.builtAt = Date.now();
111
+ await firstBuild(run, mode, deps.build);
112
+ if (death.died())
113
+ throw death.failure();
114
+ const { row, already } = await installFolder(run.host, run.dir);
115
+ const added = !already || ctx.before?.added === true;
116
+ const up = {
117
+ id: row.id,
118
+ version: row.version,
119
+ url: urlOf(ctx.port, row.id),
120
+ port: ctx.port,
121
+ added,
122
+ };
123
+ const stoppedBy = await watchUntilStopped(run, mode, { deps, ctx, death, up });
124
+ stopLine(up.id, stoppedBy, added);
125
+ exitFor(stoppedBy, death.failure);
126
+ return { ...up, stoppedBy };
127
+ };
128
+ // No record is left for down to read, so a row this up added goes with the cancelled start.
129
+ const cancelled = async (run, up, err) => {
130
+ if (up.added && err instanceof CliError && err.code === 'cancelled') {
131
+ if (await folderRow(run.host, up.id, run.dir))
132
+ await run.host.remove(up.id, false);
133
+ }
134
+ throw err;
135
+ };
136
+ // A record down removed meanwhile, or one that cannot be written, still stops the tsc it started.
137
+ const watchUntilStopped = async (run, mode, w) => {
138
+ const { watchers, tscPid } = startWatch(run, mode, w.death.onDied);
139
+ try {
140
+ const tsc = markOf(tscPid) ?? undefined;
141
+ const { nonce } = w.ctx;
142
+ await rewriteRecord(run.dir, {
143
+ up: selfMark(),
144
+ nonce,
145
+ id: w.up.id,
146
+ added: w.up.added,
147
+ ...(tsc && { tsc }),
148
+ }).catch((err) => cancelled(run, w.up, err));
149
+ ready(w.up, w.ctx.json);
150
+ return await w.deps.stopped(run.dir, nonce, w.death.ended);
151
+ }
152
+ finally {
153
+ for (const watcher of watchers)
154
+ watcher.stop();
155
+ }
75
156
  };
157
+ const urlOf = (port, id) => `http://127.0.0.1:${port}/api/${id}/`;
@@ -0,0 +1,23 @@
1
+ import { type UpMode } from './up-build.js';
2
+ export interface Stoppable {
3
+ stop: () => void;
4
+ }
5
+ export declare const watchFolder: (dir: string, onChange: () => void, debounceMs?: number) => Stoppable;
6
+ export declare const coalesced: (run: () => Promise<void>) => (() => Promise<void>);
7
+ export interface TscBuilt {
8
+ errors: number;
9
+ ms: number;
10
+ first: boolean;
11
+ }
12
+ export interface TscEvents {
13
+ onChange?: () => void;
14
+ onBuilt: (built: TscBuilt) => void;
15
+ onDied: (why: string) => void;
16
+ }
17
+ export interface TscWatch extends Stoppable {
18
+ pid: number | undefined;
19
+ }
20
+ export declare const watchTsc: (dir: string, mode: Extract<UpMode, {
21
+ kind: "tsc";
22
+ }>, events: TscEvents) => TscWatch;
23
+ export declare const runRest: (dir: string, rest: string, timeoutMs?: number) => Promise<boolean>;
@@ -0,0 +1,81 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, watch } from 'node:fs';
3
+ import { delimiter, join } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { childEnv } from '../../lib/child-env.js';
6
+ import { messageOf } from '../../lib/json-output.js';
7
+ import { deadline, how, STEP_MS } from './package-build.js';
8
+ import { NEXT } from './up-build.js';
9
+ // A recursive watch of one folder of the working copy; saves inside the debounce are one change.
10
+ export const watchFolder = (dir, onChange, debounceMs = 200) => {
11
+ if (!existsSync(dir))
12
+ return { stop: () => undefined };
13
+ let timer;
14
+ const watcher = watch(dir, { recursive: true }, () => {
15
+ clearTimeout(timer);
16
+ timer = setTimeout(onChange, debounceMs);
17
+ });
18
+ return { stop: () => (clearTimeout(timer), watcher.close()) };
19
+ };
20
+ // One run at a time, one more after a change during it; a throw prints one line, the watch goes on.
21
+ export const coalesced = (run) => {
22
+ let busy = false;
23
+ let again = false;
24
+ const once = () => run().catch((err) => console.error(`watch ${messageOf(err)}`));
25
+ const go = async () => {
26
+ if (busy)
27
+ return void (again = true);
28
+ busy = true;
29
+ try {
30
+ do {
31
+ again = false;
32
+ await once();
33
+ } while (again);
34
+ }
35
+ finally {
36
+ busy = false;
37
+ }
38
+ };
39
+ return go;
40
+ };
41
+ const FOUND = /Found (\d+) errors?\./;
42
+ const CHANGE = /File change detected/;
43
+ // The warm watch of D13: noEmitOnError, out to dist.next; each compiler error line goes to stderr.
44
+ export const watchTsc = (dir, mode, events) => {
45
+ const args = ['-p', mode.config, '--watch', '--preserveWatchOutput', '--noEmitOnError'];
46
+ const child = spawn(process.execPath, [mode.tsc, ...args, '--outDir', NEXT, '--pretty', 'false'], {
47
+ cwd: dir,
48
+ env: childEnv(),
49
+ stdio: ['ignore', 'pipe', 'inherit'],
50
+ windowsHide: true,
51
+ });
52
+ let stopping = false;
53
+ child.once('error', (err) => stopping || events.onDied(`tsc did not start: ${err.message}`));
54
+ child.once('exit', (code, signal) => stopping || events.onDied(`tsc ${how(code, signal)}`));
55
+ readBuilds(child.stdout, events);
56
+ return { pid: child.pid, stop: () => void ((stopping = true), child.kill()) };
57
+ };
58
+ const readBuilds = (out, events) => {
59
+ let since = Date.now();
60
+ let first = true;
61
+ createInterface({ input: out }).on('line', (line) => {
62
+ if (CHANGE.test(line)) {
63
+ since = Date.now();
64
+ events.onChange?.();
65
+ }
66
+ const found = FOUND.exec(line);
67
+ if (!found)
68
+ return void (/error TS\d+/.test(line) && console.error(line));
69
+ events.onBuilt({ errors: Number(found[1]), ms: Date.now() - since, first });
70
+ first = false;
71
+ });
72
+ };
73
+ // The rest of the build script (the widget bundle) runs in the folder; it writes dist/ui itself.
74
+ export const runRest = (dir, rest, timeoutMs = STEP_MS) => new Promise((done) => {
75
+ const bin = join(dir, 'node_modules', '.bin');
76
+ const env = { ...childEnv(), PATH: `${bin}${delimiter}${process.env['PATH'] ?? ''}` };
77
+ const child = spawn(rest, { cwd: dir, env, shell: true, stdio: ['ignore', 2, 2] });
78
+ const clock = deadline(child, timeoutMs, 1_000);
79
+ child.once('error', () => (clock.stop(), done(false)));
80
+ child.once('exit', (code) => (clock.stop(), done(code === 0)));
81
+ });