@agentshouse/kit 0.2.1-c53a84236c3d9 → 0.2.1-c5883630417e1

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 (86) hide show
  1. package/README.md +25 -24
  2. package/dist/agents.js +25 -5
  3. package/dist/api.js +6 -2
  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 +9 -5
  8. package/dist/copies.js +20 -10
  9. package/dist/end.js +17 -3
  10. package/dist/enrol-main.js +7 -1
  11. package/dist/files.js +7 -1
  12. package/dist/git.js +11 -8
  13. package/dist/home.js +81 -6
  14. package/dist/house-main.js +164 -63
  15. package/dist/instructions.js +7 -31
  16. package/dist/kit-main.js +53 -8
  17. package/dist/login.js +102 -21
  18. package/dist/parts.js +34 -16
  19. package/dist/placement.js +48 -0
  20. package/dist/relay.js +12 -2
  21. package/dist/resident.js +14 -5
  22. package/dist/service-main.js +9 -0
  23. package/dist/service.js +33 -0
  24. package/dist/skills.js +81 -12
  25. package/dist/stream.js +9 -4
  26. package/dist/transcription.js +3 -3
  27. package/dist/update.js +28 -6
  28. package/dist/wire.js +6 -0
  29. package/how-we-work.md +13 -3
  30. package/package.json +3 -2
  31. package/skills/ask-matt/SKILL.md +17 -11
  32. package/skills/ask-matt/agents/openai.yaml +1 -0
  33. package/skills/code-review/SKILL.md +5 -5
  34. package/skills/codebase-design/DESIGN-IT-TWICE.md +1 -1
  35. package/skills/codebase-design/SKILL.md +0 -2
  36. package/skills/diagnosing-bugs/SKILL.md +2 -4
  37. package/skills/domain-modeling/{CONTEXT-FORMAT.md → GLOSSARY-FORMAT.md} +10 -10
  38. package/skills/domain-modeling/SKILL.md +12 -14
  39. package/skills/grill-me/SKILL.md +1 -2
  40. package/skills/grill-me/agents/openai.yaml +1 -0
  41. package/skills/grill-with-docs/SKILL.md +1 -2
  42. package/skills/grill-with-docs/agents/openai.yaml +1 -0
  43. package/skills/grilling/SKILL.md +2 -2
  44. package/skills/handoff/SKILL.md +2 -3
  45. package/skills/handoff/agents/openai.yaml +1 -0
  46. package/skills/implement/SKILL.md +5 -4
  47. package/skills/implement/agents/openai.yaml +1 -0
  48. package/skills/implement-spec/SKILL.md +40 -0
  49. package/skills/implement-spec/agents/openai.yaml +5 -0
  50. package/skills/improve-codebase-architecture/SKILL.md +6 -7
  51. package/skills/improve-codebase-architecture/agents/openai.yaml +1 -0
  52. package/skills/pr/CREDITS.md +3 -0
  53. package/skills/pr/LICENSE +21 -0
  54. package/skills/pr/SKILL.md +170 -0
  55. package/skills/pr/agents/openai.yaml +3 -0
  56. package/skills/prototype/SKILL.md +0 -2
  57. package/skills/research/SKILL.md +0 -2
  58. package/skills/retro/LICENSE +21 -0
  59. package/skills/retro/SKILL.md +44 -0
  60. package/skills/retro/agents/openai.yaml +5 -0
  61. package/skills/tdd/SKILL.md +2 -4
  62. package/skills/teach/SKILL.md +3 -4
  63. package/skills/teach/agents/openai.yaml +1 -0
  64. package/skills/to-questionnaire/SKILL.md +1 -2
  65. package/skills/to-questionnaire/agents/openai.yaml +1 -0
  66. package/skills/to-spec/SKILL.md +1 -2
  67. package/skills/to-spec/agents/openai.yaml +1 -0
  68. package/skills/to-tickets/SKILL.md +3 -4
  69. package/skills/to-tickets/agents/openai.yaml +1 -0
  70. package/skills/triage/AGENT-BRIEF.md +207 -0
  71. package/skills/triage/LICENSE +21 -0
  72. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  73. package/skills/triage/SKILL.md +112 -0
  74. package/skills/triage/agents/openai.yaml +5 -0
  75. package/skills/wait-what/SKILL.md +2 -3
  76. package/skills/wait-what/agents/openai.yaml +1 -0
  77. package/skills/wayfinder/SKILL.md +5 -6
  78. package/skills/wayfinder/agents/openai.yaml +1 -0
  79. package/skills/wizard/LICENSE +21 -0
  80. package/skills/wizard/SKILL.md +44 -0
  81. package/skills/wizard/agents/openai.yaml +3 -0
  82. package/skills/wizard/template.sh +223 -0
  83. package/skills/writing-for-agents/SKILL.md +0 -2
  84. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  85. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  86. /package/skills/{resolving-merge-conflicts → implement-spec}/LICENSE +0 -0
package/dist/home.js CHANGED
@@ -1,13 +1,49 @@
1
- import { existsSync } from 'node:fs';
1
+ import { randomUUID } from 'node:crypto';
2
+ import { accessSync, chmodSync, constants, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync } from 'node:fs';
2
3
  import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
- import { homedir } from 'node:os';
4
+ import { homedir, tmpdir } from 'node:os';
4
5
  import { join } from 'node:path';
6
+ import { selectRelay } from './relay.js';
5
7
  const ENROLMENT = 'credential.json';
6
8
  const DISCONNECTED = 'disconnected.json';
7
9
  const CONFIGURATION = 'kit.json';
8
10
  const OWN_AGENT = 'own-agent.json';
11
+ const RESTART = 'restart';
12
+ let defaulted;
13
+ function writable(directory) {
14
+ try {
15
+ accessSync(directory, constants.W_OK | constants.X_OK);
16
+ return true;
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ function ownTemporaryHome() {
23
+ const home = join(tmpdir(), `house-kit-${process.getuid()}`);
24
+ try {
25
+ mkdirSync(home, { mode: 0o700 });
26
+ }
27
+ catch (error) {
28
+ if (error.code !== 'EEXIST')
29
+ throw error;
30
+ }
31
+ const found = lstatSync(home);
32
+ if (found.isSymbolicLink())
33
+ throw new Error(`${home} is a symbolic link`);
34
+ if (!found.isDirectory())
35
+ throw new Error(`${home} is not a directory`);
36
+ if (found.uid !== process.getuid())
37
+ throw new Error(`${home} is not owned by this User`);
38
+ chmodSync(home, 0o700);
39
+ return home;
40
+ }
41
+ function defaultHome() {
42
+ const home = join(homedir(), '.house-kit');
43
+ return existsSync(home) || writable(homedir()) ? home : ownTemporaryHome();
44
+ }
9
45
  export function kitHome() {
10
- return process.env.HOUSE_KIT_HOME ?? join(homedir(), '.house-kit');
46
+ return process.env.HOUSE_KIT_HOME || (defaulted ??= defaultHome());
11
47
  }
12
48
  export function workspaceRoot() {
13
49
  return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
@@ -28,12 +64,15 @@ export async function readHome(name) {
28
64
  export async function writeHome(name, value) {
29
65
  const home = kitHome();
30
66
  await mkdir(home, { recursive: true, mode: 0o700 });
31
- const temporary = join(home, `${name}.${process.pid}`);
67
+ const temporary = join(home, `${name}.${randomUUID()}`);
32
68
  await writeFile(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600 });
33
69
  await rename(temporary, join(home, name));
34
70
  }
35
- export function readEnrolment() {
36
- return readHome(ENROLMENT);
71
+ export async function readEnrolment() {
72
+ const enrolment = await readHome(ENROLMENT);
73
+ if (enrolment !== null)
74
+ selectRelay(process.env.HOUSE_KIT_RELAY || enrolment.relay);
75
+ return enrolment;
37
76
  }
38
77
  export async function writeEnrolment(enrolment) {
39
78
  await writeHome(ENROLMENT, enrolment);
@@ -42,13 +81,49 @@ export async function writeEnrolment(enrolment) {
42
81
  export function readDisconnected() {
43
82
  return readHome(DISCONNECTED);
44
83
  }
84
+ export function forgetDisconnected() {
85
+ return rm(join(kitHome(), DISCONNECTED), { force: true });
86
+ }
45
87
  export async function forgetEnrolment({ house, environment }) {
46
88
  await writeHome(DISCONNECTED, { house, environment });
47
89
  await rm(join(kitHome(), ENROLMENT), { force: true });
48
90
  }
91
+ export async function forgetRejected(rejected) {
92
+ const held = await readHome(ENROLMENT);
93
+ if (held?.credential !== rejected)
94
+ return;
95
+ await writeHome(DISCONNECTED, { house: held.house, environment: held.environment });
96
+ const enrolment = join(kitHome(), ENROLMENT);
97
+ const taken = `${enrolment}.${process.pid}`;
98
+ try {
99
+ renameSync(enrolment, taken);
100
+ }
101
+ catch (error) {
102
+ if (error.code === 'ENOENT')
103
+ return;
104
+ throw error;
105
+ }
106
+ if (JSON.parse(readFileSync(taken, 'utf8')).credential !== rejected) {
107
+ try {
108
+ linkSync(taken, enrolment);
109
+ }
110
+ catch (error) {
111
+ if (error.code !== 'EEXIST')
112
+ throw error;
113
+ }
114
+ rmSync(join(kitHome(), DISCONNECTED), { force: true });
115
+ }
116
+ rmSync(taken);
117
+ }
49
118
  export function enrolled() {
50
119
  return existsSync(join(kitHome(), ENROLMENT));
51
120
  }
121
+ export function restartAsked() {
122
+ return existsSync(join(kitHome(), RESTART));
123
+ }
124
+ export function forgetRestart() {
125
+ return rm(join(kitHome(), RESTART), { force: true });
126
+ }
52
127
  export function readOwnAgent() {
53
128
  return readHome(OWN_AGENT);
54
129
  }
@@ -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 { basename, dirname, extname, join, resolve } from 'node:path';
6
+ import { verified } from './files.js';
6
7
  import { HOUSE_REF } from './git.js';
7
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);
95
+ selectRelay(process.env.HOUSE_KIT_RELAY || ownAgent.relay);
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,102 @@ 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),
107
- bytes: bytes.length,
108
- sha256: createHash('sha256').update(bytes).digest('hex'),
109
- }));
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);
110
174
  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;
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;
116
214
  }
117
215
  async function push(args) {
118
- if (args.includes('--help'))
216
+ const { flags, positionals: [commit = 'HEAD'] } = accepted(args, ['--help', '--owner'], 1, PUSH_USAGE);
217
+ if (flags.has('--help'))
119
218
  return PUSH_USAGE;
120
- const owner = args.includes('--owner');
121
- const commit = args.find((arg) => arg !== '--owner') ?? 'HEAD';
219
+ const owner = flags.has('--owner');
122
220
  if (owner && socketPath !== undefined)
123
221
  throw new Error('--owner is not for Agent conversations; run house push without it');
124
222
  if (!owner && socketPath === undefined)
@@ -129,7 +227,7 @@ async function push(args) {
129
227
  return pushed.text;
130
228
  }
131
229
  async function fetched(args) {
132
- if (args.includes('--help'))
230
+ if (accepted(args, ['--help'], 0, FETCH_USAGE).flags.has('--help'))
133
231
  return FETCH_USAGE;
134
232
  const answer = JSON.parse(await bridged('/git/fetch', {}, undefined, socketPath ?? join(kitHome(), 'owner.sock')));
135
233
  if (answer.refused)
@@ -150,28 +248,23 @@ function argumentsOf(argument) {
150
248
  throw new Error(ARGUMENTS);
151
249
  return parsed;
152
250
  }
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');
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');
156
259
  }
157
- if (argument === '--help') {
260
+ if (flags.has('--help')) {
158
261
  const tool = (await tools()).find((listed) => listed.name === verb);
159
262
  if (tool === undefined)
160
263
  throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
161
264
  return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
162
265
  }
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);
266
+ const parsed = argumentsOf(argument);
267
+ return verb === 'upload' ? upload(parsed) : verb === 'append_record' ? appendRecord(parsed) : called(verb, parsed);
175
268
  }
176
269
  async function called(name, args) {
177
270
  const result = await mcp('tools/call', { name, arguments: args });
@@ -181,7 +274,15 @@ async function called(name, args) {
181
274
  return text;
182
275
  }
183
276
  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) => {
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) => {
185
286
  process.stdout.write(`${text}\n`);
186
287
  if (argv[0] === 'shell')
187
288
  process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
@@ -1,35 +1,11 @@
1
1
  import { HOUSE_REF } from './git.js';
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`.';
2
+ import { readHowWeWork } from './skills.js';
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
- const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
8
- const FAILED = /^exit: [1-9]\d*$/;
9
- const CUT = /^stderr: shell: output_cut (\d+) of \d+ bytes; continue with: (.+)$/;
10
- function cutOf(lines) {
11
- const cut = CUT.exec(lines[0] ?? '');
12
- return cut !== null && Buffer.byteLength(lines.slice(1).join('\n')) === Number(cut[1]) ? cut : null;
13
- }
14
- async function howWeWork(bridge) {
15
- let document = '';
16
- for (let command = `cat ${HOW_WE_WORK}`; command !== undefined;) {
17
- const read = await bridge.tool('shell', { command });
18
- const text = read.content.map((content) => content.text).join('\n');
19
- const lines = text.split('\n');
20
- if (read.isError === true || (FAILED.test(lines[0] ?? '') && lines[1]?.startsWith('stderr: '))) {
21
- const refusal = read.isError === true ? text : lines.slice(1).join('\n').replace(/^stderr: /gm, '');
22
- if (UNREADABLE.test(refusal))
23
- return '';
24
- throw new Error(refusal);
25
- }
26
- const cut = cutOf(lines);
27
- document += lines.slice(cut === null ? 0 : 1).join('\n');
28
- command = cut?.[2];
29
- }
30
- return document.replace(/\n$/, '');
31
- }
32
8
  export async function instructions(bridge, base, copies) {
33
- const lines = [HOUSE_LINE, FILE_LINE, READ_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
34
- return [lines.join('\n'), base, await howWeWork(bridge)].filter((part) => part !== '').join('\n\n');
9
+ const lines = [SOURCE_LINE, HOUSE_LINE, FILE_LINE, READ_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
10
+ return [lines.join('\n'), base, (await readHowWeWork(bridge)).replace(/\n$/, '')].filter((part) => part !== '').join('\n\n');
35
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`);