@agentage/cli 0.52.0 → 0.53.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 (48) hide show
  1. package/dist/commands/daemon/daemon.d.ts +3 -1
  2. package/dist/commands/daemon/daemon.js +27 -5
  3. package/dist/commands/daemon/installer.d.ts +4 -0
  4. package/dist/commands/daemon/installer.js +29 -2
  5. package/dist/commands/daemon/move-plan.js +1 -1
  6. package/dist/commands/daemon/run.d.ts +3 -0
  7. package/dist/commands/daemon/run.js +11 -1
  8. package/dist/commands/extension/install-spec.d.ts +7 -0
  9. package/dist/commands/extension/install-spec.js +33 -0
  10. package/dist/commands/extension/lifecycle.d.ts +3 -4
  11. package/dist/commands/extension/lifecycle.js +5 -29
  12. package/dist/commands/extension/package-build.d.ts +1 -1
  13. package/dist/commands/extension/package-build.js +27 -10
  14. package/dist/commands/extension/setup-install.js +48 -21
  15. package/dist/commands/extension/setup-marker.d.ts +6 -0
  16. package/dist/commands/extension/setup-marker.js +23 -0
  17. package/dist/commands/extension/up-build.d.ts +18 -0
  18. package/dist/commands/extension/up-build.js +77 -0
  19. package/dist/commands/extension/up-commands.js +11 -10
  20. package/dist/commands/extension/up-local.d.ts +12 -12
  21. package/dist/commands/extension/up-local.js +40 -58
  22. package/dist/commands/extension/up-reload.d.ts +24 -0
  23. package/dist/commands/extension/up-reload.js +92 -0
  24. package/dist/commands/extension/up-run.d.ts +9 -11
  25. package/dist/commands/extension/up-run.js +97 -51
  26. package/dist/commands/extension/up-watch.d.ts +23 -0
  27. package/dist/commands/extension/up-watch.js +81 -0
  28. package/dist/commands/extension/up.d.ts +5 -3
  29. package/dist/commands/extension/up.js +47 -26
  30. package/dist/core/installer/version-spec.d.ts +2 -0
  31. package/dist/core/installer/version-spec.js +5 -0
  32. package/dist/core/loader/manifest.d.ts +2 -1
  33. package/dist/core/loader/manifest.js +14 -8
  34. package/dist/lib/daemon/daemon-client.d.ts +3 -1
  35. package/dist/lib/daemon/daemon-client.js +37 -16
  36. package/dist/lib/daemon/daemon-file.d.ts +2 -0
  37. package/dist/lib/daemon/daemon-file.js +4 -0
  38. package/dist/lib/daemon/daemon-health.d.ts +5 -0
  39. package/dist/lib/daemon/daemon-health.js +27 -2
  40. package/dist/lib/daemon/daemon-probe.d.ts +11 -5
  41. package/dist/lib/daemon/daemon-probe.js +10 -0
  42. package/dist/lib/daemon/host-client.d.ts +14 -1
  43. package/dist/lib/daemon/host-client.js +36 -9
  44. package/dist/lib/json-output.js +7 -5
  45. package/dist/lib/proc/start-time.d.ts +10 -0
  46. package/dist/lib/proc/start-time.js +44 -0
  47. package/dist/program-deps.js +3 -1
  48. package/package.json +2 -2
@@ -16,20 +16,21 @@ export const issuerUrl = (value) => {
16
16
  };
17
17
  const UP_HELP = `
18
18
  With no Docker (the default): builds the package in --dir (default: the current folder) as
19
- extension build does, prints what check refuses without stopping, and runs it in this terminal
20
- with the kit host on the first free port from 4244 (127.0.0.1). It prints the URL and runs until
21
- Ctrl-C. It does not use the daemon and does not change installation.json; its store is in
22
- .agentage/data of the folder.
19
+ extension build does, prints what check refuses without stopping, adds the folder to the daemon
20
+ (as extension install <folder> does; the daemon starts when none runs) and prints its URL on
21
+ 127.0.0.1:4243. Then it watches src/: each change is built into dist.next/ (never the live dist/)
22
+ and the daemon reloads that one extension; one line per reload says reloaded or why it was
23
+ refused (the last good build runs). Ctrl-C stops the watch; extension down removes the row.
23
24
 
24
25
  --docker runs the package the way a deployment runs it: the part images built with the release
25
26
  recipe, the store with its migrations and seeds, a dev token issuer and a local gateway. Each
26
27
  working copy is its own compose project; up refuses while another one holds localhost:4280 or
27
28
  4281 and names it. Prints one line per step as the kit reports it. Exits 1 when a step fails.`;
28
29
  const DOWN_HELP = `
29
- Stops what agentage extension up started for the package in --dir, and nothing else: the local
30
- run of this folder (only when its port still answers as it), and the Docker stack up --docker
31
- started there (its containers, network and the store's volume; --keep-data keeps the volume).
32
- It says so when nothing runs. Exits 1 when that fails.`;
30
+ Stops what agentage extension up started for the package in --dir, and nothing else: the watch
31
+ of this folder and the daemon row up added (its data stays; a row up found there stays), and the
32
+ Docker stack up --docker started there (its containers, network and the store's volume;
33
+ --keep-data keeps the volume). It says so when nothing runs. Exits 1 when that fails.`;
33
34
  const TOKEN_HELP = `
34
35
  Prints a token from the dev issuer agentage extension up started for the package in --dir,
35
36
  alone on stdout, for calling /api/v1/ and /mcp by hand or from tests. Only up trusts it. Exits 1
@@ -40,10 +41,10 @@ const DIR_TEXT = 'the extension package folder (default: the current folder)';
40
41
  const addUp = (group, up) => {
41
42
  addJson(group
42
43
  .command('up')
43
- .description('Run the working copy in this terminal until Ctrl-C; --docker = on Docker')
44
+ .description('Run the working copy on the daemon and reload each change; --docker = on Docker')
44
45
  .option(DIR, DIR_TEXT)
45
46
  .option('--docker', 'the images, store, issuer and gateway on Docker')
46
- .option('--local', 'the run with no Docker, asked for on purpose (no notice; for CI)'))
47
+ .option('--local', 'deprecated: the old name of plain up (removed in the next minor)'))
47
48
  .addHelpText('after', UP_HELP)
48
49
  .action(up);
49
50
  };
@@ -1,21 +1,21 @@
1
- import { type RequestListener, type Server } from 'node:http';
2
- export declare const UP_FROM = 4244;
1
+ import { type ProcessMark } from '../../lib/proc/start-time.js';
3
2
  export interface UpRecord {
4
- pid: number;
5
- port: number;
3
+ up: ProcessMark;
4
+ nonce: string;
6
5
  id: string;
7
- instance: string;
6
+ added: boolean;
7
+ tsc?: ProcessMark;
8
8
  }
9
9
  export declare const recordPath: (dir: string) => string;
10
- export declare const dataDirOf: (dir: string) => string;
11
10
  export declare const readRecord: (dir: string) => UpRecord | null;
12
11
  export declare const ignoreLocal: (dir: string) => void;
13
12
  export declare const writeRecord: (dir: string, record: UpRecord) => void;
14
13
  export declare const removeRecord: (dir: string) => void;
15
- export declare const listenFrom: (handler: RequestListener, from?: number) => Promise<Server>;
16
- export declare const portOf: (server: Server) => number;
17
- export type Answer = 'ours' | 'other' | 'none';
18
- export declare const answerOf: (record: UpRecord, timeoutMs?: number) => Promise<Answer>;
19
- export declare const untilSignal: () => Promise<string>;
14
+ export declare const stopOrphan: (record: UpRecord | null) => void;
15
+ export declare const refuseRunning: (dir: string) => UpRecord | null;
16
+ export declare const untilStopped: (dir: string, nonce: string, ended: Promise<string>, everyMs?: number) => Promise<string>;
20
17
  export type LocalDown = 'stopped' | 'stale' | 'none';
21
- export declare const stopLocal: (dir: string, timeoutMs?: number) => Promise<LocalDown>;
18
+ export declare const stopLocal: (dir: string, timeoutMs?: number) => Promise<{
19
+ down: LocalDown;
20
+ record: UpRecord | null;
21
+ }>;
@@ -1,23 +1,18 @@
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, proven, stopProven } from '../../lib/proc/start-time.js';
5
4
  import { isRecord, readJson, writeTextAtomic } from '../../lib/fs/json-file.js';
6
- import { CliError, messageOf } from '../../lib/json-output.js';
5
+ import { CliError } from '../../lib/json-output.js';
7
6
  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
7
  // The kit's own folder in a working copy (`.agentage/`, ignored by the template).
11
8
  const LOCAL = '.agentage';
12
9
  export const recordPath = (dir) => join(resolve(dir), LOCAL, 'up.json');
13
- export const dataDirOf = (dir) => join(resolve(dir), LOCAL, 'data');
14
10
  const isUpRecord = (value) => isRecord(value) &&
15
- isPid(value['pid']) &&
16
- Number.isInteger(value['port']) &&
17
- value['port'] >= 1024 &&
18
- value['port'] <= 65535 &&
11
+ isMark(value['up']) &&
12
+ typeof value['nonce'] === 'string' &&
19
13
  typeof value['id'] === 'string' &&
20
- typeof value['instance'] === 'string';
14
+ typeof value['added'] === 'boolean' &&
15
+ (value['tsc'] === undefined || isMark(value['tsc']));
21
16
  export const readRecord = (dir) => readJson(recordPath(dir), isUpRecord);
22
17
  // The run state stays out of git: `.agentage/` goes into the folder's .gitignore when missing.
23
18
  export const ignoreLocal = (dir) => {
@@ -36,59 +31,46 @@ export const writeRecord = (dir, record) => {
36
31
  writeTextAtomic(recordPath(dir), `${JSON.stringify(record)}\n`);
37
32
  };
38
33
  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}`);
34
+ // A tsc that outlived its up (killed hard): stopped only when proven to be that tsc.
35
+ export const stopOrphan = (record) => {
36
+ if (!record?.tsc || proven(record.up))
37
+ return;
38
+ if (stopProven(record.tsc))
39
+ console.error(`stopped the tsc watch (pid ${record.tsc.pid}) of an up that ended`);
52
40
  };
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';
41
+ // A live up of the folder is refused; a record of an up that ended keeps only its `added`.
42
+ export const refuseRunning = (dir) => {
43
+ const record = readRecord(dir);
44
+ if (!record || !proven(record.up) || record.up.pid === process.pid)
45
+ return (stopOrphan(record), record);
46
+ throw new CliError('already_running', `extension up runs for ${dir} (pid ${record.up.pid}): agentage extension down`);
64
47
  };
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);
48
+ // up ends on Ctrl-C or SIGTERM (the row stays), when down removes its record or another up
49
+ // rewrote it (`down`), or when its watch dies (`ended`, with the reason).
50
+ export const untilStopped = (dir, nonce, ended, everyMs = 300) => new Promise((done) => {
51
+ const finish = (why) => {
52
+ clearInterval(timer);
53
+ process.off('SIGINT', onInt);
54
+ process.off('SIGTERM', onTerm);
55
+ done(why);
71
56
  };
72
- process.once('SIGINT', on);
73
- process.once('SIGTERM', on);
57
+ const onInt = () => finish('SIGINT');
58
+ const onTerm = () => finish('SIGTERM');
59
+ const timer = setInterval(() => readRecord(dir)?.nonce === nonce || finish('down'), everyMs);
60
+ process.once('SIGINT', onInt);
61
+ process.once('SIGTERM', onTerm);
62
+ void ended.then(finish);
74
63
  });
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.
64
+ // Removing the record is the stop: the up of that pid sees it and exits; no up is signalled.
77
65
  export const stopLocal = async (dir, timeoutMs = 10_000) => {
78
66
  const record = readRecord(dir);
79
67
  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`);
68
+ return { down: 'none', record };
92
69
  removeRecord(dir);
93
- return 'stopped';
70
+ if (!proven(record.up))
71
+ return (stopOrphan(record), { down: 'stale', record });
72
+ if (!(await waitFor(() => !proven(record.up), timeoutMs)))
73
+ throw new CliError('stop_failed', `extension up (pid ${record.up.pid}) did not stop`);
74
+ stopOrphan(record);
75
+ return { down: 'stopped', record };
94
76
  };
@@ -0,0 +1,24 @@
1
+ import { type HostClient } from '../../lib/daemon/host-client.js';
2
+ import { type Npm } from './package-build.js';
3
+ import { type UpMode } from './up-build.js';
4
+ import { type Stoppable, type TscBuilt } from './up-watch.js';
5
+ export interface Run {
6
+ dir: string;
7
+ id: string;
8
+ host: HostClient;
9
+ npm: Npm;
10
+ }
11
+ type Task = () => Promise<void>;
12
+ export declare const lane: () => ((task: Task) => Promise<void>);
13
+ export declare const reload: ({ host, id }: Run, since: number) => Promise<void>;
14
+ export declare const stageAndReload: (run: Run) => Promise<void>;
15
+ export declare const tscReloads: (run: Run, inLane: (task: Task) => Promise<void>) => {
16
+ onChange: () => undefined;
17
+ onBuilt: ({ errors, ms, first }: TscBuilt) => void;
18
+ };
19
+ export interface Watch {
20
+ watchers: Stoppable[];
21
+ tscPid?: number;
22
+ }
23
+ export declare const startWatch: (run: Run, mode: UpMode, onDied: (why: string) => void) => Watch;
24
+ export {};
@@ -0,0 +1,92 @@
1
+ import { cpSync, existsSync } 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
+ // One lane for every write into dist.next and every reload: two of them never overlap.
9
+ export const lane = () => {
10
+ let tail = Promise.resolve();
11
+ return (task) => {
12
+ const next = tail.then(task);
13
+ tail = next.catch(() => undefined);
14
+ return next;
15
+ };
16
+ };
17
+ // One line per reload: reloaded and the time, or the daemon's refusal (the last good build runs).
18
+ export const reload = async ({ host, id }, since) => {
19
+ const answer = await host.reload(id).catch((err) => ({ error: messageOf(err) }));
20
+ const ms = Date.now() - since;
21
+ if ('error' in answer)
22
+ return console.error(`reload ${id} failed: ${answer.error}`);
23
+ if (answer.reloaded)
24
+ return console.log(`reload ${id} reloaded: true in ${ms} ms`);
25
+ console.log(`reload ${id} reloaded: false, refused: ${answer.refused ?? 'no reason'} (${ms} ms)`);
26
+ console.log(` ${id} the last good build runs`);
27
+ };
28
+ // A build that fails prints the compiler's words (its own stderr) and sends no reload.
29
+ export const stageAndReload = async (run) => {
30
+ const since = Date.now();
31
+ try {
32
+ await stagedBuild(run.dir, run.npm);
33
+ }
34
+ catch (err) {
35
+ return console.error(`build failed, no reload: ${messageOf(err)}`);
36
+ }
37
+ await reload(run, since);
38
+ };
39
+ // D17: a change under src/ui runs the widget bundle into dist/ui; the daemon serves no ui yet.
40
+ const bundleUi = async (run, rest) => {
41
+ const since = Date.now();
42
+ if (!(await runRest(run.dir, rest)))
43
+ return console.error('ui the bundle failed');
44
+ cpSync(join(run.dir, 'dist', 'ui'), join(run.dir, NEXT, 'ui'), { recursive: true, force: true });
45
+ console.log(`ui bundled into dist/ui in ${Date.now() - since} ms (no reload)`);
46
+ };
47
+ // A reload only after tsc finished a clean build, never while it writes the next one; a build
48
+ // that ends during a reload gives one more reload after it.
49
+ export const tscReloads = (run, inLane) => {
50
+ const state = { building: false, pending: false, since: 0 };
51
+ const go = coalesced(() => inLane(async () => {
52
+ if (state.building || !state.pending)
53
+ return;
54
+ state.pending = false;
55
+ await reload(run, state.since);
56
+ }));
57
+ const onBuilt = ({ errors, ms, first }) => {
58
+ state.building = false;
59
+ if (errors > 0)
60
+ console.error(`build ${errors} error(s), no reload`);
61
+ if (errors === 0 && !first)
62
+ Object.assign(state, { pending: true, since: Date.now() - ms });
63
+ if (state.pending)
64
+ void go();
65
+ };
66
+ return { onChange: () => void (state.building = true), onBuilt };
67
+ };
68
+ const watchWithTsc = (run, mode, onDied) => {
69
+ const inLane = lane();
70
+ const tsc = watchTsc(run.dir, mode, { ...tscReloads(run, inLane), onDied });
71
+ if (!mode.rest)
72
+ return { watchers: [tsc], tscPid: tsc.pid };
73
+ const rest = mode.rest;
74
+ const bundle = coalesced(() => inLane(() => bundleUi(run, rest)));
75
+ const ui = watchFolder(join(run.dir, 'src', 'ui'), bundle);
76
+ return { watchers: [tsc, ui], tscPid: tsc.pid };
77
+ };
78
+ export const startWatch = (run, mode, onDied) => {
79
+ if (mode.kind === 'tsc')
80
+ return watchWithTsc(run, mode, onDied);
81
+ if (!mode.script)
82
+ console.error('watch no build script: a change in src/ is not built');
83
+ if (!existsSync(join(run.dir, 'src')))
84
+ console.error('watch no src/ folder: nothing to watch');
85
+ if (!mode.script)
86
+ return { watchers: [] };
87
+ return {
88
+ watchers: [
89
+ watchFolder(join(run.dir, 'src'), coalesced(() => stageAndReload(run))),
90
+ ],
91
+ };
92
+ };
@@ -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,28 +1,40 @@
1
- import {} from 'node:http';
2
- import { resolve } from 'node:path';
1
+ import { randomUUID } from 'node:crypto';
2
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
3
+ import { markOf } from '../../lib/proc/start-time.js';
4
+ import { join, resolve } from 'node:path';
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 { 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 } from './package-build.js';
12
+ import { removeStage, seedNext, upModeOf } from './up-build.js';
13
+ import { refuseRunning, untilStopped, writeRecord } 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
+ const real = (path) => (existsSync(path) ? realpathSync(path) : path);
25
+ // Checked before the daemon starts: a folder that is no extension package starts nothing.
26
+ const idOf = (dir) => {
27
+ const file = join(dir, 'package.json');
28
+ if (!existsSync(file))
29
+ throw new CliError('invalid_argument', `no package.json in ${dir}: run it in an extension package folder`);
30
+ const pkg = JSON.parse(readFileSync(file, 'utf8'));
31
+ const id = pkg.agentage?.id;
32
+ if (typeof id !== 'string')
33
+ throw new CliError('invalid_argument', `${dir}: no agentage.id`);
34
+ return id;
25
35
  };
36
+ // The daemon runs this folder already (a create or an earlier up): its live dist is not rebuilt.
37
+ const runsHere = async (host, id, dir) => (await host.list()).some((row) => row.id === id && real(row.source) === real(dir));
26
38
  // Problems do not stop a local run; they are printed, as `extension build` would refuse them.
27
39
  const warnProblems = async ({ report }) => {
28
40
  if (report.conforms)
@@ -30,46 +42,80 @@ const warnProblems = async ({ report }) => {
30
42
  for (const text of (await loadKitTool()).checkLines(report))
31
43
  console.error(`check ${text}`);
32
44
  };
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
45
  // 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 };
46
+ const ready = (up, json) => {
47
+ console.log(`up ${up.id} ${up.version} on ${up.url} (watching src/; Ctrl-C stops)`);
48
+ const line = { ready: true, id: up.id, version: up.version, url: up.url, port: up.port };
43
49
  if (json)
44
50
  process.stdout.write(`${JSON.stringify(line)}\n`);
45
51
  };
46
- const runHosted = async (dir, hosted, deps, json) => {
47
- let server = null;
52
+ const stopLine = (id, stoppedBy, added) => {
53
+ if (stoppedBy === 'down')
54
+ return console.log(`stopped watching ${id} (extension down)`);
55
+ console.log(`stopped watching ${id} (${stoppedBy}); the daemon still runs it`);
56
+ if (added)
57
+ console.log(` agentage extension down removes it (its data stays)`);
58
+ };
59
+ // The first build: in the folder while no child runs it, else staged and reloaded.
60
+ const firstBuild = async (run, mode, build) => {
61
+ if (!(await runsHere(run.host, run.id, run.dir))) {
62
+ await warnProblems(await build(run.dir));
63
+ return seedNext(run.dir);
64
+ }
65
+ seedNext(run.dir);
66
+ if (mode.kind === 'tsc' || mode.script)
67
+ await stageAndReload(run);
68
+ };
69
+ // A watch that ends by itself stops up: one line, and a non-zero exit.
70
+ const deathOf = () => {
71
+ let died = () => undefined;
72
+ const ended = new Promise((done) => (died = done));
73
+ const onDied = (why) => {
74
+ console.error(`watch tsc ${why}; extension up stops (run it again)`);
75
+ died('watch died');
76
+ };
77
+ return { ended, onDied };
78
+ };
79
+ const exitFor = (stoppedBy) => {
80
+ if (stoppedBy === 'SIGINT')
81
+ setExit(130);
82
+ if (stoppedBy === 'watch died')
83
+ setExit(1);
84
+ };
85
+ // D12: build, the folder as a daemon row, a watch that builds to dist.next and reloads that child.
86
+ export const runLocalUp = async (folder = '.', deps = localUpDeps, json = false) => {
87
+ const dir = resolve(folder);
88
+ const before = refuseRunning(dir);
89
+ const id = idOf(dir);
90
+ const { port, host } = await deps.daemon();
91
+ const run = { dir, id, host, npm: deps.npm };
92
+ const mode = upModeOf(dir);
93
+ // A stage of an earlier up may hold an old package.json: the first staged build copies it again.
94
+ removeStage(dir);
48
95
  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 };
96
+ return await upAndWatch(run, mode, deps, { port, json, before });
57
97
  }
58
98
  finally {
59
- await close(server, hosted, dir);
99
+ removeStage(dir);
60
100
  }
61
101
  };
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;
102
+ const upAndWatch = async (run, mode, deps, ctx) => {
103
+ await firstBuild(run, mode, deps.build);
104
+ const { row, already } = await installFolder(run.host, run.dir);
105
+ const added = !already || ctx.before?.added === true;
106
+ const nonce = randomUUID();
107
+ const death = deathOf();
108
+ const { watchers, tscPid } = startWatch(run, mode, death.onDied);
109
+ const tsc = markOf(tscPid) ?? undefined;
110
+ writeRecord(run.dir, { up: selfMark(), nonce, id: row.id, added, ...(tsc && { tsc }) });
111
+ const url = `http://127.0.0.1:${ctx.port}/api/${row.id}/`;
112
+ ready({ id: row.id, version: row.version, url, port: ctx.port, added }, ctx.json);
113
+ const stoppedBy = await deps.stopped(run.dir, nonce, death.ended);
114
+ for (const watcher of watchers)
115
+ watcher.stop();
116
+ stopLine(row.id, stoppedBy, added);
117
+ exitFor(stoppedBy);
118
+ return { id: row.id, version: row.version, url, port: ctx.port, added, stoppedBy };
75
119
  };
120
+ // This up: pid and start time; where the start time cannot be read (Windows) it is never proven.
121
+ const selfMark = () => markOf(process.pid) ?? { pid: process.pid, started: 'unknown' };
@@ -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) => 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 { NEXT } from './up-build.js';
8
+ // A recursive watch of one folder of the working copy; saves inside the debounce are one change.
9
+ export const watchFolder = (dir, onChange, debounceMs = 200) => {
10
+ if (!existsSync(dir))
11
+ return { stop: () => undefined };
12
+ let timer;
13
+ const watcher = watch(dir, { recursive: true }, () => {
14
+ clearTimeout(timer);
15
+ timer = setTimeout(onChange, debounceMs);
16
+ });
17
+ return { stop: () => (clearTimeout(timer), watcher.close()) };
18
+ };
19
+ // One run at a time; a change during a run gives one more run after it, not one per save.
20
+ // A run that throws 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
+ const exitWhy = (code, signal) => code === null ? `exited by signal ${signal ?? 'unknown'}` : `exited ${code}`;
44
+ // The warm watch of D13: noEmitOnError, out to dist.next; each compiler error line goes to stderr.
45
+ export const watchTsc = (dir, mode, events) => {
46
+ const args = ['-p', mode.config, '--watch', '--preserveWatchOutput', '--noEmitOnError'];
47
+ const child = spawn(process.execPath, [mode.tsc, ...args, '--outDir', NEXT, '--pretty', 'false'], {
48
+ cwd: dir,
49
+ env: childEnv(),
50
+ stdio: ['ignore', 'pipe', 'inherit'],
51
+ windowsHide: true,
52
+ });
53
+ let stopping = false;
54
+ child.once('error', (err) => stopping || events.onDied(`did not start: ${err.message}`));
55
+ child.once('exit', (code, signal) => stopping || events.onDied(exitWhy(code, signal)));
56
+ readBuilds(child.stdout, events);
57
+ return { pid: child.pid, stop: () => void ((stopping = true), child.kill()) };
58
+ };
59
+ const readBuilds = (out, events) => {
60
+ let since = Date.now();
61
+ let first = true;
62
+ createInterface({ input: out }).on('line', (line) => {
63
+ if (CHANGE.test(line)) {
64
+ since = Date.now();
65
+ events.onChange?.();
66
+ }
67
+ const found = FOUND.exec(line);
68
+ if (!found)
69
+ return void (/error TS\d+/.test(line) && console.error(line));
70
+ events.onBuilt({ errors: Number(found[1]), ms: Date.now() - since, first });
71
+ first = false;
72
+ });
73
+ };
74
+ // The rest of the build script (the widget bundle) runs in the folder; it writes dist/ui itself.
75
+ export const runRest = (dir, rest) => new Promise((done) => {
76
+ const bin = join(dir, 'node_modules', '.bin');
77
+ const env = { ...childEnv(), PATH: `${bin}${delimiter}${process.env['PATH'] ?? ''}` };
78
+ const child = spawn(rest, { cwd: dir, env, shell: true, stdio: ['ignore', 2, 2] });
79
+ child.once('error', () => done(false));
80
+ child.once('exit', (code) => done(code === 0));
81
+ });