@agentshouse/kit 0.2.1-c903d1429e34a → 0.2.1-c9a26041e119a

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 (83) hide show
  1. package/README.md +16 -15
  2. package/dist/agents.js +58 -4
  3. package/dist/api.js +5 -1
  4. package/dist/bootstrap.json +4 -4
  5. package/dist/chatgpt.js +26 -0
  6. package/dist/clis.js +42 -9
  7. package/dist/conversations.js +6 -5
  8. package/dist/copies.js +18 -8
  9. package/dist/end.js +4 -0
  10. package/dist/files.js +7 -1
  11. package/dist/git.js +11 -8
  12. package/dist/home.js +41 -4
  13. package/dist/house-main.js +165 -65
  14. package/dist/instructions.js +4 -29
  15. package/dist/kit-main.js +53 -8
  16. package/dist/login.js +39 -13
  17. package/dist/parts.js +34 -16
  18. package/dist/placement.js +48 -0
  19. package/dist/relay.js +1 -1
  20. package/dist/resident.js +8 -4
  21. package/dist/skills.js +81 -12
  22. package/dist/stream.js +62 -13
  23. package/dist/transcription.js +3 -3
  24. package/dist/update.js +28 -6
  25. package/dist/wire.js +6 -0
  26. package/how-we-work.md +13 -3
  27. package/package.json +2 -1
  28. package/skills/ask-matt/SKILL.md +17 -11
  29. package/skills/ask-matt/agents/openai.yaml +1 -0
  30. package/skills/code-review/SKILL.md +5 -5
  31. package/skills/codebase-design/DESIGN-IT-TWICE.md +1 -1
  32. package/skills/codebase-design/SKILL.md +0 -2
  33. package/skills/diagnosing-bugs/SKILL.md +2 -4
  34. package/skills/domain-modeling/{CONTEXT-FORMAT.md → GLOSSARY-FORMAT.md} +10 -10
  35. package/skills/domain-modeling/SKILL.md +12 -14
  36. package/skills/grill-me/SKILL.md +1 -2
  37. package/skills/grill-me/agents/openai.yaml +1 -0
  38. package/skills/grill-with-docs/SKILL.md +1 -2
  39. package/skills/grill-with-docs/agents/openai.yaml +1 -0
  40. package/skills/grilling/SKILL.md +2 -2
  41. package/skills/handoff/SKILL.md +2 -3
  42. package/skills/handoff/agents/openai.yaml +1 -0
  43. package/skills/implement/SKILL.md +5 -4
  44. package/skills/implement/agents/openai.yaml +1 -0
  45. package/skills/implement-spec/SKILL.md +40 -0
  46. package/skills/implement-spec/agents/openai.yaml +5 -0
  47. package/skills/improve-codebase-architecture/SKILL.md +6 -7
  48. package/skills/improve-codebase-architecture/agents/openai.yaml +1 -0
  49. package/skills/pr/CREDITS.md +3 -0
  50. package/skills/pr/LICENSE +21 -0
  51. package/skills/pr/SKILL.md +170 -0
  52. package/skills/pr/agents/openai.yaml +3 -0
  53. package/skills/prototype/SKILL.md +0 -2
  54. package/skills/research/SKILL.md +0 -2
  55. package/skills/retro/LICENSE +21 -0
  56. package/skills/retro/SKILL.md +44 -0
  57. package/skills/retro/agents/openai.yaml +5 -0
  58. package/skills/tdd/SKILL.md +2 -4
  59. package/skills/teach/SKILL.md +3 -4
  60. package/skills/teach/agents/openai.yaml +1 -0
  61. package/skills/to-questionnaire/SKILL.md +1 -2
  62. package/skills/to-questionnaire/agents/openai.yaml +1 -0
  63. package/skills/to-spec/SKILL.md +1 -2
  64. package/skills/to-spec/agents/openai.yaml +1 -0
  65. package/skills/to-tickets/SKILL.md +3 -4
  66. package/skills/to-tickets/agents/openai.yaml +1 -0
  67. package/skills/triage/AGENT-BRIEF.md +207 -0
  68. package/skills/triage/LICENSE +21 -0
  69. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  70. package/skills/triage/SKILL.md +112 -0
  71. package/skills/triage/agents/openai.yaml +5 -0
  72. package/skills/wait-what/SKILL.md +2 -3
  73. package/skills/wait-what/agents/openai.yaml +1 -0
  74. package/skills/wayfinder/SKILL.md +5 -6
  75. package/skills/wayfinder/agents/openai.yaml +1 -0
  76. package/skills/wizard/LICENSE +21 -0
  77. package/skills/wizard/SKILL.md +44 -0
  78. package/skills/wizard/agents/openai.yaml +3 -0
  79. package/skills/wizard/template.sh +223 -0
  80. package/skills/writing-for-agents/SKILL.md +0 -2
  81. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  82. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  83. /package/skills/{resolving-merge-conflicts → implement-spec}/LICENSE +0 -0
@@ -1,69 +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 { basename, dirname, extname, join, resolve } from 'node:path';
6
+ import { verified } from './files.js';
6
7
  import { HOUSE_REF } from './git.js';
7
- import { kitHome, readEnrolment, readOwnAgent } from './home.js';
8
+ import { kitHome, readOwnAgent } from './home.js';
8
9
  import { callHouse, rpc, UNREACHABLE } from './mcp.js';
9
10
  import { refusalOf } from './refusals.js';
10
- import { relayed } from './relay.js';
11
- import { parse } from 'yaml';
11
+ import { relayed, selectRelay } from './relay.js';
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);
59
- await readEnrolment();
95
+ selectRelay(process.env.HOUSE_KIT_RELAY || ownAgent.relay);
60
96
  setGlobalProxyFromEnv();
61
97
  const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
62
98
  throw new Error(UNREACHABLE);
63
99
  });
64
100
  if (answer.status === 200)
65
101
  return answer.text;
66
- 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)));
67
103
  }
68
104
  async function mcp(method, params) {
69
105
  const message = rpc(method, params);
@@ -85,41 +121,102 @@ async function localFile(path) {
85
121
  : `${path} is not a readable file`);
86
122
  }
87
123
  }
88
- async function sent(url, bytes, operation) {
89
- const headers = { 'content-type': 'application/octet-stream', 'x-house-byte-operation': operation };
124
+ async function transferred(url, method, bytes, headers) {
90
125
  if (socketPath !== undefined)
91
- return bridged(url, bytes, headers);
126
+ return exchanged(url, method, bytes, headers);
92
127
  setGlobalProxyFromEnv();
93
- 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(() => {
94
129
  throw new Error(UNREACHABLE);
95
130
  });
96
- const text = await answer.text();
131
+ const received = Buffer.from(await answer.arrayBuffer());
97
132
  if (answer.status === 200)
98
- return text;
99
- throw new Error(refused(url, answer.status, text));
100
- }
101
- async function upload(path, roomRef, missing) {
102
- if (typeof path !== 'string' || path === '')
103
- throw new Error(missing);
104
- const bytes = await localFile(path);
105
- const declared = parse(await called('upload', {
106
- ...(roomRef === undefined ? {} : { room_ref: roomRef }),
107
- name: basename(path),
108
- bytes: bytes.length,
109
- sha256: createHash('sha256').update(bytes).digest('hex'),
110
- }));
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 described(file) {
157
+ const bytes = await localFile(file);
158
+ const mediaType = MEDIA_TYPES.get(extname(file).slice(1).toLowerCase());
159
+ return {
160
+ bytes,
161
+ description: {
162
+ bytes: bytes.length,
163
+ sha256: createHash('sha256').update(bytes).digest('hex'),
164
+ ...(mediaType === undefined ? {} : { media_type: mediaType }),
165
+ },
166
+ };
167
+ }
168
+ async function upload({ file, ...destination }) {
169
+ if (typeof file !== 'string' || file === '')
170
+ throw new Error('upload needs "file", a local file');
171
+ const { bytes, description } = await described(file);
172
+ const answer = await called('upload', { ...destination, ...description });
173
+ const declared = parse(answer);
111
174
  if (declared.upload === undefined)
112
- return declared.attachment;
113
- const saved = JSON.parse(await sent(declared.upload.url, bytes, declared.upload.operation));
114
- if (saved.upload_failure !== undefined)
115
- throw new Error(`${path} was not saved: ${saved.upload_failure}; call again later`);
116
- return saved.attachment;
175
+ return answer;
176
+ const written = JSON.parse(await sent(declared.upload.url, bytes, declared.upload.operation));
177
+ return stringify(written, { lineWidth: 0 }).trimEnd();
178
+ }
179
+ async function appendRecord(args) {
180
+ const held = new Map();
181
+ const attachments = Array.isArray(args.attachments)
182
+ ? await Promise.all(args.attachments.map(async (attachment) => {
183
+ if (typeof attachment !== 'string')
184
+ return attachment;
185
+ const { bytes, description } = await described(attachment);
186
+ held.set(description.sha256, bytes);
187
+ return { name: basename(attachment), ...description };
188
+ }))
189
+ : args.attachments;
190
+ const record = { ...args, attachments };
191
+ for (;;) {
192
+ const answer = await called('append_record', record);
193
+ const { upload } = parse(answer);
194
+ if (upload === undefined)
195
+ return answer;
196
+ for (const grant of upload)
197
+ await sent(grant.url, held.get(grant.sha256), grant.operation);
198
+ }
199
+ }
200
+ function unexpected(argument, usage) {
201
+ return new Error(`unexpected argument ${argument}; ${usage}`);
202
+ }
203
+ function accepted(args, flags, positionals, usage) {
204
+ const given = { flags: new Set(), positionals: [] };
205
+ for (const arg of args) {
206
+ if (flags.includes(arg))
207
+ given.flags.add(arg);
208
+ else if (!arg.startsWith('-') && given.positionals.length < positionals)
209
+ given.positionals.push(arg);
210
+ else
211
+ throw unexpected(arg, usage);
212
+ }
213
+ return given;
117
214
  }
118
215
  async function push(args) {
119
- if (args.includes('--help'))
216
+ const { flags, positionals: [commit = 'HEAD'] } = accepted(args, ['--help', '--owner'], 1, PUSH_USAGE);
217
+ if (flags.has('--help'))
120
218
  return PUSH_USAGE;
121
- const owner = args.includes('--owner');
122
- const commit = args.find((arg) => arg !== '--owner') ?? 'HEAD';
219
+ const owner = flags.has('--owner');
123
220
  if (owner && socketPath !== undefined)
124
221
  throw new Error('--owner is not for Agent conversations; run house push without it');
125
222
  if (!owner && socketPath === undefined)
@@ -130,7 +227,7 @@ async function push(args) {
130
227
  return pushed.text;
131
228
  }
132
229
  async function fetched(args) {
133
- if (args.includes('--help'))
230
+ if (accepted(args, ['--help'], 0, FETCH_USAGE).flags.has('--help'))
134
231
  return FETCH_USAGE;
135
232
  const answer = JSON.parse(await bridged('/git/fetch', {}, undefined, socketPath ?? join(kitHome(), 'owner.sock')));
136
233
  if (answer.refused)
@@ -151,28 +248,23 @@ function argumentsOf(argument) {
151
248
  throw new Error(ARGUMENTS);
152
249
  return parsed;
153
250
  }
154
- async function house([verb, argument]) {
155
- if (verb === undefined || verb === '--help' || verb === 'help') {
156
- return [USAGE, 'help', PUSH, FETCH, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
251
+ async function house(args) {
252
+ const { flags, positionals: [verb, argument] } = accepted(args, ['--help'], 2, USAGE);
253
+ if (verb === 'help' && argument !== undefined)
254
+ throw unexpected(argument, USAGE);
255
+ if (flags.has('--help') && argument !== undefined)
256
+ throw unexpected('--help', USAGE);
257
+ if (verb === undefined || verb === 'help') {
258
+ return [USAGE, 'help', PUSH, FETCH, DOWNLOAD, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
157
259
  }
158
- if (argument === '--help') {
260
+ if (flags.has('--help')) {
159
261
  const tool = (await tools()).find((listed) => listed.name === verb);
160
262
  if (tool === undefined)
161
263
  throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
162
264
  return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
163
265
  }
164
- const args = argumentsOf(argument);
165
- if (verb === 'upload') {
166
- return JSON.stringify({ attachment: await upload(args.path, args.room_ref, 'upload needs "path", a local file') });
167
- }
168
- if (verb === 'append_record' && Array.isArray(args.attachments)) {
169
- const attachments = [];
170
- for (const path of args.attachments) {
171
- attachments.push(await upload(path, args.room_ref, 'each attachments entry is the path of a local file'));
172
- }
173
- args.attachments = attachments;
174
- }
175
- return called(verb, args);
266
+ const parsed = argumentsOf(argument);
267
+ return verb === 'upload' ? upload(parsed) : verb === 'append_record' ? appendRecord(parsed) : called(verb, parsed);
176
268
  }
177
269
  async function called(name, args) {
178
270
  const result = await mcp('tools/call', { name, arguments: args });
@@ -182,7 +274,15 @@ async function called(name, args) {
182
274
  return text;
183
275
  }
184
276
  const argv = process.argv.slice(2);
185
- (argv[0] === 'push' ? push(argv.slice(1)) : argv[0] === 'fetch' ? fetched(argv.slice(1)) : house(argv)).then((text) => {
277
+ const named = argv.findIndex((arg) => !arg.startsWith('-'));
278
+ const rest = argv.filter((_arg, index) => index !== named);
279
+ (argv[named] === 'push'
280
+ ? push(rest)
281
+ : argv[named] === 'fetch'
282
+ ? fetched(rest)
283
+ : argv[named] === 'download'
284
+ ? download(rest)
285
+ : house(argv)).then((text) => {
186
286
  process.stdout.write(`${text}\n`);
187
287
  if (argv[0] === 'shell')
188
288
  process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
@@ -1,36 +1,11 @@
1
1
  import { HOUSE_REF } from './git.js';
2
- import { HOW_WE_WORK } from './skills.js';
2
+ import { readHowWeWork } from './skills.js';
3
3
  const SOURCE_LINE = "From House:";
4
- const HOUSE_LINE = 'Work with House through the `house` CLI: run `house --help`.';
5
- const FILE_LINE = 'To give the User a file or a page, upload it with `house upload` and link it; never start a server.';
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
6
  const READ_LINE = "Optional per-Room instructions: `/rooms/private/rooms/<handle>/AGENTS.md`.";
7
7
  const COPIES_LINE = `House Local copies; before work run \`house fetch\` and rebase onto \`${HOUSE_REF}\`; after it commit, then \`house push\`:`;
8
- const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
9
- const FAILED = /^exit: [1-9]\d*$/;
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
- }
15
- async function howWeWork(bridge) {
16
- let document = '';
17
- for (let command = `cat ${HOW_WE_WORK}`; command !== undefined;) {
18
- const read = await bridge.tool('shell', { command });
19
- const text = read.content.map((content) => content.text).join('\n');
20
- const lines = text.split('\n');
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, '');
23
- if (UNREADABLE.test(refusal))
24
- return '';
25
- throw new Error(refusal);
26
- }
27
- const cut = cutOf(lines);
28
- document += lines.slice(cut === null ? 0 : 1).join('\n');
29
- command = cut?.[2];
30
- }
31
- return document.replace(/\n$/, '');
32
- }
33
8
  export async function instructions(bridge, base, copies) {
34
9
  const lines = [SOURCE_LINE, HOUSE_LINE, FILE_LINE, READ_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
35
- return [lines.join('\n'), base, await howWeWork(bridge)].filter((part) => part !== '').join('\n\n');
10
+ return [lines.join('\n'), base, (await readHowWeWork(bridge)).replace(/\n$/, '')].filter((part) => part !== '').join('\n\n');
36
11
  }
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
@@ -2,13 +2,16 @@ import { spawn } from 'node:child_process';
2
2
  import { createHash, randomBytes } from 'node:crypto';
3
3
  import { hostname } from 'node:os';
4
4
  import { parseArgs } from 'node:util';
5
- import { post, retrying } from './api.js';
5
+ import { HouseRefusal, post, retrying } from './api.js';
6
6
  import { placeAppGit } from './app-git.js';
7
- import { forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
7
+ import { writeCodexRule } from './clis.js';
8
+ import { forgetDisconnected, forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent, } from './home.js';
8
9
  import { callHouse, rpc } from './mcp.js';
10
+ import { refusalOf } from './refusals.js';
9
11
  import { selectRelay } from './relay.js';
10
12
  import { startService } from './service.js';
11
- const DEFAULT_HOUSE = 'https://agents.house';
13
+ import { placeSkillSet } from './skills.js';
14
+ export const DEFAULT_HOUSE = 'https://agents.house';
12
15
  const OPENER = process.platform === 'darwin' ? 'open' : 'xdg-open';
13
16
  // Polling every two seconds brings the User's confirmation to the waiting Kit moments after they give it.
14
17
  const POLL_INTERVAL_MS = 2000;
@@ -17,7 +20,7 @@ function open(link) {
17
20
  .on('error', () => undefined)
18
21
  .unref();
19
22
  }
20
- async function accepted(house, credential) {
23
+ export async function accepted(house, credential) {
21
24
  const checked = await callHouse(house, credential, rpc('tools/list', {}));
22
25
  if (checked.status === 200)
23
26
  return true;
@@ -25,13 +28,17 @@ async function accepted(house, credential) {
25
28
  return false;
26
29
  throw new Error(`House answered ${checked.status} when Kit checked this computer's own agent's connection: ${checked.text}`);
27
30
  }
28
- const USAGE = `usage: kit login [--house <origin>] [--environment <id>] [--rooms <ref>[,<ref>...] | --no-private] [--code <code>]
31
+ const USAGE = `usage: kit login [--house <origin>] [--environment <id>] [--rooms <ref>[,<ref>...] | --no-private]
32
+ kit login [--house <origin>] --code <code>
29
33
  --house <origin> the House to connect to, ${DEFAULT_HOUSE} unless one is stored
30
34
  --environment <id> reconnect this Environment
31
35
  --rooms <ref>[,<ref>...] give this Environment only these Rooms
32
36
  --no-private give this Environment every Room but your Private Room
33
37
  --code <code> connect this machine with a login code
34
38
  `;
39
+ function gone(error) {
40
+ return error instanceof HouseRefusal && refusalOf(error.text)?.code === 'kit_environment_not_found';
41
+ }
35
42
  function chosenRooms(rooms, noPrivate) {
36
43
  if (rooms !== undefined && noPrivate)
37
44
  throw new Error('--rooms and --no-private are two choices of Rooms; pass one');
@@ -70,7 +77,8 @@ export async function login(argv) {
70
77
  selectRelay(relay);
71
78
  const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
72
79
  const replaces = process.env.HOUSE_KIT_REPLACES;
73
- const environment = replaces === undefined ? (values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined)) : undefined;
80
+ const remembered = replaces === undefined && values.environment === undefined && enrolled?.house === house ? enrolled.environment : undefined;
81
+ const environment = replaces === undefined ? (values.environment ?? remembered) : undefined;
74
82
  const ownAgent = await readOwnAgent();
75
83
  let held = false;
76
84
  let exchanged;
@@ -80,33 +88,51 @@ export async function login(argv) {
80
88
  else {
81
89
  held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
82
90
  const verifier = randomBytes(32).toString('base64url');
83
- const started = await retrying(() => post(house, '/kit', {
84
- ...(environment === undefined
85
- ? { act: 'new_environment', label: hostname(), ...(replaces === undefined ? {} : { replaces }) }
86
- : { act: 'existing_environment', environment_id: environment }),
91
+ const start = (named) => retrying(() => post(house, '/kit', {
92
+ label: hostname(),
93
+ ...(named === undefined
94
+ ? { act: 'new_environment', ...(replaces === undefined ? {} : { replaces }) }
95
+ : { act: 'existing_environment', environment_id: named }),
87
96
  ...rooms,
88
97
  code_challenge: createHash('sha256').update(verifier).digest('base64url'),
89
98
  ...(held ? {} : { headless: true }),
90
99
  }));
100
+ let started;
101
+ try {
102
+ started = await start(environment);
103
+ }
104
+ catch (error) {
105
+ if (remembered === undefined || !gone(error))
106
+ throw error;
107
+ await forgetDisconnected();
108
+ process.stdout.write(`House no longer holds Environment ${remembered}; connecting this computer as a new one.\n`);
109
+ started = await start(undefined);
110
+ }
91
111
  process.stdout.write(`Open this link and confirm: ${started.start_url}\n`);
92
112
  open(started.start_url);
93
113
  exchanged = await retrying(() => post(house, '/kit/token', { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
94
114
  }
115
+ await placeSkillSet();
116
+ await writeCodexRule().catch((error) => process.stderr.write(`kit: ${error.message}\n`));
117
+ const relayRecord = relay === undefined ? {} : { relay };
95
118
  await writeEnrolment({
96
119
  house,
97
- ...(relay === undefined ? {} : { relay }),
120
+ ...relayRecord,
98
121
  environment: exchanged.environment,
99
122
  credential: exchanged.credential,
100
123
  });
101
124
  process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
102
125
  if (exchanged.headless_credential !== undefined) {
103
- await writeOwnAgent({ house, user: exchanged.user, credential: exchanged.headless_credential });
126
+ await writeOwnAgent({ house, ...relayRecord, user: exchanged.user, credential: exchanged.headless_credential });
104
127
  }
105
128
  else if (held && ownAgent !== null && ownAgent.user !== exchanged.user) {
106
129
  await forgetOwnAgent();
107
130
  process.stdout.write("This computer's own agent was another User's; run kit login again to connect it to you.\n");
108
131
  }
109
- await placeAppGit(ownAgent, await readOwnAgent());
132
+ else if (held && ownAgent !== null) {
133
+ await writeOwnAgent({ house, ...relayRecord, user: ownAgent.user, credential: ownAgent.credential });
134
+ }
135
+ await placeAppGit(ownAgent, await readOwnAgent()).catch((error) => process.stderr.write(`kit: ${error.message}\n`));
110
136
  try {
111
137
  startService();
112
138
  }
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
  }