@agentshouse/kit 0.2.1-c3cf4b145dcda → 0.2.1-c3e86aacccc80

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/login.js CHANGED
@@ -1,54 +1,22 @@
1
+ import { spawn } from 'node:child_process';
1
2
  import { createHash, randomBytes } from 'node:crypto';
2
- import { createServer } from 'node:http';
3
3
  import { hostname } from 'node:os';
4
- import { createInterface } from 'node:readline/promises';
5
4
  import { parseArgs } from 'node:util';
6
- import { post } from './api.js';
5
+ import { post, retrying } from './api.js';
7
6
  import { placeAppGit } from './app-git.js';
8
7
  import { forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
9
8
  import { callHouse, rpc } from './mcp.js';
9
+ import { selectRelay } from './relay.js';
10
+ import { startService } from './service.js';
11
+ import { placeSkillSet } from './skills.js';
10
12
  const DEFAULT_HOUSE = 'https://agents.house';
11
- function listen() {
12
- return new Promise((resolve, reject) => {
13
- let deliver = () => undefined;
14
- let held = null;
15
- const code = new Promise((settle) => {
16
- deliver = settle;
17
- });
18
- const server = createServer((request, response) => {
19
- const received = new URL(request.url ?? '/', 'http://127.0.0.1').searchParams.get('code');
20
- if (received === null || held !== null) {
21
- response.writeHead(404).end();
22
- return;
23
- }
24
- held = response;
25
- deliver(received);
26
- });
27
- const close = () => {
28
- server.close();
29
- server.closeAllConnections();
30
- };
31
- const port = Number(process.env.HOUSE_KIT_LOGIN_PORT ?? 0);
32
- server.once('error', reject);
33
- server.listen(port, port === 0 ? '127.0.0.1' : '0.0.0.0', () => {
34
- const address = server.address();
35
- if (address === null || typeof address === 'string') {
36
- reject(new Error('the login callback has no port'));
37
- return;
38
- }
39
- resolve({
40
- uri: `http://127.0.0.1:${address.port}/callback`,
41
- code,
42
- answer: (text) => new Promise((written) => {
43
- if (held === null || held.destroyed || !held.socket || held.socket.destroyed)
44
- return written();
45
- held.once('close', () => written());
46
- held.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', connection: 'close' }).end(`${text}\n`);
47
- }),
48
- close,
49
- });
50
- });
51
- });
13
+ const OPENER = process.platform === 'darwin' ? 'open' : 'xdg-open';
14
+ // Polling every two seconds brings the User's confirmation to the waiting Kit moments after they give it.
15
+ const POLL_INTERVAL_MS = 2000;
16
+ function open(link) {
17
+ spawn(OPENER, [link], { detached: true, stdio: 'ignore' })
18
+ .on('error', () => undefined)
19
+ .unref();
52
20
  }
53
21
  async function accepted(house, credential) {
54
22
  const checked = await callHouse(house, credential, rpc('tools/list', {}));
@@ -58,17 +26,19 @@ async function accepted(house, credential) {
58
26
  return false;
59
27
  throw new Error(`House answered ${checked.status} when Kit checked this computer's own agent's connection: ${checked.text}`);
60
28
  }
61
- async function typed(question) {
62
- const reader = createInterface({ input: process.stdin, output: process.stdout });
63
- const closed = new Promise((_, reject) => {
64
- reader.once('close', () => reject(new Error('no code was typed')));
65
- });
66
- try {
67
- return (await Promise.race([reader.question(question), closed])).trim();
68
- }
69
- finally {
70
- reader.close();
71
- }
29
+ const USAGE = `usage: kit login [--house <origin>] [--environment <id>] [--rooms <ref>[,<ref>...] | --no-private] [--code <code>]
30
+ --house <origin> the House to connect to, ${DEFAULT_HOUSE} unless one is stored
31
+ --environment <id> reconnect this Environment
32
+ --rooms <ref>[,<ref>...] give this Environment only these Rooms
33
+ --no-private give this Environment every Room but your Private Room
34
+ --code <code> connect this machine with a login code
35
+ `;
36
+ function chosenRooms(rooms, noPrivate) {
37
+ if (rooms !== undefined && noPrivate)
38
+ throw new Error('--rooms and --no-private are two choices of Rooms; pass one');
39
+ if (rooms !== undefined)
40
+ return { rooms: { reach: 'selected', refs: rooms.split(',') } };
41
+ return noPrivate ? { rooms: { reach: 'all_but_private' } } : {};
72
42
  }
73
43
  export async function login(argv) {
74
44
  const { values } = parseArgs({
@@ -76,65 +46,79 @@ export async function login(argv) {
76
46
  options: {
77
47
  house: { type: 'string' },
78
48
  environment: { type: 'string' },
79
- manual: { type: 'boolean', default: false },
49
+ rooms: { type: 'string' },
50
+ 'no-private': { type: 'boolean', default: false },
51
+ code: { type: 'string' },
52
+ help: { type: 'boolean', default: false },
80
53
  },
81
54
  });
55
+ if (values.help) {
56
+ process.stdout.write(USAGE);
57
+ return;
58
+ }
59
+ if (values.code !== undefined && values.rooms !== undefined)
60
+ throw new Error('--code cannot be used with --rooms');
61
+ if (values.code !== undefined && values['no-private'])
62
+ throw new Error('--code cannot be used with --no-private');
63
+ if (values.code !== undefined && values.environment !== undefined)
64
+ throw new Error('--code cannot be used with --environment');
65
+ const rooms = chosenRooms(values.rooms, values['no-private']);
82
66
  const enrolled = (await readEnrolment()) ?? (await readDisconnected());
67
+ if (values.code !== undefined && enrolled !== null) {
68
+ throw new Error(`--code connects a new machine; this Kit home records Environment ${enrolled.environment}, so run kit login to reconnect it`);
69
+ }
70
+ const relay = process.env.HOUSE_KIT_RELAY || undefined;
71
+ selectRelay(relay);
83
72
  const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
84
73
  const replaces = process.env.HOUSE_KIT_REPLACES;
85
74
  const environment = replaces === undefined ? (values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined)) : undefined;
86
75
  const ownAgent = await readOwnAgent();
87
- const held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
88
- const verifier = randomBytes(32).toString('base64url');
89
- const started = {
90
- ...(environment === undefined
91
- ? { act: 'new_environment', label: hostname(), ...(replaces === undefined ? {} : { replaces }) }
92
- : { act: 'existing_environment', environment_id: environment }),
93
- code_challenge: createHash('sha256').update(verifier).digest('base64url'),
94
- ...(held ? {} : { headless: true }),
95
- };
96
- const exchange = async (code) => {
97
- const exchanged = await post(house, '/kit/token', { code, code_verifier: verifier });
98
- await writeEnrolment({ house, environment: exchanged.environment, credential: exchanged.credential });
99
- process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
100
- if (exchanged.headless_credential !== undefined) {
101
- await writeOwnAgent({ house, user: exchanged.user, credential: exchanged.headless_credential });
102
- }
103
- else if (held && ownAgent.user !== exchanged.user) {
104
- await forgetOwnAgent();
105
- process.stdout.write("This computer's own agent was another User's; run kit login again to connect it to you.\n");
106
- }
107
- };
108
- const placeGit = async () => placeAppGit(ownAgent, await readOwnAgent());
109
- if (values.manual) {
110
- const { start_url } = await post(house, '/kit', {
111
- ...started,
112
- presentation: 'manual',
113
- });
114
- process.stdout.write(`Open this link and confirm: ${start_url}\n`);
115
- await exchange(await typed('Code: '));
116
- await placeGit();
117
- return;
76
+ let held = false;
77
+ let exchanged;
78
+ if (values.code !== undefined) {
79
+ exchanged = await post(house, '/kit/token', { code: values.code, label: hostname() });
80
+ }
81
+ else {
82
+ held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
83
+ const verifier = randomBytes(32).toString('base64url');
84
+ const started = await retrying(() => post(house, '/kit', {
85
+ label: hostname(),
86
+ ...(environment === undefined
87
+ ? { act: 'new_environment', ...(replaces === undefined ? {} : { replaces }) }
88
+ : { act: 'existing_environment', environment_id: environment }),
89
+ ...rooms,
90
+ code_challenge: createHash('sha256').update(verifier).digest('base64url'),
91
+ ...(held ? {} : { headless: true }),
92
+ }));
93
+ process.stdout.write(`Open this link and confirm: ${started.start_url}\n`);
94
+ open(started.start_url);
95
+ exchanged = await retrying(() => post(house, '/kit/token', { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
96
+ }
97
+ try {
98
+ await placeSkillSet();
99
+ }
100
+ catch (error) {
101
+ process.stderr.write(`kit: the skills could not be placed: ${error.message}\n`);
102
+ }
103
+ await writeEnrolment({
104
+ house,
105
+ ...(relay === undefined ? {} : { relay }),
106
+ environment: exchanged.environment,
107
+ credential: exchanged.credential,
108
+ });
109
+ process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
110
+ if (exchanged.headless_credential !== undefined) {
111
+ await writeOwnAgent({ house, user: exchanged.user, credential: exchanged.headless_credential });
112
+ }
113
+ else if (held && ownAgent !== null && ownAgent.user !== exchanged.user) {
114
+ await forgetOwnAgent();
115
+ process.stdout.write("This computer's own agent was another User's; run kit login again to connect it to you.\n");
118
116
  }
119
- const callback = await listen();
117
+ await placeAppGit(ownAgent, await readOwnAgent());
120
118
  try {
121
- const { start_url } = await post(house, '/kit', {
122
- ...started,
123
- presentation: 'loopback',
124
- loopback_uri: callback.uri,
125
- });
126
- process.stdout.write(`Open this link and confirm: ${start_url}\n`);
127
- try {
128
- await exchange(await callback.code);
129
- }
130
- catch (error) {
131
- await callback.answer(`This Environment was not connected: ${error.message}`);
132
- throw error;
133
- }
134
- await callback.answer('This Environment is connected. You can close this tab.');
119
+ startService();
135
120
  }
136
- finally {
137
- callback.close();
121
+ catch (error) {
122
+ process.stderr.write(`kit: ${error.message}\n`);
138
123
  }
139
- await placeGit();
140
124
  }
package/dist/logout.js CHANGED
@@ -1,21 +1,21 @@
1
1
  import { HouseRefusal, post } from './api.js';
2
2
  import { forgetAppGit } from './app-git.js';
3
- import { forgetEnrolment, readEnrolment } from './home.js';
3
+ import { forgetEnrolment, forgetOwnAgent, readEnrolment } from './home.js';
4
4
  export async function logout() {
5
5
  const enrolled = await readEnrolment();
6
- if (enrolled === null) {
7
- await forgetAppGit();
8
- process.stdout.write('This computer is not connected to House.\n');
9
- return;
6
+ if (enrolled !== null) {
7
+ try {
8
+ await post(enrolled.house, '/kit/logout', {}, enrolled.credential);
9
+ }
10
+ catch (error) {
11
+ if (!(error instanceof HouseRefusal && error.status === 401))
12
+ throw error;
13
+ }
14
+ await forgetEnrolment(enrolled);
10
15
  }
11
- try {
12
- await post(enrolled.house, '/kit/logout', {}, enrolled.credential);
13
- }
14
- catch (error) {
15
- if (!(error instanceof HouseRefusal && error.status === 401))
16
- throw error;
17
- }
18
- await forgetEnrolment(enrolled);
19
16
  await forgetAppGit();
20
- process.stdout.write(`Environment ${enrolled.environment} is disconnected; kit login reconnects it.\n`);
17
+ await forgetOwnAgent();
18
+ process.stdout.write(enrolled === null
19
+ ? 'This computer is not connected to House.\n'
20
+ : `Environment ${enrolled.environment} is disconnected; kit login reconnects it.\n`);
21
21
  }
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
  }
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
+ 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
@@ -2,45 +2,52 @@ import { once } from 'node:events';
2
2
  import { watch } from 'node:fs';
3
3
  import { mkdir, rm, writeFile } from 'node:fs/promises';
4
4
  import { createServer } from 'node:http';
5
- import { extname, join } from 'node:path';
5
+ import { dirname, extname, join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
- import { killDescendants } from './acp.js';
8
7
  import { Agents } from './agents.js';
9
8
  import { house } from './api.js';
10
9
  import { received } from './bridge.js';
11
10
  import { Conversations } from './conversations.js';
12
11
  import { LocalCopies } from './copies.js';
13
- import { agentBase, enrolled, kitHome } from './home.js';
12
+ import { restart } from './end.js';
13
+ import { agentBase, enrolled, forgetRestart, kitHome, restartAsked } from './home.js';
14
+ import { killDescendants } from './scope.js';
14
15
  import { quoted } from './shell.js';
15
16
  import { SignIns } from './sign-in.js';
16
17
  import { placeSkillSet } from './skills.js';
17
18
  import { holdStream } from './stream.js';
18
19
  import { Updates } from './update.js';
20
+ import { codexLauncher } from './work.js';
19
21
  function report(error) {
20
22
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
21
23
  }
22
24
  function logged(work) {
23
25
  work.catch(report);
24
26
  }
25
- async function installShim() {
26
- const main = fileURLToPath(new URL(`./git-main${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
27
- await mkdir(join(kitHome(), 'shim'), { recursive: true });
28
- await writeFile(join(kitHome(), 'shim', 'git'), `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, {
29
- mode: 0o755,
30
- });
27
+ async function installShim(path, module) {
28
+ const main = fileURLToPath(new URL(`./${module}${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
29
+ await mkdir(dirname(path), { recursive: true });
30
+ await writeFile(path, `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, { mode: 0o755 });
31
31
  }
32
32
  async function serveOwner(copies) {
33
33
  const socketPath = join(kitHome(), 'owner.sock');
34
34
  await rm(socketPath, { force: true });
35
35
  const server = createServer(async (request, response) => {
36
36
  try {
37
- if (request.url !== '/git/push') {
37
+ const text = await received(request);
38
+ let answered;
39
+ if (request.url === '/git/fetch') {
40
+ answered = await copies.fetch();
41
+ }
42
+ else if (request.url === '/git/push') {
43
+ const { cwd, commit } = JSON.parse(text);
44
+ answered = await copies.push(cwd, commit, copies.owner);
45
+ }
46
+ else {
38
47
  response.writeHead(404).end();
39
48
  return;
40
49
  }
41
- const { cwd, commit } = JSON.parse(await received(request));
42
- const pushed = await copies.push(cwd, commit, copies.owner);
43
- response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(pushed));
50
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(answered));
44
51
  }
45
52
  catch (error) {
46
53
  response.writeHead(502).end(error instanceof Error ? error.message : String(error));
@@ -67,6 +74,7 @@ function connected() {
67
74
  }
68
75
  export async function resident() {
69
76
  await connected();
77
+ await forgetRestart();
70
78
  watch(kitHome(), () => {
71
79
  if (enrolled())
72
80
  return;
@@ -79,7 +87,8 @@ export async function resident() {
79
87
  const agents = new Agents(house);
80
88
  const copies = new LocalCopies(house);
81
89
  await copies.load();
82
- await installShim();
90
+ await installShim(join(kitHome(), 'shim', 'git'), 'git-main');
91
+ await installShim(codexLauncher(), 'codex-main');
83
92
  await serveOwner(copies);
84
93
  let stream = null;
85
94
  let reported = false;
@@ -88,6 +97,9 @@ export async function resident() {
88
97
  if (!idle()) {
89
98
  reported = false;
90
99
  }
100
+ else if (restartAsked() && conversations.quiet()) {
101
+ restart('restarting for an updated CLI');
102
+ }
91
103
  else if (!reported) {
92
104
  reported = true;
93
105
  logged(house.deliver('/kit/idle', {}, idle));
@@ -115,18 +127,13 @@ export async function resident() {
115
127
  opened: () => {
116
128
  conversations.opened();
117
129
  changed();
118
- logged(copies.select());
130
+ logged(copies.connected());
119
131
  },
120
132
  frame: (arrived) => {
121
133
  if (arrived.type === 'watching')
122
134
  conversations.watching(arrived.watching === true);
123
135
  if (arrived.type === 'work_available' && arrived.subject === 'agents')
124
136
  logged(agents.refresh());
125
- if (arrived.type === 'work_available' && arrived.subject === 'local_copy')
126
- logged(copies.select());
127
- if (arrived.type === 'entries') {
128
- copies.entries(arrived);
129
- }
130
137
  if (arrived.type === 'input') {
131
138
  reported = false;
132
139
  if (arrived.kind === 'sign_in')