@agentshouse/kit 0.2.1-c53a84236c3d9 → 0.2.1-c5987c9cb6553

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.
@@ -1,68 +1,105 @@
1
1
  #!/usr/bin/env node
2
2
  import { createHash } from 'node:crypto';
3
- import { readFile } from 'node:fs/promises';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
4
  import { request, setGlobalProxyFromEnv } from 'node:http';
5
- import { basename, join } from 'node:path';
5
+ import { dirname, extname, join, resolve } from 'node:path';
6
+ import { verified } from './files.js';
6
7
  import { HOUSE_REF } from './git.js';
7
- import { kitHome, readOwnAgent } from './home.js';
8
+ import { kitHome, readEnrolment, readOwnAgent } from './home.js';
8
9
  import { callHouse, rpc, UNREACHABLE } from './mcp.js';
9
10
  import { refusalOf } from './refusals.js';
10
11
  import { relayed } from './relay.js';
11
- import { parse } from 'yaml';
12
+ import { parse, stringify } from 'yaml';
12
13
  const USAGE = "usage: house <tool> ['<arguments as JSON>']";
13
14
  const PUSH_USAGE = 'usage: house push [commit] [--owner]';
14
15
  const PUSH = "push [commit]: sends the Local copy's committed changes to House";
15
16
  const FETCH_USAGE = 'usage: house fetch';
16
17
  const FETCH = `fetch: records House's changes on each Local copy's ${HOUSE_REF}`;
18
+ const DOWNLOAD_USAGE = `usage: house download '{"path":"/rooms/<handle>/<path>","file":"<local file>"}', adding "ref" for a revision`;
19
+ const DOWNLOAD = 'download: writes a binary file of a Room to the local file named by file';
17
20
  const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
18
21
  const CLOSED = "this conversation's House connection is closed; nothing to do from here";
19
22
  const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
20
23
  const REVOKED = 'this conversation no longer has House access; nothing to do from here';
21
24
  const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
22
25
  const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login";
26
+ const UNCONFIRMED = 'with no result; a write may or may not have taken effect, so read before you repeat it';
23
27
  const socketPath = process.env.HOUSE_BRIDGE;
24
- function refused(path, status, text) {
28
+ const MEDIA_TYPES = new Map([
29
+ ['avif', 'image/avif'],
30
+ ['csv', 'text/csv'],
31
+ ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
32
+ ['gif', 'image/gif'],
33
+ ['heic', 'image/heic'],
34
+ ['html', 'text/html'],
35
+ ['jpeg', 'image/jpeg'],
36
+ ['jpg', 'image/jpeg'],
37
+ ['json', 'application/json'],
38
+ ['m4a', 'audio/mp4'],
39
+ ['md', 'text/markdown'],
40
+ ['mov', 'video/quicktime'],
41
+ ['mp3', 'audio/mpeg'],
42
+ ['mp4', 'video/mp4'],
43
+ ['ogg', 'audio/ogg'],
44
+ ['pdf', 'application/pdf'],
45
+ ['png', 'image/png'],
46
+ ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
47
+ ['svg', 'image/svg+xml'],
48
+ ['txt', 'text/plain'],
49
+ ['wav', 'audio/wav'],
50
+ ['webm', 'video/webm'],
51
+ ['webp', 'image/webp'],
52
+ ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
53
+ ['zip', 'application/zip'],
54
+ ]);
55
+ function refused(path, method, status, text, local) {
25
56
  const refusal = refusalOf(text);
26
57
  if (refusal !== null)
27
58
  return refusal.text;
28
59
  if (status === 401)
29
60
  return REVOKED;
61
+ const act = method === 'GET' ? 'download' : 'upload';
30
62
  if (URL.canParse(path))
31
- return `the upload answered ${status}; upload the file again`;
32
- if (status === 502 && /^[A-Za-z]/.test(text))
63
+ return `the ${act} answered ${status}; ${act} the file again`;
64
+ if (status === 502 && local)
33
65
  return text;
34
- return `${path} answered ${status}`;
66
+ return path === '/' ? unconfirmed(status) : `${path} answered ${status}`;
35
67
  }
36
- function bridged(path, body, headers = { 'content-type': 'application/json' }, to = socketPath) {
68
+ function unconfirmed(status) {
69
+ return `House answered ${status} ${UNCONFIRMED}`;
70
+ }
71
+ function exchanged(path, method, body, headers = { 'content-type': 'application/json' }, to = socketPath) {
37
72
  return new Promise((resolve, reject) => {
38
- const sent = request({ socketPath: to, path, method: 'POST', headers }, (answer) => {
39
- let text = '';
40
- answer.setEncoding('utf8');
41
- answer.on('data', (chunk) => {
42
- text += chunk;
43
- });
73
+ const sent = request({ socketPath: to, path, method, headers }, (answer) => {
74
+ const chunks = [];
75
+ answer.on('data', (chunk) => chunks.push(chunk));
44
76
  answer.on('end', () => {
77
+ const bytes = Buffer.concat(chunks);
45
78
  if (answer.statusCode === 200)
46
- resolve(text);
79
+ resolve(bytes);
47
80
  else
48
- reject(new Error(refused(path, answer.statusCode, text)));
81
+ reject(new Error(refused(path, method, answer.statusCode, bytes.toString('utf8'), answer.headers['content-type'] === undefined)));
49
82
  });
50
83
  });
51
84
  sent.on('error', (error) => reject(new Error(error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED)));
52
- sent.end(body instanceof Buffer ? body : JSON.stringify(body));
85
+ sent.end(body === undefined ? undefined : body instanceof Buffer ? body : JSON.stringify(body));
53
86
  });
54
87
  }
88
+ async function bridged(path, body, headers, to = socketPath) {
89
+ return (await exchanged(path, 'POST', body, headers, to)).toString('utf8');
90
+ }
55
91
  async function direct(message) {
56
92
  const ownAgent = await readOwnAgent();
57
93
  if (ownAgent === null)
58
94
  throw new Error(UNCONNECTED);
95
+ await readEnrolment();
59
96
  setGlobalProxyFromEnv();
60
97
  const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
61
98
  throw new Error(UNREACHABLE);
62
99
  });
63
100
  if (answer.status === 200)
64
101
  return answer.text;
65
- throw new Error(answer.status === 401 ? DISCONNECTED : (refusalOf(answer.text)?.text ?? `House answered ${answer.status}`));
102
+ throw new Error(answer.status === 401 ? DISCONNECTED : (refusalOf(answer.text)?.text ?? unconfirmed(answer.status)));
66
103
  }
67
104
  async function mcp(method, params) {
68
105
  const message = rpc(method, params);
@@ -84,41 +121,75 @@ async function localFile(path) {
84
121
  : `${path} is not a readable file`);
85
122
  }
86
123
  }
87
- async function sent(url, bytes, operation) {
88
- const headers = { 'content-type': 'application/octet-stream', 'x-house-byte-operation': operation };
124
+ async function transferred(url, method, bytes, headers) {
89
125
  if (socketPath !== undefined)
90
- return bridged(url, bytes, headers);
126
+ return exchanged(url, method, bytes, headers);
91
127
  setGlobalProxyFromEnv();
92
- const answer = await fetch(relayed(url), { method: 'POST', headers, body: bytes }).catch(() => {
128
+ const answer = await fetch(relayed(url), { method, ...(headers === undefined ? {} : { headers }), ...(bytes === undefined ? {} : { body: bytes }) }).catch(() => {
93
129
  throw new Error(UNREACHABLE);
94
130
  });
95
- const text = await answer.text();
131
+ const received = Buffer.from(await answer.arrayBuffer());
96
132
  if (answer.status === 200)
97
- return text;
98
- throw new Error(refused(url, answer.status, text));
99
- }
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),
133
+ return received;
134
+ throw new Error(refused(url, method, answer.status, received.toString('utf8'), false));
135
+ }
136
+ async function sent(url, bytes, operation) {
137
+ const headers = { 'content-type': 'application/octet-stream', 'x-house-byte-operation': operation };
138
+ return (await transferred(url, 'POST', bytes, headers)).toString('utf8');
139
+ }
140
+ async function download(args) {
141
+ const { flags, positionals: [argument] } = accepted(args, ['--help'], 1, DOWNLOAD_USAGE);
142
+ if (flags.has('--help'))
143
+ return DOWNLOAD_USAGE;
144
+ const { file, ...selected } = argumentsOf(argument);
145
+ if (typeof file !== 'string' || file === '')
146
+ throw new Error('download needs "file", the local file to write');
147
+ const inspected = parse(await called('inspect', selected));
148
+ if (typeof inspected?.download !== 'string')
149
+ throw new Error(`${String(selected.path)} holds no binary file; shell reads its text`);
150
+ const bytes = verified(await transferred(inspected.download, 'GET'), String(inspected.sha256), String(selected.path));
151
+ const written = resolve(file);
152
+ await mkdir(dirname(written), { recursive: true });
153
+ await writeFile(written, bytes);
154
+ return written;
155
+ }
156
+ async function upload({ file, ...destination }) {
157
+ if (typeof file !== 'string' || file === '')
158
+ throw new Error('upload needs "file", a local file');
159
+ const bytes = await localFile(file);
160
+ const mediaType = MEDIA_TYPES.get(extname(file).slice(1).toLowerCase());
161
+ const answer = await called('upload', {
162
+ ...destination,
107
163
  bytes: bytes.length,
108
164
  sha256: createHash('sha256').update(bytes).digest('hex'),
109
- }));
165
+ ...(mediaType === undefined ? {} : { media_type: mediaType }),
166
+ });
167
+ const declared = parse(answer);
110
168
  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;
169
+ return answer;
170
+ const written = JSON.parse(await sent(declared.upload.url, bytes, declared.upload.operation));
171
+ return stringify(written, { lineWidth: 0 }).trimEnd();
172
+ }
173
+ function unexpected(argument, usage) {
174
+ return new Error(`unexpected argument ${argument}; ${usage}`);
175
+ }
176
+ function accepted(args, flags, positionals, usage) {
177
+ const given = { flags: new Set(), positionals: [] };
178
+ for (const arg of args) {
179
+ if (flags.includes(arg))
180
+ given.flags.add(arg);
181
+ else if (!arg.startsWith('-') && given.positionals.length < positionals)
182
+ given.positionals.push(arg);
183
+ else
184
+ throw unexpected(arg, usage);
185
+ }
186
+ return given;
116
187
  }
117
188
  async function push(args) {
118
- if (args.includes('--help'))
189
+ const { flags, positionals: [commit = 'HEAD'] } = accepted(args, ['--help', '--owner'], 1, PUSH_USAGE);
190
+ if (flags.has('--help'))
119
191
  return PUSH_USAGE;
120
- const owner = args.includes('--owner');
121
- const commit = args.find((arg) => arg !== '--owner') ?? 'HEAD';
192
+ const owner = flags.has('--owner');
122
193
  if (owner && socketPath !== undefined)
123
194
  throw new Error('--owner is not for Agent conversations; run house push without it');
124
195
  if (!owner && socketPath === undefined)
@@ -129,7 +200,7 @@ async function push(args) {
129
200
  return pushed.text;
130
201
  }
131
202
  async function fetched(args) {
132
- if (args.includes('--help'))
203
+ if (accepted(args, ['--help'], 0, FETCH_USAGE).flags.has('--help'))
133
204
  return FETCH_USAGE;
134
205
  const answer = JSON.parse(await bridged('/git/fetch', {}, undefined, socketPath ?? join(kitHome(), 'owner.sock')));
135
206
  if (answer.refused)
@@ -150,28 +221,23 @@ function argumentsOf(argument) {
150
221
  throw new Error(ARGUMENTS);
151
222
  return parsed;
152
223
  }
153
- async function house([verb, argument]) {
154
- if (verb === undefined || verb === '--help' || verb === 'help') {
155
- return [USAGE, 'help', PUSH, FETCH, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
224
+ async function house(args) {
225
+ const { flags, positionals: [verb, argument] } = accepted(args, ['--help'], 2, USAGE);
226
+ if (verb === 'help' && argument !== undefined)
227
+ throw unexpected(argument, USAGE);
228
+ if (flags.has('--help') && argument !== undefined)
229
+ throw unexpected('--help', USAGE);
230
+ if (verb === undefined || verb === 'help') {
231
+ return [USAGE, 'help', PUSH, FETCH, DOWNLOAD, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
156
232
  }
157
- if (argument === '--help') {
233
+ if (flags.has('--help')) {
158
234
  const tool = (await tools()).find((listed) => listed.name === verb);
159
235
  if (tool === undefined)
160
236
  throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
161
237
  return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
162
238
  }
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);
239
+ const parsed = argumentsOf(argument);
240
+ return verb === 'upload' ? upload(parsed) : called(verb, parsed);
175
241
  }
176
242
  async function called(name, args) {
177
243
  const result = await mcp('tools/call', { name, arguments: args });
@@ -181,7 +247,15 @@ async function called(name, args) {
181
247
  return text;
182
248
  }
183
249
  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) => {
250
+ const named = argv.findIndex((arg) => !arg.startsWith('-'));
251
+ const rest = argv.filter((_arg, index) => index !== named);
252
+ (argv[named] === 'push'
253
+ ? push(rest)
254
+ : argv[named] === 'fetch'
255
+ ? fetched(rest)
256
+ : argv[named] === 'download'
257
+ ? download(rest)
258
+ : house(argv)).then((text) => {
185
259
  process.stdout.write(`${text}\n`);
186
260
  if (argv[0] === 'shell')
187
261
  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 { chatgpt } from './chatgpt.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|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
+ ]);
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 === '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);
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
  }