@agentage/cli 0.53.0 → 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 (37) hide show
  1. package/README.md +9 -11
  2. package/dist/commands/daemon/daemon.d.ts +3 -3
  3. package/dist/commands/daemon/daemon.js +21 -8
  4. package/dist/commands/daemon/installer.js +4 -7
  5. package/dist/commands/extension/build.js +5 -3
  6. package/dist/commands/extension/configure.js +2 -1
  7. package/dist/commands/extension/create-install.js +3 -2
  8. package/dist/commands/extension/install-once.d.ts +2 -0
  9. package/dist/commands/extension/install-once.js +5 -5
  10. package/dist/commands/extension/lifecycle.d.ts +0 -2
  11. package/dist/commands/extension/lifecycle.js +4 -4
  12. package/dist/commands/extension/package-build.d.ts +10 -0
  13. package/dist/commands/extension/package-build.js +28 -9
  14. package/dist/commands/extension/release-guard.d.ts +8 -1
  15. package/dist/commands/extension/release-guard.js +39 -16
  16. package/dist/commands/extension/release.js +35 -19
  17. package/dist/commands/extension/setup-install.js +2 -4
  18. package/dist/commands/extension/up-build.d.ts +0 -1
  19. package/dist/commands/extension/up-build.js +3 -9
  20. package/dist/commands/extension/up-local.d.ts +3 -0
  21. package/dist/commands/extension/up-local.js +30 -11
  22. package/dist/commands/extension/up-reload.d.ts +7 -1
  23. package/dist/commands/extension/up-reload.js +30 -7
  24. package/dist/commands/extension/up-run.js +74 -38
  25. package/dist/commands/extension/up-watch.d.ts +1 -1
  26. package/dist/commands/extension/up-watch.js +8 -8
  27. package/dist/commands/extension/up.js +6 -4
  28. package/dist/core/loader/manifest.js +1 -2
  29. package/dist/lib/daemon/daemon-client.js +3 -6
  30. package/dist/lib/daemon/daemon-probe.d.ts +1 -0
  31. package/dist/lib/daemon/daemon-probe.js +7 -2
  32. package/dist/lib/daemon/host-client.d.ts +6 -4
  33. package/dist/lib/daemon/host-client.js +19 -16
  34. package/dist/lib/fs/file-lock.js +6 -0
  35. package/dist/lib/proc/start-time.d.ts +2 -2
  36. package/dist/lib/proc/start-time.js +12 -10
  37. package/package.json +2 -2
@@ -1,17 +1,12 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, symlinkSync, unlinkSync, } from 'node:fs';
2
+ import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, rmSync, symlinkSync, unlinkSync, } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import { basename, join, resolve } from 'node:path';
5
5
  import { getConfigDir } from '../../lib/fs/config.js';
6
- import {} from './package-build.js';
6
+ import { buildScriptOf } from './package-build.js';
7
7
  // The live tree the daemon runs is dist; the watcher writes only dist.next (the daemon copies it).
8
8
  export const NEXT = 'dist.next';
9
9
  const TSC = /^tsc(?:\s+-p\s+(\S+))?$/;
10
- export const buildScriptOf = (dir) => {
11
- const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
12
- const script = pkg.scripts?.['build'];
13
- return typeof script === 'string' ? script : null;
14
- };
15
10
  // The folder's own typescript, run as `node typescript/bin/tsc` (no .bin shim, none on Windows).
16
11
  const tscOf = (dir) => {
17
12
  try {
@@ -51,8 +46,7 @@ export const removeStage = (dir) => {
51
46
  unlinkSync(modules);
52
47
  rmSync(stageOf(dir), { recursive: true, force: true });
53
48
  };
54
- // A copy of the folder with its node_modules linked: the build there never touches the live dist.
55
- // No .env*, coverage, .git or dist*; a `../` path in the build script resolves from the cache.
49
+ // A copy with node_modules linked, no .env*, coverage, .git or dist*: never the live dist.
56
50
  export const prepareStage = (dir) => {
57
51
  const stage = stageOf(dir);
58
52
  removeStage(dir);
@@ -13,6 +13,9 @@ export declare const writeRecord: (dir: string, record: UpRecord) => void;
13
13
  export declare const removeRecord: (dir: string) => void;
14
14
  export declare const stopOrphan: (record: UpRecord | null) => void;
15
15
  export declare const refuseRunning: (dir: string) => UpRecord | null;
16
+ export declare const selfMark: () => ProcessMark;
17
+ export declare const claimFolder: (dir: string, nonce: string, id: string) => Promise<UpRecord | null>;
18
+ export declare const rewriteRecord: (dir: string, record: UpRecord) => Promise<void>;
16
19
  export declare const untilStopped: (dir: string, nonce: string, ended: Promise<string>, everyMs?: number) => Promise<string>;
17
20
  export type LocalDown = 'stopped' | 'stale' | 'none';
18
21
  export declare const stopLocal: (dir: string, timeoutMs?: number) => Promise<{
@@ -1,6 +1,7 @@
1
1
  import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
2
2
  import { join, resolve } from 'node:path';
3
- import { isMark, proven, stopProven } from '../../lib/proc/start-time.js';
3
+ import { isMark, markOf, proven, stopProven } from '../../lib/proc/start-time.js';
4
+ import { withFileLock } from '../../lib/fs/file-lock.js';
4
5
  import { isRecord, readJson, writeTextAtomic } from '../../lib/fs/json-file.js';
5
6
  import { CliError } from '../../lib/json-output.js';
6
7
  import { waitFor } from '../../lib/wait.js';
@@ -45,28 +46,46 @@ export const refuseRunning = (dir) => {
45
46
  return (stopOrphan(record), record);
46
47
  throw new CliError('already_running', `extension up runs for ${dir} (pid ${record.up.pid}): agentage extension down`);
47
48
  };
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).
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.
50
66
  export const untilStopped = (dir, nonce, ended, everyMs = 300) => new Promise((done) => {
67
+ const on = STOPS.map((name) => [name, () => finish(name)]);
51
68
  const finish = (why) => {
52
69
  clearInterval(timer);
53
- process.off('SIGINT', onInt);
54
- process.off('SIGTERM', onTerm);
70
+ for (const [name, handler] of on)
71
+ process.off(name, handler);
55
72
  done(why);
56
73
  };
57
- const onInt = () => finish('SIGINT');
58
- const onTerm = () => finish('SIGTERM');
59
74
  const timer = setInterval(() => readRecord(dir)?.nonce === nonce || finish('down'), everyMs);
60
- process.once('SIGINT', onInt);
61
- process.once('SIGTERM', onTerm);
75
+ for (const [name, handler] of on)
76
+ process.once(name, handler);
62
77
  void ended.then(finish);
63
78
  });
64
79
  // Removing the record is the stop: the up of that pid sees it and exits; no up is signalled.
65
80
  export const stopLocal = async (dir, timeoutMs = 10_000) => {
66
- 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
+ });
67
87
  if (!record)
68
88
  return { down: 'none', record };
69
- removeRecord(dir);
70
89
  if (!proven(record.up))
71
90
  return (stopOrphan(record), { down: 'stale', record });
72
91
  if (!(await waitFor(() => !proven(record.up), timeoutMs)))
@@ -1,4 +1,5 @@
1
1
  import { type HostClient } from '../../lib/daemon/host-client.js';
2
+ import { type Code } from '../../lib/json-output.js';
2
3
  import { type Npm } from './package-build.js';
3
4
  import { type UpMode } from './up-build.js';
4
5
  import { type Stoppable, type TscBuilt } from './up-watch.js';
@@ -7,10 +8,15 @@ export interface Run {
7
8
  id: string;
8
9
  host: HostClient;
9
10
  npm: Npm;
11
+ fatal?: (why: string, code?: Code) => void;
12
+ failed?: number;
13
+ builtAt?: number;
10
14
  }
15
+ export declare const editedSince: (dir: string, since?: number) => boolean;
16
+ export declare const RELOAD_STRIKES = 3;
11
17
  type Task = () => Promise<void>;
12
18
  export declare const lane: () => ((task: Task) => Promise<void>);
13
- export declare const reload: ({ host, id }: Run, since: number) => Promise<void>;
19
+ export declare const reload: (run: Run, since: number) => Promise<void>;
14
20
  export declare const stageAndReload: (run: Run) => Promise<void>;
15
21
  export declare const tscReloads: (run: Run, inLane: (task: Task) => Promise<void>) => {
16
22
  onChange: () => undefined;
@@ -1,10 +1,25 @@
1
- import { cpSync, existsSync } from 'node:fs';
1
+ import { cpSync, existsSync, readdirSync, statSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import {} from '../../lib/daemon/host-client.js';
4
4
  import { messageOf } from '../../lib/json-output.js';
5
5
  import {} from './package-build.js';
6
6
  import { NEXT, stagedBuild } from './up-build.js';
7
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
+ };
8
23
  // One lane for every write into dist.next and every reload: two of them never overlap.
9
24
  export const lane = () => {
10
25
  let tail = Promise.resolve();
@@ -15,16 +30,20 @@ export const lane = () => {
15
30
  };
16
31
  };
17
32
  // 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) => {
33
+ export const reload = async (run, since) => {
34
+ const { host, id } = run;
19
35
  const answer = await host.reload(id).catch((err) => ({ error: messageOf(err) }));
20
36
  const ms = Date.now() - since;
21
37
  if ('error' in answer)
22
- return console.error(`reload ${id} failed: ${answer.error}`);
38
+ return failedReload(run, answer.error);
39
+ run.failed = 0;
23
40
  if (answer.reloaded)
24
41
  return console.log(`reload ${id} reloaded: true in ${ms} ms`);
25
42
  console.log(`reload ${id} reloaded: false, refused: ${answer.refused ?? 'no reason'} (${ms} ms)`);
26
43
  console.log(` ${id} the last good build runs`);
27
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$/;
28
47
  // A build that fails prints the compiler's words (its own stderr) and sends no reload.
29
48
  export const stageAndReload = async (run) => {
30
49
  const since = Date.now();
@@ -32,7 +51,10 @@ export const stageAndReload = async (run) => {
32
51
  await stagedBuild(run.dir, run.npm);
33
52
  }
34
53
  catch (err) {
35
- return console.error(`build failed, no reload: ${messageOf(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;
36
58
  }
37
59
  await reload(run, since);
38
60
  };
@@ -44,8 +66,7 @@ const bundleUi = async (run, rest) => {
44
66
  cpSync(join(run.dir, 'dist', 'ui'), join(run.dir, NEXT, 'ui'), { recursive: true, force: true });
45
67
  console.log(`ui bundled into dist/ui in ${Date.now() - since} ms (no reload)`);
46
68
  };
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.
69
+ // A reload only after a clean tsc build, never during one; a build during a reload gives one more.
49
70
  export const tscReloads = (run, inLane) => {
50
71
  const state = { building: false, pending: false, since: 0 };
51
72
  const go = coalesced(() => inLane(async () => {
@@ -58,7 +79,9 @@ export const tscReloads = (run, inLane) => {
58
79
  state.building = false;
59
80
  if (errors > 0)
60
81
  console.error(`build ${errors} error(s), no reload`);
61
- if (errors === 0 && !first)
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)
62
85
  Object.assign(state, { pending: true, since: Date.now() - ms });
63
86
  if (state.pending)
64
87
  void go();
@@ -1,16 +1,16 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { existsSync, readFileSync, realpathSync } from 'node:fs';
3
2
  import { markOf } from '../../lib/proc/start-time.js';
4
- import { join, resolve } from 'node:path';
3
+ import { resolve } from 'node:path';
4
+ import { isRecord } from '../../lib/fs/json-file.js';
5
5
  import { ensureDaemon } from '../../lib/daemon/daemon-client.js';
6
6
  import { hostClient } from '../../lib/daemon/host-client.js';
7
7
  import { setExit } from '../../lib/exit-code.js';
8
8
  import { CliError } from '../../lib/json-output.js';
9
- import { installFolder } from './install-once.js';
9
+ import { folderRow, installFolder } from './install-once.js';
10
10
  import { loadKitTool } from './kit-tool.js';
11
- import { buildPackage, npmIn } from './package-build.js';
11
+ import { buildPackage, npmIn, packageOf } from './package-build.js';
12
12
  import { removeStage, seedNext, upModeOf } from './up-build.js';
13
- import { refuseRunning, untilStopped, writeRecord } from './up-local.js';
13
+ import { claimFolder, rewriteRecord, selfMark, untilStopped } from './up-local.js';
14
14
  import { stageAndReload, startWatch } from './up-reload.js';
15
15
  export const localUpDeps = {
16
16
  build: (dir) => buildPackage(dir),
@@ -21,20 +21,14 @@ export const localUpDeps = {
21
21
  npm: npmIn,
22
22
  stopped: (dir, nonce, ended) => untilStopped(dir, nonce, ended),
23
23
  };
24
- const real = (path) => (existsSync(path) ? realpathSync(path) : path);
25
24
  // Checked before the daemon starts: a folder that is no extension package starts nothing.
26
25
  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;
26
+ const agentage = packageOf(dir)['agentage'];
27
+ const id = isRecord(agentage) ? agentage['id'] : undefined;
32
28
  if (typeof id !== 'string')
33
29
  throw new CliError('invalid_argument', `${dir}: no agentage.id`);
34
30
  return id;
35
31
  };
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));
38
32
  // Problems do not stop a local run; they are printed, as `extension build` would refuse them.
39
33
  const warnProblems = async ({ report }) => {
40
34
  if (report.conforms)
@@ -56,9 +50,9 @@ const stopLine = (id, stoppedBy, added) => {
56
50
  if (added)
57
51
  console.log(` agentage extension down removes it (its data stays)`);
58
52
  };
59
- // The first build: in the folder while no child runs it, else staged and reloaded.
53
+ // The first build: in the folder while no child runs it (a create or an earlier up), else staged.
60
54
  const firstBuild = async (run, mode, build) => {
61
- if (!(await runsHere(run.host, run.id, run.dir))) {
55
+ if (!(await folderRow(run.host, run.id, run.dir))) {
62
56
  await warnProblems(await build(run.dir));
63
57
  return seedNext(run.dir);
64
58
  }
@@ -66,56 +60,98 @@ const firstBuild = async (run, mode, build) => {
66
60
  if (mode.kind === 'tsc' || mode.script)
67
61
  await stageAndReload(run);
68
62
  };
69
- // A watch that ends by itself stops up: one line, and a non-zero exit.
63
+ // A watch that ends by itself, a missing build tool or a reload that keeps failing stops up.
70
64
  const deathOf = () => {
71
65
  let died = () => undefined;
66
+ let reason = '';
67
+ let code = 'build_failed';
72
68
  const ended = new Promise((done) => (died = done));
73
- const onDied = (why) => {
74
- console.error(`watch tsc ${why}; extension up stops (run it again)`);
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)`);
75
74
  died('watch died');
76
75
  };
77
- return { ended, onDied };
76
+ const failure = () => new CliError(code, `extension up stopped: ${reason}`);
77
+ return { ended, onDied, failure, died: () => reason !== '' };
78
78
  };
79
- const exitFor = (stoppedBy) => {
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) => {
80
81
  if (stoppedBy === 'SIGINT')
81
82
  setExit(130);
83
+ if (stoppedBy === 'SIGHUP')
84
+ setExit(129);
82
85
  if (stoppedBy === 'watch died')
83
- setExit(1);
86
+ throw failure();
84
87
  };
85
88
  // D12: build, the folder as a daemon row, a watch that builds to dist.next and reloads that child.
86
89
  export const runLocalUp = async (folder = '.', deps = localUpDeps, json = false) => {
87
90
  const dir = resolve(folder);
88
- const before = refuseRunning(dir);
89
91
  const id = idOf(dir);
92
+ const nonce = randomUUID();
93
+ const before = await claimFolder(dir, nonce, id);
90
94
  const { port, host } = await deps.daemon();
91
95
  const run = { dir, id, host, npm: deps.npm };
92
96
  const mode = upModeOf(dir);
93
97
  // A stage of an earlier up may hold an old package.json: the first staged build copies it again.
94
98
  removeStage(dir);
95
99
  try {
96
- return await upAndWatch(run, mode, deps, { port, json, before });
100
+ return await upAndWatch(run, mode, deps, { port, json, before, nonce });
97
101
  }
98
102
  finally {
99
103
  removeStage(dir);
100
104
  }
101
105
  };
106
+ // The fatal channel is wired before the first build: a second up with no build tool stops too.
102
107
  const upAndWatch = async (run, mode, deps, ctx) => {
108
+ const death = deathOf();
109
+ run.fatal = death.onDied;
110
+ run.builtAt = Date.now();
103
111
  await firstBuild(run, mode, deps.build);
112
+ if (death.died())
113
+ throw death.failure();
104
114
  const { row, already } = await installFolder(run.host, run.dir);
105
115
  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 };
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
+ }
119
156
  };
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' };
157
+ const urlOf = (port, id) => `http://127.0.0.1:${port}/api/${id}/`;
@@ -20,4 +20,4 @@ export interface TscWatch extends Stoppable {
20
20
  export declare const watchTsc: (dir: string, mode: Extract<UpMode, {
21
21
  kind: "tsc";
22
22
  }>, events: TscEvents) => TscWatch;
23
- export declare const runRest: (dir: string, rest: string) => Promise<boolean>;
23
+ export declare const runRest: (dir: string, rest: string, timeoutMs?: number) => Promise<boolean>;
@@ -4,6 +4,7 @@ import { delimiter, join } from 'node:path';
4
4
  import { createInterface } from 'node:readline';
5
5
  import { childEnv } from '../../lib/child-env.js';
6
6
  import { messageOf } from '../../lib/json-output.js';
7
+ import { deadline, how, STEP_MS } from './package-build.js';
7
8
  import { NEXT } from './up-build.js';
8
9
  // A recursive watch of one folder of the working copy; saves inside the debounce are one change.
9
10
  export const watchFolder = (dir, onChange, debounceMs = 200) => {
@@ -16,8 +17,7 @@ export const watchFolder = (dir, onChange, debounceMs = 200) => {
16
17
  });
17
18
  return { stop: () => (clearTimeout(timer), watcher.close()) };
18
19
  };
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.
20
+ // One run at a time, one more after a change during it; a throw prints one line, the watch goes on.
21
21
  export const coalesced = (run) => {
22
22
  let busy = false;
23
23
  let again = false;
@@ -40,7 +40,6 @@ export const coalesced = (run) => {
40
40
  };
41
41
  const FOUND = /Found (\d+) errors?\./;
42
42
  const CHANGE = /File change detected/;
43
- const exitWhy = (code, signal) => code === null ? `exited by signal ${signal ?? 'unknown'}` : `exited ${code}`;
44
43
  // The warm watch of D13: noEmitOnError, out to dist.next; each compiler error line goes to stderr.
45
44
  export const watchTsc = (dir, mode, events) => {
46
45
  const args = ['-p', mode.config, '--watch', '--preserveWatchOutput', '--noEmitOnError'];
@@ -51,8 +50,8 @@ export const watchTsc = (dir, mode, events) => {
51
50
  windowsHide: true,
52
51
  });
53
52
  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)));
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)}`));
56
55
  readBuilds(child.stdout, events);
57
56
  return { pid: child.pid, stop: () => void ((stopping = true), child.kill()) };
58
57
  };
@@ -72,10 +71,11 @@ const readBuilds = (out, events) => {
72
71
  });
73
72
  };
74
73
  // 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) => {
74
+ export const runRest = (dir, rest, timeoutMs = STEP_MS) => new Promise((done) => {
76
75
  const bin = join(dir, 'node_modules', '.bin');
77
76
  const env = { ...childEnv(), PATH: `${bin}${delimiter}${process.env['PATH'] ?? ''}` };
78
77
  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));
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
81
  });
@@ -1,14 +1,15 @@
1
- import { existsSync, realpathSync } from 'node:fs';
1
+ import { existsSync } from 'node:fs';
2
2
  import { join, resolve } from 'node:path';
3
3
  import { ensureDaemon } from '../../lib/daemon/daemon-client.js';
4
4
  import { hostClient } from '../../lib/daemon/host-client.js';
5
5
  import { CliError, omitJson } from '../../lib/json-output.js';
6
+ import { folderRow } from './install-once.js';
6
7
  import { loadKitTool } from './kit-tool.js';
7
8
  import { execIn } from './release-guard.js';
8
9
  import { assertOwnStack } from './stack-owner.js';
10
+ import { removeStage } from './up-build.js';
9
11
  import { readRecord, stopLocal } from './up-local.js';
10
12
  import { runLocalUp } from './up-run.js';
11
- const real = (path) => (existsSync(path) ? realpathSync(path) : path);
12
13
  // Prints each line as the kit reports it and keeps them for the --json answer.
13
14
  const printed = () => {
14
15
  const lines = [];
@@ -46,8 +47,7 @@ const removeAdded = async (dir, record, host) => {
46
47
  if (!record?.added)
47
48
  return [];
48
49
  const client = await host();
49
- const row = (await client.list()).find((r) => r.id === record.id);
50
- if (!row || real(row.source) !== real(dir))
50
+ if (!(await folderRow(client, record.id, dir)))
51
51
  return [];
52
52
  await client.remove(record.id, false);
53
53
  return [`removed ${record.id} from the daemon (its data stays)`];
@@ -60,6 +60,8 @@ const stopAndRemove = async (dir, host, stopMs) => {
60
60
  let down = 'none';
61
61
  try {
62
62
  down = (await stopLocal(dir, stopMs)).down;
63
+ // Only once no up runs: a killed up leaves its stage in the config cache.
64
+ removeStage(dir);
63
65
  if (down !== 'none')
64
66
  lines.push(LOCAL_LINES[down]);
65
67
  }
@@ -85,8 +85,7 @@ const engineProblem = (engine, version, against) => {
85
85
  };
86
86
  // C10 (D8): the oldest kit minor this cli runs; it moves only with a breaking ctx change.
87
87
  export const KIT_FLOOR = '0.12';
88
- // Every minor from KIT_FLOOR up to the one below the bundled kit: their part modules and command
89
- // contract are those of the bundled kit (the update smoke proves it).
88
+ // KIT_FLOOR up to the bundled minor: they share its parts and command contract (the update smoke).
90
89
  export const olderKitMinors = (kit = kitVersion()) => {
91
90
  const [major, minor] = kit.split('.').map(Number);
92
91
  const [floorMajor, floor] = KIT_FLOOR.split('.').map(Number);
@@ -9,7 +9,7 @@ import { compareVersions } from '../update/update-check.js';
9
9
  import { VERSION } from '../../utils/version.js';
10
10
  import { waitFor } from '../wait.js';
11
11
  import { daemonFilePath, daemonOff, daemonPort, EADDRINUSE_EXIT, isAlive, readDaemonFile, removeDaemonFile, } from './daemon-file.js';
12
- import { otherFolder, unreadableFile, portInUse, probe, probeRetry, PROGRESS_MS, PROTOCOL, proven, unresponsive, } from './daemon-probe.js';
12
+ import { otherFolder, unreadableFile, portInUse, probe, probeRetry, PROGRESS_MS, PROTOCOL, proven, provenPort, unresponsive, } from './daemon-probe.js';
13
13
  import { stopDaemon } from './daemon-stop.js';
14
14
  const START_MS = 30_000;
15
15
  // Over this the log moves to daemon.log.1 at the next start; one old file is kept.
@@ -18,7 +18,7 @@ export const LOG_CAP = 5 * 1024 * 1024;
18
18
  export const LATE_FILE_MS = 2_000;
19
19
  const answersAs = (pid, found) => found.kind === 'ours' && found.health.pid === pid;
20
20
  const announced = (pid) => readDaemonFile()?.pid === pid;
21
- // Healthy only as the spawned pid, and once its daemon.json (the host token) is written after listen.
21
+ // Healthy only as the spawned pid, once its daemon.json (the host token) is written.
22
22
  export const waitForHealth = (port, pid, timeoutMs = START_MS) => waitFor(async () => answersAs(pid, await probe(port, 500)) && announced(pid), timeoutMs, {
23
23
  afterMs: PROGRESS_MS,
24
24
  line: `waiting for the daemon to start on 127.0.0.1:${port}...`,
@@ -55,10 +55,7 @@ export const defaultEnsureDeps = {
55
55
  log: (line) => console.error(line),
56
56
  };
57
57
  // A start that timed out may still have come up late: a proven daemon in daemon.json serves.
58
- const lateDaemon = async (deps) => {
59
- const file = readDaemonFile();
60
- return file && proven(file, await deps.probe(file.port)) ? file.port : null;
61
- };
58
+ const lateDaemon = (deps) => provenPort(deps.probe);
62
59
  const notStarted = () => new CliError('daemon_unavailable', `the daemon did not start: it did not answer; see agentage daemon status and ${daemonLogPath()}`);
63
60
  // Another cli of this folder may have started one at the same time: its daemon.json can lag.
64
61
  const ownLate = async (deps, port, ms) => waitFor(async () => (await lateDaemon(deps)) === port, ms);
@@ -32,6 +32,7 @@ export type Probe = {
32
32
  export declare const probe: (port: number, timeoutMs?: number) => Promise<Probe>;
33
33
  export declare const probeRetry: (port: number, tries?: number, timeoutMs?: number) => Promise<Probe>;
34
34
  export declare const proven: (file: DaemonFile, found: Probe) => Health | null;
35
+ export declare const provenPort: (look?: (port: number) => Promise<Probe>) => Promise<number | null>;
35
36
  export declare const unresponsive: (file: DaemonFile) => CliError;
36
37
  export declare const otherFolder: (port: number, pid: number, platform?: NodeJS.Platform) => CliError;
37
38
  export declare const unreadableFile: (port: number, pid: number) => CliError;
@@ -1,9 +1,9 @@
1
1
  import { isRecord } from '../fs/json-file.js';
2
2
  import { CliError } from '../json-output.js';
3
- import {} from './daemon-file.js';
4
- // C4/C5: the protocol this cli speaks; a daemon with another one is restarted.
3
+ import { readDaemonFile } from './daemon-file.js';
5
4
  // A wait longer than this prints one line on stderr, so a slow start or stop does not look hung.
6
5
  export const PROGRESS_MS = 3_000;
6
+ // C4/C5: the protocol this cli speaks; a daemon with another one is restarted.
7
7
  export const PROTOCOL = 1;
8
8
  export const DAEMON_SERVICE = 'agentage-daemon';
9
9
  const isHealth = (body) => isRecord(body) &&
@@ -37,6 +37,11 @@ export const probeRetry = async (port, tries = 3, timeoutMs = 2000) => {
37
37
  };
38
38
  // The proof that daemon.json names a daemon of ours: its port answers with the same pid.
39
39
  export const proven = (file, found) => found.kind === 'ours' && found.health.pid === file.pid ? found.health : null;
40
+ // The port of daemon.json when its daemon is proven there, else null.
41
+ export const provenPort = async (look = probe) => {
42
+ const file = readDaemonFile();
43
+ return file && proven(file, await look(file.port)) ? file.port : null;
44
+ };
40
45
  export const unresponsive = (file) => new CliError('daemon_unresponsive', `the daemon (pid ${file.pid}) does not answer on 127.0.0.1:${file.port}; ` +
41
46
  'try again, or stop that process yourself');
42
47
  const killLine = (pid, platform = process.platform) => platform === 'win32' ? `taskkill /PID ${pid} /F` : `kill ${pid}`;
@@ -43,11 +43,13 @@ export interface HostReload {
43
43
  reloaded: boolean;
44
44
  refused?: string;
45
45
  }
46
+ export interface Waits {
47
+ read: number;
48
+ change: number;
49
+ reload?: number;
50
+ }
46
51
  type Token = () => string | undefined;
47
52
  type Same = (port: number) => Promise<boolean>;
48
53
  export declare const sameDaemon: Same;
49
- export declare const hostClient: (port: number, waits?: {
50
- read: number;
51
- change: number;
52
- }, token?: Token, same?: Same) => HostClient;
54
+ export declare const hostClient: (port: number, waits?: Waits, token?: Token, same?: Same) => HostClient;
53
55
  export {};