@agentshouse/kit 0.2.1-alpha.9 → 0.2.1-c073f4e9391b2

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/README.md +44 -26
  2. package/dist/abort.js +9 -0
  3. package/dist/acp.js +18 -75
  4. package/dist/agents.js +266 -53
  5. package/dist/api.js +40 -4
  6. package/dist/app-git.js +64 -0
  7. package/dist/bootstrap.json +10 -14
  8. package/dist/bridge.js +89 -71
  9. package/dist/chatgpt.js +25 -0
  10. package/dist/clis-main.js +23 -0
  11. package/dist/clis.js +203 -71
  12. package/dist/codex-main.js +58 -0
  13. package/dist/conversations.js +328 -199
  14. package/dist/copies.js +188 -161
  15. package/dist/end.js +22 -0
  16. package/dist/enrol-main.js +7 -1
  17. package/dist/events.js +521 -0
  18. package/dist/files.js +16 -1
  19. package/dist/git-main.js +2 -2
  20. package/dist/git.js +6 -2
  21. package/dist/home.js +72 -5
  22. package/dist/house-main.js +181 -57
  23. package/dist/instructions.js +16 -13
  24. package/dist/kit-main.js +55 -4
  25. package/dist/login.js +108 -97
  26. package/dist/logout.js +21 -0
  27. package/dist/mcp.js +39 -0
  28. package/dist/operation.js +7 -4
  29. package/dist/parts.js +82 -0
  30. package/dist/placement.js +48 -0
  31. package/dist/refusals.js +53 -0
  32. package/dist/relay.js +20 -0
  33. package/dist/resident.js +70 -34
  34. package/dist/scope.js +203 -0
  35. package/dist/secret-input.js +7 -2
  36. package/dist/service-main.js +9 -0
  37. package/dist/service.js +33 -0
  38. package/dist/shell.js +3 -0
  39. package/dist/sign-in.js +48 -11
  40. package/dist/skills.js +5 -10
  41. package/dist/stream.js +37 -7
  42. package/dist/transcription.js +170 -0
  43. package/dist/update.js +140 -0
  44. package/dist/wire.js +6 -0
  45. package/dist/work.js +348 -0
  46. package/how-we-work.md +10 -12
  47. package/package.json +4 -7
  48. package/dist/blocks.js +0 -51
@@ -0,0 +1,33 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ const UNIT = 'house-kit.service';
3
+ // launchctl and systemctl answer at once, so ten seconds only bounds a stuck service manager.
4
+ const MANAGER_MS = 10_000;
5
+ function manage(command, args) {
6
+ return spawnSync(command, args, { encoding: 'utf8', timeout: MANAGER_MS });
7
+ }
8
+ function start(command, args) {
9
+ const started = manage(command, args);
10
+ if (started.status === 0)
11
+ return;
12
+ const cause = started.error?.message ?? (started.stderr.trim() || `${command} exited with ${started.status ?? 'a signal'}`);
13
+ throw new Error(`the House Kit service could not be started: ${cause}`);
14
+ }
15
+ export function startService() {
16
+ if (process.platform === 'darwin') {
17
+ const service = `gui/${process.getuid()}/house-kit`;
18
+ const printed = manage('launchctl', ['print', service]);
19
+ if (printed.status !== 0 || /^\tstate = running$/m.test(printed.stdout))
20
+ return false;
21
+ start('launchctl', ['kickstart', service]);
22
+ return true;
23
+ }
24
+ for (const scope of [['--user'], []]) {
25
+ if (manage('systemctl', [...scope, 'is-enabled', '--quiet', UNIT]).status !== 0)
26
+ continue;
27
+ if (manage('systemctl', [...scope, 'is-active', '--quiet', UNIT]).status === 0)
28
+ return false;
29
+ start('systemctl', [...scope, 'start', UNIT]);
30
+ return true;
31
+ }
32
+ return false;
33
+ }
package/dist/shell.js ADDED
@@ -0,0 +1,3 @@
1
+ export function quoted(value) {
2
+ return `'${value.replaceAll("'", `'\\''`)}'`;
3
+ }
package/dist/sign-in.js CHANGED
@@ -1,13 +1,19 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createInterface } from 'node:readline';
3
- import { killTree } from './acp.js';
4
- import { CLIS, cliCommand, withoutProxy } from './clis.js';
3
+ import { CLIS, withoutProxy } from './clis.js';
4
+ import { killTree } from './scope.js';
5
5
  import { holdSecretInput } from './secret-input.js';
6
6
  const ESCAPE = /\u001b\[[\d;]*m/g;
7
7
  const LINK = /https:\/\/\S+/;
8
8
  const CODE = /^[A-Z0-9]+-[A-Z0-9]+$/;
9
+ function causeOf(error) {
10
+ return error instanceof Error ? error.message : String(error);
11
+ }
9
12
  function logged(error) {
10
- process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
13
+ process.stderr.write(`kit: ${causeOf(error)}\n`);
14
+ }
15
+ function endOf(signal) {
16
+ return new Promise((resolve) => signal.addEventListener('abort', () => resolve(true), { once: true }));
11
17
  }
12
18
  export class SignIns {
13
19
  house;
@@ -27,24 +33,52 @@ export class SignIns {
27
33
  return;
28
34
  this.running.add(input.input_id);
29
35
  this.changed();
30
- this.login(input)
31
- .then(() => this.agents.report())
32
- .then(() => this.house.deliver(`/kit/inputs/${input.input_id}/ack`, {}))
36
+ this.signIn(input)
33
37
  .catch(logged)
34
38
  .finally(() => {
35
39
  this.running.delete(input.input_id);
36
40
  this.changed();
37
41
  });
38
42
  }
39
- async login(input) {
40
- await this.agents.installed();
43
+ async signIn(input) {
44
+ const ending = new AbortController();
45
+ // House stops waiting for a sign-in ten minutes after it wrote it and sends the seconds left, so its install and login end with the page.
46
+ const timer = setTimeout(() => ending.abort(), input.ends_in * 1000);
47
+ const ended = await Promise.race([this.signedIn(input, ending.signal), endOf(ending.signal)]);
48
+ clearTimeout(timer);
49
+ if (ended)
50
+ process.stderr.write(`kit: the ${input.cli} sign-in reached the end House set for it\n`);
51
+ await this.house.deliver(`/kit/inputs/${input.input_id}/ack`, {});
52
+ if (!ended)
53
+ await this.agents.reread(input.cli);
54
+ }
55
+ async signedIn(input, signal) {
56
+ await this.login(input, signal);
57
+ if (!signal.aborted)
58
+ await this.agents.recheck(input.cli, signal);
59
+ return false;
60
+ }
61
+ async login(input, signal) {
62
+ let cli;
63
+ try {
64
+ cli = await this.agents.located(input.cli, signal);
65
+ }
66
+ catch (error) {
67
+ if (!signal.aborted)
68
+ process.stderr.write(`kit: the ${input.cli} sign-in failed: ${causeOf(error)}\n`);
69
+ return;
70
+ }
71
+ if (signal.aborted)
72
+ return;
41
73
  const login = CLIS[input.cli].login;
42
- const child = spawn(cliCommand(input.cli), login.args, {
74
+ const child = spawn(cli, login.args, {
43
75
  stdio: ['pipe', 'pipe', 'pipe'],
44
76
  detached: true,
45
77
  env: withoutProxy(),
46
78
  });
47
79
  const running = () => child.exitCode === null && child.signalCode === null;
80
+ const stop = () => killTree(child);
81
+ signal.addEventListener('abort', stop, { once: true });
48
82
  let link;
49
83
  let code;
50
84
  let last = '';
@@ -54,6 +88,8 @@ export class SignIns {
54
88
  if (plain === '')
55
89
  return;
56
90
  last = plain;
91
+ if (login.code === 'collect' && plain.includes(login.rejected))
92
+ killTree(child);
57
93
  link ??= LINK.exec(plain)?.[0];
58
94
  if (CODE.test(plain))
59
95
  code ??= plain;
@@ -79,9 +115,10 @@ export class SignIns {
79
115
  createInterface({ input: output }).on('line', read);
80
116
  const failed = await new Promise((resolve) => {
81
117
  child.on('error', (error) => resolve(error.message));
82
- child.on('close', (status, signal) => resolve(status === 0 ? null : `exited with ${status ?? signal}${last ? `: ${last}` : ''}`));
118
+ child.on('close', (status, killed) => resolve(status === 0 ? null : `exited with ${status ?? killed}${last ? `: ${last}` : ''}`));
83
119
  });
84
- if (failed !== null)
120
+ signal.removeEventListener('abort', stop);
121
+ if (failed !== null && !signal.aborted)
85
122
  process.stderr.write(`kit: the ${input.cli} sign-in failed: ${failed}\n`);
86
123
  }
87
124
  }
package/dist/skills.js CHANGED
@@ -3,11 +3,10 @@ import { cp, lstat, mkdir, readdir, realpath, rm, symlink, writeFile } from 'nod
3
3
  import { homedir } from 'node:os';
4
4
  import { join, relative } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
- import { parse } from 'yaml';
7
6
  import { KIT_VERSION } from './clis.js';
8
- import { refusalCode } from './copies.js';
9
7
  import { kitHome, readConfiguration, readHome, writeHome } from './home.js';
10
- export const HOW_WE_WORK = '/private/library/how-we-work.md';
8
+ import { refusalOf } from './refusals.js';
9
+ export const HOW_WE_WORK = '/rooms/private/how-we-work.md';
11
10
  const SKILL_SET = fileURLToPath(new URL('../skills/', import.meta.url));
12
11
  const HOW_WE_WORK_TEXT = readFileSync(new URL('../how-we-work.md', import.meta.url), 'utf8');
13
12
  const RECORD = 'skill-set.json';
@@ -63,20 +62,16 @@ export async function placeSkillSet() {
63
62
  else
64
63
  await rm(join(kitHome(), RECORD), { force: true });
65
64
  }
66
- function documentPresent(refusal) {
67
- const { conflicts } = parse(refusal.slice(refusal.indexOf('\n') + 1));
68
- return conflicts.some((conflict) => conflict.code === 'path_exists');
69
- }
70
65
  export async function createHowWeWork(bridge) {
71
66
  if ((await readHome(RECORD)) === null || (await present(join(kitHome(), CREATED))))
72
67
  return;
73
68
  const created = await bridge.tool('edit', { changes: [{ op: 'create', path: HOW_WE_WORK, content: HOW_WE_WORK_TEXT }] });
74
69
  if (created.isError === true) {
75
70
  const text = created.content.map((content) => content.text).join('\n');
76
- const code = refusalCode(text);
77
- if (UNWRITABLE.has(code))
71
+ const refusal = refusalOf(text);
72
+ if (UNWRITABLE.has(refusal?.code ?? ''))
78
73
  return;
79
- if (code !== 'edit_conflict' || !documentPresent(text))
74
+ if (refusal?.code !== 'edit_conflict' || !refusal.conflicts.includes('path_exists'))
80
75
  throw new Error(text);
81
76
  }
82
77
  await writeFile(join(kitHome(), CREATED), '');
package/dist/stream.js CHANGED
@@ -1,16 +1,38 @@
1
+ import { subscribe } from 'node:diagnostics_channel';
2
+ import { finalRefusal, HouseRefusal, retryDelay } from './api.js';
3
+ import { end, REPLACED, signInAgain, updateRequired } from './end.js';
1
4
  import { readEnrolment } from './home.js';
2
- const SUBPROTOCOL = 'house.kit.stream.1';
5
+ import { relayed } from './relay.js';
6
+ import { KIT_WIRE, tooOld } from './wire.js';
7
+ const PATH = '/kit/stream';
8
+ const SUBPROTOCOL = `house.kit.stream.${KIT_WIRE}`;
9
+ const REFUSAL_HEADER = 'x-house-refusal';
3
10
  function streamUrl(house) {
4
- const url = new URL('/kit/stream', house);
11
+ const url = new URL(PATH, house);
5
12
  url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
6
13
  return url;
7
14
  }
15
+ function header(headers, name) {
16
+ for (let index = 0; index < headers.length; index += 2) {
17
+ if (headers[index].toString('latin1').toLowerCase() === name)
18
+ return headers[index + 1].toString('latin1');
19
+ }
20
+ return '';
21
+ }
22
+ let refused = null;
23
+ subscribe('undici:request:headers', (message) => {
24
+ const { request, response } = message;
25
+ if (!request.path.endsWith(PATH))
26
+ return;
27
+ refused = new HouseRefusal(PATH, response.statusCode, header(response.headers, REFUSAL_HEADER) || response.statusText);
28
+ });
8
29
  export function holdStream(handlers) {
9
30
  let socket = null;
10
31
  let failures = 0;
11
32
  const connect = async () => {
12
33
  const { house, credential } = (await readEnrolment());
13
- const opening = new WebSocket(streamUrl(house), {
34
+ refused = null;
35
+ const opening = new WebSocket(relayed(streamUrl(house)), {
14
36
  protocols: [SUBPROTOCOL],
15
37
  headers: { authorization: `Bearer ${credential}` },
16
38
  });
@@ -29,10 +51,18 @@ export function holdStream(handlers) {
29
51
  if (socket === opening)
30
52
  socket = null;
31
53
  process.stderr.write(`kit: control stream closed ${event.code} ${event.reason}\n`);
32
- const delay = opened
33
- ? 1000 + Math.random() * 2000
34
- : Math.min(30_000, 1000 * 2 ** failures++);
35
- setTimeout(() => void connect(), delay);
54
+ if (event.reason === 'replaced')
55
+ end(REPLACED);
56
+ if (event.reason === 'credential_rejected' || refused?.status === 401) {
57
+ void signInAgain(credential);
58
+ return;
59
+ }
60
+ if (refused !== null && tooOld(refused.text))
61
+ updateRequired(house);
62
+ if (finalRefusal(refused))
63
+ end(refused.message);
64
+ // A closed socket reopens in one to three seconds, spread so Kits one restart closed return apart; an opening House refused as retryable or left unanswered backs off on the jittered curve.
65
+ setTimeout(() => void connect(), opened ? 1000 + Math.random() * 2000 : retryDelay(failures++));
36
66
  };
37
67
  };
38
68
  void connect();
@@ -0,0 +1,170 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { chmod, mkdir, mkdtemp, readdir, readFile, rename, rm, stat } from 'node:fs/promises';
4
+ import { availableParallelism, tmpdir } from 'node:os';
5
+ import { basename, join } from 'node:path';
6
+ import { pipeline } from 'node:stream/promises';
7
+ import { unlessAborted } from './abort.js';
8
+ import { failureOf, run } from './clis.js';
9
+ import { kitHome } from './home.js';
10
+ const RELEASE = 'https://github.com/agentshouse/kit/releases/download/engine-2';
11
+ export const MODEL = {
12
+ url: 'https://huggingface.co/ggml-org/parakeet-GGUF/resolve/35156454d1a39de06863303dd209fd2bed6ee079/ggml-parakeet-tdt-0.6b-v3-q4_k.bin',
13
+ sha256: '8b205b8b39c6535e153de6fb11c51db46125d45c4f16ba496fe41a0fe71b885e',
14
+ executable: false,
15
+ };
16
+ export const ENGINES = {
17
+ 'linux-x64': {
18
+ decoder: { url: `${RELEASE}/ffmpeg-linux-x86_64`, sha256: '1f8235d206428305afb89c6e8ab99d100425a0ba61e22bb4c7aff017db8c8de5', executable: true },
19
+ engine: { url: `${RELEASE}/parakeet-cli-linux-x86_64`, sha256: 'bb2585695992fe1927a33960002cdf51b8a90a96ad65593c3d0a9f1fbc0865c2', executable: true },
20
+ },
21
+ 'linux-arm64': {
22
+ decoder: { url: `${RELEASE}/ffmpeg-linux-aarch64`, sha256: 'a7e08a0fae0179d1078312f6bb13d2a9aa4d4c71a1d82a022953f25dee452f5e', executable: true },
23
+ engine: { url: `${RELEASE}/parakeet-cli-linux-aarch64`, sha256: 'cbc0bedc8daae97f1ef9dcee4200c06226218e300e0fd62ead1306d22742b7ed', executable: true },
24
+ },
25
+ 'darwin-arm64': {
26
+ decoder: { url: `${RELEASE}/ffmpeg-darwin-arm64`, sha256: '7abe154aaed3d6b49f5167ca7221bb66bed51388925d99a7e4261a41fe52fba6', executable: true },
27
+ engine: { url: `${RELEASE}/parakeet-cli-darwin-arm64`, sha256: '9a2aafc0922ad7c0b6db6eff1641e96572ba32ac40bf995a1df242ed2febf297', executable: true },
28
+ },
29
+ };
30
+ const CHUNK_SECONDS = 20;
31
+ let held = Promise.resolve();
32
+ let holding = Promise.resolve();
33
+ let setting = null;
34
+ let downloading = null;
35
+ let readiness = { installed: false, failure: null };
36
+ function directory() {
37
+ return join(kitHome(), 'transcription');
38
+ }
39
+ function installed(artifact) {
40
+ return join(directory(), artifact.sha256);
41
+ }
42
+ async function executed(command, args, signal) {
43
+ // A download or a transcription runs as long as its size needs; the setting turning off or the turn's interrupt or end aborts it instead.
44
+ const ran = await run(command, args, 0, false, signal);
45
+ if (ran.status !== 0)
46
+ throw new Error(failureOf(ran, basename(command)));
47
+ return ran.stdout;
48
+ }
49
+ function present(path) {
50
+ return stat(path).then(() => true, () => false);
51
+ }
52
+ async function cpus() {
53
+ const [quota, period] = (await readFile('/sys/fs/cgroup/cpu.max', 'utf8').catch(() => 'max')).split(' ');
54
+ const allowed = quota === 'max' ? Infinity : Math.ceil(Number(quota) / Number(period));
55
+ return Math.min(availableParallelism(), allowed);
56
+ }
57
+ async function sha256(path) {
58
+ const hash = createHash('sha256');
59
+ await pipeline(createReadStream(path), hash);
60
+ return hash.digest('hex');
61
+ }
62
+ function causeOf(error) {
63
+ return error instanceof Error ? error.message : String(error);
64
+ }
65
+ function pinnedHere() {
66
+ return ENGINES[`${process.platform}-${process.arch}`];
67
+ }
68
+ async function install(artifacts, signal) {
69
+ await mkdir(directory(), { recursive: true });
70
+ const pinned = new Set(artifacts.map((artifact) => artifact.sha256));
71
+ for (const name of await readdir(directory())) {
72
+ if (!pinned.has(name))
73
+ await rm(join(directory(), name), { recursive: true, force: true });
74
+ }
75
+ const missing = [];
76
+ for (const artifact of artifacts)
77
+ if (!(await present(installed(artifact))))
78
+ missing.push(artifact);
79
+ try {
80
+ for (const artifact of missing) {
81
+ const part = `${installed(artifact)}.part`;
82
+ // Three retries carry a large download past a dropped connection before the download fails.
83
+ await executed('curl', ['-fsSL', '--retry', '3', '-o', part, artifact.url], signal);
84
+ if ((await sha256(part)) !== artifact.sha256)
85
+ throw new Error(`${artifact.url} does not match its sha256`);
86
+ }
87
+ for (const artifact of missing) {
88
+ if (artifact.executable)
89
+ await chmod(`${installed(artifact)}.part`, 0o755);
90
+ await rename(`${installed(artifact)}.part`, installed(artifact));
91
+ }
92
+ }
93
+ finally {
94
+ for (const artifact of missing)
95
+ await rm(`${installed(artifact)}.part`, { force: true });
96
+ }
97
+ }
98
+ function reported(next) {
99
+ const changed = next.installed !== readiness.installed || next.failure !== readiness.failure;
100
+ readiness = next;
101
+ return changed;
102
+ }
103
+ async function settle(transcribe) {
104
+ if (transcribe === setting)
105
+ return false;
106
+ setting = transcribe;
107
+ if (!transcribe) {
108
+ await rm(directory(), { recursive: true, force: true });
109
+ return reported({ installed: false, failure: null });
110
+ }
111
+ const download = new AbortController();
112
+ downloading = download;
113
+ try {
114
+ const pinned = pinnedHere();
115
+ await install([pinned.decoder, pinned.engine, MODEL], download.signal);
116
+ return reported({ installed: true, failure: null });
117
+ }
118
+ catch (error) {
119
+ await rm(directory(), { recursive: true, force: true });
120
+ return reported({ installed: false, failure: download.signal.aborted ? null : causeOf(error) });
121
+ }
122
+ finally {
123
+ downloading = null;
124
+ }
125
+ }
126
+ export function holdTranscription(transcribe) {
127
+ if (!transcribe)
128
+ downloading?.abort();
129
+ const settled = holding.then(() => settle(transcribe));
130
+ holding = settled.catch(() => undefined);
131
+ return settled;
132
+ }
133
+ export function transcriptionReport() {
134
+ return readiness;
135
+ }
136
+ async function transcribed(path, signal) {
137
+ const pinned = pinnedHere();
138
+ const work = await mkdtemp(join(tmpdir(), 'kit-transcription-'));
139
+ try {
140
+ await executed(installed(pinned.decoder), ['-nostdin', '-hide_banner', '-loglevel', 'error', '-i', path, '-ar', '16000', '-ac', '1', '-c:a', 'pcm_s16le',
141
+ '-f', 'segment', '-segment_time', String(CHUNK_SECONDS), join(work, '%05d.wav')], signal);
142
+ const parts = (await readdir(work)).sort().flatMap((part) => ['-f', join(work, part)]);
143
+ const text = await executed(installed(pinned.engine), ['-t', String(await cpus()), '-np', '-m', installed(MODEL), ...parts], signal);
144
+ return text
145
+ .split('\n')
146
+ .map((line) => line.trim())
147
+ .filter((line) => line !== '')
148
+ .join(' ');
149
+ }
150
+ finally {
151
+ await rm(work, { recursive: true, force: true });
152
+ }
153
+ }
154
+ export async function transcribe(path, signal) {
155
+ if (!readiness.installed)
156
+ return null;
157
+ const before = held;
158
+ let release;
159
+ const mine = new Promise((resolve) => {
160
+ release = resolve;
161
+ });
162
+ held = Promise.all([before, mine]);
163
+ try {
164
+ await unlessAborted(before, signal);
165
+ return readiness.installed ? await transcribed(path, signal) : null;
166
+ }
167
+ finally {
168
+ release();
169
+ }
170
+ }
package/dist/update.js ADDED
@@ -0,0 +1,140 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { run } from './clis.js';
7
+ import { kitHome, workspaceRoot } from './home.js';
8
+ import { service, throughSudo } from './placement.js';
9
+ function logged(error) {
10
+ process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
11
+ }
12
+ function directory() {
13
+ return join(kitHome(), 'update');
14
+ }
15
+ function pending() {
16
+ return join(directory(), 'pending.json');
17
+ }
18
+ function outcome() {
19
+ return join(directory(), 'outcome');
20
+ }
21
+ function unit(inputId) {
22
+ return `house-kit-update-${inputId}`;
23
+ }
24
+ function manager() {
25
+ return service() === 'user' ? ['--user'] : [];
26
+ }
27
+ function elevated() {
28
+ return throughSudo() ? ['sudo', '-n'] : [];
29
+ }
30
+ function account() {
31
+ return throughSudo() ? [`--uid=${process.getuid()}`, `--gid=${process.getgid()}`] : [];
32
+ }
33
+ function placement() {
34
+ return service() === 'user' ? ['--workspace', workspaceRoot()] : ['--linux'];
35
+ }
36
+ function record() {
37
+ return `outcome=$1; shift; bash "$0" "$@"; printf %s "$?" > "$outcome"; ${[...elevated(), 'systemctl', ...manager(), 'start', 'house-kit.service'].join(' ')}`;
38
+ }
39
+ async function pendingInput() {
40
+ try {
41
+ return JSON.parse(await readFile(pending(), 'utf8')).input_id;
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ async function recorded() {
48
+ const status = await readFile(outcome(), 'utf8').catch(() => null);
49
+ if (status === null)
50
+ return null;
51
+ return status.trim() === '0' ? {} : { refused: `the Kit bootstrap exited with ${status.trim()}` };
52
+ }
53
+ async function finished(inputId) {
54
+ for (;;) {
55
+ const ack = await recorded();
56
+ if (ack !== null)
57
+ return ack;
58
+ // systemctl answers at once, so ten seconds only bounds a stuck service manager.
59
+ if ((await run('systemctl', [...manager(), 'is-active', '--quiet', unit(inputId)], 10_000)).status !== 0) {
60
+ return (await recorded()) ?? { refused: 'the Kit bootstrap did not finish' };
61
+ }
62
+ // The bootstrap runs for minutes, so checking each second sees its outcome within a second at little cost.
63
+ await new Promise((resolve) => setTimeout(resolve, 1000));
64
+ }
65
+ }
66
+ function rerun(script, inputId, flags) {
67
+ return new Promise((resolve) => {
68
+ const [command, ...args] = [
69
+ ...elevated(),
70
+ 'systemd-run',
71
+ ...manager(),
72
+ ...account(),
73
+ '--wait',
74
+ '--collect',
75
+ '--quiet',
76
+ `--unit=${unit(inputId)}`,
77
+ `--setenv=HOME=${homedir()}`,
78
+ '/bin/sh',
79
+ '-c',
80
+ record(),
81
+ script,
82
+ outcome(),
83
+ ...placement(),
84
+ ...flags,
85
+ ];
86
+ const child = spawn(command, args, { stdio: ['ignore', 'ignore', 'inherit'] });
87
+ child.on('error', () => resolve({ refused: 'no service manager runs this Kit' }));
88
+ child.on('close', () => resolve(null));
89
+ });
90
+ }
91
+ export class Updates {
92
+ house;
93
+ held = new Set();
94
+ queue = Promise.resolve();
95
+ constructor(house) {
96
+ this.house = house;
97
+ }
98
+ async resumed() {
99
+ const inputId = await pendingInput();
100
+ if (inputId === null)
101
+ return;
102
+ await this.acknowledge(inputId, await finished(inputId));
103
+ }
104
+ start(input) {
105
+ if (this.held.has(input.input_id))
106
+ return;
107
+ this.held.add(input.input_id);
108
+ this.queue = this.queue
109
+ .then(() => this.carry(input))
110
+ .then((ack) => this.acknowledge(input.input_id, ack))
111
+ .catch(logged)
112
+ .finally(() => this.held.delete(input.input_id));
113
+ }
114
+ async carry(input) {
115
+ if ((await pendingInput()) === input.input_id)
116
+ return finished(input.input_id);
117
+ const answer = await fetch(input.bootstrap);
118
+ if (!answer.ok)
119
+ return { refused: `the Kit bootstrap could not be downloaded: ${answer.status}` };
120
+ const script = Buffer.from(await answer.arrayBuffer());
121
+ if (createHash('sha256').update(script).digest('hex') !== input.sha256) {
122
+ return { refused: 'the Kit bootstrap does not match its sha256' };
123
+ }
124
+ await mkdir(directory(), { recursive: true, mode: 0o700 });
125
+ const path = join(directory(), 'connect-linux.sh');
126
+ await writeFile(path, script, { mode: 0o700 });
127
+ await rm(outcome(), { force: true });
128
+ await writeFile(pending(), `${JSON.stringify({ input_id: input.input_id })}\n`, { mode: 0o600 });
129
+ return (await rerun(path, input.input_id, input.update_clis ? ['--update-clis'] : [])) ?? (await recorded()) ?? {
130
+ refused: 'the Kit bootstrap did not finish',
131
+ };
132
+ }
133
+ async acknowledge(inputId, ack) {
134
+ await this.house.deliver(`/kit/inputs/${inputId}/ack`, ack);
135
+ if ((await pendingInput()) !== inputId)
136
+ return;
137
+ await rm(pending(), { force: true });
138
+ await rm(outcome(), { force: true });
139
+ }
140
+ }
package/dist/wire.js ADDED
@@ -0,0 +1,6 @@
1
+ import { refusalOf } from './refusals.js';
2
+ export const KIT_WIRE = 1;
3
+ export const KIT_WIRE_HEADER = 'x-house-kit-wire';
4
+ export function tooOld(text) {
5
+ return refusalOf(text)?.code === 'kit_update_required';
6
+ }