@agentshouse/kit 0.2.1-c3cf4b145dcda → 0.2.1-c3db1f18aed8f

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 (94) hide show
  1. package/README.md +24 -23
  2. package/dist/acp.js +7 -97
  3. package/dist/agents.js +27 -6
  4. package/dist/api.js +9 -5
  5. package/dist/bootstrap.json +4 -4
  6. package/dist/bridge.js +11 -37
  7. package/dist/chatgpt.js +26 -0
  8. package/dist/clis.js +86 -14
  9. package/dist/codex-main.js +58 -0
  10. package/dist/conversations.js +56 -55
  11. package/dist/copies.js +145 -110
  12. package/dist/end.js +18 -4
  13. package/dist/enrol-main.js +7 -1
  14. package/dist/events.js +10 -76
  15. package/dist/files.js +7 -1
  16. package/dist/git.js +11 -8
  17. package/dist/home.js +78 -6
  18. package/dist/house-main.js +183 -56
  19. package/dist/instructions.js +9 -32
  20. package/dist/kit-main.js +53 -8
  21. package/dist/login.js +93 -107
  22. package/dist/logout.js +14 -14
  23. package/dist/parts.js +34 -16
  24. package/dist/placement.js +48 -0
  25. package/dist/relay.js +12 -2
  26. package/dist/resident.js +35 -24
  27. package/dist/scope.js +203 -0
  28. package/dist/service-main.js +9 -0
  29. package/dist/service.js +33 -0
  30. package/dist/sign-in.js +1 -1
  31. package/dist/skills.js +80 -12
  32. package/dist/stream.js +9 -4
  33. package/dist/transcription.js +3 -3
  34. package/dist/update.js +28 -6
  35. package/dist/wire.js +6 -0
  36. package/dist/work.js +348 -0
  37. package/how-we-work.md +11 -3
  38. package/package.json +3 -2
  39. package/skills/ask-matt/SKILL.md +17 -11
  40. package/skills/ask-matt/agents/openai.yaml +1 -0
  41. package/skills/code-review/SKILL.md +5 -5
  42. package/skills/codebase-design/DESIGN-IT-TWICE.md +1 -1
  43. package/skills/codebase-design/SKILL.md +0 -2
  44. package/skills/diagnosing-bugs/SKILL.md +2 -4
  45. package/skills/domain-modeling/{CONTEXT-FORMAT.md → GLOSSARY-FORMAT.md} +10 -10
  46. package/skills/domain-modeling/SKILL.md +12 -14
  47. package/skills/grill-me/SKILL.md +1 -2
  48. package/skills/grill-me/agents/openai.yaml +1 -0
  49. package/skills/grill-with-docs/SKILL.md +1 -2
  50. package/skills/grill-with-docs/agents/openai.yaml +1 -0
  51. package/skills/grilling/SKILL.md +2 -2
  52. package/skills/handoff/SKILL.md +2 -3
  53. package/skills/handoff/agents/openai.yaml +1 -0
  54. package/skills/implement/SKILL.md +5 -4
  55. package/skills/implement/agents/openai.yaml +1 -0
  56. package/skills/implement-spec/SKILL.md +40 -0
  57. package/skills/implement-spec/agents/openai.yaml +5 -0
  58. package/skills/improve-codebase-architecture/SKILL.md +6 -7
  59. package/skills/improve-codebase-architecture/agents/openai.yaml +1 -0
  60. package/skills/pr/CREDITS.md +3 -0
  61. package/skills/pr/LICENSE +21 -0
  62. package/skills/pr/SKILL.md +170 -0
  63. package/skills/pr/agents/openai.yaml +3 -0
  64. package/skills/prototype/SKILL.md +0 -2
  65. package/skills/research/SKILL.md +0 -2
  66. package/skills/retro/LICENSE +21 -0
  67. package/skills/retro/SKILL.md +44 -0
  68. package/skills/retro/agents/openai.yaml +5 -0
  69. package/skills/tdd/SKILL.md +2 -4
  70. package/skills/teach/SKILL.md +3 -4
  71. package/skills/teach/agents/openai.yaml +1 -0
  72. package/skills/to-questionnaire/SKILL.md +1 -2
  73. package/skills/to-questionnaire/agents/openai.yaml +1 -0
  74. package/skills/to-spec/SKILL.md +1 -2
  75. package/skills/to-spec/agents/openai.yaml +1 -0
  76. package/skills/to-tickets/SKILL.md +3 -4
  77. package/skills/to-tickets/agents/openai.yaml +1 -0
  78. package/skills/triage/AGENT-BRIEF.md +207 -0
  79. package/skills/triage/LICENSE +21 -0
  80. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  81. package/skills/triage/SKILL.md +112 -0
  82. package/skills/triage/agents/openai.yaml +5 -0
  83. package/skills/wait-what/SKILL.md +2 -3
  84. package/skills/wait-what/agents/openai.yaml +1 -0
  85. package/skills/wayfinder/SKILL.md +5 -6
  86. package/skills/wayfinder/agents/openai.yaml +1 -0
  87. package/skills/wizard/LICENSE +21 -0
  88. package/skills/wizard/SKILL.md +44 -0
  89. package/skills/wizard/agents/openai.yaml +3 -0
  90. package/skills/wizard/template.sh +223 -0
  91. package/skills/writing-for-agents/SKILL.md +0 -2
  92. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  93. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  94. /package/skills/{resolving-merge-conflicts → implement-spec}/LICENSE +0 -0
package/dist/git.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { isUtf8 } from 'node:buffer';
2
3
  import { createHash } from 'node:crypto';
3
4
  import { join } from 'node:path';
4
5
  import { withoutProxy } from './clis.js';
@@ -48,14 +49,16 @@ export async function tree(repository, commit) {
48
49
  }
49
50
  return entries;
50
51
  }
51
- export async function blobText(repository, object, path) {
52
- const bytes = (await run(repository, ['cat-file', 'blob', object])).stdout;
53
- try {
54
- return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
55
- }
56
- catch {
57
- throw new Error(`${path} is binary and House stores only text; remove it from the commit`);
58
- }
52
+ const TEXT_MAX_BYTES = 16 * 1024 * 1024;
53
+ async function blob(repository, object) {
54
+ return (await run(repository, ['cat-file', 'blob', object])).stdout;
55
+ }
56
+ export async function blobText(repository, object) {
57
+ return (await blob(repository, object)).toString('utf8');
58
+ }
59
+ export async function isText(repository, object) {
60
+ const bytes = await blob(repository, object);
61
+ return bytes.length <= TEXT_MAX_BYTES && isUtf8(bytes) && !bytes.includes(0);
59
62
  }
60
63
  export function blobId(content) {
61
64
  const bytes = Buffer.from(content, 'utf8');
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);
@@ -46,9 +85,42 @@ export async function forgetEnrolment({ house, environment }) {
46
85
  await writeHome(DISCONNECTED, { house, environment });
47
86
  await rm(join(kitHome(), ENROLMENT), { force: true });
48
87
  }
88
+ export async function forgetRejected(rejected) {
89
+ const held = await readHome(ENROLMENT);
90
+ if (held?.credential !== rejected)
91
+ return;
92
+ await writeHome(DISCONNECTED, { house: held.house, environment: held.environment });
93
+ const enrolment = join(kitHome(), ENROLMENT);
94
+ const taken = `${enrolment}.${process.pid}`;
95
+ try {
96
+ renameSync(enrolment, taken);
97
+ }
98
+ catch (error) {
99
+ if (error.code === 'ENOENT')
100
+ return;
101
+ throw error;
102
+ }
103
+ if (JSON.parse(readFileSync(taken, 'utf8')).credential !== rejected) {
104
+ try {
105
+ linkSync(taken, enrolment);
106
+ }
107
+ catch (error) {
108
+ if (error.code !== 'EEXIST')
109
+ throw error;
110
+ }
111
+ rmSync(join(kitHome(), DISCONNECTED), { force: true });
112
+ }
113
+ rmSync(taken);
114
+ }
49
115
  export function enrolled() {
50
116
  return existsSync(join(kitHome(), ENROLMENT));
51
117
  }
118
+ export function restartAsked() {
119
+ return existsSync(join(kitHome(), RESTART));
120
+ }
121
+ export function forgetRestart() {
122
+ return rm(join(kitHome(), RESTART), { force: true });
123
+ }
52
124
  export function readOwnAgent() {
53
125
  return readHome(OWN_AGENT);
54
126
  }
@@ -1,63 +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';
7
+ import { HOUSE_REF } from './git.js';
6
8
  import { kitHome, readOwnAgent } from './home.js';
7
9
  import { callHouse, rpc, UNREACHABLE } from './mcp.js';
8
10
  import { refusalOf } from './refusals.js';
11
+ import { relayed, selectRelay } from './relay.js';
12
+ import { parse, stringify } from 'yaml';
9
13
  const USAGE = "usage: house <tool> ['<arguments as JSON>']";
10
14
  const PUSH_USAGE = 'usage: house push [commit] [--owner]';
11
15
  const PUSH = "push [commit]: sends the Local copy's committed changes to House";
16
+ const FETCH_USAGE = 'usage: house fetch';
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';
12
20
  const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
13
21
  const CLOSED = "this conversation's House connection is closed; nothing to do from here";
14
- const SANDBOXED = "your CLI's sandbox kept house from House; run house as a command of its own, with no pipe, chain or redirect";
22
+ const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
15
23
  const REVOKED = 'this conversation no longer has House access; nothing to do from here';
16
24
  const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
17
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';
18
27
  const socketPath = process.env.HOUSE_BRIDGE;
19
- 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) {
20
56
  const refusal = refusalOf(text);
21
57
  if (refusal !== null)
22
58
  return refusal.text;
23
59
  if (status === 401)
24
60
  return REVOKED;
61
+ const act = method === 'GET' ? 'download' : 'upload';
25
62
  if (URL.canParse(path))
26
- return `the upload answered ${status}; upload the file again`;
27
- if (status === 502 && /^[A-Za-z]/.test(text))
63
+ return `the ${act} answered ${status}; ${act} the file again`;
64
+ if (status === 502 && local)
28
65
  return text;
29
- return `${path} answered ${status}`;
66
+ return path === '/' ? unconfirmed(status) : `${path} answered ${status}`;
30
67
  }
31
- 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) {
32
72
  return new Promise((resolve, reject) => {
33
- const sent = request({ socketPath: to, path, method: 'POST', headers }, (answer) => {
34
- let text = '';
35
- answer.setEncoding('utf8');
36
- answer.on('data', (chunk) => {
37
- text += chunk;
38
- });
73
+ const sent = request({ socketPath: to, path, method, headers }, (answer) => {
74
+ const chunks = [];
75
+ answer.on('data', (chunk) => chunks.push(chunk));
39
76
  answer.on('end', () => {
77
+ const bytes = Buffer.concat(chunks);
40
78
  if (answer.statusCode === 200)
41
- resolve(text);
79
+ resolve(bytes);
42
80
  else
43
- 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)));
44
82
  });
45
83
  });
46
84
  sent.on('error', (error) => reject(new Error(error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED)));
47
- sent.end(body instanceof Buffer ? body : JSON.stringify(body));
85
+ sent.end(body === undefined ? undefined : body instanceof Buffer ? body : JSON.stringify(body));
48
86
  });
49
87
  }
88
+ async function bridged(path, body, headers, to = socketPath) {
89
+ return (await exchanged(path, 'POST', body, headers, to)).toString('utf8');
90
+ }
50
91
  async function direct(message) {
51
92
  const ownAgent = await readOwnAgent();
52
93
  if (ownAgent === null)
53
94
  throw new Error(UNCONNECTED);
95
+ selectRelay(process.env.HOUSE_KIT_RELAY || ownAgent.relay);
54
96
  setGlobalProxyFromEnv();
55
97
  const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
56
98
  throw new Error(UNREACHABLE);
57
99
  });
58
100
  if (answer.status === 200)
59
101
  return answer.text;
60
- 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)));
61
103
  }
62
104
  async function mcp(method, params) {
63
105
  const message = rpc(method, params);
@@ -79,31 +121,102 @@ async function localFile(path) {
79
121
  : `${path} is not a readable file`);
80
122
  }
81
123
  }
82
- async function upload(path, roomRef, missing) {
83
- if (typeof path !== 'string' || path === '')
84
- throw new Error(missing);
85
- const bytes = await localFile(path);
86
- const declared = JSON.parse(await bridged('/kit/attachments/upload', {
87
- ...(roomRef === undefined ? {} : { room_ref: roomRef }),
88
- name: basename(path),
89
- bytes: bytes.length,
90
- sha256: createHash('sha256').update(bytes).digest('hex'),
91
- }));
124
+ async function transferred(url, method, bytes, headers) {
125
+ if (socketPath !== undefined)
126
+ return exchanged(url, method, bytes, headers);
127
+ setGlobalProxyFromEnv();
128
+ const answer = await fetch(relayed(url), { method, ...(headers === undefined ? {} : { headers }), ...(bytes === undefined ? {} : { body: bytes }) }).catch(() => {
129
+ throw new Error(UNREACHABLE);
130
+ });
131
+ const received = Buffer.from(await answer.arrayBuffer());
132
+ if (answer.status === 200)
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);
92
174
  if (declared.upload === undefined)
93
- return declared.attachment;
94
- const saved = JSON.parse(await bridged(declared.upload.url, bytes, {
95
- 'content-type': 'application/octet-stream',
96
- 'x-house-byte-operation': declared.upload.operation,
97
- }));
98
- if (saved.upload_failure !== undefined)
99
- throw new Error(`${path} was not saved: ${saved.upload_failure}; call again later`);
100
- 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;
101
214
  }
102
215
  async function push(args) {
103
- if (args.includes('--help'))
216
+ const { flags, positionals: [commit = 'HEAD'] } = accepted(args, ['--help', '--owner'], 1, PUSH_USAGE);
217
+ if (flags.has('--help'))
104
218
  return PUSH_USAGE;
105
- const owner = args.includes('--owner');
106
- const commit = args.find((arg) => arg !== '--owner') ?? 'HEAD';
219
+ const owner = flags.has('--owner');
107
220
  if (owner && socketPath !== undefined)
108
221
  throw new Error('--owner is not for Agent conversations; run house push without it');
109
222
  if (!owner && socketPath === undefined)
@@ -113,6 +226,14 @@ async function push(args) {
113
226
  throw new Error(pushed.text);
114
227
  return pushed.text;
115
228
  }
229
+ async function fetched(args) {
230
+ if (accepted(args, ['--help'], 0, FETCH_USAGE).flags.has('--help'))
231
+ return FETCH_USAGE;
232
+ const answer = JSON.parse(await bridged('/git/fetch', {}, undefined, socketPath ?? join(kitHome(), 'owner.sock')));
233
+ if (answer.refused)
234
+ throw new Error(answer.text);
235
+ return answer.text;
236
+ }
116
237
  function argumentsOf(argument) {
117
238
  if (argument === undefined)
118
239
  return {};
@@ -127,35 +248,41 @@ function argumentsOf(argument) {
127
248
  throw new Error(ARGUMENTS);
128
249
  return parsed;
129
250
  }
130
- async function house([verb, argument]) {
131
- if (verb === undefined || verb === '--help' || verb === 'help') {
132
- return [USAGE, 'help', PUSH, ...(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');
133
259
  }
134
- if (argument === '--help') {
260
+ if (flags.has('--help')) {
135
261
  const tool = (await tools()).find((listed) => listed.name === verb);
136
262
  if (tool === undefined)
137
263
  throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
138
264
  return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
139
265
  }
140
- const args = argumentsOf(argument);
141
- if (socketPath !== undefined && verb === 'upload_attachment') {
142
- return JSON.stringify({ attachment: await upload(args.path, args.room_ref, 'upload_attachment needs "path", a local file') });
143
- }
144
- if (socketPath !== undefined && verb === 'append_record' && Array.isArray(args.attachments)) {
145
- const attachments = [];
146
- for (const path of args.attachments) {
147
- attachments.push(await upload(path, args.room_ref, 'each attachments entry is the path of a local file'));
148
- }
149
- args.attachments = attachments;
150
- }
151
- const result = await mcp('tools/call', { name: verb, arguments: args });
266
+ const parsed = argumentsOf(argument);
267
+ return verb === 'upload' ? upload(parsed) : verb === 'append_record' ? appendRecord(parsed) : called(verb, parsed);
268
+ }
269
+ async function called(name, args) {
270
+ const result = await mcp('tools/call', { name, arguments: args });
152
271
  const text = result.content.map((content) => content.text).join('\n');
153
272
  if (result.isError === true)
154
273
  throw new Error(text.replace(/\n+$/, ''));
155
274
  return text;
156
275
  }
157
276
  const argv = process.argv.slice(2);
158
- (argv[0] === 'push' ? push(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) => {
159
286
  process.stdout.write(`${text}\n`);
160
287
  if (argv[0] === 'shell')
161
288
  process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
@@ -1,34 +1,11 @@
1
- import { HOW_WE_WORK } from './skills.js';
2
- const HOUSE_LINE = 'Work with House through the `house` CLI: run `house --help`.';
3
- const FILE_LINE = 'To give the User a file or a page, upload it with `house upload_attachment` and link it; never start a server.';
4
- const READ_LINE = 'Before working in a Room, read `/rooms/private/rooms/<handle>/AGENTS.md`.';
5
- const COPIES_LINE = 'House Local copies; commit, then `house push`:';
6
- const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
7
- const FAILED = /^exit: [1-9]\d*$/;
8
- const CUT = /^stderr: shell: output_cut (\d+) of \d+ bytes; continue with: (.+)$/;
9
- function cutOf(lines) {
10
- const cut = CUT.exec(lines[0] ?? '');
11
- return cut !== null && Buffer.byteLength(lines.slice(1).join('\n')) === Number(cut[1]) ? cut : null;
12
- }
13
- async function howWeWork(bridge) {
14
- let document = '';
15
- for (let command = `cat ${HOW_WE_WORK}`; command !== undefined;) {
16
- const read = await bridge.tool('shell', { command });
17
- const text = read.content.map((content) => content.text).join('\n');
18
- const lines = text.split('\n');
19
- if (read.isError === true || (FAILED.test(lines[0] ?? '') && lines[1]?.startsWith('stderr: '))) {
20
- const refusal = read.isError === true ? text : lines.slice(1).join('\n').replace(/^stderr: /gm, '');
21
- if (UNREADABLE.test(refusal))
22
- return '';
23
- throw new Error(refusal);
24
- }
25
- const cut = cutOf(lines);
26
- document += lines.slice(cut === null ? 0 : 1).join('\n');
27
- command = cut?.[2];
28
- }
29
- return document.replace(/\n$/, '');
30
- }
1
+ import { HOUSE_REF } from './git.js';
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`.";
7
+ const COPIES_LINE = `House Local copies; before work run \`house fetch\` and rebase onto \`${HOUSE_REF}\`; after it commit, then \`house push\`:`;
31
8
  export async function instructions(bridge, base, copies) {
32
- const lines = [HOUSE_LINE, FILE_LINE, READ_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
33
- 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');
34
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`);