@agentshouse/kit 0.2.1-cf268dff1869b → 0.2.1-cf2c570b41f24

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 (54) hide show
  1. package/README.md +18 -25
  2. package/dist/acp.js +12 -9
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +72 -26
  5. package/dist/api.js +18 -4
  6. package/dist/binaries.js +60 -0
  7. package/dist/bridge.js +99 -44
  8. package/dist/calls.js +18 -1
  9. package/dist/chunks.js +54 -0
  10. package/dist/clis.js +33 -15
  11. package/dist/connect.js +121 -0
  12. package/dist/connection.js +25 -10
  13. package/dist/content.js +106 -0
  14. package/dist/conversations.js +251 -158
  15. package/dist/copies.js +1260 -599
  16. package/dist/earlier.js +273 -0
  17. package/dist/end.js +6 -9
  18. package/dist/events.js +544 -297
  19. package/dist/files.js +77 -11
  20. package/dist/git.js +0 -70
  21. package/dist/grok.js +39 -0
  22. package/dist/home.js +86 -22
  23. package/dist/house-cli.js +145 -162
  24. package/dist/instructions.js +2 -4
  25. package/dist/keys.js +238 -0
  26. package/dist/kit-cli.js +14 -4
  27. package/dist/login.js +34 -20
  28. package/dist/logout.js +2 -2
  29. package/dist/manifest.js +75 -0
  30. package/dist/mcp.js +43 -7
  31. package/dist/owner.js +46 -0
  32. package/dist/placement.js +0 -6
  33. package/dist/refusals.js +50 -23
  34. package/dist/resident.js +117 -76
  35. package/dist/scripts.js +79 -15
  36. package/dist/secret-input.js +1 -1
  37. package/dist/settings.js +247 -0
  38. package/dist/sign-in.js +49 -4
  39. package/dist/supervisor.js +163 -0
  40. package/dist/transcription.js +5 -2
  41. package/dist/update.js +31 -22
  42. package/dist/wire.js +2 -10
  43. package/dist/work.js +27 -2
  44. package/dist/workspace.js +113 -0
  45. package/package.json +12 -8
  46. package/dist/authority-main.js +0 -22
  47. package/dist/chatgpt.js +0 -32
  48. package/dist/configure-main.js +0 -6
  49. package/dist/enrol-main.js +0 -10
  50. package/dist/git-main.js +0 -153
  51. package/dist/parts.js +0 -82
  52. package/dist/service-main.js +0 -9
  53. package/dist/service.js +0 -55
  54. package/dist/translate.js +0 -45
@@ -0,0 +1,247 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, mkdir, readdir, rm, stat } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import { house } from './api.js';
5
+ import { KIT_RELEASE } from './clis.js';
6
+ import { LocalCopies } from './copies.js';
7
+ import { earlierPrefix, enrolled, houseFolder, kitHome, readDisconnected, oneFolder, readConfiguration, readEnrolment, readHome, storedConfiguration, workspaceRoot, writeConfiguration, writeHome, } from './home.js';
8
+ import { askOwner, holdOwner } from './owner.js';
9
+ import { placeSkillSet } from './skills.js';
10
+ import { followRoot, merged, present, within } from './workspace.js';
11
+ const FOLDERS = ['agents', 'rooms'];
12
+ const RECORDS = join('local-copies', 'rooms');
13
+ const MOVE = 'workspace-move.json';
14
+ const WORKING = 'an Agent is working; change the workspace once its turn ends';
15
+ const UNCHOSEN = "Kit is logged out, so it cannot tell which Agents' folders their owners chose";
16
+ const LOGGED_OUT = `${UNCHOSEN}; run kit login, then change its workspace`;
17
+ export const SETTINGS_USAGE = 'usage: kit settings [skills on|off | workspace <absolute path>]';
18
+ export async function enrolledRoutes() {
19
+ if (enrolled())
20
+ return (await house.act('agents/desired/list', {})).routes;
21
+ return (await readDisconnected()) === null ? [] : null;
22
+ }
23
+ export async function launchDirectories() {
24
+ return ((await enrolledRoutes()) ?? []).map(({ working_directory }) => resolve(working_directory));
25
+ }
26
+ const IDLE = { working: () => false, end: () => undefined, routes: enrolledRoutes };
27
+ export async function heldSettings() {
28
+ return { skills: (await readConfiguration()).skills, workspace: workspaceRoot() };
29
+ }
30
+ function records() {
31
+ return join(kitHome(), RECORDS);
32
+ }
33
+ function placing(kept) {
34
+ return (source) => {
35
+ if (kept.includes(source))
36
+ return 'stays';
37
+ return kept.some((folder) => within(folder, source)) ? 'opens' : 'moves';
38
+ };
39
+ }
40
+ function causeOf(error) {
41
+ return error instanceof Error ? error.message : String(error);
42
+ }
43
+ async function writable(root) {
44
+ for (let at = root;; at = dirname(at)) {
45
+ const found = await stat(at).catch((error) => {
46
+ if (error.code === 'ENOENT')
47
+ return null;
48
+ throw error;
49
+ });
50
+ if (found !== null) {
51
+ return found.isDirectory() && access(at, constants.W_OK | constants.X_OK).then(() => true, () => false);
52
+ }
53
+ if (dirname(at) === at)
54
+ return false;
55
+ }
56
+ }
57
+ async function refusedRoot(from, to) {
58
+ for (const name of FOLDERS) {
59
+ const moving = join(from, name);
60
+ if (within(to, moving))
61
+ return `${to} is inside ${moving}, which the change moves`;
62
+ }
63
+ if (!(await writable(to)))
64
+ return `this account cannot write ${to}`;
65
+ for (const name of FOLDERS) {
66
+ const held = join(to, name);
67
+ if ((await present(held)) === null)
68
+ continue;
69
+ return `${to} already holds ${held}`;
70
+ }
71
+ return null;
72
+ }
73
+ async function forward({ from, to, kept = [] }) {
74
+ await mkdir(to, { recursive: true, mode: 0o700 });
75
+ for (const name of FOLDERS)
76
+ await merged(join(from, name), join(to, name), placing(kept));
77
+ await followRoot(records(), from, to, kept);
78
+ await writeConfiguration({ ...(await storedConfiguration()), workspace: to });
79
+ await rm(join(kitHome(), MOVE), { force: true });
80
+ }
81
+ async function backward({ from, to, kept = [] }) {
82
+ for (const name of FOLDERS)
83
+ await merged(join(to, name), join(from, name), placing([]));
84
+ await followRoot(records(), to, from, kept);
85
+ await rm(join(kitHome(), MOVE), { force: true });
86
+ }
87
+ async function finished(move) {
88
+ try {
89
+ await forward(move);
90
+ return null;
91
+ }
92
+ catch (error) {
93
+ const cause = causeOf(error);
94
+ try {
95
+ await backward(move);
96
+ return cause;
97
+ }
98
+ catch (again) {
99
+ return `${cause}; its folders could not all go back to ${move.from} (${causeOf(again)}), so Kit moves them again when it next starts`;
100
+ }
101
+ }
102
+ }
103
+ export async function resumeWorkspaceMove() {
104
+ const move = await readHome(MOVE);
105
+ if (move === null)
106
+ return;
107
+ process.stderr.write(`kit: moving the workspace ${move.from} to ${move.to}, as a change that did not finish asked\n`);
108
+ const failure = await finished(move);
109
+ if (failure !== null)
110
+ process.stderr.write(`kit: the workspace could not be moved to ${move.to}: ${failure}\n`);
111
+ }
112
+ export const HOUSE_NOT_KITS = `${houseFolder()} holds what is not Kit's; move it elsewhere, then run this command again`;
113
+ async function free(folder, from) {
114
+ if ((await present(folder)) !== null) {
115
+ const held = await stat(folder).catch(() => null);
116
+ if (held === null || !held.isDirectory() || (await readdir(folder)).length > 0)
117
+ return false;
118
+ }
119
+ return (await refusedRoot(from, folder)) === null;
120
+ }
121
+ async function earlierLayout(root) {
122
+ const copies = await readdir(join(root, RECORDS), { withFileTypes: true }).catch(() => []);
123
+ if (copies.some((entry) => entry.isDirectory() && !entry.name.startsWith('.')))
124
+ return true;
125
+ return root === kitHome() && (await present(join(root, 'agents'))) !== null && (await present(join(root, 'rooms'))) === null;
126
+ }
127
+ export async function houseRoot() {
128
+ if (await earlierLayout(kitHome()))
129
+ return kitHome();
130
+ return (await free(houseFolder(), kitHome())) ? houseFolder() : null;
131
+ }
132
+ function chosenFolders(routes, from) {
133
+ const agents = join(from, 'agents');
134
+ const roots = [agents, join(from, 'rooms'), join(from, RECORDS)];
135
+ return routes
136
+ .filter(({ agent_id, working_directory }) => resolve(working_directory) !== join(agents, agent_id))
137
+ .map(({ working_directory }) => resolve(working_directory))
138
+ .filter((folder) => roots.some((root) => folder.startsWith(`${root}/`)));
139
+ }
140
+ export async function moveIntoHouse(copies) {
141
+ if (earlierPrefix() !== null)
142
+ return null;
143
+ const stored = await storedConfiguration();
144
+ const from = stored.workspace ?? kitHome();
145
+ if (!(await earlierLayout(from))) {
146
+ if (stored.workspace !== undefined)
147
+ return null;
148
+ const root = await houseRoot();
149
+ if (root === null)
150
+ throw new Error(HOUSE_NOT_KITS);
151
+ await writeConfiguration({ ...stored, workspace: root });
152
+ return null;
153
+ }
154
+ if (stored.workspace === undefined)
155
+ await writeConfiguration({ ...stored, workspace: from });
156
+ const routes = await enrolledRoutes().catch((error) => {
157
+ process.stderr.write(`kit: the workspace stays at ${from} and moves at the next start: ${causeOf(error)}\n`);
158
+ return undefined;
159
+ });
160
+ if (routes === undefined)
161
+ return null;
162
+ if (routes === null) {
163
+ process.stderr.write(`kit: the workspace stays at ${from} and moves at the next start: ${UNCHOSEN}; run kit login\n`);
164
+ return null;
165
+ }
166
+ const chosen = chosenFolders(routes, from);
167
+ const to = from === kitHome() && (await free(houseFolder(), from)) ? houseFolder() : from;
168
+ const laid = await copies.laidOut(join(from, RECORDS), join(from, 'rooms'), chosen);
169
+ if (to === from)
170
+ return laid.moved ? `Kit ${KIT_RELEASE} laid out its workspace ${from}; its supervisor starts it again` : null;
171
+ const move = { from, to, kept: [...chosen, ...laid.kept] };
172
+ await writeHome(MOVE, move);
173
+ const failure = await finished(move);
174
+ if (failure === null)
175
+ return `Kit ${KIT_RELEASE} moved its workspace to ${to}; its supervisor starts it there`;
176
+ return `the workspace could not be moved to ${to}: ${failure}; it stays at ${from} and its supervisor starts Kit again`;
177
+ }
178
+ async function changeSkills(on) {
179
+ const stored = await storedConfiguration();
180
+ await writeConfiguration({ ...stored, skills: on });
181
+ const enrolment = await readEnrolment();
182
+ if (enrolment !== null)
183
+ await placeSkillSet(enrolment.house);
184
+ }
185
+ export async function applySettings(change, kit) {
186
+ const from = workspaceRoot();
187
+ let move = null;
188
+ if (change.workspace !== undefined) {
189
+ if (earlierPrefix() !== null) {
190
+ return { refused: `Kit runs where an earlier install placed it; its workspace changes once Kit moves into ${oneFolder()}`, ended: false };
191
+ }
192
+ if (!isAbsolute(change.workspace))
193
+ return { refused: `${change.workspace} is not an absolute path`, ended: false };
194
+ const to = resolve(change.workspace);
195
+ if (to !== from) {
196
+ const refused = await refusedRoot(from, to);
197
+ if (refused !== null)
198
+ return { refused, ended: false };
199
+ const routes = await kit.routes();
200
+ if (routes === null)
201
+ return { refused: LOGGED_OUT, ended: false };
202
+ move = { from, to, kept: chosenFolders(routes, from) };
203
+ }
204
+ }
205
+ if (move !== null) {
206
+ if (kit.working())
207
+ return { refused: WORKING, ended: false };
208
+ kit.end();
209
+ await writeHome(MOVE, move);
210
+ const failure = await finished(move);
211
+ if (failure !== null)
212
+ return { refused: `the workspace could not be moved to ${move.to}: ${failure}`, ended: true };
213
+ }
214
+ if (change.skills !== undefined)
215
+ await changeSkills(change.skills);
216
+ return { settings: await heldSettings(), moved: move !== null };
217
+ }
218
+ function changeOf(operands) {
219
+ const [name, value, ...rest] = operands;
220
+ if (name === undefined)
221
+ return null;
222
+ if (rest.length === 0 && name === 'skills' && (value === 'on' || value === 'off'))
223
+ return { skills: value === 'on' };
224
+ if (rest.length === 0 && name === 'workspace' && value !== undefined)
225
+ return { workspace: value };
226
+ throw new Error(SETTINGS_USAGE);
227
+ }
228
+ async function appliedHere(change) {
229
+ const lock = await holdOwner();
230
+ try {
231
+ await resumeWorkspaceMove();
232
+ const copies = new LocalCopies(house, launchDirectories);
233
+ await copies.load();
234
+ await moveIntoHouse(copies);
235
+ return await applySettings(change, IDLE);
236
+ }
237
+ finally {
238
+ lock.close();
239
+ }
240
+ }
241
+ export async function kitSettings(operands) {
242
+ const change = changeOf(operands);
243
+ const answer = change === null ? { settings: await heldSettings(), moved: false } : ((await askOwner('/settings', change)) ?? (await appliedHere(change)));
244
+ if ('refused' in answer)
245
+ throw new Error(answer.refused);
246
+ process.stdout.write(`skills ${answer.settings.skills ? 'on' : 'off'}\nworkspace ${answer.settings.workspace}\n`);
247
+ }
package/dist/sign-in.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createInterface } from 'node:readline';
3
- import { CLIS } from './clis.js';
4
- import { childEnvironment } from './relay.js';
3
+ import { CLIS, cliEnvironment } from './clis.js';
5
4
  import { killTree } from './scope.js';
6
5
  import { holdSecretInput } from './secret-input.js';
7
6
  const ESCAPE = /\u001b\[[\d;]*m/g;
@@ -10,6 +9,33 @@ const CODE = /^[A-Z0-9]+-[A-Z0-9]+$/;
10
9
  function causeOf(error) {
11
10
  return error instanceof Error ? error.message : String(error);
12
11
  }
12
+ function keySteps(name) {
13
+ return [
14
+ { kind: 'collect', label: 'API key', name: 'key' },
15
+ {
16
+ kind: 'collect',
17
+ label: 'Endpoint, for another provider',
18
+ name: 'endpoint',
19
+ description: `Leave Endpoint empty for ${name}’s own. Both stay on this computer.`,
20
+ optional: true,
21
+ },
22
+ ];
23
+ }
24
+ function endpointOf(given) {
25
+ const endpoint = given.trim();
26
+ if (endpoint === '')
27
+ return null;
28
+ let protocol;
29
+ try {
30
+ protocol = new URL(endpoint).protocol;
31
+ }
32
+ catch {
33
+ protocol = '';
34
+ }
35
+ if (protocol !== 'https:' && protocol !== 'http:')
36
+ throw new Error('the endpoint is no http or https address');
37
+ return endpoint;
38
+ }
13
39
  function endOf(signal) {
14
40
  return new Promise((resolve) => signal.addEventListener('abort', () => resolve(true), { once: true }));
15
41
  }
@@ -36,15 +62,34 @@ export class SignIns {
36
62
  return ended ? { result: {} } : { result: {}, returned: () => this.agents.reread(call.cli) };
37
63
  }
38
64
  async signedIn(call, signal) {
39
- await this.login(call, signal);
65
+ await (call.api_key === true ? this.keyed(call, signal) : this.login(call, signal));
40
66
  if (!signal.aborted)
41
67
  await this.agents.recheck(call.cli, signal);
42
68
  return false;
43
69
  }
70
+ async keyed(call, signal) {
71
+ const { name, key } = CLIS[call.cli];
72
+ let secret = '';
73
+ try {
74
+ const cli = await this.agents.located(call.cli, signal);
75
+ const given = await holdSecretInput(this.house, call.input_id, keySteps(name), () => !signal.aborted);
76
+ if (given === null || signal.aborted)
77
+ return;
78
+ secret = given.key.trim();
79
+ await key.write(secret, endpointOf(given.endpoint), cli, signal);
80
+ }
81
+ catch (error) {
82
+ const cause = secret === '' ? causeOf(error) : causeOf(error).replaceAll(secret, 'the key');
83
+ if (!signal.aborted)
84
+ process.stderr.write(`kit: the ${call.cli} sign-in failed: ${cause}\n`);
85
+ }
86
+ }
44
87
  async login(call, signal) {
45
88
  let cli;
89
+ let env;
46
90
  try {
47
91
  cli = await this.agents.located(call.cli, signal);
92
+ env = await cliEnvironment(call.cli);
48
93
  }
49
94
  catch (error) {
50
95
  if (!signal.aborted)
@@ -57,7 +102,7 @@ export class SignIns {
57
102
  const child = spawn(cli, login.args, {
58
103
  stdio: ['pipe', 'pipe', 'pipe'],
59
104
  detached: true,
60
- env: childEnvironment(),
105
+ env,
61
106
  });
62
107
  const running = () => child.exitCode === null && child.signalCode === null;
63
108
  const stop = () => killTree(child);
@@ -0,0 +1,163 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { oneFolder } from './home.js';
8
+ const SERVICE = 'house-kit';
9
+ const UNIT = `${SERVICE}.service`;
10
+ // launchctl, loginctl and systemctl answer at once and lingering starts the account's service manager within a second, so ten seconds only bound a stuck one.
11
+ const MANAGER_MS = 10_000;
12
+ // The service manager lingering starts answers within a second, so a check every tenth of a second starts Kit as soon as it does.
13
+ const MANAGER_CHECK_MS = 100;
14
+ // A Kit that failed restarts after five seconds, back soon without spinning on a failure that repeats; a Kit that ended itself stays stopped.
15
+ const RESTART_SECONDS = 5;
16
+ export function userUnit() {
17
+ return join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'systemd', 'user', UNIT);
18
+ }
19
+ export function launchAgent() {
20
+ return join(homedir(), 'Library', 'LaunchAgents', `${SERVICE}.plist`);
21
+ }
22
+ export function launcher() {
23
+ return join(oneFolder(), 'bin', 'kit');
24
+ }
25
+ export function systemd() {
26
+ return existsSync('/run/systemd/system');
27
+ }
28
+ function userBus() {
29
+ if (process.env.XDG_RUNTIME_DIR)
30
+ return process.env;
31
+ return { ...process.env, XDG_RUNTIME_DIR: `/run/user/${process.getuid()}` };
32
+ }
33
+ export function manage(command, args) {
34
+ return spawnSync(command, args, { encoding: 'utf8', timeout: MANAGER_MS, env: command === 'systemctl' ? userBus() : process.env });
35
+ }
36
+ export function required(command, args, failed) {
37
+ const ran = manage(command, args);
38
+ if (ran.status === 0)
39
+ return;
40
+ const cause = ran.error?.message ?? (ran.stderr.trim() || `${command} exited with ${ran.status ?? 'a signal'}`);
41
+ throw new Error(`${failed}: ${cause}`);
42
+ }
43
+ function unitWord(text) {
44
+ return `"${text.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%')}"`;
45
+ }
46
+ function xmlText(text) {
47
+ return text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
48
+ }
49
+ function unitText() {
50
+ return `[Unit]
51
+ Description=Kit
52
+
53
+ [Service]
54
+ ExecStart=${unitWord(launcher())} resident
55
+ Restart=on-failure
56
+ RestartSec=${RESTART_SECONDS}
57
+ Delegate=yes
58
+ OOMPolicy=continue
59
+
60
+ [Install]
61
+ WantedBy=default.target
62
+ `;
63
+ }
64
+ function plistText() {
65
+ return `<?xml version="1.0" encoding="UTF-8"?>
66
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
67
+ <plist version="1.0">
68
+ <dict>
69
+ \t<key>Label</key>
70
+ \t<string>${SERVICE}</string>
71
+ \t<key>ProgramArguments</key>
72
+ \t<array>
73
+ \t\t<string>${xmlText(launcher())}</string>
74
+ \t\t<string>resident</string>
75
+ \t</array>
76
+ \t<key>RunAtLoad</key>
77
+ \t<true/>
78
+ \t<key>KeepAlive</key>
79
+ \t<dict>
80
+ \t\t<key>SuccessfulExit</key>
81
+ \t\t<false/>
82
+ \t</dict>
83
+ \t<key>ProcessType</key>
84
+ \t<string>Interactive</string>
85
+ \t<key>StandardErrorPath</key>
86
+ \t<string>${xmlText(join(oneFolder(), 'kit.log'))}</string>
87
+ </dict>
88
+ </plist>
89
+ `;
90
+ }
91
+ async function define(path, text) {
92
+ if ((await readFile(path, 'utf8').catch(() => null)) === text)
93
+ return false;
94
+ await mkdir(dirname(path), { recursive: true });
95
+ await writeFile(`${path}.new`, text);
96
+ await rename(`${path}.new`, path);
97
+ return true;
98
+ }
99
+ export function defineSupervisor() {
100
+ return process.platform === 'darwin' ? define(launchAgent(), plistText()) : define(userUnit(), unitText());
101
+ }
102
+ export async function linger() {
103
+ required('loginctl', ['enable-linger', String(process.getuid())], 'lingering could not be turned on for this account');
104
+ if (process.getuid() === 0)
105
+ required('systemctl', ['start', 'user@0.service'], "root's service manager could not be started");
106
+ const stuck = Date.now() + MANAGER_MS;
107
+ while (manage('systemctl', ['--user', 'show-environment']).status !== 0) {
108
+ if (Date.now() >= stuck) {
109
+ throw new Error(`this account's service manager did not start within ${MANAGER_MS / 1000} seconds; restart this computer, then run this command again`);
110
+ }
111
+ await delay(MANAGER_CHECK_MS);
112
+ }
113
+ }
114
+ function macos() {
115
+ const target = `gui/${process.getuid()}`;
116
+ return { target, service: `${target}/${SERVICE}` };
117
+ }
118
+ export async function supervise(changed, restart) {
119
+ if (process.platform === 'darwin') {
120
+ const { target, service } = macos();
121
+ const printed = manage('launchctl', ['print', service]);
122
+ const loaded = printed.status === 0;
123
+ if (loaded && changed)
124
+ required('launchctl', ['bootout', service], 'the Kit service could not be stopped');
125
+ if (!loaded || changed) {
126
+ manage('launchctl', ['enable', service]);
127
+ required('launchctl', ['bootstrap', target, launchAgent()], 'the Kit service could not be started');
128
+ }
129
+ else if (restart) {
130
+ required('launchctl', ['kickstart', '-k', service], 'the Kit service could not be restarted');
131
+ }
132
+ else if (!/^\tstate = running$/m.test(printed.stdout)) {
133
+ required('launchctl', ['kickstart', service], 'the Kit service could not be started');
134
+ }
135
+ return;
136
+ }
137
+ await linger();
138
+ if (changed)
139
+ required('systemctl', ['--user', 'daemon-reload'], 'systemd could not read the Kit service');
140
+ required('systemctl', ['--user', '--quiet', 'enable', UNIT], 'the Kit service could not be enabled');
141
+ if (manage('systemctl', ['--user', '--quiet', 'is-active', UNIT]).status !== 0) {
142
+ required('systemctl', ['--user', 'start', UNIT], 'the Kit service could not be started');
143
+ }
144
+ else if (changed || restart) {
145
+ required('systemctl', ['--user', 'restart', UNIT], 'the Kit service could not be restarted');
146
+ }
147
+ }
148
+ export function startService() {
149
+ if (process.platform === 'darwin') {
150
+ const { service } = macos();
151
+ const printed = manage('launchctl', ['print', service]);
152
+ if (printed.status !== 0 || /^\tstate = running$/m.test(printed.stdout))
153
+ return false;
154
+ required('launchctl', ['kickstart', service], 'the Kit service could not be started');
155
+ return true;
156
+ }
157
+ if (manage('systemctl', ['--user', '--quiet', 'is-enabled', UNIT]).status !== 0)
158
+ return false;
159
+ if (manage('systemctl', ['--user', '--quiet', 'is-active', UNIT]).status === 0)
160
+ return false;
161
+ required('systemctl', ['--user', 'start', UNIT], 'the Kit service could not be started');
162
+ return true;
163
+ }
@@ -1,6 +1,7 @@
1
1
  import { chmod, mkdir, mkdtemp, readdir, readFile, rename, rm, stat } from 'node:fs/promises';
2
2
  import { availableParallelism, tmpdir } from 'node:os';
3
3
  import { basename, join } from 'node:path';
4
+ import { isDeepStrictEqual } from 'node:util';
4
5
  import { unlessAborted } from './abort.js';
5
6
  import { downloadServed } from './building.js';
6
7
  import { failureOf, run } from './clis.js';
@@ -125,7 +126,7 @@ async function install(artifacts, signal) {
125
126
  }
126
127
  }
127
128
  function reported(next) {
128
- const changed = next.installed !== readiness.installed || next.failure !== readiness.failure;
129
+ const changed = !isDeepStrictEqual(next, readiness);
129
130
  readiness = next;
130
131
  return changed;
131
132
  }
@@ -137,10 +138,12 @@ async function settle(transcribe) {
137
138
  await rm(directory(), { recursive: true, force: true });
138
139
  return reported({ installed: false, failure: null });
139
140
  }
141
+ const pinned = pinnedHere();
142
+ if (pinned === undefined)
143
+ return reported({ installed: false, failure: null, no_engine: true });
140
144
  const download = new AbortController();
141
145
  downloading = download;
142
146
  try {
143
- const pinned = pinnedHere();
144
147
  await install([pinned.decoder, pinned.engine, MODEL], download.signal);
145
148
  return reported({ installed: true, failure: null });
146
149
  }
package/dist/update.js CHANGED
@@ -3,7 +3,7 @@ import { mkdir } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { downloadServed, servedRelease } from './building.js';
5
5
  import { KIT_RELEASE } from './clis.js';
6
- import { restart, updateLine } from './end.js';
6
+ import { restartPlaced, updateLine } from './end.js';
7
7
  import { kitHome, readEnrolment } from './home.js';
8
8
  import { placedPrefix } from './placement.js';
9
9
  import { childEnvironment, relayOrigin } from './relay.js';
@@ -58,6 +58,27 @@ function placing(installer, house, prefix, signal) {
58
58
  });
59
59
  });
60
60
  }
61
+ async function placed(prefix, admit) {
62
+ const signal = AbortSignal.timeout(PLACEMENT_MS);
63
+ let version = '';
64
+ try {
65
+ const placedIn = prefix();
66
+ const served = await servedRelease(signal);
67
+ admit(served.version);
68
+ version = served.version;
69
+ await mkdir(join(kitHome(), 'update'), { recursive: true, mode: 0o700 });
70
+ const installer = join(kitHome(), 'update', served.installer);
71
+ await downloadServed(served.installer, served.sha256, installer, signal, INSTALLER_BYTES);
72
+ return { version, failure: await placing(installer, (await readEnrolment()).house, placedIn, signal) };
73
+ }
74
+ catch (error) {
75
+ return { version, failure: signal.aborted ? `the placement did not end within ${PLACEMENT_MS / 1000} seconds` : causeOf(error) };
76
+ }
77
+ }
78
+ export async function placeServedRelease(prefix) {
79
+ const { version, failure } = await placed(() => prefix, () => undefined);
80
+ return failure === null ? null : `${version === '' ? "The Building's Kit release" : `Kit ${version}`} could not be placed: ${failure}`;
81
+ }
61
82
  export class KitUpdate {
62
83
  calls;
63
84
  queue = Promise.resolve();
@@ -72,7 +93,7 @@ export class KitUpdate {
72
93
  for (;;) {
73
94
  const failure = await this.queued(async () => (this.placed === null ? this.place(release, 'served') : null));
74
95
  if (failure === null)
75
- restart(`Kit ${this.placed} is placed; its supervisor starts it`);
96
+ restartPlaced(this.placed);
76
97
  process.stderr.write(`kit: ${updateLine(`Kit ${KIT_RELEASE} stays offline and tries again in ${PLACEMENT_RETRY_MS / 60_000} minutes`)}\n`);
77
98
  await new Promise((resolve) => setTimeout(resolve, PLACEMENT_RETRY_MS));
78
99
  }
@@ -93,31 +114,19 @@ export class KitUpdate {
93
114
  const failure = await this.place(release, 'named');
94
115
  if (failure !== null)
95
116
  return { refused: failure };
96
- process.stderr.write(`kit: Kit ${release} is placed; it starts once no turn is open\n`);
117
+ const starts = process.env.HOUSE_KIT_SANDBOX === '1' ? 'when the Sandbox starts again' : 'once no turn is open';
118
+ process.stderr.write(`kit: Kit ${release} is placed; it starts ${starts}\n`);
97
119
  return {};
98
120
  }
99
121
  async place(release, which) {
100
- const signal = AbortSignal.timeout(PLACEMENT_MS);
101
- let version = release;
102
- let failure;
103
- try {
104
- const prefix = placedPrefix();
105
- const served = await servedRelease(signal);
106
- if (which === 'named' && served.version !== release)
107
- throw new Error(`the Building serves Kit ${served.version}, not Kit ${release}`);
108
- version = served.version;
109
- if (version === KIT_RELEASE)
122
+ const { version, failure } = await placed(placedPrefix, (served) => {
123
+ if (which === 'named' && served !== release)
124
+ throw new Error(`the Building serves Kit ${served}, not Kit ${release}`);
125
+ if (served === KIT_RELEASE)
110
126
  throw new Error(`the Building serves Kit ${KIT_RELEASE}, which this Kit runs`);
111
- await mkdir(join(kitHome(), 'update'), { recursive: true, mode: 0o700 });
112
- const installer = join(kitHome(), 'update', served.installer);
113
- await downloadServed(served.installer, served.sha256, installer, signal, INSTALLER_BYTES);
114
- failure = await placing(installer, (await readEnrolment()).house, prefix, signal);
115
- }
116
- catch (error) {
117
- failure = signal.aborted ? `the placement did not end within ${PLACEMENT_MS / 1000} seconds` : causeOf(error);
118
- }
127
+ });
119
128
  if (failure !== null) {
120
- const refused = `Kit ${version} could not be placed: ${failure}`;
129
+ const refused = `Kit ${version || release} could not be placed: ${failure}`;
121
130
  process.stderr.write(`kit: ${refused}\n`);
122
131
  return refused;
123
132
  }
package/dist/wire.js CHANGED
@@ -1,8 +1,5 @@
1
- import { newerThanHouse, updateRequired } from './end.js';
2
- import { machine } from './placement.js';
1
+ import { updateRequired } from './end.js';
3
2
  import { refusalOf } from './refusals.js';
4
- export const KIT_WIRE = 4;
5
- export const KIT_WIRE_HEADER = 'x-house-kit-wire';
6
3
  let take = null;
7
4
  let taken = false;
8
5
  function unservedBy(text) {
@@ -13,10 +10,7 @@ function unservedBy(text) {
13
10
  catch {
14
11
  return null;
15
12
  }
16
- const error = body?.error;
17
- if (error?.code !== 'kit_update_required' && error?.code !== 'kit_newer_than_house')
18
- return null;
19
- return typeof error.release === 'string' ? error : null;
13
+ return body?.error?.code === 'kit_update_required' ? body.error : null;
20
14
  }
21
15
  export function takeUnservedRelease(taking) {
22
16
  take = taking;
@@ -35,6 +29,4 @@ export function endUnserved(text) {
35
29
  }
36
30
  if (refusalOf(text)?.code === 'kit_update_required')
37
31
  updateRequired();
38
- if (refused?.code === 'kit_newer_than_house')
39
- newerThanHouse(refused.release, refused.commands[machine()]);
40
32
  }