@agentshouse/kit 0.2.1-alpha.9 → 0.2.1-c073f4e9391b2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +44 -26
  2. package/dist/abort.js +9 -0
  3. package/dist/acp.js +18 -75
  4. package/dist/agents.js +266 -53
  5. package/dist/api.js +40 -4
  6. package/dist/app-git.js +64 -0
  7. package/dist/bootstrap.json +10 -14
  8. package/dist/bridge.js +89 -71
  9. package/dist/chatgpt.js +25 -0
  10. package/dist/clis-main.js +23 -0
  11. package/dist/clis.js +203 -71
  12. package/dist/codex-main.js +58 -0
  13. package/dist/conversations.js +328 -199
  14. package/dist/copies.js +188 -161
  15. package/dist/end.js +22 -0
  16. package/dist/enrol-main.js +7 -1
  17. package/dist/events.js +521 -0
  18. package/dist/files.js +16 -1
  19. package/dist/git-main.js +2 -2
  20. package/dist/git.js +6 -2
  21. package/dist/home.js +72 -5
  22. package/dist/house-main.js +181 -57
  23. package/dist/instructions.js +16 -13
  24. package/dist/kit-main.js +55 -4
  25. package/dist/login.js +108 -97
  26. package/dist/logout.js +21 -0
  27. package/dist/mcp.js +39 -0
  28. package/dist/operation.js +7 -4
  29. package/dist/parts.js +82 -0
  30. package/dist/placement.js +48 -0
  31. package/dist/refusals.js +53 -0
  32. package/dist/relay.js +20 -0
  33. package/dist/resident.js +70 -34
  34. package/dist/scope.js +203 -0
  35. package/dist/secret-input.js +7 -2
  36. package/dist/service-main.js +9 -0
  37. package/dist/service.js +33 -0
  38. package/dist/shell.js +3 -0
  39. package/dist/sign-in.js +48 -11
  40. package/dist/skills.js +5 -10
  41. package/dist/stream.js +37 -7
  42. package/dist/transcription.js +170 -0
  43. package/dist/update.js +140 -0
  44. package/dist/wire.js +6 -0
  45. package/dist/work.js +348 -0
  46. package/how-we-work.md +10 -12
  47. package/package.json +4 -7
  48. package/dist/blocks.js +0 -51
@@ -1,13 +1,65 @@
1
1
  #!/usr/bin/env node
2
- import { createHash, randomUUID } from 'node:crypto';
2
+ import { createHash } from 'node:crypto';
3
3
  import { readFile } from 'node:fs/promises';
4
- import { request } from 'node:http';
5
- import { basename, join } from 'node:path';
6
- import { kitHome } from './home.js';
4
+ import { request, setGlobalProxyFromEnv } from 'node:http';
5
+ import { extname, join } from 'node:path';
6
+ import { HOUSE_REF } from './git.js';
7
+ import { kitHome, readEnrolment, readOwnAgent } from './home.js';
8
+ import { callHouse, rpc, UNREACHABLE } from './mcp.js';
9
+ import { refusalOf } from './refusals.js';
10
+ import { relayed } from './relay.js';
11
+ import { parse, stringify } from 'yaml';
7
12
  const USAGE = "usage: house <tool> ['<arguments as JSON>']";
8
- const GIT_HELP = 'Submit a Room commit to House; default HEAD. Use --owner only outside an Agent conversation. Native git push is not a House remote.';
9
- const GIT_USAGE = `usage: house git push [commit] [--owner]\n${GIT_HELP}`;
13
+ const PUSH_USAGE = 'usage: house push [commit] [--owner]';
14
+ const PUSH = "push [commit]: sends the Local copy's committed changes to House";
15
+ const FETCH_USAGE = 'usage: house fetch';
16
+ const FETCH = `fetch: records House's changes on each Local copy's ${HOUSE_REF}`;
17
+ const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
18
+ const CLOSED = "this conversation's House connection is closed; nothing to do from here";
19
+ const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
20
+ const REVOKED = 'this conversation no longer has House access; nothing to do from here';
21
+ const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
22
+ const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login";
10
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
+ ]);
51
+ function refused(path, status, text) {
52
+ const refusal = refusalOf(text);
53
+ if (refusal !== null)
54
+ return refusal.text;
55
+ if (status === 401)
56
+ return REVOKED;
57
+ if (URL.canParse(path))
58
+ return `the upload answered ${status}; upload the file again`;
59
+ if (status === 502 && /^[A-Za-z]/.test(text))
60
+ return text;
61
+ return `${path} answered ${status}`;
62
+ }
11
63
  function bridged(path, body, headers = { 'content-type': 'application/json' }, to = socketPath) {
12
64
  return new Promise((resolve, reject) => {
13
65
  const sent = request({ socketPath: to, path, method: 'POST', headers }, (answer) => {
@@ -20,15 +72,29 @@ function bridged(path, body, headers = { 'content-type': 'application/json' }, t
20
72
  if (answer.statusCode === 200)
21
73
  resolve(text);
22
74
  else
23
- reject(new Error(`${path} answered ${answer.statusCode}: ${text}`));
75
+ reject(new Error(refused(path, answer.statusCode, text)));
24
76
  });
25
77
  });
26
- sent.on('error', reject);
78
+ sent.on('error', (error) => reject(new Error(error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED)));
27
79
  sent.end(body instanceof Buffer ? body : JSON.stringify(body));
28
80
  });
29
81
  }
82
+ async function direct(message) {
83
+ const ownAgent = await readOwnAgent();
84
+ if (ownAgent === null)
85
+ throw new Error(UNCONNECTED);
86
+ await readEnrolment();
87
+ setGlobalProxyFromEnv();
88
+ const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
89
+ throw new Error(UNREACHABLE);
90
+ });
91
+ if (answer.status === 200)
92
+ return answer.text;
93
+ throw new Error(answer.status === 401 ? DISCONNECTED : (refusalOf(answer.text)?.text ?? `House answered ${answer.status}`));
94
+ }
30
95
  async function mcp(method, params) {
31
- const answer = JSON.parse(await bridged('/', { jsonrpc: '2.0', id: 1, method, params }));
96
+ const message = rpc(method, params);
97
+ const answer = JSON.parse(socketPath === undefined ? await direct(message) : await bridged('/', message));
32
98
  if (answer.error !== undefined)
33
99
  throw new Error(answer.error.message);
34
100
  return answer.result;
@@ -36,72 +102,130 @@ async function mcp(method, params) {
36
102
  async function tools() {
37
103
  return (await mcp('tools/list', {})).tools;
38
104
  }
39
- async function upload(path, roomRef) {
40
- const bytes = await readFile(path);
41
- const declared = JSON.parse(await bridged('/kit/attachments/upload', {
42
- ...(roomRef === undefined ? {} : { room_ref: roomRef }),
43
- version: randomUUID(),
44
- name: basename(path),
105
+ async function localFile(path) {
106
+ try {
107
+ return await readFile(path);
108
+ }
109
+ catch (error) {
110
+ throw new Error(error.code === 'EISDIR'
111
+ ? `${path} is a folder; upload one file at a time`
112
+ : `${path} is not a readable file`);
113
+ }
114
+ }
115
+ async function sent(url, bytes, operation) {
116
+ const headers = { 'content-type': 'application/octet-stream', 'x-house-byte-operation': operation };
117
+ if (socketPath !== undefined)
118
+ return bridged(url, bytes, headers);
119
+ setGlobalProxyFromEnv();
120
+ const answer = await fetch(relayed(url), { method: 'POST', headers, body: bytes }).catch(() => {
121
+ throw new Error(UNREACHABLE);
122
+ });
123
+ const text = await answer.text();
124
+ if (answer.status === 200)
125
+ return text;
126
+ throw new Error(refused(url, answer.status, text));
127
+ }
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,
45
135
  bytes: bytes.length,
46
136
  sha256: createHash('sha256').update(bytes).digest('hex'),
47
- }));
48
- return bridged(declared.upload.url, bytes, {
49
- 'content-type': 'application/octet-stream',
50
- 'x-house-byte-operation': declared.upload.operation,
137
+ ...(mediaType === undefined ? {} : { media_type: mediaType }),
51
138
  });
139
+ const declared = parse(answer);
140
+ if (declared.upload === undefined)
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;
52
159
  }
53
- async function gitPush(args) {
54
- if (args.includes('--help'))
55
- return GIT_USAGE;
56
- if (args[0] !== 'push')
57
- throw new Error(GIT_USAGE);
58
- const owner = args.includes('--owner');
59
- const commit = args.slice(1).find((arg) => arg !== '--owner') ?? 'HEAD';
160
+ async function push(args) {
161
+ const { flags, positionals: [commit = 'HEAD'] } = accepted(args, ['--help', '--owner'], 1, PUSH_USAGE);
162
+ if (flags.has('--help'))
163
+ return PUSH_USAGE;
164
+ const owner = flags.has('--owner');
60
165
  if (owner && socketPath !== undefined)
61
- throw new Error('house git push --owner runs outside an Agent conversation');
166
+ throw new Error('--owner is not for Agent conversations; run house push without it');
62
167
  if (!owner && socketPath === undefined)
63
- throw new Error('outside an Agent conversation, house git push needs --owner');
168
+ throw new Error('outside an Agent conversation, house push needs --owner');
64
169
  const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, undefined, owner ? join(kitHome(), 'owner.sock') : socketPath));
65
170
  if (pushed.refused)
66
171
  throw new Error(pushed.text);
67
172
  return pushed.text;
68
173
  }
69
- async function house([verb, argument]) {
70
- if (verb === undefined || verb === '--help') {
71
- return [USAGE, `git push [commit]: ${GIT_HELP}`, ...(await tools()).map((tool) => `${tool.name}: ${tool.description}`)].join('\n');
174
+ async function fetched(args) {
175
+ if (accepted(args, ['--help'], 0, FETCH_USAGE).flags.has('--help'))
176
+ return FETCH_USAGE;
177
+ const answer = JSON.parse(await bridged('/git/fetch', {}, undefined, socketPath ?? join(kitHome(), 'owner.sock')));
178
+ if (answer.refused)
179
+ throw new Error(answer.text);
180
+ return answer.text;
181
+ }
182
+ function argumentsOf(argument) {
183
+ if (argument === undefined)
184
+ return {};
185
+ let parsed;
186
+ try {
187
+ parsed = JSON.parse(argument);
188
+ }
189
+ catch {
190
+ throw new Error(ARGUMENTS);
191
+ }
192
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
193
+ throw new Error(ARGUMENTS);
194
+ return parsed;
195
+ }
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') {
203
+ return [USAGE, 'help', PUSH, FETCH, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
72
204
  }
73
- if (argument === '--help') {
205
+ if (flags.has('--help')) {
74
206
  const tool = (await tools()).find((listed) => listed.name === verb);
75
207
  if (tool === undefined)
76
- throw new Error(`House has no tool ${verb}`);
77
- return `${tool.description}\n${JSON.stringify(tool.inputSchema, null, 2)}`;
208
+ throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
209
+ return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
78
210
  }
79
- const args = (argument === undefined ? {} : JSON.parse(argument));
80
- if (verb === 'upload_attachment')
81
- return upload(String(args.path), args.room_ref);
82
- if (verb === 'append_record' && Array.isArray(args.attachments)) {
83
- const attachments = [];
84
- for (const path of args.attachments) {
85
- attachments.push(JSON.parse(await upload(String(path), args.room_ref)).attachment);
86
- }
87
- args.attachments = attachments;
88
- }
89
- const result = await mcp('tools/call', { name: verb, arguments: args });
211
+ const parsed = argumentsOf(argument);
212
+ return verb === 'upload' ? upload(parsed) : called(verb, parsed);
213
+ }
214
+ async function called(name, args) {
215
+ const result = await mcp('tools/call', { name, arguments: args });
90
216
  const text = result.content.map((content) => content.text).join('\n');
91
217
  if (result.isError === true)
92
- throw new Error(text);
218
+ throw new Error(text.replace(/\n+$/, ''));
93
219
  return text;
94
220
  }
95
221
  const argv = process.argv.slice(2);
96
- if (argv[0] !== 'git' && socketPath === undefined) {
97
- process.stderr.write('house: house runs inside an Agent conversation\n');
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) => {
225
+ process.stdout.write(`${text}\n`);
226
+ if (argv[0] === 'shell')
227
+ process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
228
+ }, (error) => {
229
+ process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
98
230
  process.exitCode = 1;
99
- }
100
- else {
101
- (argv[0] === 'git' ? gitPush(argv.slice(1)) : house(argv)).then((text) => {
102
- process.stdout.write(`${text}\n`);
103
- }, (error) => {
104
- process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
105
- process.exitCode = 1;
106
- });
107
- }
231
+ });
@@ -1,33 +1,36 @@
1
- import { readEnrolment } from './home.js';
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, upload it with `house upload_attachment` and link it in your answer.';
5
- const COPIES_LINE = 'These House paths are Git working copies here; commit in one and run `house git push` to send the commit to House:';
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`.";
7
+ const COPIES_LINE = `House Local copies; before work run \`house fetch\` and rebase onto \`${HOUSE_REF}\`; after it commit, then \`house push\`:`;
6
8
  const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
9
+ const FAILED = /^exit: [1-9]\d*$/;
7
10
  const CUT = /^stderr: shell: output_cut (\d+) of \d+ bytes; continue with: (.+)$/;
11
+ function cutOf(lines) {
12
+ const cut = CUT.exec(lines[0] ?? '');
13
+ return cut !== null && Buffer.byteLength(lines.slice(1).join('\n')) === Number(cut[1]) ? cut : null;
14
+ }
8
15
  async function howWeWork(bridge) {
9
16
  let document = '';
10
17
  for (let command = `cat ${HOW_WE_WORK}`; command !== undefined;) {
11
18
  const read = await bridge.tool('shell', { command });
12
19
  const text = read.content.map((content) => content.text).join('\n');
13
20
  const lines = text.split('\n');
14
- let at = lines[5]?.startsWith('authority: ') ? 6 : 5;
15
- if (read.isError === true || lines[2] !== 'exit: 0') {
16
- const refusal = read.isError === true ? text : lines.slice(at).join('\n').replace(/^stderr: /gm, '');
21
+ if (read.isError === true || (FAILED.test(lines[0] ?? '') && lines[1]?.startsWith('stderr: '))) {
22
+ const refusal = read.isError === true ? text : lines.slice(1).join('\n').replace(/^stderr: /gm, '');
17
23
  if (UNREADABLE.test(refusal))
18
24
  return '';
19
25
  throw new Error(refusal);
20
26
  }
21
- const cut = lines[3] === 'truncation: egress' ? CUT.exec(lines[at++] ?? '') : null;
22
- const shown = Buffer.from(`${lines.slice(at).join('\n')}\n`);
23
- document += (cut === null ? shown : shown.subarray(0, Number(cut[1]))).toString();
27
+ const cut = cutOf(lines);
28
+ document += lines.slice(cut === null ? 0 : 1).join('\n');
24
29
  command = cut?.[2];
25
30
  }
26
31
  return document.replace(/\n$/, '');
27
32
  }
28
33
  export async function instructions(bridge, base, copies) {
29
- const app = new URL('/app/new.git', (await readEnrolment()).house).href;
30
- const appLine = `To show the User a page, upload it or push it to an App instead of starting a server; \`git clone ${app}\` starts a new App.`;
31
- const lines = [HOUSE_LINE, FILE_LINE, appLine, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
34
+ const lines = [SOURCE_LINE, HOUSE_LINE, FILE_LINE, READ_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
32
35
  return [lines.join('\n'), base, await howWeWork(bridge)].filter((part) => part !== '').join('\n\n');
33
36
  }
package/dist/kit-main.js CHANGED
@@ -1,16 +1,67 @@
1
1
  #!/usr/bin/env node
2
2
  import { setGlobalProxyFromEnv } from 'node:http';
3
+ import { parseArgs } from 'node:util';
4
+ import { answerGitCredential } from './app-git.js';
5
+ import { chatgpt } from './chatgpt.js';
3
6
  import { login } from './login.js';
7
+ import { logout } from './logout.js';
4
8
  import { resident } from './resident.js';
9
+ const USAGE = 'usage: kit <login|logout|resident|chatgpt>\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
+ ]);
5
39
  const [command, ...argv] = process.argv.slice(2);
6
40
  setGlobalProxyFromEnv();
7
41
  async function run() {
8
42
  if (command === 'login')
9
43
  return login(argv);
10
- if (command === 'resident')
11
- return resident();
12
- process.stderr.write('usage: kit <login|resident>\n');
13
- process.exitCode = 2;
44
+ if (command === 'chatgpt')
45
+ return chatgpt(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);
14
65
  }
15
66
  run().catch((error) => {
16
67
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
package/dist/login.js CHANGED
@@ -1,64 +1,46 @@
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';
7
- import { readEnrolment, writeEnrolment } from './home.js';
8
- const DEFAULT_HOUSE = 'https://agents.house';
9
- function listen() {
10
- return new Promise((resolve, reject) => {
11
- let deliver = () => undefined;
12
- let held = null;
13
- const code = new Promise((settle) => {
14
- deliver = settle;
15
- });
16
- const server = createServer((request, response) => {
17
- const received = new URL(request.url ?? '/', 'http://127.0.0.1').searchParams.get('code');
18
- if (received === null || held !== null) {
19
- response.writeHead(404).end();
20
- return;
21
- }
22
- held = response;
23
- deliver(received);
24
- });
25
- const close = () => {
26
- server.close();
27
- server.closeAllConnections();
28
- };
29
- const port = Number(process.env.HOUSE_KIT_LOGIN_PORT ?? 0);
30
- server.once('error', reject);
31
- server.listen(port, port === 0 ? '127.0.0.1' : '0.0.0.0', () => {
32
- const address = server.address();
33
- if (address === null || typeof address === 'string') {
34
- reject(new Error('the login callback has no port'));
35
- return;
36
- }
37
- resolve({
38
- uri: `http://127.0.0.1:${address.port}/callback`,
39
- code,
40
- answer: (text) => new Promise((written) => {
41
- if (held === null || held.destroyed || !held.socket || held.socket.destroyed)
42
- return written();
43
- held.once('close', () => written());
44
- held.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', connection: 'close' }).end(`${text}\n`);
45
- }),
46
- close,
47
- });
48
- });
49
- });
5
+ import { post, retrying } from './api.js';
6
+ import { placeAppGit } from './app-git.js';
7
+ import { writeCodexRule } from './clis.js';
8
+ import { forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
9
+ import { callHouse, rpc } from './mcp.js';
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';
14
+ const OPENER = process.platform === 'darwin' ? 'open' : 'xdg-open';
15
+ // Polling every two seconds brings the User's confirmation to the waiting Kit moments after they give it.
16
+ const POLL_INTERVAL_MS = 2000;
17
+ function open(link) {
18
+ spawn(OPENER, [link], { detached: true, stdio: 'ignore' })
19
+ .on('error', () => undefined)
20
+ .unref();
50
21
  }
51
- async function typed(question) {
52
- const reader = createInterface({ input: process.stdin, output: process.stdout });
53
- const closed = new Promise((_, reject) => {
54
- reader.once('close', () => reject(new Error('no code was typed')));
55
- });
56
- try {
57
- return (await Promise.race([reader.question(question), closed])).trim();
58
- }
59
- finally {
60
- reader.close();
61
- }
22
+ export async function accepted(house, credential) {
23
+ const checked = await callHouse(house, credential, rpc('tools/list', {}));
24
+ if (checked.status === 200)
25
+ return true;
26
+ if (checked.status === 401)
27
+ return false;
28
+ throw new Error(`House answered ${checked.status} when Kit checked this computer's own agent's connection: ${checked.text}`);
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' } } : {};
62
44
  }
63
45
  export async function login(argv) {
64
46
  const { values } = parseArgs({
@@ -66,51 +48,80 @@ export async function login(argv) {
66
48
  options: {
67
49
  house: { type: 'string' },
68
50
  environment: { type: 'string' },
69
- manual: { type: 'boolean', default: false },
51
+ rooms: { type: 'string' },
52
+ 'no-private': { type: 'boolean', default: false },
53
+ code: { type: 'string' },
54
+ help: { type: 'boolean', default: false },
70
55
  },
71
56
  });
72
- const enrolled = await readEnrolment();
73
- const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
74
- const environment = values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined);
75
- const verifier = randomBytes(32).toString('base64url');
76
- const started = {
77
- ...(environment === undefined
78
- ? { act: 'new_environment', label: hostname() }
79
- : { act: 'existing_environment', environment_id: environment }),
80
- code_challenge: createHash('sha256').update(verifier).digest('base64url'),
81
- };
82
- const exchange = async (code) => {
83
- const exchanged = await post(house, '/kit/token', { code, code_verifier: verifier });
84
- await writeEnrolment({ house, environment: exchanged.environment, credential: exchanged.credential });
85
- process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
86
- };
87
- if (values.manual) {
88
- const { start_url } = await post(house, '/kit', {
89
- ...started,
90
- presentation: 'manual',
91
- });
92
- process.stdout.write(`Open this link and confirm: ${start_url}\n`);
93
- await exchange(await typed('Code: '));
57
+ if (values.help) {
58
+ process.stdout.write(USAGE);
94
59
  return;
95
60
  }
96
- const callback = await listen();
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']);
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);
74
+ const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
75
+ const replaces = process.env.HOUSE_KIT_REPLACES;
76
+ const environment = replaces === undefined ? (values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined)) : undefined;
77
+ const ownAgent = await readOwnAgent();
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
+ });
112
+ process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
113
+ if (exchanged.headless_credential !== undefined) {
114
+ await writeOwnAgent({ house, user: exchanged.user, credential: exchanged.headless_credential });
115
+ }
116
+ else if (held && ownAgent !== null && ownAgent.user !== exchanged.user) {
117
+ await forgetOwnAgent();
118
+ process.stdout.write("This computer's own agent was another User's; run kit login again to connect it to you.\n");
119
+ }
120
+ await placeAppGit(ownAgent, await readOwnAgent());
97
121
  try {
98
- const { start_url } = await post(house, '/kit', {
99
- ...started,
100
- presentation: 'loopback',
101
- loopback_uri: callback.uri,
102
- });
103
- process.stdout.write(`Open this link and confirm: ${start_url}\n`);
104
- try {
105
- await exchange(await callback.code);
106
- }
107
- catch (error) {
108
- await callback.answer(`This Environment was not connected: ${error.message}`);
109
- throw error;
110
- }
111
- await callback.answer('This Environment is connected. You can close this tab.');
122
+ startService();
112
123
  }
113
- finally {
114
- callback.close();
124
+ catch (error) {
125
+ process.stderr.write(`kit: ${error.message}\n`);
115
126
  }
116
127
  }
package/dist/logout.js ADDED
@@ -0,0 +1,21 @@
1
+ import { HouseRefusal, post } from './api.js';
2
+ import { forgetAppGit } from './app-git.js';
3
+ import { forgetEnrolment, forgetOwnAgent, readEnrolment } from './home.js';
4
+ export async function logout() {
5
+ const enrolled = await readEnrolment();
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);
15
+ }
16
+ await forgetAppGit();
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
+ }