@agentshouse/kit 0.2.1-c5d36e97b0fea → 0.2.1-c8179f06883b6

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.
package/README.md CHANGED
@@ -1,14 +1,12 @@
1
1
  # House Kit
2
2
 
3
- House Kit connects an Environment, a Linux computer or server, to
4
- [agents.house](https://agents.house). It runs your Agents' conversations
5
- through the agent CLIs you chose and gives each Agent the `house` command.
3
+ House Kit connects an Environment, a Linux computer or server, to [agents.house](https://agents.house). It runs
4
+ your Agents' conversations through the agent CLIs you chose and gives each Agent the `house` command.
6
5
 
7
6
  ## Install
8
7
 
9
- Run `curl -fsSL agents.house/kit | sh`, or `irm agents.house/kit.ps1 | iex` on
10
- Windows, and again to update; options follow `sh -s --`. On macOS and Linux it
11
- installs House Kit natively under your own account, without an admin password,
8
+ Run `curl -fsSL agents.house/kit | sh`, or `irm agents.house/kit.ps1 | iex` on Windows, and again to update;
9
+ options follow `sh -s --`. On macOS and Linux it installs House Kit natively under your own account, without an admin password,
12
10
  as a service that runs while you are logged in. `kit` and `house` are then on
13
11
  your login shell's `PATH`, and your workspace is `~/AgentsHouse` unless you
14
12
  pass `--workspace <path>`.
@@ -20,7 +18,7 @@ workspace. On Windows 11 the container is the one choice. Append a `kit` or
20
18
  Running the command for the other choice on a connected computer asks you to
21
19
  confirm, then replaces its Environment, whose Agents end, with a new one.
22
20
 
23
- On your own Ubuntu 26.04 server, run the Linux command with `--linux` to
21
+ On your own Linux server, run the Linux command with `--linux` to
24
22
  install House Kit natively, with its workspace at `/agents/house`; `kit` and
25
23
  `house` are then on the server's `PATH`.
26
24
 
@@ -33,22 +31,24 @@ them out; running it again without the flag brings them back.
33
31
 
34
32
  ## Commands
35
33
 
36
- `kit login` opens or prints a link you confirm in any browser, on this
37
- computer or another, continues on its own and keeps the Environment's
38
- credential in `~/.house-kit`, or in `$HOUSE_KIT_HOME` when it is set. Pass
39
- `--environment <id>` to reconnect an Environment you already have. It also
40
- connects your own agent: outside an Agent conversation, `house <tool>` calls
41
- House as you and `git` clones and pushes your Apps at `<house>/app/` as you,
42
- until you revoke that connection on Connections. `house help` lists the Tools.
43
- `kit logout` disconnects this computer, stops House Kit and ends your own
44
- agent's connection, so `house` and `git` no longer act as you here; a later
45
- `kit login` reconnects the same Environment.
46
-
47
- `kit resident` keeps the Environment connected and the Rooms you chose for it
48
- as Git repositories under `local-copies` in the workspace. `house fetch`
49
- records House's changes on each copy's `refs/house/received`; rebase onto it,
50
- commit and run `house push --owner` in the copy, through the install command in
51
- the container. An Agent runs both, without `--owner`.
34
+ `kit login` opens or prints a link you confirm in any browser, on this computer
35
+ or another, continues on its own and keeps the Environment's credential in
36
+ `~/.house-kit`, or in `$HOUSE_KIT_HOME` when it is set. `--environment <id>`
37
+ reconnects an Environment you already have; `--rooms <ref>[,<ref>...]` gives it
38
+ only those Rooms and `--no-private` every Room but your Private Room; `--code <code>` connects immediately without a link.
39
+ A login also connects your own agent: outside an Agent conversation, `house <tool>` calls
40
+ House as you and `git` clones and pushes your Apps at `<house>/app/` as you, until you revoke
41
+ that connection on Connections. `house help` lists the Tools. Codex sessions started after a
42
+ login run a lone `house` command outside their sandbox. `kit logout` disconnects this
43
+ computer, stops House Kit and ends your own agent's connection, so `house` and `git` no
44
+ longer act as you here; a later `kit login` reconnects the same Environment.
45
+ `kit codex --key <key>` starts Codex with `house` acting as you through a key made on Connections; next time, just `kit codex`.
46
+
47
+ `kit resident` keeps the Environment connected and, as it connects, copies each
48
+ Room you chose for it as a Git repository in the workspace's `local-copies`.
49
+ `house fetch` records House's changes on each copy's `refs/house/received`;
50
+ rebase onto it, commit and run `house push --owner` in the copy, through the
51
+ install command in the container. An Agent runs both, without `--owner`.
52
52
 
53
53
  House Kit turns each audio file of your message to an Agent into text on this
54
54
  computer before the Agent reads it. While transcription is on, the speech
package/dist/agents.js CHANGED
@@ -3,8 +3,10 @@ import { readFile, realpath } from 'node:fs/promises';
3
3
  import { startAdapter } from './acp.js';
4
4
  import { CLIS, KIT_VERSION, below, installAdapter, installCli, locate, run, versionOf } from './clis.js';
5
5
  import { agentBase, kitHome } from './home.js';
6
+ import { updatesItself } from './placement.js';
6
7
  import { killTree } from './scope.js';
7
8
  import { holdTranscription, transcriptionReport } from './transcription.js';
9
+ import { KIT_WIRE } from './wire.js';
8
10
  const SIGNED_OUT = { signed_in: false, models: [], modes: [] };
9
11
  function select(options, category) {
10
12
  const option = options.find((candidate) => candidate.category === category);
@@ -257,7 +259,7 @@ export class Agents {
257
259
  }
258
260
  async load(kind) {
259
261
  const known = this.readings.get(kind);
260
- if (known !== undefined && known.failure === null)
262
+ if (known !== undefined && known.failure === null && known.minimum === undefined)
261
263
  return;
262
264
  await this.examine(kind, SIGNED_OUT, offer);
263
265
  }
@@ -270,6 +272,8 @@ export class Agents {
270
272
  const body = {
271
273
  os: await operatingSystem(),
272
274
  kit_version: KIT_VERSION,
275
+ wire: KIT_WIRE,
276
+ updates_itself: await updatesItself(),
273
277
  agent_base: agentBase(),
274
278
  agents,
275
279
  transcription: transcriptionReport(),
package/dist/api.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
- import { end, SIGN_IN_AGAIN } from './end.js';
2
+ import { signInAgain, updateRequired } from './end.js';
3
3
  import { readEnrolment } from './home.js';
4
4
  import { retryable } from './refusals.js';
5
5
  import { relayed } from './relay.js';
6
+ import { KIT_WIRE, KIT_WIRE_HEADER, tooOld } from './wire.js';
6
7
  export class HouseRefusal extends Error {
7
8
  status;
8
9
  text;
@@ -37,12 +38,15 @@ export async function post(house, path, body, credential, signal) {
37
38
  method: 'POST',
38
39
  headers: {
39
40
  'content-type': 'application/json',
41
+ [KIT_WIRE_HEADER]: String(KIT_WIRE),
40
42
  ...(credential === undefined ? {} : { authorization: `Bearer ${credential}` }),
41
43
  },
42
44
  body: JSON.stringify(body),
43
45
  signal,
44
46
  });
45
47
  const text = await answer.text();
48
+ if (!answer.ok && tooOld(text))
49
+ updateRequired(house);
46
50
  if (!answer.ok)
47
51
  throw new HouseRefusal(path, answer.status, text);
48
52
  return JSON.parse(text);
@@ -54,7 +58,7 @@ async function enrolledPost(path, body, signal) {
54
58
  }
55
59
  catch (error) {
56
60
  if (error instanceof HouseRefusal && error.status === 401)
57
- end(SIGN_IN_AGAIN);
61
+ await signInAgain(credential);
58
62
  throw error;
59
63
  }
60
64
  }
@@ -1,23 +1,23 @@
1
1
  {
2
2
  "schemaVersion": 2,
3
- "version": "0.2.1-c5d36e97b0fea",
3
+ "version": "0.2.1-c8179f06883b6",
4
4
  "hosts": {
5
5
  "macos": {
6
6
  "asset": {
7
7
  "name": "connect-linux.sh",
8
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c5d36e97b0fea/connect-linux.sh"
8
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c8179f06883b6/connect-linux.sh"
9
9
  }
10
10
  },
11
11
  "linux": {
12
12
  "asset": {
13
13
  "name": "connect-linux.sh",
14
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c5d36e97b0fea/connect-linux.sh"
14
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c8179f06883b6/connect-linux.sh"
15
15
  }
16
16
  },
17
17
  "windows": {
18
18
  "asset": {
19
19
  "name": "connect-windows.ps1",
20
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c5d36e97b0fea/connect-windows.ps1"
20
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c8179f06883b6/connect-windows.ps1"
21
21
  }
22
22
  }
23
23
  }
package/dist/clis.js CHANGED
@@ -1,9 +1,13 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { constants, readFileSync } from 'node:fs';
3
- import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
4
4
  import { homedir, userInfo } from 'node:os';
5
- import { delimiter, isAbsolute, join } from 'node:path';
5
+ import { delimiter, dirname, isAbsolute, join } from 'node:path';
6
6
  import { kitHome } from './home.js';
7
+ const HOUSE_EXECUTABLES = /^host_executable\(name = "house", paths = (\[.*\])\)$/m;
8
+ function houseRule(houses) {
9
+ return `prefix_rule(pattern = ["house"], decision = "allow")\nhost_executable(name = "house", paths = ${JSON.stringify(houses)})\n`;
10
+ }
7
11
  const RAW_SUBTYPES = [
8
12
  'background_tasks_changed',
9
13
  'task_started',
@@ -13,7 +17,7 @@ const RAW_SUBTYPES = [
13
17
  'hook_started',
14
18
  'hook_response',
15
19
  ];
16
- async function executable(path) {
20
+ export async function executable(path) {
17
21
  try {
18
22
  await access(path, constants.X_OK);
19
23
  return true;
@@ -22,15 +26,37 @@ async function executable(path) {
22
26
  return false;
23
27
  }
24
28
  }
25
- async function allowHouseInCodex(path) {
29
+ async function listedHouses(file) {
30
+ let text;
31
+ try {
32
+ text = await readFile(file, 'utf8');
33
+ }
34
+ catch (error) {
35
+ if (error.code === 'ENOENT')
36
+ return [];
37
+ throw error;
38
+ }
39
+ try {
40
+ const listed = JSON.parse(HOUSE_EXECUTABLES.exec(text)?.[1] ?? '[]');
41
+ return Array.isArray(listed) ? listed.filter((house) => typeof house === 'string') : [];
42
+ }
43
+ catch {
44
+ return [];
45
+ }
46
+ }
47
+ export async function allowHouseInCodex(path) {
26
48
  const candidates = [...new Set(path.split(delimiter).filter((directory) => isAbsolute(directory)))].map((directory) => join(directory, 'house'));
27
- const houses = [];
28
- for (const candidate of candidates)
29
- if (await executable(candidate))
30
- houses.push(candidate);
31
49
  const rules = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'rules');
50
+ const file = join(rules, 'house.rules');
51
+ const houses = [];
52
+ for (const house of [...(await listedHouses(file)), ...candidates]) {
53
+ if (!houses.includes(house) && (await executable(house)))
54
+ houses.push(house);
55
+ }
32
56
  await mkdir(rules, { recursive: true });
33
- await writeFile(join(rules, 'house.rules'), `prefix_rule(pattern = ["house"], decision = "allow")\nhost_executable(name = "house", paths = ${JSON.stringify(houses)})\n`);
57
+ const temporary = `${file}.${process.pid}`;
58
+ await writeFile(temporary, houseRule(houses));
59
+ await rename(temporary, file);
34
60
  }
35
61
  async function nothing() { }
36
62
  function bridgeInClaudeSandbox(bridge) {
@@ -198,6 +224,12 @@ export async function loginPath() {
198
224
  const ran = await inLoginShell(`printf "${marker}%s\\n" "$PATH"`);
199
225
  return ran.stdout.split('\n').findLast((line) => line.startsWith(marker)).slice(marker.length);
200
226
  }
227
+ export async function writeCodexRule() {
228
+ const shell = await loginPath().catch(() => '');
229
+ await allowHouseInCodex([dirname(process.execPath), process.env.PATH ?? '', shell].join(delimiter)).catch((error) => {
230
+ throw new Error(`Codex's rule for house could not be written: ${error.message}`);
231
+ });
232
+ }
201
233
  export async function versionOf(path, signal) {
202
234
  return VERSION.exec((await run(path, ['--version'], READ_MS, false, signal)).stdout)?.[0] ?? null;
203
235
  }
package/dist/codex.js ADDED
@@ -0,0 +1,61 @@
1
+ import { homedir } from 'node:os';
2
+ import { delimiter, join, resolve } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { CLIS, executable, writeCodexRule } from './clis.js';
5
+ import { kitHome, readOwnAgent, writeOwnAgent } from './home.js';
6
+ import { accepted, DEFAULT_HOUSE } from './login.js';
7
+ const USAGE = `usage: kit codex [--key <key>] [--house <origin>] [<codex argument>...]
8
+ --key <key> a key from New key for a script on Connections, kept for later runs
9
+ --house <origin> the House of the key, ${DEFAULT_HOUSE} unless one is stored
10
+ `;
11
+ const VALUED = ['--key', '--house'];
12
+ const KEY_SOURCE = 'New key for a script on Connections';
13
+ function codexArgumentsStart(argv) {
14
+ let index = 0;
15
+ while (index < argv.length) {
16
+ const arg = argv[index];
17
+ if (VALUED.includes(arg))
18
+ index += 2;
19
+ else if (arg === '--help' || VALUED.some((option) => arg.startsWith(`${option}=`)))
20
+ index += 1;
21
+ else
22
+ break;
23
+ }
24
+ return index;
25
+ }
26
+ async function onPath(name) {
27
+ for (const directory of (process.env.PATH ?? '').split(delimiter)) {
28
+ const path = resolve(directory, name);
29
+ if (await executable(path))
30
+ return path;
31
+ }
32
+ throw new Error(`${name} is not on your PATH; install it with ${CLIS['codex-acp'].install}`);
33
+ }
34
+ export async function codex(argv) {
35
+ const start = codexArgumentsStart(argv);
36
+ const { values } = parseArgs({
37
+ args: argv.slice(0, start),
38
+ options: { key: { type: 'string' }, house: { type: 'string' }, help: { type: 'boolean', default: false } },
39
+ });
40
+ if (values.help) {
41
+ process.stdout.write(USAGE);
42
+ return;
43
+ }
44
+ process.env.HOUSE_KIT_HOME = resolve(process.env.HOUSE_KIT_HOME || join(homedir(), '.house-kit-outside'));
45
+ const stored = await readOwnAgent();
46
+ if (values.key !== undefined) {
47
+ const house = values.house ?? stored?.house ?? DEFAULT_HOUSE;
48
+ if (!(await accepted(house, values.key)))
49
+ throw new Error(`${house} does not accept this key; pass one from ${KEY_SOURCE}`);
50
+ await writeOwnAgent({ house, credential: values.key });
51
+ }
52
+ else if (values.house !== undefined) {
53
+ throw new Error('--house names the House of a --key; pass the key with it');
54
+ }
55
+ else if (stored === null) {
56
+ throw new Error(`${kitHome()} holds no House key; pass --key with one from ${KEY_SOURCE}`);
57
+ }
58
+ await writeCodexRule();
59
+ const path = await onPath('codex');
60
+ process.execve(path, [path, ...argv.slice(start)], process.env);
61
+ }
@@ -17,6 +17,7 @@ import { createHowWeWork } from './skills.js';
17
17
  import { transcribe } from './transcription.js';
18
18
  import { workFor } from './work.js';
19
19
  const KILLED = 'the conversation was killed';
20
+ export const CONVERSATION_INPUTS = new Set(['open', 'message', 'interrupt', 'kill', 'option', 'answer']);
20
21
  function causeOf(error) {
21
22
  return error instanceof Error ? error.message : String(error);
22
23
  }
@@ -132,6 +133,9 @@ export class Conversations {
132
133
  return false;
133
134
  return !conversations.some((conversation) => conversation.running?.scope.working() || [...conversation.leftovers].some((scope) => scope.working()));
134
135
  }
136
+ quiet() {
137
+ return this.idle() && [...this.conversations.values()].every((conversation) => conversation.open === 0);
138
+ }
135
139
  look() {
136
140
  for (const conversation of this.conversations.values()) {
137
141
  for (const scope of conversation.leftovers) {
@@ -499,7 +503,7 @@ export class Conversations {
499
503
  if (conversation.turn === turn)
500
504
  conversation.turn = null;
501
505
  const body = Promise.allSettled(turn.uploads).then(() => ({
502
- parts: turn.parts.parts,
506
+ parts: turn.parts.saved(),
503
507
  context: turn.parts.context,
504
508
  ...failed,
505
509
  }));
@@ -644,7 +648,7 @@ export class Conversations {
644
648
  turn.parts.plan(event.entries);
645
649
  return;
646
650
  case 'image':
647
- turn.uploads.push(this.image(conversation, turn, event.data, event.mediaType));
651
+ turn.uploads.push(this.image(conversation, turn, turn.parts.reserve(), event.data, event.mediaType));
648
652
  this.kit.changed();
649
653
  return;
650
654
  }
@@ -664,7 +668,7 @@ export class Conversations {
664
668
  else
665
669
  conversation.turn.parts.start(part);
666
670
  }
667
- async image(conversation, turn, data, mediaType) {
671
+ async image(conversation, turn, reserved, data, mediaType) {
668
672
  const bytes = Buffer.from(data, 'base64');
669
673
  const name = `image-${++turn.images}.${mediaType.split('/')[1]}`;
670
674
  try {
@@ -677,10 +681,10 @@ export class Conversations {
677
681
  const saved = declared.upload === undefined ? declared : await uploadBytes(declared.upload, bytes);
678
682
  if (saved.save.status !== 'saved')
679
683
  throw new Error(saved.save.failure ?? saved.save.status);
680
- turn.parts.start({ type: 'image', file: saved.version, name, media_type: mediaType });
684
+ turn.parts.arrive({ type: 'image', file: saved.version, name, media_type: mediaType }, reserved);
681
685
  }
682
686
  catch (error) {
683
- turn.parts.start({ type: 'marker', marker: 'retry', text: `${name} was not saved: ${causeOf(error)}` });
687
+ turn.parts.arrive({ type: 'marker', marker: 'retry', text: `${name} was not saved: ${causeOf(error)}` }, reserved);
684
688
  }
685
689
  }
686
690
  }
package/dist/copies.js CHANGED
@@ -42,7 +42,7 @@ function expiredAuthority(error) {
42
42
  return undefined;
43
43
  try {
44
44
  const { error: refused } = JSON.parse(error.text);
45
- return refused?.code === 'position_expired' && typeof refused.authority === 'string' ? refused.authority : undefined;
45
+ return refused?.code === 'expired' && typeof refused.authority === 'string' ? refused.authority : undefined;
46
46
  }
47
47
  catch {
48
48
  return undefined;
@@ -168,7 +168,7 @@ export class LocalCopies {
168
168
  house;
169
169
  copies = new Map();
170
170
  queues = new Map();
171
- selecting = Promise.resolve();
171
+ answering = Promise.resolve();
172
172
  constructor(house) {
173
173
  this.house = house;
174
174
  this.owner = {
@@ -200,39 +200,39 @@ export class LocalCopies {
200
200
  }
201
201
  }
202
202
  async mapping() {
203
- await this.selecting;
203
+ await this.answering;
204
204
  return [...this.copies.values()]
205
205
  .filter((copy) => copy.active)
206
206
  .map((copy) => `${rootOf(copy.room_handle)}: ${copy.repository}`)
207
207
  .sort();
208
208
  }
209
- async select() {
210
- const selected = await this.selected(() => this.fetched(false));
211
- if (selected.refused)
212
- logged(selected.text);
209
+ async connected() {
210
+ const copied = await this.answered(() => this.fetched(false));
211
+ if (copied.refused)
212
+ logged(copied.text);
213
213
  }
214
214
  fetch() {
215
- return this.selected(() => this.fetched(true));
215
+ return this.answered(() => this.fetched(true));
216
216
  }
217
- selected(work) {
218
- const selected = this.selecting.then(work);
219
- this.selecting = selected.catch(() => undefined);
220
- return selected;
217
+ answered(work) {
218
+ const answered = this.answering.then(work);
219
+ this.answering = answered.catch(() => undefined);
220
+ return answered;
221
221
  }
222
222
  async fetched(refreshing) {
223
- const { local_copy: chosen } = await this.house.post('/kit/local-copy/selection', {});
224
- const selected = new Map(chosen.rooms.map((room) => [`rooms/${room.room_ref}`, room.room_handle]));
225
- return this.holding([...new Set([...this.copies.keys(), ...selected.keys()])].sort(), async () => {
223
+ const { local_copy: answer } = await this.house.post('/kit/local-copy/selection', {});
224
+ const synced = new Map(answer.rooms.map((room) => [`rooms/${room.room_ref}`, room.room_handle]));
225
+ return this.holding([...new Set([...this.copies.keys(), ...synced.keys()])].sort(), async () => {
226
226
  const said = [];
227
227
  let refused = false;
228
228
  for (const copy of this.copies.values()) {
229
- if (selected.has(copy.key) || !copy.active)
229
+ if (synced.has(copy.key) || !copy.active)
230
230
  continue;
231
231
  await this.save({ ...copy, active: false });
232
232
  said.push(`${rootOf(copy.room_handle)}: no longer synced to this Environment; its files stay`);
233
233
  }
234
234
  const current = [];
235
- for (const [key, handle] of selected) {
235
+ for (const [key, handle] of synced) {
236
236
  try {
237
237
  const held = this.copies.get(key);
238
238
  if (held === undefined || !(await exists(held.repository))) {
@@ -623,7 +623,7 @@ export class LocalCopies {
623
623
  const { upload, ...unstaged } = copy.push;
624
624
  return this.settle(await this.save({ ...copy, push: unstaged }), caller, true);
625
625
  }
626
- if (outcome.refused.code === 'operation_expired')
626
+ if (outcome.refused.code === 'expired')
627
627
  return this.recovered(copy);
628
628
  const rebased = rebaseFixes(outcome.refused);
629
629
  let settled = await this.save(without(copy));
package/dist/end.js CHANGED
@@ -1,8 +1,22 @@
1
+ import { forgetRejected } from './home.js';
2
+ import { installCommand } from './placement.js';
1
3
  import { killDescendants } from './scope.js';
2
4
  export const REPLACED = 'another Kit started for this Environment';
3
- export const SIGN_IN_AGAIN = 'sign in again';
4
- export function end(reason) {
5
+ function exit(reason, status) {
5
6
  process.stderr.write(`kit: ${reason}\n`);
6
7
  killDescendants();
7
- process.exit(0);
8
+ process.exit(status);
9
+ }
10
+ export function end(reason) {
11
+ exit(reason, 0);
12
+ }
13
+ export function restart(reason) {
14
+ exit(reason, 1);
15
+ }
16
+ export function updateRequired(house) {
17
+ end(`This Kit is too old for House. Update it: ${installCommand(house)}`);
18
+ }
19
+ export async function signInAgain(rejected) {
20
+ await forgetRejected(rejected);
21
+ restart('sign in again');
8
22
  }
@@ -1,4 +1,10 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { writeEnrolment } from './home.js';
3
3
  const [house, environment] = process.argv.slice(2);
4
- await writeEnrolment({ house: house, environment: environment, credential: readFileSync(0, 'utf8').trim() });
4
+ const relay = process.env.HOUSE_KIT_RELAY || undefined;
5
+ await writeEnrolment({
6
+ house: house,
7
+ ...(relay === undefined ? {} : { relay }),
8
+ environment: environment,
9
+ credential: readFileSync(0, 'utf8').trim(),
10
+ });
package/dist/home.js CHANGED
@@ -1,11 +1,13 @@
1
- import { existsSync } from 'node:fs';
1
+ import { existsSync, linkSync, readFileSync, renameSync, rmSync } from 'node:fs';
2
2
  import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
+ import { selectRelay } from './relay.js';
5
6
  const ENROLMENT = 'credential.json';
6
7
  const DISCONNECTED = 'disconnected.json';
7
8
  const CONFIGURATION = 'kit.json';
8
9
  const OWN_AGENT = 'own-agent.json';
10
+ const RESTART = 'restart';
9
11
  export function kitHome() {
10
12
  return process.env.HOUSE_KIT_HOME ?? join(homedir(), '.house-kit');
11
13
  }
@@ -32,8 +34,11 @@ export async function writeHome(name, value) {
32
34
  await writeFile(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600 });
33
35
  await rename(temporary, join(home, name));
34
36
  }
35
- export function readEnrolment() {
36
- return readHome(ENROLMENT);
37
+ export async function readEnrolment() {
38
+ const enrolment = await readHome(ENROLMENT);
39
+ if (enrolment !== null)
40
+ selectRelay(process.env.HOUSE_KIT_RELAY || enrolment.relay);
41
+ return enrolment;
37
42
  }
38
43
  export async function writeEnrolment(enrolment) {
39
44
  await writeHome(ENROLMENT, enrolment);
@@ -46,9 +51,42 @@ export async function forgetEnrolment({ house, environment }) {
46
51
  await writeHome(DISCONNECTED, { house, environment });
47
52
  await rm(join(kitHome(), ENROLMENT), { force: true });
48
53
  }
54
+ export async function forgetRejected(rejected) {
55
+ const held = await readHome(ENROLMENT);
56
+ if (held?.credential !== rejected)
57
+ return;
58
+ await writeHome(DISCONNECTED, { house: held.house, environment: held.environment });
59
+ const enrolment = join(kitHome(), ENROLMENT);
60
+ const taken = `${enrolment}.${process.pid}`;
61
+ try {
62
+ renameSync(enrolment, taken);
63
+ }
64
+ catch (error) {
65
+ if (error.code === 'ENOENT')
66
+ return;
67
+ throw error;
68
+ }
69
+ if (JSON.parse(readFileSync(taken, 'utf8')).credential !== rejected) {
70
+ try {
71
+ linkSync(taken, enrolment);
72
+ }
73
+ catch (error) {
74
+ if (error.code !== 'EEXIST')
75
+ throw error;
76
+ }
77
+ rmSync(join(kitHome(), DISCONNECTED), { force: true });
78
+ }
79
+ rmSync(taken);
80
+ }
49
81
  export function enrolled() {
50
82
  return existsSync(join(kitHome(), ENROLMENT));
51
83
  }
84
+ export function restartAsked() {
85
+ return existsSync(join(kitHome(), RESTART));
86
+ }
87
+ export function forgetRestart() {
88
+ return rm(join(kitHome(), RESTART), { force: true });
89
+ }
52
90
  export function readOwnAgent() {
53
91
  return readHome(OWN_AGENT);
54
92
  }