@agentshouse/kit 0.2.1-ce145e9aadbf6 → 0.2.1-ceeaf32286734

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 (136) hide show
  1. package/README.md +42 -41
  2. package/dist/acp.js +102 -108
  3. package/dist/agents.js +152 -45
  4. package/dist/api.js +34 -2
  5. package/dist/app-git.js +48 -0
  6. package/dist/authority-main.js +2 -2
  7. package/dist/bridge.js +37 -58
  8. package/dist/building.js +46 -0
  9. package/dist/calls.js +71 -0
  10. package/dist/chatgpt.js +32 -0
  11. package/dist/clis-main.js +2 -2
  12. package/dist/clis.js +161 -80
  13. package/dist/codex-main.js +58 -0
  14. package/dist/connection.js +116 -0
  15. package/dist/conversations.js +731 -332
  16. package/dist/copies.js +188 -128
  17. package/dist/end.js +33 -0
  18. package/dist/enrol-main.js +7 -1
  19. package/dist/events.js +546 -0
  20. package/dist/files.js +139 -17
  21. package/dist/git.js +13 -11
  22. package/dist/home.js +96 -7
  23. package/dist/house-cli.js +299 -0
  24. package/dist/house-main.js +7 -159
  25. package/dist/instructions.js +8 -10
  26. package/dist/kit-cli.js +68 -0
  27. package/dist/kit-main.js +8 -19
  28. package/dist/login.js +119 -104
  29. package/dist/logout.js +14 -13
  30. package/dist/mcp.js +6 -2
  31. package/dist/parts.js +82 -0
  32. package/dist/placement.js +39 -0
  33. package/dist/refusals.js +12 -0
  34. package/dist/relay.js +33 -2
  35. package/dist/resident.js +118 -51
  36. package/dist/scope.js +206 -0
  37. package/dist/scripts.js +255 -0
  38. package/dist/secret-input.js +3 -2
  39. package/dist/service-main.js +9 -0
  40. package/dist/service.js +55 -0
  41. package/dist/shell.js +3 -0
  42. package/dist/sign-in.js +40 -33
  43. package/dist/silence.js +28 -0
  44. package/dist/skills.js +49 -35
  45. package/dist/transcription.js +129 -41
  46. package/dist/translate.js +2 -8
  47. package/dist/update.js +117 -53
  48. package/dist/wire.js +22 -0
  49. package/dist/work.js +346 -0
  50. package/package.json +20 -20
  51. package/dist/blocks.js +0 -51
  52. package/dist/bootstrap.json +0 -24
  53. package/dist/stream.js +0 -47
  54. package/how-we-work.md +0 -23
  55. package/skills/ask-matt/LICENSE +0 -21
  56. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  57. package/skills/ask-matt/SKILL.md +0 -91
  58. package/skills/ask-matt/agents/openai.yaml +0 -4
  59. package/skills/code-review/LICENSE +0 -21
  60. package/skills/code-review/SKILL.md +0 -89
  61. package/skills/code-review/agents/openai.yaml +0 -3
  62. package/skills/codebase-design/DEEPENING.md +0 -37
  63. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  64. package/skills/codebase-design/LICENSE +0 -21
  65. package/skills/codebase-design/SKILL.md +0 -116
  66. package/skills/codebase-design/agents/openai.yaml +0 -3
  67. package/skills/diagnosing-bugs/LICENSE +0 -21
  68. package/skills/diagnosing-bugs/SKILL.md +0 -140
  69. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  70. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  71. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  72. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  73. package/skills/domain-modeling/LICENSE +0 -21
  74. package/skills/domain-modeling/SKILL.md +0 -76
  75. package/skills/domain-modeling/agents/openai.yaml +0 -3
  76. package/skills/grill-me/LICENSE +0 -21
  77. package/skills/grill-me/SKILL.md +0 -8
  78. package/skills/grill-me/agents/openai.yaml +0 -4
  79. package/skills/grill-with-docs/LICENSE +0 -21
  80. package/skills/grill-with-docs/SKILL.md +0 -8
  81. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  82. package/skills/grilling/LICENSE +0 -21
  83. package/skills/grilling/SKILL.md +0 -30
  84. package/skills/grilling/agents/openai.yaml +0 -3
  85. package/skills/handoff/LICENSE +0 -21
  86. package/skills/handoff/SKILL.md +0 -17
  87. package/skills/handoff/agents/openai.yaml +0 -4
  88. package/skills/implement/LICENSE +0 -21
  89. package/skills/implement/SKILL.md +0 -16
  90. package/skills/implement/agents/openai.yaml +0 -4
  91. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  92. package/skills/improve-codebase-architecture/LICENSE +0 -21
  93. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  94. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  95. package/skills/prototype/LICENSE +0 -21
  96. package/skills/prototype/LOGIC.md +0 -67
  97. package/skills/prototype/SKILL.md +0 -28
  98. package/skills/prototype/UI.md +0 -112
  99. package/skills/prototype/agents/openai.yaml +0 -3
  100. package/skills/research/LICENSE +0 -21
  101. package/skills/research/SKILL.md +0 -14
  102. package/skills/research/agents/openai.yaml +0 -3
  103. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  104. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  105. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  106. package/skills/tdd/LICENSE +0 -21
  107. package/skills/tdd/SKILL.md +0 -40
  108. package/skills/tdd/agents/openai.yaml +0 -3
  109. package/skills/tdd/mocking.md +0 -59
  110. package/skills/tdd/tests.md +0 -77
  111. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  112. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  113. package/skills/teach/LICENSE +0 -21
  114. package/skills/teach/MISSION-FORMAT.md +0 -31
  115. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  116. package/skills/teach/SKILL.md +0 -141
  117. package/skills/teach/agents/openai.yaml +0 -4
  118. package/skills/to-questionnaire/LICENSE +0 -21
  119. package/skills/to-questionnaire/SKILL.md +0 -55
  120. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  121. package/skills/to-spec/LICENSE +0 -21
  122. package/skills/to-spec/SKILL.md +0 -76
  123. package/skills/to-spec/agents/openai.yaml +0 -4
  124. package/skills/to-tickets/LICENSE +0 -21
  125. package/skills/to-tickets/SKILL.md +0 -106
  126. package/skills/to-tickets/agents/openai.yaml +0 -4
  127. package/skills/wait-what/LICENSE +0 -21
  128. package/skills/wait-what/SKILL.md +0 -8
  129. package/skills/wait-what/agents/openai.yaml +0 -4
  130. package/skills/wayfinder/LICENSE +0 -21
  131. package/skills/wayfinder/SKILL.md +0 -129
  132. package/skills/wayfinder/agents/openai.yaml +0 -4
  133. package/skills/writing-for-agents/LICENSE +0 -21
  134. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  135. package/skills/writing-for-agents/SKILL.md +0 -83
  136. package/skills/writing-for-agents/agents/openai.yaml +0 -3
@@ -1,34 +1,44 @@
1
- import { createHash } from 'node:crypto';
2
- import { createReadStream } from 'node:fs';
3
1
  import { chmod, mkdir, mkdtemp, readdir, readFile, rename, rm, stat } from 'node:fs/promises';
4
2
  import { availableParallelism, tmpdir } from 'node:os';
5
3
  import { basename, join } from 'node:path';
6
- import { pipeline } from 'node:stream/promises';
7
4
  import { unlessAborted } from './abort.js';
5
+ import { downloadServed } from './building.js';
8
6
  import { failureOf, run } from './clis.js';
7
+ import { downloaded, fetched } from './files.js';
9
8
  import { kitHome } from './home.js';
10
9
  const RELEASE = 'https://github.com/agentshouse/kit/releases/download/engine-2';
11
10
  export const MODEL = {
12
- url: 'https://huggingface.co/ggml-org/parakeet-GGUF/resolve/35156454d1a39de06863303dd209fd2bed6ee079/ggml-parakeet-tdt-0.6b-v3-q4_k.bin',
11
+ name: 'ggml-parakeet-tdt-0.6b-v3-q4_k.bin',
12
+ from: 'https://huggingface.co/ggml-org/parakeet-GGUF/resolve/35156454d1a39de06863303dd209fd2bed6ee079/ggml-parakeet-tdt-0.6b-v3-q4_k.bin',
13
13
  sha256: '8b205b8b39c6535e153de6fb11c51db46125d45c4f16ba496fe41a0fe71b885e',
14
+ bytes: 415_611_879,
14
15
  executable: false,
15
16
  };
16
17
  export const ENGINES = {
17
18
  '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 },
19
+ decoder: { name: 'ffmpeg-linux-x86_64', from: `${RELEASE}/ffmpeg-linux-x86_64`, sha256: '1f8235d206428305afb89c6e8ab99d100425a0ba61e22bb4c7aff017db8c8de5', bytes: 5_175_832, executable: true },
20
+ engine: { name: 'parakeet-cli-linux-x86_64', from: `${RELEASE}/parakeet-cli-linux-x86_64`, sha256: 'bb2585695992fe1927a33960002cdf51b8a90a96ad65593c3d0a9f1fbc0865c2', bytes: 3_801_616, executable: true },
20
21
  },
21
22
  '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 },
23
+ decoder: { name: 'ffmpeg-linux-aarch64', from: `${RELEASE}/ffmpeg-linux-aarch64`, sha256: 'a7e08a0fae0179d1078312f6bb13d2a9aa4d4c71a1d82a022953f25dee452f5e', bytes: 4_590_208, executable: true },
24
+ engine: { name: 'parakeet-cli-linux-aarch64', from: `${RELEASE}/parakeet-cli-linux-aarch64`, sha256: 'cbc0bedc8daae97f1ef9dcee4200c06226218e300e0fd62ead1306d22742b7ed', bytes: 3_477_624, executable: true },
24
25
  },
25
26
  '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 },
27
+ decoder: { name: 'ffmpeg-darwin-arm64', from: `${RELEASE}/ffmpeg-darwin-arm64`, sha256: '7abe154aaed3d6b49f5167ca7221bb66bed51388925d99a7e4261a41fe52fba6', bytes: 3_696_768, executable: true },
28
+ engine: { name: 'parakeet-cli-darwin-arm64', from: `${RELEASE}/parakeet-cli-darwin-arm64`, sha256: '9a2aafc0922ad7c0b6db6eff1641e96572ba32ac40bf995a1df242ed2febf297', bytes: 1_939_728, executable: true },
28
29
  },
29
30
  };
30
31
  const CHUNK_SECONDS = 20;
32
+ const OFF = "transcription is off on the Agent's Environment, so this message's audio has no text; turn it on or write instead";
33
+ const NOT_INSTALLED = "the speech engine is not installed on the Agent's Environment, so this message's audio has no text";
34
+ const NOT_DOWNLOADED = 'an audio file this message links could not be downloaded; send the message again';
35
+ const UNDECODABLE = 'an audio file this message links could not be decoded';
36
+ const UNTRANSCRIBED = 'an audio file this message links could not be transcribed';
31
37
  let held = Promise.resolve();
38
+ let holding = Promise.resolve();
39
+ let setting = null;
40
+ let downloading = null;
41
+ let readiness = { installed: false, failure: null };
32
42
  function directory() {
33
43
  return join(kitHome(), 'transcription');
34
44
  }
@@ -36,6 +46,7 @@ function installed(artifact) {
36
46
  return join(directory(), artifact.sha256);
37
47
  }
38
48
  async function executed(command, args, signal) {
49
+ // A decode or a transcription runs as long as its audio needs; the setting turning off or the turn's interrupt or end aborts it instead.
39
50
  const ran = await run(command, args, 0, false, signal);
40
51
  if (ran.status !== 0)
41
52
  throw new Error(failureOf(ran, basename(command)));
@@ -44,15 +55,49 @@ async function executed(command, args, signal) {
44
55
  function present(path) {
45
56
  return stat(path).then(() => true, () => false);
46
57
  }
47
- async function cpus() {
58
+ async function threads() {
48
59
  const [quota, period] = (await readFile('/sys/fs/cgroup/cpu.max', 'utf8').catch(() => 'max')).split(' ');
49
60
  const allowed = quota === 'max' ? Infinity : Math.ceil(Number(quota) / Number(period));
50
- return Math.min(availableParallelism(), allowed);
61
+ return Math.max(1, Math.floor(Math.min(availableParallelism(), allowed) / 2));
51
62
  }
52
- async function sha256(path) {
53
- const hash = createHash('sha256');
54
- await pipeline(createReadStream(path), hash);
55
- return hash.digest('hex');
63
+ function causeOf(error) {
64
+ return error instanceof Error ? error.message : String(error);
65
+ }
66
+ async function failing(reason, work) {
67
+ try {
68
+ return await work;
69
+ }
70
+ catch (error) {
71
+ throw new Error(reason, { cause: error });
72
+ }
73
+ }
74
+ function ready() {
75
+ if (setting !== true)
76
+ throw new Error(OFF);
77
+ if (!readiness.installed)
78
+ throw new Error(NOT_INSTALLED);
79
+ }
80
+ function pinnedHere() {
81
+ return ENGINES[`${process.platform}-${process.arch}`];
82
+ }
83
+ const DOWNLOADS = 3;
84
+ async function downloadedAgain(artifact, signal) {
85
+ // An artifact arrives at a hundred kilobytes a second or its download ends, so a stalled Building cannot hold the install open.
86
+ const deadlineMs = Math.ceil(artifact.bytes / 100);
87
+ const deadline = AbortSignal.timeout(deadlineMs);
88
+ for (let attempt = 1;; attempt++) {
89
+ try {
90
+ return await downloadServed(artifact.name, artifact.sha256, `${installed(artifact)}.part`, AbortSignal.any([signal, deadline]), artifact.bytes);
91
+ }
92
+ catch (error) {
93
+ if (signal.aborted)
94
+ throw error;
95
+ if (deadline.aborted)
96
+ throw new Error(`${artifact.name} did not arrive within ${Math.ceil(deadlineMs / 1000)} seconds`);
97
+ if (attempt === DOWNLOADS)
98
+ throw error;
99
+ }
100
+ }
56
101
  }
57
102
  async function install(artifacts, signal) {
58
103
  await mkdir(directory(), { recursive: true });
@@ -66,12 +111,8 @@ async function install(artifacts, signal) {
66
111
  if (!(await present(installed(artifact))))
67
112
  missing.push(artifact);
68
113
  try {
69
- for (const artifact of missing) {
70
- const part = `${installed(artifact)}.part`;
71
- await executed('curl', ['-fsSL', '--retry', '3', '-o', part, artifact.url], signal);
72
- if ((await sha256(part)) !== artifact.sha256)
73
- throw new Error(`${artifact.url} does not match its sha256`);
74
- }
114
+ for (const artifact of missing)
115
+ await downloadedAgain(artifact, signal);
75
116
  for (const artifact of missing) {
76
117
  if (artifact.executable)
77
118
  await chmod(`${installed(artifact)}.part`, 0o755);
@@ -83,29 +124,61 @@ async function install(artifacts, signal) {
83
124
  await rm(`${installed(artifact)}.part`, { force: true });
84
125
  }
85
126
  }
86
- async function transcribed(path, signal) {
87
- const platform = `${process.platform}-${process.arch}`;
88
- const pinned = ENGINES[platform];
89
- if (pinned === undefined)
90
- throw new Error(`no transcription engine is pinned for ${platform}`);
91
- await install([pinned.decoder, pinned.engine, MODEL], signal);
92
- const work = await mkdtemp(join(tmpdir(), 'kit-transcription-'));
127
+ function reported(next) {
128
+ const changed = next.installed !== readiness.installed || next.failure !== readiness.failure;
129
+ readiness = next;
130
+ return changed;
131
+ }
132
+ async function settle(transcribe) {
133
+ if (transcribe === setting)
134
+ return false;
135
+ setting = transcribe;
136
+ if (!transcribe) {
137
+ await rm(directory(), { recursive: true, force: true });
138
+ return reported({ installed: false, failure: null });
139
+ }
140
+ const download = new AbortController();
141
+ downloading = download;
93
142
  try {
94
- await executed(installed(pinned.decoder), ['-nostdin', '-hide_banner', '-loglevel', 'error', '-i', path, '-ar', '16000', '-ac', '1', '-c:a', 'pcm_s16le',
95
- '-f', 'segment', '-segment_time', String(CHUNK_SECONDS), join(work, '%05d.wav')], signal);
96
- const parts = (await readdir(work)).sort().flatMap((part) => ['-f', join(work, part)]);
97
- const text = await executed(installed(pinned.engine), ['-t', String(await cpus()), '-np', '-m', installed(MODEL), ...parts], signal);
98
- return text
99
- .split('\n')
100
- .map((line) => line.trim())
101
- .filter((line) => line !== '')
102
- .join(' ');
143
+ const pinned = pinnedHere();
144
+ await install([pinned.decoder, pinned.engine, MODEL], download.signal);
145
+ return reported({ installed: true, failure: null });
146
+ }
147
+ catch (error) {
148
+ await rm(directory(), { recursive: true, force: true });
149
+ return reported({ installed: false, failure: download.signal.aborted ? null : causeOf(error) });
103
150
  }
104
151
  finally {
105
- await rm(work, { recursive: true, force: true });
152
+ downloading = null;
106
153
  }
107
154
  }
108
- export async function transcribe(path, signal) {
155
+ export function holdTranscription(transcribe) {
156
+ if (!transcribe)
157
+ downloading?.abort();
158
+ const settled = holding.then(() => settle(transcribe));
159
+ holding = settled.catch(() => undefined);
160
+ return settled;
161
+ }
162
+ export function transcriptionReport() {
163
+ return readiness;
164
+ }
165
+ async function transcribed(audio, parts, signal) {
166
+ const pinned = pinnedHere();
167
+ await mkdir(parts);
168
+ await failing(UNDECODABLE, executed(installed(pinned.decoder), ['-nostdin', '-hide_banner', '-loglevel', 'error', '-i', audio, '-ar', '16000', '-ac', '1', '-c:a', 'pcm_s16le',
169
+ '-f', 'segment', '-segment_time', String(CHUNK_SECONDS), join(parts, '%05d.wav')], signal));
170
+ const segments = (await readdir(parts)).sort().flatMap((part) => ['-f', join(parts, part)]);
171
+ const said = await failing(UNTRANSCRIBED, executed(installed(pinned.engine), ['-t', String(await threads()), '-np', '-m', installed(MODEL), ...segments], signal));
172
+ const text = said
173
+ .split('\n')
174
+ .map((line) => line.trim())
175
+ .filter((line) => line !== '')
176
+ .join(' ');
177
+ if (text === '')
178
+ throw new Error(UNTRANSCRIBED);
179
+ return text;
180
+ }
181
+ async function alone(work, signal) {
109
182
  const before = held;
110
183
  let release;
111
184
  const mine = new Promise((resolve) => {
@@ -114,9 +187,24 @@ export async function transcribe(path, signal) {
114
187
  held = Promise.all([before, mine]);
115
188
  try {
116
189
  await unlessAborted(before, signal);
117
- return await transcribed(path, signal);
190
+ return await work();
118
191
  }
119
192
  finally {
120
193
  release();
121
194
  }
122
195
  }
196
+ export async function transcribe(address, signal) {
197
+ ready();
198
+ const work = await mkdtemp(join(tmpdir(), 'kit-transcription-'));
199
+ try {
200
+ const audio = join(work, 'audio');
201
+ await failing(NOT_DOWNLOADED, downloaded(address, (url) => fetched(url, signal), audio, 'audio'));
202
+ return await alone(() => {
203
+ ready();
204
+ return transcribed(audio, join(work, 'parts'), signal);
205
+ }, signal);
206
+ }
207
+ finally {
208
+ await rm(work, { recursive: true, force: true });
209
+ }
210
+ }
package/dist/translate.js CHANGED
@@ -3,14 +3,8 @@ function same(left, right) {
3
3
  return JSON.stringify(left) === JSON.stringify(right);
4
4
  }
5
5
  function applied(document, changes) {
6
- let current = document;
7
- for (const change of changes) {
8
- const result = apply(current, change);
9
- if (result.outcome !== 'applied')
10
- return null;
11
- current = result.document;
12
- }
13
- return serialize(current);
6
+ const result = apply(document, changes);
7
+ return result.outcome === 'applied' ? serialize(result.document) : null;
14
8
  }
15
9
  function components(path, before, after, text) {
16
10
  const edits = [];
package/dist/update.js CHANGED
@@ -4,11 +4,15 @@ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
4
4
  import { homedir } from 'node:os';
5
5
  import { join } from 'node:path';
6
6
  import { run } from './clis.js';
7
- import { kitHome } from './home.js';
8
- const RECORD = 'outcome=$1; shift; bash "$0" --linux "$@"; printf %s "$?" > "$outcome"; systemctl start house-kit.service';
9
- function logged(error) {
10
- process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
11
- }
7
+ import { kitHome, workspaceRoot } from './home.js';
8
+ import { service, throughSudo } from './placement.js';
9
+ import { relayed } from './relay.js';
10
+ const BOOTSTRAP_BYTES = 1_000_000;
11
+ // A bootstrap is at most a million bytes, so two minutes carry it over ten kilobytes a second and no stalled host holds the update queue.
12
+ const BOOTSTRAP_MS = 120_000;
13
+ // A bootstrap's downloads and CLI updates take minutes, so one still running after an hour has hung and is ended before it keeps the Kit offline.
14
+ const RERUN_MS = 60 * 60_000;
15
+ const TIMED_OUT = '124';
12
16
  function directory() {
13
17
  return join(kitHome(), 'update');
14
18
  }
@@ -18,10 +22,25 @@ function pending() {
18
22
  function outcome() {
19
23
  return join(directory(), 'outcome');
20
24
  }
21
- function unit(inputId) {
22
- return `house-kit-update-${inputId}`;
25
+ function unit(callId) {
26
+ return `house-kit-update-${callId}`;
27
+ }
28
+ function manager() {
29
+ return service() === 'user' ? ['--user'] : [];
30
+ }
31
+ function elevated() {
32
+ return throughSudo() ? ['sudo', '-n'] : [];
33
+ }
34
+ function account() {
35
+ return throughSudo() ? [`--uid=${process.getuid()}`, `--gid=${process.getgid()}`] : [];
36
+ }
37
+ function placement() {
38
+ return service() === 'user' ? ['--workspace', workspaceRoot()] : ['--linux'];
23
39
  }
24
- async function pendingInput() {
40
+ function record() {
41
+ return `outcome=$1; shift; timeout ${RERUN_MS / 1000} bash "$0" "$@"; printf %s "$?" > "$outcome"; ${[...elevated(), 'systemctl', ...manager(), 'start', 'house-kit.service'].join(' ')}`;
42
+ }
43
+ async function pendingCall() {
25
44
  try {
26
45
  return JSON.parse(await readFile(pending(), 'utf8')).input_id;
27
46
  }
@@ -33,85 +52,130 @@ async function recorded() {
33
52
  const status = await readFile(outcome(), 'utf8').catch(() => null);
34
53
  if (status === null)
35
54
  return null;
55
+ if (status.trim() === TIMED_OUT)
56
+ return { refused: `the Kit bootstrap did not finish within ${RERUN_MS / 1000} seconds` };
36
57
  return status.trim() === '0' ? {} : { refused: `the Kit bootstrap exited with ${status.trim()}` };
37
58
  }
38
- async function finished(inputId) {
59
+ async function forget(callId) {
60
+ if ((await pendingCall()) !== callId)
61
+ return;
62
+ await rm(pending(), { force: true });
63
+ await rm(outcome(), { force: true });
64
+ }
65
+ async function finished(callId) {
39
66
  for (;;) {
40
- const ack = await recorded();
41
- if (ack !== null)
42
- return ack;
43
- if ((await run('systemctl', ['is-active', '--quiet', unit(inputId)], 10_000)).status !== 0) {
67
+ const result = await recorded();
68
+ if (result !== null)
69
+ return result;
70
+ // systemctl answers at once, so ten seconds only bounds a stuck service manager.
71
+ if ((await run('systemctl', [...manager(), 'is-active', '--quiet', unit(callId)], 10_000)).status !== 0) {
44
72
  return (await recorded()) ?? { refused: 'the Kit bootstrap did not finish' };
45
73
  }
74
+ // The bootstrap runs for minutes, so checking each second sees its outcome within a second at little cost.
46
75
  await new Promise((resolve) => setTimeout(resolve, 1000));
47
76
  }
48
77
  }
49
- function rerun(script, inputId, flags) {
78
+ async function bounded(body, most) {
79
+ const chunks = [];
80
+ let bytes = 0;
81
+ for await (const chunk of body ?? []) {
82
+ bytes += chunk.length;
83
+ if (bytes > most)
84
+ return null;
85
+ chunks.push(chunk);
86
+ }
87
+ return Buffer.concat(chunks, bytes);
88
+ }
89
+ function rerun(script, callId, flags) {
50
90
  return new Promise((resolve) => {
51
- const child = spawn('systemd-run', [
91
+ const [command, ...args] = [
92
+ ...elevated(),
93
+ 'systemd-run',
94
+ ...manager(),
95
+ ...account(),
52
96
  '--wait',
53
97
  '--collect',
54
98
  '--quiet',
55
- `--unit=${unit(inputId)}`,
99
+ `--unit=${unit(callId)}`,
56
100
  `--setenv=HOME=${homedir()}`,
101
+ `--setenv=HOUSE_KIT_HOME=${kitHome()}`,
57
102
  '/bin/sh',
58
103
  '-c',
59
- RECORD,
104
+ record(),
60
105
  script,
61
106
  outcome(),
107
+ ...placement(),
62
108
  ...flags,
63
- ], { stdio: ['ignore', 'ignore', 'inherit'] });
64
- child.on('error', () => resolve({ refused: 'no service manager runs this Kit' }));
109
+ ];
110
+ const child = spawn(command, args, { stdio: ['ignore', 'ignore', 'inherit'] });
111
+ child.on('error', () => resolve({ refused: 'no service manager runs this Kit process' }));
65
112
  child.on('close', () => resolve(null));
66
113
  });
67
114
  }
68
- export class Updates {
69
- house;
70
- held = new Set();
115
+ export class KitUpdate {
116
+ calls;
117
+ changed;
118
+ waiting = new Map();
71
119
  queue = Promise.resolve();
72
- constructor(house) {
73
- this.house = house;
120
+ constructor(calls, changed) {
121
+ this.calls = calls;
122
+ this.changed = changed;
74
123
  }
75
124
  async resumed() {
76
- const inputId = await pendingInput();
77
- if (inputId === null)
125
+ const callId = await pendingCall();
126
+ if (callId === null)
78
127
  return;
79
- await this.acknowledge(inputId, await finished(inputId));
128
+ await this.enqueue(callId, () => finished(callId));
80
129
  }
81
- start(input) {
82
- if (this.held.has(input.input_id))
83
- return;
84
- this.held.add(input.input_id);
85
- this.queue = this.queue
86
- .then(() => this.carry(input))
87
- .then((ack) => this.acknowledge(input.input_id, ack))
88
- .catch(logged)
89
- .finally(() => this.held.delete(input.input_id));
130
+ hold(call) {
131
+ this.waiting.set(call.input_id, call);
132
+ this.changed();
133
+ }
134
+ held() {
135
+ return this.waiting.size > 0;
136
+ }
137
+ apply(resume) {
138
+ const held = [...this.waiting.values()];
139
+ this.waiting.clear();
140
+ void Promise.all(held.map((call) => this.enqueue(call.input_id, () => this.carry(call)))).then(resume);
90
141
  }
91
- async carry(input) {
92
- if ((await pendingInput()) === input.input_id)
93
- return finished(input.input_id);
94
- const answer = await fetch(input.bootstrap);
95
- if (!answer.ok)
96
- return { refused: `the Kit bootstrap could not be downloaded: ${answer.status}` };
97
- const script = Buffer.from(await answer.arrayBuffer());
98
- if (createHash('sha256').update(script).digest('hex') !== input.sha256) {
142
+ enqueue(callId, work) {
143
+ const before = this.queue;
144
+ const carried = this.calls.carry(callId, async () => {
145
+ await before;
146
+ return { result: await work(), returned: () => forget(callId) };
147
+ });
148
+ this.queue = before.then(() => carried);
149
+ return carried;
150
+ }
151
+ async carry(call) {
152
+ if ((await pendingCall()) === call.input_id)
153
+ return finished(call.input_id);
154
+ const deadline = AbortSignal.timeout(BOOTSTRAP_MS);
155
+ let script;
156
+ try {
157
+ const answer = await fetch(relayed(call.bootstrap), { signal: deadline });
158
+ if (!answer.ok)
159
+ return { refused: `the Kit bootstrap could not be downloaded: ${answer.status}` };
160
+ script = await bounded(answer.body, BOOTSTRAP_BYTES);
161
+ }
162
+ catch (error) {
163
+ if (!deadline.aborted)
164
+ throw error;
165
+ return { refused: `the Kit bootstrap did not arrive within ${BOOTSTRAP_MS / 1000} seconds` };
166
+ }
167
+ if (script === null)
168
+ return { refused: `the Kit bootstrap is larger than ${BOOTSTRAP_BYTES} bytes` };
169
+ if (createHash('sha256').update(script).digest('hex') !== call.sha256) {
99
170
  return { refused: 'the Kit bootstrap does not match its sha256' };
100
171
  }
101
172
  await mkdir(directory(), { recursive: true, mode: 0o700 });
102
173
  const path = join(directory(), 'connect-linux.sh');
103
174
  await writeFile(path, script, { mode: 0o700 });
104
175
  await rm(outcome(), { force: true });
105
- await writeFile(pending(), `${JSON.stringify({ input_id: input.input_id })}\n`, { mode: 0o600 });
106
- return (await rerun(path, input.input_id, input.update_clis ? ['--update-clis'] : [])) ?? (await recorded()) ?? {
176
+ await writeFile(pending(), `${JSON.stringify({ input_id: call.input_id })}\n`, { mode: 0o600 });
177
+ return (await rerun(path, call.input_id, call.update_clis ? ['--update-clis'] : [])) ?? (await recorded()) ?? {
107
178
  refused: 'the Kit bootstrap did not finish',
108
179
  };
109
180
  }
110
- async acknowledge(inputId, ack) {
111
- await this.house.deliver(`/kit/inputs/${inputId}/ack`, ack);
112
- if ((await pendingInput()) !== inputId)
113
- return;
114
- await rm(pending(), { force: true });
115
- await rm(outcome(), { force: true });
116
- }
117
181
  }
package/dist/wire.js ADDED
@@ -0,0 +1,22 @@
1
+ import { newerThanHouse, updateRequired } from './end.js';
2
+ import { machine } from './placement.js';
3
+ import { refusalOf } from './refusals.js';
4
+ export const KIT_WIRE = 3;
5
+ export const KIT_WIRE_HEADER = 'x-house-kit-wire';
6
+ function newer(text) {
7
+ let body;
8
+ try {
9
+ body = JSON.parse(text);
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ return body?.error?.code === 'kit_newer_than_house' ? body.error : null;
15
+ }
16
+ export function endUnserved(text) {
17
+ if (refusalOf(text)?.code === 'kit_update_required')
18
+ updateRequired();
19
+ const refused = newer(text);
20
+ if (refused !== null)
21
+ newerThanHouse(refused.release, refused.commands[machine()]);
22
+ }