@agentshouse/kit 0.2.1-c53a84236c3d9 → 0.2.1-c62e8a5e845ed

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,19 +31,21 @@ 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.
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
46
 
47
47
  `kit resident` keeps the Environment connected and, as it connects, copies each
48
- Room you may sync here as a Git repository in the workspace's `local-copies`.
48
+ Room you chose for it as a Git repository in the workspace's `local-copies`.
49
49
  `house fetch` records House's changes on each copy's `refs/house/received`;
50
50
  rebase onto it, commit and run `house push --owner` in the copy, through the
51
51
  install command in the container. An Agent runs both, without `--owner`.
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-c53a84236c3d9",
3
+ "version": "0.2.1-c62e8a5e845ed",
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-c53a84236c3d9/connect-linux.sh"
8
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c62e8a5e845ed/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-c53a84236c3d9/connect-linux.sh"
14
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c62e8a5e845ed/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-c53a84236c3d9/connect-windows.ps1"
20
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c62e8a5e845ed/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;
@@ -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
  }
@@ -2,13 +2,13 @@
2
2
  import { createHash } from 'node:crypto';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { request, setGlobalProxyFromEnv } from 'node:http';
5
- import { basename, join } from 'node:path';
5
+ import { extname, join } from 'node:path';
6
6
  import { HOUSE_REF } from './git.js';
7
- import { kitHome, readOwnAgent } from './home.js';
7
+ import { kitHome, readEnrolment, readOwnAgent } from './home.js';
8
8
  import { callHouse, rpc, UNREACHABLE } from './mcp.js';
9
9
  import { refusalOf } from './refusals.js';
10
10
  import { relayed } from './relay.js';
11
- import { parse } from 'yaml';
11
+ import { parse, stringify } from 'yaml';
12
12
  const USAGE = "usage: house <tool> ['<arguments as JSON>']";
13
13
  const PUSH_USAGE = 'usage: house push [commit] [--owner]';
14
14
  const PUSH = "push [commit]: sends the Local copy's committed changes to House";
@@ -21,6 +21,33 @@ const REVOKED = 'this conversation no longer has House access; nothing to do fro
21
21
  const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
22
22
  const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login";
23
23
  const socketPath = process.env.HOUSE_BRIDGE;
24
+ const MEDIA_TYPES = new Map([
25
+ ['avif', 'image/avif'],
26
+ ['csv', 'text/csv'],
27
+ ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
28
+ ['gif', 'image/gif'],
29
+ ['heic', 'image/heic'],
30
+ ['html', 'text/html'],
31
+ ['jpeg', 'image/jpeg'],
32
+ ['jpg', 'image/jpeg'],
33
+ ['json', 'application/json'],
34
+ ['m4a', 'audio/mp4'],
35
+ ['md', 'text/markdown'],
36
+ ['mov', 'video/quicktime'],
37
+ ['mp3', 'audio/mpeg'],
38
+ ['mp4', 'video/mp4'],
39
+ ['ogg', 'audio/ogg'],
40
+ ['pdf', 'application/pdf'],
41
+ ['png', 'image/png'],
42
+ ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
43
+ ['svg', 'image/svg+xml'],
44
+ ['txt', 'text/plain'],
45
+ ['wav', 'audio/wav'],
46
+ ['webm', 'video/webm'],
47
+ ['webp', 'image/webp'],
48
+ ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
49
+ ['zip', 'application/zip'],
50
+ ]);
24
51
  function refused(path, status, text) {
25
52
  const refusal = refusalOf(text);
26
53
  if (refusal !== null)
@@ -56,6 +83,7 @@ async function direct(message) {
56
83
  const ownAgent = await readOwnAgent();
57
84
  if (ownAgent === null)
58
85
  throw new Error(UNCONNECTED);
86
+ await readEnrolment();
59
87
  setGlobalProxyFromEnv();
60
88
  const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
61
89
  throw new Error(UNREACHABLE);
@@ -97,28 +125,43 @@ async function sent(url, bytes, operation) {
97
125
  return text;
98
126
  throw new Error(refused(url, answer.status, text));
99
127
  }
100
- async function upload(path, roomRef, missing) {
101
- if (typeof path !== 'string' || path === '')
102
- throw new Error(missing);
103
- const bytes = await localFile(path);
104
- const declared = parse(await called('upload', {
105
- ...(roomRef === undefined ? {} : { room_ref: roomRef }),
106
- name: basename(path),
128
+ async function upload({ file, ...destination }) {
129
+ if (typeof file !== 'string' || file === '')
130
+ throw new Error('upload needs "file", a local file');
131
+ const bytes = await localFile(file);
132
+ const mediaType = MEDIA_TYPES.get(extname(file).slice(1).toLowerCase());
133
+ const answer = await called('upload', {
134
+ ...destination,
107
135
  bytes: bytes.length,
108
136
  sha256: createHash('sha256').update(bytes).digest('hex'),
109
- }));
137
+ ...(mediaType === undefined ? {} : { media_type: mediaType }),
138
+ });
139
+ const declared = parse(answer);
110
140
  if (declared.upload === undefined)
111
- return declared.attachment;
112
- const saved = JSON.parse(await sent(declared.upload.url, bytes, declared.upload.operation));
113
- if (saved.upload_failure !== undefined)
114
- throw new Error(`${path} was not saved: ${saved.upload_failure}; call again later`);
115
- return saved.attachment;
141
+ return answer;
142
+ const written = JSON.parse(await sent(declared.upload.url, bytes, declared.upload.operation));
143
+ return stringify(written, { lineWidth: 0 }).trimEnd();
144
+ }
145
+ function unexpected(argument, usage) {
146
+ return new Error(`unexpected argument ${argument}; ${usage}`);
147
+ }
148
+ function accepted(args, flags, positionals, usage) {
149
+ const given = { flags: new Set(), positionals: [] };
150
+ for (const arg of args) {
151
+ if (flags.includes(arg))
152
+ given.flags.add(arg);
153
+ else if (!arg.startsWith('-') && given.positionals.length < positionals)
154
+ given.positionals.push(arg);
155
+ else
156
+ throw unexpected(arg, usage);
157
+ }
158
+ return given;
116
159
  }
117
160
  async function push(args) {
118
- if (args.includes('--help'))
161
+ const { flags, positionals: [commit = 'HEAD'] } = accepted(args, ['--help', '--owner'], 1, PUSH_USAGE);
162
+ if (flags.has('--help'))
119
163
  return PUSH_USAGE;
120
- const owner = args.includes('--owner');
121
- const commit = args.find((arg) => arg !== '--owner') ?? 'HEAD';
164
+ const owner = flags.has('--owner');
122
165
  if (owner && socketPath !== undefined)
123
166
  throw new Error('--owner is not for Agent conversations; run house push without it');
124
167
  if (!owner && socketPath === undefined)
@@ -129,7 +172,7 @@ async function push(args) {
129
172
  return pushed.text;
130
173
  }
131
174
  async function fetched(args) {
132
- if (args.includes('--help'))
175
+ if (accepted(args, ['--help'], 0, FETCH_USAGE).flags.has('--help'))
133
176
  return FETCH_USAGE;
134
177
  const answer = JSON.parse(await bridged('/git/fetch', {}, undefined, socketPath ?? join(kitHome(), 'owner.sock')));
135
178
  if (answer.refused)
@@ -150,28 +193,23 @@ function argumentsOf(argument) {
150
193
  throw new Error(ARGUMENTS);
151
194
  return parsed;
152
195
  }
153
- async function house([verb, argument]) {
154
- if (verb === undefined || verb === '--help' || verb === 'help') {
196
+ async function house(args) {
197
+ const { flags, positionals: [verb, argument] } = accepted(args, ['--help'], 2, USAGE);
198
+ if (verb === 'help' && argument !== undefined)
199
+ throw unexpected(argument, USAGE);
200
+ if (flags.has('--help') && argument !== undefined)
201
+ throw unexpected('--help', USAGE);
202
+ if (verb === undefined || verb === 'help') {
155
203
  return [USAGE, 'help', PUSH, FETCH, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
156
204
  }
157
- if (argument === '--help') {
205
+ if (flags.has('--help')) {
158
206
  const tool = (await tools()).find((listed) => listed.name === verb);
159
207
  if (tool === undefined)
160
208
  throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
161
209
  return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
162
210
  }
163
- const args = argumentsOf(argument);
164
- if (verb === 'upload') {
165
- return JSON.stringify({ attachment: await upload(args.path, args.room_ref, 'upload needs "path", a local file') });
166
- }
167
- if (verb === 'append_record' && Array.isArray(args.attachments)) {
168
- const attachments = [];
169
- for (const path of args.attachments) {
170
- attachments.push(await upload(path, args.room_ref, 'each attachments entry is the path of a local file'));
171
- }
172
- args.attachments = attachments;
173
- }
174
- return called(verb, args);
211
+ const parsed = argumentsOf(argument);
212
+ return verb === 'upload' ? upload(parsed) : called(verb, parsed);
175
213
  }
176
214
  async function called(name, args) {
177
215
  const result = await mcp('tools/call', { name, arguments: args });
@@ -181,7 +219,9 @@ async function called(name, args) {
181
219
  return text;
182
220
  }
183
221
  const argv = process.argv.slice(2);
184
- (argv[0] === 'push' ? push(argv.slice(1)) : argv[0] === 'fetch' ? fetched(argv.slice(1)) : house(argv)).then((text) => {
222
+ const named = argv.findIndex((arg) => !arg.startsWith('-'));
223
+ const rest = argv.filter((_arg, index) => index !== named);
224
+ (argv[named] === 'push' ? push(rest) : argv[named] === 'fetch' ? fetched(rest) : house(argv)).then((text) => {
185
225
  process.stdout.write(`${text}\n`);
186
226
  if (argv[0] === 'shell')
187
227
  process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
@@ -1,8 +1,9 @@
1
1
  import { HOUSE_REF } from './git.js';
2
2
  import { HOW_WE_WORK } from './skills.js';
3
- const HOUSE_LINE = 'Work with House through the `house` CLI: run `house --help`.';
4
- const FILE_LINE = 'To give the User a file or a page, upload it with `house upload` and link it; never start a server.';
5
- const READ_LINE = 'Before working in a Room, read `/rooms/private/rooms/<handle>/AGENTS.md`.';
3
+ const SOURCE_LINE = "From House:";
4
+ const HOUSE_LINE = "Work with House through the `house` CLI: run `house --help`, and `house find_command` for House's guides and formats.";
5
+ const FILE_LINE = 'To give the User a file, upload it with `house upload` and link it; for an App, a Site or a website, follow `house find_command \'{"query":"app"}\'`. Never start a server.';
6
+ const READ_LINE = "Optional per-Room instructions: `/rooms/private/rooms/<handle>/AGENTS.md`.";
6
7
  const COPIES_LINE = `House Local copies; before work run \`house fetch\` and rebase onto \`${HOUSE_REF}\`; after it commit, then \`house push\`:`;
7
8
  const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
8
9
  const FAILED = /^exit: [1-9]\d*$/;
@@ -30,6 +31,6 @@ async function howWeWork(bridge) {
30
31
  return document.replace(/\n$/, '');
31
32
  }
32
33
  export async function instructions(bridge, base, copies) {
33
- const lines = [HOUSE_LINE, FILE_LINE, READ_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
34
+ const lines = [SOURCE_LINE, HOUSE_LINE, FILE_LINE, READ_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
34
35
  return [lines.join('\n'), base, await howWeWork(bridge)].filter((part) => part !== '').join('\n\n');
35
36
  }
package/dist/kit-main.js CHANGED
@@ -1,22 +1,67 @@
1
1
  #!/usr/bin/env node
2
2
  import { setGlobalProxyFromEnv } from 'node:http';
3
+ import { parseArgs } from 'node:util';
3
4
  import { answerGitCredential } from './app-git.js';
5
+ import { codex } from './codex.js';
4
6
  import { login } from './login.js';
5
7
  import { logout } from './logout.js';
6
8
  import { resident } from './resident.js';
9
+ const USAGE = 'usage: kit <login|logout|resident|codex>\n';
10
+ const COMMANDS = new Map([
11
+ [
12
+ 'logout',
13
+ {
14
+ usage: 'usage: kit logout',
15
+ about: "disconnects this computer, stops House Kit and ends your own agent's connection",
16
+ operands: 0,
17
+ run: logout,
18
+ },
19
+ ],
20
+ [
21
+ 'resident',
22
+ {
23
+ usage: 'usage: kit resident',
24
+ about: "keeps this Environment connected; House Kit's service runs it",
25
+ operands: 0,
26
+ run: resident,
27
+ },
28
+ ],
29
+ [
30
+ 'git-credential',
31
+ {
32
+ usage: 'usage: kit git-credential <get|store|erase>',
33
+ about: "answers git with your own agent's House credential; git runs it",
34
+ operands: 1,
35
+ run: ([operation]) => answerGitCredential(operation),
36
+ },
37
+ ],
38
+ ]);
7
39
  const [command, ...argv] = process.argv.slice(2);
8
40
  setGlobalProxyFromEnv();
9
41
  async function run() {
10
42
  if (command === 'login')
11
43
  return login(argv);
12
- if (command === 'logout')
13
- return logout();
14
- if (command === 'resident')
15
- return resident();
16
- if (command === 'git-credential')
17
- return answerGitCredential(argv[0]);
18
- process.stderr.write('usage: kit <login|logout|resident>\n');
19
- process.exitCode = 2;
44
+ if (command === 'codex')
45
+ return codex(argv);
46
+ if (command === '--help') {
47
+ parseArgs({ args: argv });
48
+ process.stdout.write(USAGE);
49
+ return;
50
+ }
51
+ const chosen = COMMANDS.get(command ?? '');
52
+ if (chosen === undefined) {
53
+ process.stderr.write(USAGE);
54
+ process.exitCode = 2;
55
+ return;
56
+ }
57
+ const { values, positionals } = parseArgs({ args: argv, options: { help: { type: 'boolean', default: false } }, allowPositionals: true });
58
+ if (positionals.length > chosen.operands)
59
+ throw new Error(`unexpected argument ${positionals[chosen.operands]}; ${chosen.usage}`);
60
+ if (values.help) {
61
+ process.stdout.write(`${chosen.usage}\n ${chosen.about}\n`);
62
+ return;
63
+ }
64
+ return chosen.run(positionals);
20
65
  }
21
66
  run().catch((error) => {
22
67
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
package/dist/login.js CHANGED
@@ -4,9 +4,13 @@ import { hostname } from 'node:os';
4
4
  import { parseArgs } from 'node:util';
5
5
  import { post, retrying } from './api.js';
6
6
  import { placeAppGit } from './app-git.js';
7
+ import { writeCodexRule } from './clis.js';
7
8
  import { forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
8
9
  import { callHouse, rpc } from './mcp.js';
9
- const DEFAULT_HOUSE = 'https://agents.house';
10
+ import { selectRelay } from './relay.js';
11
+ import { startService } from './service.js';
12
+ import { placeSkillSet } from './skills.js';
13
+ export const DEFAULT_HOUSE = 'https://agents.house';
10
14
  const OPENER = process.platform === 'darwin' ? 'open' : 'xdg-open';
11
15
  // Polling every two seconds brings the User's confirmation to the waiting Kit moments after they give it.
12
16
  const POLL_INTERVAL_MS = 2000;
@@ -15,7 +19,7 @@ function open(link) {
15
19
  .on('error', () => undefined)
16
20
  .unref();
17
21
  }
18
- async function accepted(house, credential) {
22
+ export async function accepted(house, credential) {
19
23
  const checked = await callHouse(house, credential, rpc('tools/list', {}));
20
24
  if (checked.status === 200)
21
25
  return true;
@@ -23,39 +27,101 @@ async function accepted(house, credential) {
23
27
  return false;
24
28
  throw new Error(`House answered ${checked.status} when Kit checked this computer's own agent's connection: ${checked.text}`);
25
29
  }
30
+ const USAGE = `usage: kit login [--house <origin>] [--environment <id>] [--rooms <ref>[,<ref>...] | --no-private]
31
+ kit login [--house <origin>] --code <code>
32
+ --house <origin> the House to connect to, ${DEFAULT_HOUSE} unless one is stored
33
+ --environment <id> reconnect this Environment
34
+ --rooms <ref>[,<ref>...] give this Environment only these Rooms
35
+ --no-private give this Environment every Room but your Private Room
36
+ --code <code> connect this machine with a login code
37
+ `;
38
+ function chosenRooms(rooms, noPrivate) {
39
+ if (rooms !== undefined && noPrivate)
40
+ throw new Error('--rooms and --no-private are two choices of Rooms; pass one');
41
+ if (rooms !== undefined)
42
+ return { rooms: { reach: 'selected', refs: rooms.split(',') } };
43
+ return noPrivate ? { rooms: { reach: 'all_but_private' } } : {};
44
+ }
26
45
  export async function login(argv) {
27
46
  const { values } = parseArgs({
28
47
  args: argv,
29
48
  options: {
30
49
  house: { type: 'string' },
31
50
  environment: { type: 'string' },
51
+ rooms: { type: 'string' },
52
+ 'no-private': { type: 'boolean', default: false },
53
+ code: { type: 'string' },
54
+ help: { type: 'boolean', default: false },
32
55
  },
33
56
  });
57
+ if (values.help) {
58
+ process.stdout.write(USAGE);
59
+ return;
60
+ }
61
+ if (values.code !== undefined && values.rooms !== undefined)
62
+ throw new Error('--code cannot be used with --rooms');
63
+ if (values.code !== undefined && values['no-private'])
64
+ throw new Error('--code cannot be used with --no-private');
65
+ if (values.code !== undefined && values.environment !== undefined)
66
+ throw new Error('--code cannot be used with --environment');
67
+ const rooms = chosenRooms(values.rooms, values['no-private']);
34
68
  const enrolled = (await readEnrolment()) ?? (await readDisconnected());
69
+ if (values.code !== undefined && enrolled !== null) {
70
+ throw new Error(`--code connects a new machine; this Kit home records Environment ${enrolled.environment}, so run kit login to reconnect it`);
71
+ }
72
+ const relay = process.env.HOUSE_KIT_RELAY || undefined;
73
+ selectRelay(relay);
35
74
  const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
36
75
  const replaces = process.env.HOUSE_KIT_REPLACES;
37
76
  const environment = replaces === undefined ? (values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined)) : undefined;
38
77
  const ownAgent = await readOwnAgent();
39
- const held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
40
- const verifier = randomBytes(32).toString('base64url');
41
- const started = await retrying(() => post(house, '/kit', {
42
- ...(environment === undefined
43
- ? { act: 'new_environment', label: hostname(), ...(replaces === undefined ? {} : { replaces }) }
44
- : { act: 'existing_environment', environment_id: environment }),
45
- code_challenge: createHash('sha256').update(verifier).digest('base64url'),
46
- ...(held ? {} : { headless: true }),
47
- }));
48
- process.stdout.write(`Open this link and confirm: ${started.start_url}\n`);
49
- open(started.start_url);
50
- const exchanged = await retrying(() => post(house, '/kit/token', { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
51
- await writeEnrolment({ house, environment: exchanged.environment, credential: exchanged.credential });
78
+ let held = false;
79
+ let exchanged;
80
+ if (values.code !== undefined) {
81
+ exchanged = await post(house, '/kit/token', { code: values.code, label: hostname() });
82
+ }
83
+ else {
84
+ held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
85
+ const verifier = randomBytes(32).toString('base64url');
86
+ const started = await retrying(() => post(house, '/kit', {
87
+ label: hostname(),
88
+ ...(environment === undefined
89
+ ? { act: 'new_environment', ...(replaces === undefined ? {} : { replaces }) }
90
+ : { act: 'existing_environment', environment_id: environment }),
91
+ ...rooms,
92
+ code_challenge: createHash('sha256').update(verifier).digest('base64url'),
93
+ ...(held ? {} : { headless: true }),
94
+ }));
95
+ process.stdout.write(`Open this link and confirm: ${started.start_url}\n`);
96
+ open(started.start_url);
97
+ exchanged = await retrying(() => post(house, '/kit/token', { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
98
+ }
99
+ try {
100
+ await placeSkillSet();
101
+ }
102
+ catch (error) {
103
+ process.stderr.write(`kit: the skills could not be placed: ${error.message}\n`);
104
+ }
105
+ await writeCodexRule().catch((error) => process.stderr.write(`kit: ${error.message}\n`));
106
+ await writeEnrolment({
107
+ house,
108
+ ...(relay === undefined ? {} : { relay }),
109
+ environment: exchanged.environment,
110
+ credential: exchanged.credential,
111
+ });
52
112
  process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
53
113
  if (exchanged.headless_credential !== undefined) {
54
114
  await writeOwnAgent({ house, user: exchanged.user, credential: exchanged.headless_credential });
55
115
  }
56
- else if (held && ownAgent.user !== exchanged.user) {
116
+ else if (held && ownAgent !== null && ownAgent.user !== exchanged.user) {
57
117
  await forgetOwnAgent();
58
118
  process.stdout.write("This computer's own agent was another User's; run kit login again to connect it to you.\n");
59
119
  }
60
120
  await placeAppGit(ownAgent, await readOwnAgent());
121
+ try {
122
+ startService();
123
+ }
124
+ catch (error) {
125
+ process.stderr.write(`kit: ${error.message}\n`);
126
+ }
61
127
  }
package/dist/parts.js CHANGED
@@ -2,7 +2,10 @@ export class Parts {
2
2
  parts = [];
3
3
  context = null;
4
4
  emit;
5
+ made = [];
6
+ events = 0;
5
7
  writing = null;
8
+ counting = null;
6
9
  planned = null;
7
10
  constructor(emit) {
8
11
  this.emit = emit;
@@ -10,32 +13,34 @@ export class Parts {
10
13
  write(type, id, text) {
11
14
  if (text === '')
12
15
  return;
13
- const last = this.parts.length - 1;
14
- const part = this.parts[last];
15
- if (this.writing?.type === type && this.writing.id === id && part?.type === type) {
16
- part.text += text;
17
- this.emit({ op: 'append', index: last, text });
16
+ if (this.writing?.type === type && this.writing.id === id) {
17
+ this.parts[this.writing.index].text += text;
18
+ this.emit({ op: 'append', index: this.writing.index, text });
18
19
  return;
19
20
  }
20
- this.start({ type, text });
21
- this.writing = { type, id };
21
+ this.writing = { type, id, index: this.start({ type, text }) };
22
22
  }
23
23
  command() {
24
- const last = this.parts.length - 1;
25
- const part = this.parts[last];
26
- if (part?.type !== 'commands') {
27
- this.start({ type: 'commands', count: 1 });
24
+ if (this.counting === null) {
25
+ this.counting = this.start({ type: 'commands', count: 1 });
28
26
  return;
29
27
  }
28
+ const part = this.parts[this.counting];
30
29
  part.count++;
31
- this.emit({ op: 'count', index: last, count: part.count });
30
+ this.emit({ op: 'count', index: this.counting, count: part.count });
32
31
  }
33
32
  start(part) {
34
33
  this.writing = null;
35
- this.parts.push(part);
36
- const index = this.parts.length - 1;
37
- this.emit({ op: 'start', index, part });
38
- return index;
34
+ this.counting = null;
35
+ return this.add(part, ++this.events);
36
+ }
37
+ reserve() {
38
+ this.writing = null;
39
+ this.counting = null;
40
+ return ++this.events;
41
+ }
42
+ arrive(part, reserved) {
43
+ this.add(part, reserved);
39
44
  }
40
45
  done(index, result) {
41
46
  const part = this.parts[index];
@@ -55,10 +60,23 @@ export class Parts {
55
60
  this.context = context;
56
61
  this.emit({ op: 'context', ...context });
57
62
  }
63
+ saved() {
64
+ return this.parts
65
+ .map((part, index) => ({ part, made: this.made[index] }))
66
+ .sort((a, b) => a.made - b.made)
67
+ .map(({ part }) => part);
68
+ }
58
69
  operations() {
59
70
  return [
60
71
  ...this.parts.map((part, index) => ({ op: 'start', index, part })),
61
72
  ...(this.context === null ? [] : [{ op: 'context', ...this.context }]),
62
73
  ];
63
74
  }
75
+ add(part, made) {
76
+ this.parts.push(part);
77
+ this.made.push(made);
78
+ const index = this.parts.length - 1;
79
+ this.emit({ op: 'start', index, part });
80
+ return index;
81
+ }
64
82
  }
@@ -0,0 +1,48 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { run } from './clis.js';
4
+ import { kitHome } from './home.js';
5
+ import { relayOrigin } from './relay.js';
6
+ export function service() {
7
+ if (process.platform !== 'linux' || !process.env.INVOCATION_ID)
8
+ return null;
9
+ return process.env.MANAGERPID ? 'user' : 'system';
10
+ }
11
+ export function throughSudo() {
12
+ return service() === 'system' && process.getuid() !== 0;
13
+ }
14
+ export async function updatesItself() {
15
+ if (service() === null)
16
+ return false;
17
+ if (!throughSudo())
18
+ return true;
19
+ // sudo answers at once, so ten seconds only bounds a stuck sudo.
20
+ return (await run('sudo', ['-n', 'true'], 10_000)).status === 0;
21
+ }
22
+ function installed() {
23
+ try {
24
+ return readFileSync(join(kitHome(), 'placement'), 'utf8').trim();
25
+ }
26
+ catch (error) {
27
+ if (error.code === 'ENOENT')
28
+ return null;
29
+ throw error;
30
+ }
31
+ }
32
+ function entries(house) {
33
+ const host = new URL(house).host;
34
+ const relay = relayOrigin();
35
+ if (relay === undefined)
36
+ return [`curl -fsSL ${host}/kit | sh`, `irm ${host}/kit.ps1 | iex`];
37
+ const entry = `${relay}/${host}/kit`;
38
+ return [`curl -fsSL ${entry} | HOUSE_KIT_RELAY=${relay} sh`, `$env:HOUSE_KIT_RELAY='${relay}'; irm ${entry}.ps1 | iex`];
39
+ }
40
+ export function installCommand(house) {
41
+ const [shell, windows] = entries(house);
42
+ const placement = installed();
43
+ if (placement === 'native')
44
+ return shell;
45
+ if (placement === 'server')
46
+ return `${shell} -s -- --linux`;
47
+ return `${shell} -s -- --container, or ${windows} on Windows`;
48
+ }
package/dist/relay.js CHANGED
@@ -1,7 +1,17 @@
1
+ let selected;
2
+ export function selectRelay(relay) {
3
+ selected = relay === undefined || relay === '' ? null : relay;
4
+ }
5
+ export function relayOrigin() {
6
+ if (selected !== undefined)
7
+ return selected ?? undefined;
8
+ const ambient = process.env.HOUSE_KIT_RELAY;
9
+ return ambient === undefined || ambient === '' ? undefined : ambient;
10
+ }
1
11
  export function relayed(target) {
2
12
  const url = new URL(target);
3
- const relay = process.env.HOUSE_KIT_RELAY;
4
- if (relay === undefined || relay === '')
13
+ const relay = relayOrigin();
14
+ if (relay === undefined)
5
15
  return url;
6
16
  const through = new URL(`${url.host}${url.pathname}${url.search}`, `${relay}/`);
7
17
  if (url.protocol === 'wss:' || url.protocol === 'ws:')
package/dist/resident.js CHANGED
@@ -7,9 +7,10 @@ import { fileURLToPath } from 'node:url';
7
7
  import { Agents } from './agents.js';
8
8
  import { house } from './api.js';
9
9
  import { received } from './bridge.js';
10
- import { Conversations } from './conversations.js';
10
+ import { CONVERSATION_INPUTS, Conversations } from './conversations.js';
11
11
  import { LocalCopies } from './copies.js';
12
- import { agentBase, enrolled, kitHome } from './home.js';
12
+ import { restart } from './end.js';
13
+ import { agentBase, enrolled, forgetRestart, kitHome, restartAsked } from './home.js';
13
14
  import { killDescendants } from './scope.js';
14
15
  import { quoted } from './shell.js';
15
16
  import { SignIns } from './sign-in.js';
@@ -73,6 +74,7 @@ function connected() {
73
74
  }
74
75
  export async function resident() {
75
76
  await connected();
77
+ await forgetRestart();
76
78
  watch(kitHome(), () => {
77
79
  if (enrolled())
78
80
  return;
@@ -95,6 +97,9 @@ export async function resident() {
95
97
  if (!idle()) {
96
98
  reported = false;
97
99
  }
100
+ else if (restartAsked() && conversations.quiet()) {
101
+ restart('restarting for an updated CLI');
102
+ }
98
103
  else if (!reported) {
99
104
  reported = true;
100
105
  logged(house.deliver('/kit/idle', {}, idle));
@@ -135,8 +140,12 @@ export async function resident() {
135
140
  signIns.start(arrived);
136
141
  else if (arrived.kind === 'update')
137
142
  updates.start(arrived);
138
- else
143
+ else if (CONVERSATION_INPUTS.has(arrived.kind))
139
144
  conversations.input(arrived);
145
+ else {
146
+ const refused = { refused: `This Kit does not know ${arrived.kind}; update the Kit` };
147
+ logged(house.deliver(`/kit/inputs/${arrived.input_id}/ack`, refused).finally(changed));
148
+ }
140
149
  }
141
150
  },
142
151
  });
@@ -0,0 +1,9 @@
1
+ import { startService } from './service.js';
2
+ try {
3
+ if (startService())
4
+ process.stdout.write('started\n');
5
+ }
6
+ catch (error) {
7
+ process.stderr.write(`kit: ${error.message}\n`);
8
+ process.exitCode = 1;
9
+ }
@@ -0,0 +1,33 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ const UNIT = 'house-kit.service';
3
+ // launchctl and systemctl answer at once, so ten seconds only bounds a stuck service manager.
4
+ const MANAGER_MS = 10_000;
5
+ function manage(command, args) {
6
+ return spawnSync(command, args, { encoding: 'utf8', timeout: MANAGER_MS });
7
+ }
8
+ function start(command, args) {
9
+ const started = manage(command, args);
10
+ if (started.status === 0)
11
+ return;
12
+ const cause = started.error?.message ?? (started.stderr.trim() || `${command} exited with ${started.status ?? 'a signal'}`);
13
+ throw new Error(`the House Kit service could not be started: ${cause}`);
14
+ }
15
+ export function startService() {
16
+ if (process.platform === 'darwin') {
17
+ const service = `gui/${process.getuid()}/house-kit`;
18
+ const printed = manage('launchctl', ['print', service]);
19
+ if (printed.status !== 0 || /^\tstate = running$/m.test(printed.stdout))
20
+ return false;
21
+ start('launchctl', ['kickstart', service]);
22
+ return true;
23
+ }
24
+ for (const scope of [['--user'], []]) {
25
+ if (manage('systemctl', [...scope, 'is-enabled', '--quiet', UNIT]).status !== 0)
26
+ continue;
27
+ if (manage('systemctl', [...scope, 'is-active', '--quiet', UNIT]).status === 0)
28
+ return false;
29
+ start('systemctl', [...scope, 'start', UNIT]);
30
+ return true;
31
+ }
32
+ return false;
33
+ }
package/dist/stream.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { subscribe } from 'node:diagnostics_channel';
2
2
  import { finalRefusal, HouseRefusal, retryDelay } from './api.js';
3
- import { end, REPLACED, SIGN_IN_AGAIN } from './end.js';
3
+ import { end, REPLACED, signInAgain, updateRequired } from './end.js';
4
4
  import { readEnrolment } from './home.js';
5
5
  import { relayed } from './relay.js';
6
+ import { KIT_WIRE, tooOld } from './wire.js';
6
7
  const PATH = '/kit/stream';
7
- const SUBPROTOCOL = 'house.kit.stream.1';
8
+ const SUBPROTOCOL = `house.kit.stream.${KIT_WIRE}`;
8
9
  const REFUSAL_HEADER = 'x-house-refusal';
9
10
  function streamUrl(house) {
10
11
  const url = new URL(PATH, house);
@@ -52,8 +53,12 @@ export function holdStream(handlers) {
52
53
  process.stderr.write(`kit: control stream closed ${event.code} ${event.reason}\n`);
53
54
  if (event.reason === 'replaced')
54
55
  end(REPLACED);
55
- if (event.reason === 'credential_rejected' || refused?.status === 401)
56
- end(SIGN_IN_AGAIN);
56
+ if (event.reason === 'credential_rejected' || refused?.status === 401) {
57
+ void signInAgain(credential);
58
+ return;
59
+ }
60
+ if (refused !== null && tooOld(refused.text))
61
+ updateRequired(house);
57
62
  if (finalRefusal(refused))
58
63
  end(refused.message);
59
64
  // A closed socket reopens in one to three seconds, spread so Kits one restart closed return apart; an opening House refused as retryable or left unanswered backs off on the jittered curve.
package/dist/update.js CHANGED
@@ -4,8 +4,8 @@ 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';
7
+ import { kitHome, workspaceRoot } from './home.js';
8
+ import { service, throughSudo } from './placement.js';
9
9
  function logged(error) {
10
10
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
11
11
  }
@@ -21,6 +21,21 @@ function outcome() {
21
21
  function unit(inputId) {
22
22
  return `house-kit-update-${inputId}`;
23
23
  }
24
+ function manager() {
25
+ return service() === 'user' ? ['--user'] : [];
26
+ }
27
+ function elevated() {
28
+ return throughSudo() ? ['sudo', '-n'] : [];
29
+ }
30
+ function account() {
31
+ return throughSudo() ? [`--uid=${process.getuid()}`, `--gid=${process.getgid()}`] : [];
32
+ }
33
+ function placement() {
34
+ return service() === 'user' ? ['--workspace', workspaceRoot()] : ['--linux'];
35
+ }
36
+ function record() {
37
+ return `outcome=$1; shift; bash "$0" "$@"; printf %s "$?" > "$outcome"; ${[...elevated(), 'systemctl', ...manager(), 'start', 'house-kit.service'].join(' ')}`;
38
+ }
24
39
  async function pendingInput() {
25
40
  try {
26
41
  return JSON.parse(await readFile(pending(), 'utf8')).input_id;
@@ -41,7 +56,7 @@ async function finished(inputId) {
41
56
  if (ack !== null)
42
57
  return ack;
43
58
  // systemctl answers at once, so ten seconds only bounds a stuck service manager.
44
- if ((await run('systemctl', ['is-active', '--quiet', unit(inputId)], 10_000)).status !== 0) {
59
+ if ((await run('systemctl', [...manager(), 'is-active', '--quiet', unit(inputId)], 10_000)).status !== 0) {
45
60
  return (await recorded()) ?? { refused: 'the Kit bootstrap did not finish' };
46
61
  }
47
62
  // The bootstrap runs for minutes, so checking each second sees its outcome within a second at little cost.
@@ -50,7 +65,11 @@ async function finished(inputId) {
50
65
  }
51
66
  function rerun(script, inputId, flags) {
52
67
  return new Promise((resolve) => {
53
- const child = spawn('systemd-run', [
68
+ const [command, ...args] = [
69
+ ...elevated(),
70
+ 'systemd-run',
71
+ ...manager(),
72
+ ...account(),
54
73
  '--wait',
55
74
  '--collect',
56
75
  '--quiet',
@@ -58,11 +77,13 @@ function rerun(script, inputId, flags) {
58
77
  `--setenv=HOME=${homedir()}`,
59
78
  '/bin/sh',
60
79
  '-c',
61
- RECORD,
80
+ record(),
62
81
  script,
63
82
  outcome(),
83
+ ...placement(),
64
84
  ...flags,
65
- ], { stdio: ['ignore', 'ignore', 'inherit'] });
85
+ ];
86
+ const child = spawn(command, args, { stdio: ['ignore', 'ignore', 'inherit'] });
66
87
  child.on('error', () => resolve({ refused: 'no service manager runs this Kit' }));
67
88
  child.on('close', () => resolve(null));
68
89
  });
package/dist/wire.js ADDED
@@ -0,0 +1,6 @@
1
+ import { refusalOf } from './refusals.js';
2
+ export const KIT_WIRE = 1;
3
+ export const KIT_WIRE_HEADER = 'x-house-kit-wire';
4
+ export function tooOld(text) {
5
+ return refusalOf(text)?.code === 'kit_update_required';
6
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentshouse/kit",
3
- "version": "0.2.1-c53a84236c3d9",
3
+ "version": "0.2.1-c62e8a5e845ed",
4
4
  "description": "House Kit connects an Environment to agents.house.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -27,7 +27,7 @@
27
27
  },
28
28
  "dependencies": {
29
29
  "@agentclientprotocol/sdk": "1.7.0",
30
- "@agentshouse/mdmodel": "0.1.0-alpha.19",
30
+ "@agentshouse/mdmodel": "0.1.0-c68e2039f1ca8",
31
31
  "yaml": "2.9.1"
32
32
  },
33
33
  "peerDependencies": {