@agentshouse/kit 0.2.1-c3e4a20bb3183 → 0.2.1-cb0bd1cadcfed

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/dist/copies.js CHANGED
@@ -2,15 +2,15 @@ import { parse } from '@agentshouse/mdmodel';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises';
4
4
  import { dirname, join } from 'node:path';
5
- import { HouseRefusal } from './api.js';
5
+ import { finalRefusal, HouseRefusal, retrying } from './api.js';
6
6
  import { blobId, blobText, git, HOUSE_REF, importCommits, localCopies, revision, run, succeeded, tree, } from './git.js';
7
7
  import { kitHome } from './home.js';
8
8
  import { operationId } from './operation.js';
9
9
  import { refusalOf } from './refusals.js';
10
10
  import { changed } from './translate.js';
11
+ import { relayed } from './relay.js';
11
12
  const BRANCH = 'main';
12
13
  const PROVENANCE = '_provenance';
13
- const REPLICA_RETRY_MS = 30_000;
14
14
  const IDENTITY = { GIT_COMMITTER_NAME: 'House Kit', GIT_COMMITTER_EMAIL: 'house-kit@localhost' };
15
15
  function causeOf(error) {
16
16
  return error instanceof Error ? error.message : String(error);
@@ -40,11 +40,11 @@ function sidecar(path) {
40
40
  segments.splice(-1, 0, PROVENANCE);
41
41
  return segments.join('/');
42
42
  }
43
- function rootOf(copy) {
44
- return copy.private ? '/private' : `/rooms/${copy.room_handle}`;
43
+ function rootOf(handle) {
44
+ return `/rooms/${handle}`;
45
45
  }
46
46
  function relative(path) {
47
- return path.replace(/^\/private\//, '').replace(/^\/rooms\/[^/]+\//, '');
47
+ return path.replace(/^\/rooms\/[^/]+\//, '');
48
48
  }
49
49
  function declaredWritable(path, copy) {
50
50
  const deepest = (scopes) => Math.max(-1, ...scopes.filter((scope) => covers(path, scope)).map((scope) => scope.length));
@@ -160,11 +160,11 @@ export class LocalCopies {
160
160
  key: 'owner',
161
161
  submit: async (operation, changes) => {
162
162
  try {
163
- const outcome = await house.post('/kit/door/batch', { operation_id: operation, changes });
163
+ const outcome = await retrying(() => house.post('/kit/door/batch', { operation_id: operation, changes }));
164
164
  return { accepted: outcome.contents };
165
165
  }
166
166
  catch (error) {
167
- if (!(error instanceof HouseRefusal) || error.status >= 500)
167
+ if (!finalRefusal(error))
168
168
  throw error;
169
169
  return {
170
170
  refused: refusalOf(error.text) ?? { code: '', text: `House refused it with ${error.status}`, conflicts: [] },
@@ -176,7 +176,7 @@ export class LocalCopies {
176
176
  async load() {
177
177
  const home = join(kitHome(), 'local-copies');
178
178
  const names = (await readdir(join(home, 'rooms')).catch(() => [])).filter((name) => name.endsWith('.json'));
179
- for (const path of [...names.map((name) => join(home, 'rooms', name)), join(home, 'private.json')]) {
179
+ for (const path of names.map((name) => join(home, 'rooms', name))) {
180
180
  const text = await readFile(path, 'utf8').catch(() => null);
181
181
  if (text === null)
182
182
  continue;
@@ -188,7 +188,7 @@ export class LocalCopies {
188
188
  await this.selecting;
189
189
  return [...this.copies.values()]
190
190
  .filter((copy) => copy.active)
191
- .map((copy) => `${rootOf(copy)}: ${copy.repository}`)
191
+ .map((copy) => `${rootOf(copy.room_handle)}: ${copy.repository}`)
192
192
  .sort();
193
193
  }
194
194
  select() {
@@ -198,12 +198,7 @@ export class LocalCopies {
198
198
  }
199
199
  async reselect() {
200
200
  const { local_copy: chosen } = await this.house.post('/kit/local-copy/selection', {});
201
- const selected = [
202
- ...(chosen?.rooms ?? [])
203
- .filter((room) => room.room_handle !== null)
204
- .map((room) => ({ key: `rooms/${room.room_ref}`, private: false, handle: room.room_handle })),
205
- ...(chosen?.private === true ? [{ key: 'private', private: true, handle: null }] : []),
206
- ];
201
+ const selected = (chosen?.rooms ?? []).flatMap((room) => room.room_handle === null ? [] : [{ key: `rooms/${room.room_ref}`, handle: room.room_handle }]);
207
202
  const keys = new Set(selected.map((scope) => scope.key));
208
203
  const work = [];
209
204
  for (const key of this.copies.keys()) {
@@ -255,11 +250,11 @@ export class LocalCopies {
255
250
  async push(cwd, selector, caller) {
256
251
  const located = await run(cwd, ['rev-parse', '--path-format=absolute', '--git-common-dir', '--show-toplevel']);
257
252
  if (located.status !== 0)
258
- return { refused: true, text: `${cwd} is not a House Local copy; run house git push inside one` };
253
+ return { refused: true, text: `${cwd} is not a House Local copy; run house push inside one` };
259
254
  const [common, worktree] = located.stdout.toString('utf8').split('\n');
260
255
  const key = await this.keyAt(dirname(common));
261
256
  if (key === undefined)
262
- return { refused: true, text: `${worktree} is not a House Local copy; run house git push inside one` };
257
+ return { refused: true, text: `${worktree} is not a House Local copy; run house push inside one` };
263
258
  return this.exclusive(key, () => this.pushed(key, worktree, selector, caller));
264
259
  }
265
260
  async keyAt(repository) {
@@ -287,7 +282,7 @@ export class LocalCopies {
287
282
  }).catch(logged);
288
283
  }
289
284
  async save(copy) {
290
- const path = join(kitHome(), 'local-copies', copy.private ? 'private.json' : `${copy.key}.json`);
285
+ const path = join(kitHome(), 'local-copies', `${copy.key}.json`);
291
286
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
292
287
  const temporary = `${path}.${process.pid}`;
293
288
  await writeFile(temporary, JSON.stringify(copy), { mode: 0o600 });
@@ -295,12 +290,12 @@ export class LocalCopies {
295
290
  this.copies.set(copy.key, copy);
296
291
  return copy;
297
292
  }
298
- async read(selected) {
299
- const prefixes = [rootOf(selected)];
293
+ async read(handle) {
294
+ const prefixes = [rootOf(handle)];
300
295
  const discovery = await this.house.post('/kit/door/discover', { prefixes });
301
296
  let bundle = await this.house.post('/kit/door/bootstrap', { prefixes });
302
297
  if ('transfer' in bundle)
303
- bundle = (await (await fetch(bundle.transfer.url)).json());
298
+ bundle = (await (await fetch(relayed(bundle.transfer.url))).json());
304
299
  const [view] = bundle.scopes;
305
300
  if (view === undefined)
306
301
  return null;
@@ -343,13 +338,13 @@ export class LocalCopies {
343
338
  return;
344
339
  }
345
340
  const discovery = await this.house.post('/kit/door/discover', {
346
- prefixes: [rootOf(copy)],
341
+ prefixes: [rootOf(copy.room_handle)],
347
342
  });
348
343
  const authority = discovery.authorities.find((entry) => entry.room_ref === copy.room_ref);
349
344
  if (authority === undefined)
350
345
  return;
351
346
  if (authority.managed_replication !== 'admitted') {
352
- logged(`operation_denied: ${rootOf(copy)} is not synchronized to this Environment`);
347
+ logged(`operation_denied: ${rootOf(copy.room_handle)} is not synchronized to this Environment`);
353
348
  return;
354
349
  }
355
350
  if (JSON.stringify([authority.operations.write, authority.protected_paths]) !==
@@ -360,12 +355,12 @@ export class LocalCopies {
360
355
  await this.save(await this.caughtUp(copy));
361
356
  }
362
357
  async materialize(scope) {
363
- const read = await this.read({ private: scope.private, room_handle: scope.handle });
358
+ const read = await this.read(scope.handle);
364
359
  if (read === null) {
365
- logged(`House serves nothing of ${rootOf({ private: scope.private, room_handle: scope.handle })} to copy`);
360
+ logged(`House serves nothing of ${rootOf(scope.handle)} to copy`);
366
361
  return;
367
362
  }
368
- const repository = scope.private ? join(localCopies(), 'private') : join(localCopies(), 'rooms', read.anchor);
363
+ const repository = join(localCopies(), 'rooms', read.anchor);
369
364
  if (await exists(repository)) {
370
365
  logged(`${repository} already exists and House Kit leaves it as it is`);
371
366
  return;
@@ -377,7 +372,7 @@ export class LocalCopies {
377
372
  try {
378
373
  await git(staging, ['init', '-q', '-b', BRANCH]);
379
374
  house = await importCommits(staging, [
380
- { message: `House ${rootOf({ private: scope.private, room_handle: scope.handle })}`, from: null, files: read.writable },
375
+ { message: `House ${rootOf(scope.handle)}`, from: null, files: read.writable },
381
376
  ]);
382
377
  await git(staging, ['update-ref', `refs/heads/${BRANCH}`, house]);
383
378
  await git(staging, ['reset', '-q', '--hard']);
@@ -391,7 +386,6 @@ export class LocalCopies {
391
386
  }
392
387
  await this.save({
393
388
  key: scope.key,
394
- private: scope.private,
395
389
  room_ref: read.anchor,
396
390
  room_handle: scope.handle,
397
391
  repository,
@@ -407,11 +401,11 @@ export class LocalCopies {
407
401
  });
408
402
  }
409
403
  async received(copy) {
410
- const read = await this.read(copy);
404
+ const read = await this.read(copy.room_handle);
411
405
  if (read === null)
412
406
  return copy;
413
407
  const house = await importCommits(copy.repository, [
414
- { message: `House ${rootOf(copy)} at position ${read.position}`, from: copy.house, replaces: true, files: read.writable },
408
+ { message: `House ${rootOf(copy.room_handle)} at position ${read.position}`, from: copy.house, replaces: true, files: read.writable },
415
409
  ]);
416
410
  const removed = copy.read_only.filter((path) => !read.readOnly.has(path));
417
411
  const readOnly = await readOnlyPlaced(copy.repository, copy.read_only, read.readOnly, removed);
@@ -434,7 +428,7 @@ export class LocalCopies {
434
428
  let answer;
435
429
  try {
436
430
  answer = await this.house.post('/kit/door/enumerate', {
437
- prefixes: [rootOf(copy)],
431
+ prefixes: [rootOf(copy.room_handle)],
438
432
  positions: [{ authority: copy.room_ref, position: copy.position, log_epoch: copy.log_epoch }],
439
433
  });
440
434
  }
@@ -444,7 +438,6 @@ export class LocalCopies {
444
438
  return this.received(copy);
445
439
  if (code !== 'replica_behind')
446
440
  throw error;
447
- setTimeout(() => this.deliver(copy.key), REPLICA_RETRY_MS).unref();
448
441
  return copy;
449
442
  }
450
443
  const view = answer.authorities.find((entry) => entry.authority === copy.room_ref);
@@ -484,7 +477,7 @@ export class LocalCopies {
484
477
  let { house, manifests } = copy;
485
478
  if (files.size > 0) {
486
479
  house = await importCommits(copy.repository, [
487
- { message: `House ${rootOf(copy)} at position ${position}`, from: copy.house, files },
480
+ { message: `House ${rootOf(copy.room_handle)} at position ${position}`, from: copy.house, files },
488
481
  ]);
489
482
  manifests = { ...manifests, [house]: { parent: copy.house, files: revisions } };
490
483
  }
@@ -515,7 +508,7 @@ export class LocalCopies {
515
508
  copy = await this.save(without(copy));
516
509
  }
517
510
  if (!copy.active) {
518
- return { refused: true, text: `${rootOf(copy)} is no longer synced to this Environment, so House takes no push from it` };
511
+ return { refused: true, text: `${rootOf(copy.room_handle)} is no longer synced to this Environment, so House takes no push from it` };
519
512
  }
520
513
  const listed = (await git(copy.repository, ['rev-list', '--topo-order', commit])).split('\n');
521
514
  const base = listed.find((ancestor) => ancestor in copy.manifests);
@@ -549,7 +542,7 @@ export class LocalCopies {
549
542
  return this.settle(submitted, caller);
550
543
  }
551
544
  async derived(copy, base, commit) {
552
- const root = rootOf(copy);
545
+ const root = rootOf(copy.room_handle);
553
546
  const before = await tree(copy.repository, base);
554
547
  const after = await tree(copy.repository, commit);
555
548
  const moved = movedPaths(copy.moves, before, after);
@@ -597,7 +590,7 @@ export class LocalCopies {
597
590
  const refusal = error instanceof HouseRefusal ? refusalOf(error.text) : null;
598
591
  return {
599
592
  refused: true,
600
- text: refusal?.text ?? `House's answer to ${short(push.commit)} did not arrive; run house git push again`,
593
+ text: refusal?.text ?? `House's answer to ${short(push.commit)} did not arrive; run house push again`,
601
594
  };
602
595
  }
603
596
  if ('refused' in outcome) {
@@ -631,12 +624,12 @@ export class LocalCopies {
631
624
  const push = copy.push;
632
625
  const current = await this.save(await this.caughtUp(copy));
633
626
  const house = await tree(copy.repository, current.house);
634
- const root = rootOf(current);
627
+ const root = rootOf(current.room_handle);
635
628
  if (!(await this.landed(copy.repository, push.changes, house, await tree(copy.repository, push.commit)))) {
636
629
  await this.save(without(current));
637
630
  return {
638
631
  refused: true,
639
- text: `House does not hold ${short(push.commit)}; run house git push again`,
632
+ text: `House does not hold ${short(push.commit)}; run house push again`,
640
633
  };
641
634
  }
642
635
  const written = [];
@@ -664,7 +657,7 @@ export class LocalCopies {
664
657
  catch {
665
658
  return {
666
659
  refused: false,
667
- text: `House accepted ${short(commit)}; run house git push again to finish integrating it here`,
660
+ text: `House accepted ${short(commit)}; run house push again to finish integrating it here`,
668
661
  };
669
662
  }
670
663
  }
@@ -687,7 +680,7 @@ export class LocalCopies {
687
680
  written = [
688
681
  ...written,
689
682
  {
690
- path: `${rootOf(copy)}/${path}`,
683
+ path: `${rootOf(copy.room_handle)}/${path}`,
691
684
  revision: entry === undefined ? null : (revisionAt(copy, copy.house, path) ?? null),
692
685
  content: entry === undefined ? null : await blobText(copy.repository, entry, path),
693
686
  },
@@ -707,7 +700,7 @@ export class LocalCopies {
707
700
  }
708
701
  const edits = new Map([...files].filter(([path, content]) => (content === null ? selected.has(path) : selected.get(path) !== blobId(content))));
709
702
  const received = [...files.keys()].filter((path) => revisionAt(copy, copy.house, path) === revisionAt(copy, push.house, path));
710
- const accepted = `House ${rootOf(copy)} with ${push.commit} accepted`;
703
+ const accepted = `House ${rootOf(copy.room_handle)} with ${push.commit} accepted`;
711
704
  const house = await importCommits(copy.repository, [
712
705
  ...(edits.size === 0 ? [] : [{ message: accepted, from: push.commit, files: edits }]),
713
706
  {
package/dist/end.js ADDED
@@ -0,0 +1,8 @@
1
+ import { killDescendants } from './acp.js';
2
+ export const REPLACED = 'another Kit started for this Environment';
3
+ export const SIGN_IN_AGAIN = 'sign in again';
4
+ export function end(reason) {
5
+ process.stderr.write(`kit: ${reason}\n`);
6
+ killDescendants();
7
+ process.exit(0);
8
+ }
package/dist/files.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { mkdir, writeFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
+ import { relayed } from './relay.js';
3
4
  export async function placeFiles(house, directory, files, signal) {
4
5
  const paths = [];
5
6
  for (const file of files) {
6
7
  const original = await house.post('/kit/conversation/originals/get', { version: file.version, download: true }, signal);
7
- const answer = await fetch(original.download.url, { signal });
8
+ const answer = await fetch(relayed(original.download.url), { signal });
8
9
  if (!answer.ok)
9
10
  throw new Error(`${file.name} did not download: ${answer.status}`);
10
11
  const folder = join(directory, '.house', 'files', original.message, file.version);
package/dist/home.js CHANGED
@@ -1,7 +1,9 @@
1
+ import { existsSync } from 'node:fs';
1
2
  import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
2
3
  import { homedir } from 'node:os';
3
4
  import { join } from 'node:path';
4
5
  const ENROLMENT = 'credential.json';
6
+ const DISCONNECTED = 'disconnected.json';
5
7
  const CONFIGURATION = 'kit.json';
6
8
  const OWN_AGENT = 'own-agent.json';
7
9
  export function kitHome() {
@@ -33,8 +35,19 @@ export async function writeHome(name, value) {
33
35
  export function readEnrolment() {
34
36
  return readHome(ENROLMENT);
35
37
  }
36
- export function writeEnrolment(enrolment) {
37
- return writeHome(ENROLMENT, enrolment);
38
+ export async function writeEnrolment(enrolment) {
39
+ await writeHome(ENROLMENT, enrolment);
40
+ await rm(join(kitHome(), DISCONNECTED), { force: true });
41
+ }
42
+ export function readDisconnected() {
43
+ return readHome(DISCONNECTED);
44
+ }
45
+ export async function forgetEnrolment({ house, environment }) {
46
+ await writeHome(DISCONNECTED, { house, environment });
47
+ await rm(join(kitHome(), ENROLMENT), { force: true });
48
+ }
49
+ export function enrolled() {
50
+ return existsSync(join(kitHome(), ENROLMENT));
38
51
  }
39
52
  export function readOwnAgent() {
40
53
  return readHome(OWN_AGENT);
@@ -7,7 +7,8 @@ import { kitHome, readOwnAgent } from './home.js';
7
7
  import { callHouse, rpc, UNREACHABLE } from './mcp.js';
8
8
  import { refusalOf } from './refusals.js';
9
9
  const USAGE = "usage: house <tool> ['<arguments as JSON>']";
10
- const GIT_USAGE = 'usage: house git push [commit] [--owner]';
10
+ const PUSH_USAGE = 'usage: house push [commit] [--owner]';
11
+ const PUSH = "push [commit]: sends the Local copy's committed changes to House";
11
12
  const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
12
13
  const CLOSED = "this conversation's House connection is closed; nothing to do from here";
13
14
  const REVOKED = 'this conversation no longer has House access; nothing to do from here';
@@ -97,17 +98,15 @@ async function upload(path, roomRef, missing) {
97
98
  throw new Error(`${path} was not saved: ${saved.upload_failure}; call again later`);
98
99
  return saved.attachment;
99
100
  }
100
- async function gitPush(args) {
101
+ async function push(args) {
101
102
  if (args.includes('--help'))
102
- return GIT_USAGE;
103
- if (args[0] !== 'push')
104
- throw new Error('only house git push [commit] exists; use plain git for the rest');
103
+ return PUSH_USAGE;
105
104
  const owner = args.includes('--owner');
106
- const commit = args.slice(1).find((arg) => arg !== '--owner') ?? 'HEAD';
105
+ const commit = args.find((arg) => arg !== '--owner') ?? 'HEAD';
107
106
  if (owner && socketPath !== undefined)
108
- throw new Error('--owner is not for Agent conversations; run house git push without it');
107
+ throw new Error('--owner is not for Agent conversations; run house push without it');
109
108
  if (!owner && socketPath === undefined)
110
- throw new Error('outside an Agent conversation, house git push needs --owner');
109
+ throw new Error('outside an Agent conversation, house push needs --owner');
111
110
  const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, undefined, owner ? join(kitHome(), 'owner.sock') : socketPath));
112
111
  if (pushed.refused)
113
112
  throw new Error(pushed.text);
@@ -128,14 +127,14 @@ function argumentsOf(argument) {
128
127
  return parsed;
129
128
  }
130
129
  async function house([verb, argument]) {
131
- if (verb === undefined || verb === '--help') {
132
- return [USAGE, 'git push [commit]', ...(await tools()).map((tool) => `${tool.name}: ${tool.description}`)].join('\n');
130
+ if (verb === undefined || verb === '--help' || verb === 'help') {
131
+ return [USAGE, 'help', PUSH, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
133
132
  }
134
133
  if (argument === '--help') {
135
134
  const tool = (await tools()).find((listed) => listed.name === verb);
136
135
  if (tool === undefined)
137
136
  throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
138
- return `${tool.description}\n${JSON.stringify(tool.inputSchema)}`;
137
+ return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
139
138
  }
140
139
  const args = argumentsOf(argument);
141
140
  if (socketPath !== undefined && verb === 'upload_attachment') {
@@ -155,7 +154,7 @@ async function house([verb, argument]) {
155
154
  return text;
156
155
  }
157
156
  const argv = process.argv.slice(2);
158
- (argv[0] === 'git' ? gitPush(argv.slice(1)) : house(argv)).then((text) => {
157
+ (argv[0] === 'push' ? push(argv.slice(1)) : house(argv)).then((text) => {
159
158
  process.stdout.write(`${text}\n`);
160
159
  }, (error) => {
161
160
  process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
@@ -1,8 +1,8 @@
1
1
  import { HOW_WE_WORK } from './skills.js';
2
2
  const HOUSE_LINE = 'Work with House through the `house` CLI: run `house --help`.';
3
3
  const FILE_LINE = 'To give the User a file or a page, upload it with `house upload_attachment` and link it; never start a server.';
4
- const READ_LINE = 'Before working in a Room, read `/private/rooms/<handle>/AGENTS.md`.';
5
- const COPIES_LINE = 'House Local copies; commit, then `house git push`:';
4
+ const READ_LINE = 'Before working in a Room, read `/rooms/private/rooms/<handle>/AGENTS.md`.';
5
+ const COPIES_LINE = 'House Local copies; commit, then `house push`:';
6
6
  const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
7
7
  const FAILED = /^exit: [1-9]\d*$/;
8
8
  const CUT = /^stderr: shell: output_cut (\d+) of \d+ bytes; continue with: (.+)$/;
package/dist/kit-main.js CHANGED
@@ -1,15 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { setGlobalProxyFromEnv } from 'node:http';
3
3
  import { login } from './login.js';
4
+ import { logout } from './logout.js';
4
5
  import { resident } from './resident.js';
5
6
  const [command, ...argv] = process.argv.slice(2);
6
7
  setGlobalProxyFromEnv();
7
8
  async function run() {
8
9
  if (command === 'login')
9
10
  return login(argv);
11
+ if (command === 'logout')
12
+ return logout();
10
13
  if (command === 'resident')
11
14
  return resident();
12
- process.stderr.write('usage: kit <login|resident>\n');
15
+ process.stderr.write('usage: kit <login|logout|resident>\n');
13
16
  process.exitCode = 2;
14
17
  }
15
18
  run().catch((error) => {
package/dist/login.js CHANGED
@@ -4,7 +4,7 @@ import { hostname } from 'node:os';
4
4
  import { createInterface } from 'node:readline/promises';
5
5
  import { parseArgs } from 'node:util';
6
6
  import { post } from './api.js';
7
- import { forgetOwnAgent, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
7
+ import { forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
8
8
  import { callHouse, rpc } from './mcp.js';
9
9
  const DEFAULT_HOUSE = 'https://agents.house';
10
10
  function listen() {
@@ -78,7 +78,7 @@ export async function login(argv) {
78
78
  manual: { type: 'boolean', default: false },
79
79
  },
80
80
  });
81
- const enrolled = await readEnrolment();
81
+ const enrolled = (await readEnrolment()) ?? (await readDisconnected());
82
82
  const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
83
83
  const replaces = process.env.HOUSE_KIT_REPLACES;
84
84
  const environment = replaces === undefined ? (values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined)) : undefined;
package/dist/logout.js ADDED
@@ -0,0 +1,18 @@
1
+ import { HouseRefusal, post } from './api.js';
2
+ import { forgetEnrolment, readEnrolment } from './home.js';
3
+ export async function logout() {
4
+ const enrolled = await readEnrolment();
5
+ if (enrolled === null) {
6
+ process.stdout.write('This computer is not connected to House.\n');
7
+ return;
8
+ }
9
+ try {
10
+ await post(enrolled.house, '/kit/logout', {}, enrolled.credential);
11
+ }
12
+ catch (error) {
13
+ if (!(error instanceof HouseRefusal && error.status === 401))
14
+ throw error;
15
+ }
16
+ await forgetEnrolment(enrolled);
17
+ process.stdout.write(`Environment ${enrolled.environment} is disconnected; kit login reconnects it.\n`);
18
+ }
package/dist/mcp.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { KIT_VERSION } from './clis.js';
3
+ import { relayed } from './relay.js';
3
4
  const MCP_PROTOCOL_VERSION = '2026-07-28';
4
5
  export const UNREACHABLE = 'House is unreachable; call again in a minute';
5
6
  export function rpc(method, params) {
@@ -21,7 +22,7 @@ export function mcpBody(message, operation) {
21
22
  }
22
23
  export async function callHouse(origin, credential, message, operation = null, signal) {
23
24
  const tool = message.method === 'tools/call' ? String(message.params.name) : null;
24
- const answer = await fetch(new URL('/', origin), {
25
+ const answer = await fetch(relayed(new URL('/', origin)), {
25
26
  method: 'POST',
26
27
  headers: {
27
28
  'content-type': 'application/json',
package/dist/refusals.js CHANGED
@@ -21,6 +21,18 @@ function spoken(text) {
21
21
  const detail = said.indexOf('\n');
22
22
  return { code: head[1], text: said, conflicts: detail === -1 ? [] : conflictCodes(said.slice(detail + 1)) };
23
23
  }
24
+ export function retryable(text) {
25
+ let body;
26
+ try {
27
+ body = JSON.parse(text);
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ const error = body?.error;
33
+ const verdict = error?.retryable ?? error?.data?.retryable;
34
+ return typeof verdict === 'boolean' ? verdict : null;
35
+ }
24
36
  export function refusalOf(text) {
25
37
  let body;
26
38
  try {
package/dist/relay.js ADDED
@@ -0,0 +1,10 @@
1
+ export function relayed(target) {
2
+ const url = new URL(target);
3
+ const relay = process.env.HOUSE_KIT_RELAY;
4
+ if (relay === undefined || relay === '')
5
+ return url;
6
+ const through = new URL(`${url.host}${url.pathname}${url.search}`, `${relay}/`);
7
+ if (url.protocol === 'wss:' || url.protocol === 'ws:')
8
+ through.protocol = 'wss:';
9
+ return through;
10
+ }
package/dist/resident.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { once } from 'node:events';
2
+ import { watch } from 'node:fs';
2
3
  import { mkdir, rm, writeFile } from 'node:fs/promises';
3
4
  import { createServer } from 'node:http';
4
5
  import { extname, join } from 'node:path';
@@ -9,7 +10,7 @@ import { house } from './api.js';
9
10
  import { received } from './bridge.js';
10
11
  import { Conversations } from './conversations.js';
11
12
  import { LocalCopies } from './copies.js';
12
- import { agentBase, kitHome, readEnrolment } from './home.js';
13
+ import { agentBase, enrolled, kitHome } from './home.js';
13
14
  import { SignIns } from './sign-in.js';
14
15
  import { placeSkillSet } from './skills.js';
15
16
  import { holdStream } from './stream.js';
@@ -50,12 +51,30 @@ async function serveOwner(copies) {
50
51
  server.listen(socketPath);
51
52
  await once(server, 'listening');
52
53
  }
54
+ function connected() {
55
+ return new Promise((resolve) => {
56
+ const watcher = watch(kitHome(), () => {
57
+ if (!enrolled())
58
+ return;
59
+ watcher.close();
60
+ resolve();
61
+ });
62
+ if (!enrolled()) {
63
+ process.stderr.write('kit: this Environment is not connected; run kit login\n');
64
+ return;
65
+ }
66
+ watcher.close();
67
+ resolve();
68
+ });
69
+ }
53
70
  export async function resident() {
54
- if ((await readEnrolment()) === null) {
55
- process.stderr.write('kit: this Environment is not enrolled; run kit login\n');
56
- process.exitCode = 1;
57
- return;
58
- }
71
+ await connected();
72
+ watch(kitHome(), () => {
73
+ if (enrolled())
74
+ return;
75
+ killDescendants();
76
+ process.exit(1);
77
+ });
59
78
  await placeSkillSet();
60
79
  await mkdir(agentBase(), { recursive: true });
61
80
  process.env.HOUSE_KIT_RESIDENT = String(process.pid);
@@ -1,4 +1,4 @@
1
- import { retryDelay } from './api.js';
1
+ import { finalRefusal, retryDelay } from './api.js';
2
2
  export async function holdSecretInput(house, subject, steps, waiting) {
3
3
  for (let failures = 0; waiting();) {
4
4
  try {
@@ -10,7 +10,10 @@ export async function holdSecretInput(house, subject, steps, waiting) {
10
10
  failures = 0;
11
11
  }
12
12
  catch (error) {
13
+ if (finalRefusal(error))
14
+ return null;
13
15
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
16
+ // A wait that did not reach House is held again on the jittered curve for as long as its asker still waits.
14
17
  await new Promise((resolve) => setTimeout(resolve, retryDelay(failures++)));
15
18
  }
16
19
  }
package/dist/sign-in.js CHANGED
@@ -31,8 +31,9 @@ export class SignIns {
31
31
  this.running.add(input.input_id);
32
32
  this.changed();
33
33
  this.login(input)
34
- .then(() => this.agents.reread(input.cli))
34
+ .then(() => this.agents.recheck(input.cli))
35
35
  .then(() => this.house.deliver(`/kit/inputs/${input.input_id}/ack`, {}))
36
+ .then(() => this.agents.reread(input.cli))
36
37
  .catch(logged)
37
38
  .finally(() => {
38
39
  this.running.delete(input.input_id);
package/dist/skills.js CHANGED
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url';
6
6
  import { KIT_VERSION } from './clis.js';
7
7
  import { kitHome, readConfiguration, readHome, writeHome } from './home.js';
8
8
  import { refusalOf } from './refusals.js';
9
- export const HOW_WE_WORK = '/private/how-we-work.md';
9
+ export const HOW_WE_WORK = '/rooms/private/how-we-work.md';
10
10
  const SKILL_SET = fileURLToPath(new URL('../skills/', import.meta.url));
11
11
  const HOW_WE_WORK_TEXT = readFileSync(new URL('../how-we-work.md', import.meta.url), 'utf8');
12
12
  const RECORD = 'skill-set.json';
package/dist/stream.js CHANGED
@@ -1,17 +1,37 @@
1
- import { retryDelay } from './api.js';
1
+ import { subscribe } from 'node:diagnostics_channel';
2
+ import { finalRefusal, HouseRefusal, retryDelay } from './api.js';
3
+ import { end, REPLACED, SIGN_IN_AGAIN } from './end.js';
2
4
  import { readEnrolment } from './home.js';
5
+ import { relayed } from './relay.js';
6
+ const PATH = '/kit/stream';
3
7
  const SUBPROTOCOL = 'house.kit.stream.1';
8
+ const REFUSAL_HEADER = 'x-house-refusal';
4
9
  function streamUrl(house) {
5
- const url = new URL('/kit/stream', house);
10
+ const url = new URL(PATH, house);
6
11
  url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
7
12
  return url;
8
13
  }
14
+ function header(headers, name) {
15
+ for (let index = 0; index < headers.length; index += 2) {
16
+ if (headers[index].toString('latin1').toLowerCase() === name)
17
+ return headers[index + 1].toString('latin1');
18
+ }
19
+ return '';
20
+ }
21
+ let refused = null;
22
+ subscribe('undici:request:headers', (message) => {
23
+ const { request, response } = message;
24
+ if (!request.path.endsWith(PATH))
25
+ return;
26
+ refused = new HouseRefusal(PATH, response.statusCode, header(response.headers, REFUSAL_HEADER) || response.statusText);
27
+ });
9
28
  export function holdStream(handlers) {
10
29
  let socket = null;
11
30
  let failures = 0;
12
31
  const connect = async () => {
13
32
  const { house, credential } = (await readEnrolment());
14
- const opening = new WebSocket(streamUrl(house), {
33
+ refused = null;
34
+ const opening = new WebSocket(relayed(streamUrl(house)), {
15
35
  protocols: [SUBPROTOCOL],
16
36
  headers: { authorization: `Bearer ${credential}` },
17
37
  });
@@ -30,8 +50,14 @@ export function holdStream(handlers) {
30
50
  if (socket === opening)
31
51
  socket = null;
32
52
  process.stderr.write(`kit: control stream closed ${event.code} ${event.reason}\n`);
33
- const delay = opened ? 1000 + Math.random() * 2000 : retryDelay(failures++);
34
- setTimeout(() => void connect(), delay);
53
+ if (event.reason === 'replaced')
54
+ end(REPLACED);
55
+ if (event.reason === 'credential_rejected' || refused?.status === 401)
56
+ end(SIGN_IN_AGAIN);
57
+ if (finalRefusal(refused))
58
+ end(refused.message);
59
+ // 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.
60
+ setTimeout(() => void connect(), opened ? 1000 + Math.random() * 2000 : retryDelay(failures++));
35
61
  };
36
62
  };
37
63
  void connect();