@agentshouse/kit 0.2.1-cf669c6d1ecbb → 0.2.1-cf6a92e13f031

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 (124) hide show
  1. package/README.md +36 -35
  2. package/dist/acp.js +36 -16
  3. package/dist/agents.js +110 -23
  4. package/dist/api.js +5 -1
  5. package/dist/app-git.js +10 -26
  6. package/dist/bootstrap.json +4 -4
  7. package/dist/bridge.js +4 -7
  8. package/dist/calls.js +63 -0
  9. package/dist/chatgpt.js +32 -0
  10. package/dist/clis.js +57 -12
  11. package/dist/connection.js +126 -0
  12. package/dist/conversations.js +399 -152
  13. package/dist/copies.js +89 -52
  14. package/dist/end.js +11 -2
  15. package/dist/events.js +6 -2
  16. package/dist/files.js +123 -31
  17. package/dist/git.js +11 -9
  18. package/dist/home.js +56 -5
  19. package/dist/house-cli.js +286 -0
  20. package/dist/house-main.js +7 -189
  21. package/dist/instructions.js +6 -10
  22. package/dist/kit-cli.js +68 -0
  23. package/dist/kit-main.js +8 -22
  24. package/dist/login.js +48 -16
  25. package/dist/logout.js +0 -2
  26. package/dist/mcp.js +4 -2
  27. package/dist/placement.js +39 -0
  28. package/dist/relay.js +1 -1
  29. package/dist/resident.js +88 -33
  30. package/dist/scope.js +3 -0
  31. package/dist/service.js +23 -1
  32. package/dist/sign-in.js +19 -37
  33. package/dist/skills.js +20 -32
  34. package/dist/transcription.js +53 -22
  35. package/dist/translate.js +2 -8
  36. package/dist/update.js +69 -50
  37. package/dist/web-wizard.js +100 -0
  38. package/dist/wire.js +22 -0
  39. package/dist/work.js +3 -5
  40. package/package.json +7 -6
  41. package/dist/stream.js +0 -74
  42. package/how-we-work.md +0 -23
  43. package/skills/ask-matt/LICENSE +0 -21
  44. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  45. package/skills/ask-matt/SKILL.md +0 -91
  46. package/skills/ask-matt/agents/openai.yaml +0 -4
  47. package/skills/code-review/LICENSE +0 -21
  48. package/skills/code-review/SKILL.md +0 -89
  49. package/skills/code-review/agents/openai.yaml +0 -3
  50. package/skills/codebase-design/DEEPENING.md +0 -37
  51. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  52. package/skills/codebase-design/LICENSE +0 -21
  53. package/skills/codebase-design/SKILL.md +0 -116
  54. package/skills/codebase-design/agents/openai.yaml +0 -3
  55. package/skills/diagnosing-bugs/LICENSE +0 -21
  56. package/skills/diagnosing-bugs/SKILL.md +0 -140
  57. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  58. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  59. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  60. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  61. package/skills/domain-modeling/LICENSE +0 -21
  62. package/skills/domain-modeling/SKILL.md +0 -76
  63. package/skills/domain-modeling/agents/openai.yaml +0 -3
  64. package/skills/grill-me/LICENSE +0 -21
  65. package/skills/grill-me/SKILL.md +0 -8
  66. package/skills/grill-me/agents/openai.yaml +0 -4
  67. package/skills/grill-with-docs/LICENSE +0 -21
  68. package/skills/grill-with-docs/SKILL.md +0 -8
  69. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  70. package/skills/grilling/LICENSE +0 -21
  71. package/skills/grilling/SKILL.md +0 -30
  72. package/skills/grilling/agents/openai.yaml +0 -3
  73. package/skills/handoff/LICENSE +0 -21
  74. package/skills/handoff/SKILL.md +0 -17
  75. package/skills/handoff/agents/openai.yaml +0 -4
  76. package/skills/implement/LICENSE +0 -21
  77. package/skills/implement/SKILL.md +0 -16
  78. package/skills/implement/agents/openai.yaml +0 -4
  79. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  80. package/skills/improve-codebase-architecture/LICENSE +0 -21
  81. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  82. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  83. package/skills/prototype/LICENSE +0 -21
  84. package/skills/prototype/LOGIC.md +0 -67
  85. package/skills/prototype/SKILL.md +0 -28
  86. package/skills/prototype/UI.md +0 -112
  87. package/skills/prototype/agents/openai.yaml +0 -3
  88. package/skills/research/LICENSE +0 -21
  89. package/skills/research/SKILL.md +0 -14
  90. package/skills/research/agents/openai.yaml +0 -3
  91. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  92. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  93. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  94. package/skills/tdd/LICENSE +0 -21
  95. package/skills/tdd/SKILL.md +0 -40
  96. package/skills/tdd/agents/openai.yaml +0 -3
  97. package/skills/tdd/mocking.md +0 -59
  98. package/skills/tdd/tests.md +0 -77
  99. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  100. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  101. package/skills/teach/LICENSE +0 -21
  102. package/skills/teach/MISSION-FORMAT.md +0 -31
  103. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  104. package/skills/teach/SKILL.md +0 -141
  105. package/skills/teach/agents/openai.yaml +0 -4
  106. package/skills/to-questionnaire/LICENSE +0 -21
  107. package/skills/to-questionnaire/SKILL.md +0 -55
  108. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  109. package/skills/to-spec/LICENSE +0 -21
  110. package/skills/to-spec/SKILL.md +0 -76
  111. package/skills/to-spec/agents/openai.yaml +0 -4
  112. package/skills/to-tickets/LICENSE +0 -21
  113. package/skills/to-tickets/SKILL.md +0 -106
  114. package/skills/to-tickets/agents/openai.yaml +0 -4
  115. package/skills/wait-what/LICENSE +0 -21
  116. package/skills/wait-what/SKILL.md +0 -8
  117. package/skills/wait-what/agents/openai.yaml +0 -4
  118. package/skills/wayfinder/LICENSE +0 -21
  119. package/skills/wayfinder/SKILL.md +0 -129
  120. package/skills/wayfinder/agents/openai.yaml +0 -4
  121. package/skills/writing-for-agents/LICENSE +0 -21
  122. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  123. package/skills/writing-for-agents/SKILL.md +0 -83
  124. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/home.js CHANGED
@@ -1,15 +1,63 @@
1
- import { existsSync, linkSync, readFileSync, renameSync, rmSync } from 'node:fs';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { accessSync, chmodSync, constants, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, 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 { join } from 'node:path';
4
+ import { homedir, tmpdir } from 'node:os';
5
+ import { join, resolve } from 'node:path';
5
6
  import { selectRelay } from './relay.js';
6
7
  const ENROLMENT = 'credential.json';
7
8
  const DISCONNECTED = 'disconnected.json';
8
9
  const CONFIGURATION = 'kit.json';
9
10
  const OWN_AGENT = 'own-agent.json';
10
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 privateDirectory(path) {
23
+ try {
24
+ mkdirSync(path, { mode: 0o700 });
25
+ }
26
+ catch (error) {
27
+ if (error.code !== 'EEXIST')
28
+ throw error;
29
+ }
30
+ const found = lstatSync(path);
31
+ if (found.isSymbolicLink())
32
+ throw new Error(`${path} is a symbolic link`);
33
+ if (!found.isDirectory())
34
+ throw new Error(`${path} is not a directory`);
35
+ if (found.uid !== process.geteuid())
36
+ throw new Error(`${path} is not owned by this User`);
37
+ chmodSync(path, 0o700);
38
+ return path;
39
+ }
40
+ function ownTemporaryHome() {
41
+ return privateDirectory(join(tmpdir(), `house-kit-${process.getuid()}`));
42
+ }
43
+ function defaultHome() {
44
+ const home = join(homedir(), '.house-kit');
45
+ return existsSync(home) || writable(homedir()) ? home : ownTemporaryHome();
46
+ }
11
47
  export function kitHome() {
12
- return process.env.HOUSE_KIT_HOME ?? join(homedir(), '.house-kit');
48
+ return process.env.HOUSE_KIT_HOME || (defaulted ??= defaultHome());
49
+ }
50
+ export function socketDirectory() {
51
+ const sockets = privateDirectory(join(realpathSync('/tmp'), `hk-${process.geteuid()}`));
52
+ const home = kitHome();
53
+ const physical = existsSync(home) ? realpathSync(home) : resolve(home);
54
+ return privateDirectory(join(sockets, createHash('sha256').update(physical).digest('hex').slice(0, 12)));
55
+ }
56
+ export function ownerSocket() {
57
+ return join(socketDirectory(), 'owner.sock');
58
+ }
59
+ export function ownerLock() {
60
+ return join(socketDirectory(), 'owner.lock');
13
61
  }
14
62
  export function workspaceRoot() {
15
63
  return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
@@ -30,7 +78,7 @@ export async function readHome(name) {
30
78
  export async function writeHome(name, value) {
31
79
  const home = kitHome();
32
80
  await mkdir(home, { recursive: true, mode: 0o700 });
33
- const temporary = join(home, `${name}.${process.pid}`);
81
+ const temporary = join(home, `${name}.${randomUUID()}`);
34
82
  await writeFile(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600 });
35
83
  await rename(temporary, join(home, name));
36
84
  }
@@ -47,6 +95,9 @@ export async function writeEnrolment(enrolment) {
47
95
  export function readDisconnected() {
48
96
  return readHome(DISCONNECTED);
49
97
  }
98
+ export function forgetDisconnected() {
99
+ return rm(join(kitHome(), DISCONNECTED), { force: true });
100
+ }
50
101
  export async function forgetEnrolment({ house, environment }) {
51
102
  await writeHome(DISCONNECTED, { house, environment });
52
103
  await rm(join(kitHome(), ENROLMENT), { force: true });
@@ -0,0 +1,286 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { request, setGlobalProxyFromEnv } from 'node:http';
4
+ import { request as httpsRequest } from 'node:https';
5
+ import { extname, join, resolve } from 'node:path';
6
+ import { Readable } from 'node:stream';
7
+ import { pipeline } from 'node:stream/promises';
8
+ import { downloaded, inspectedFile, storeRefusal, uploaded } from './files.js';
9
+ import { HOUSE_REF } from './git.js';
10
+ import { ownerSocket, readOwnAgent } from './home.js';
11
+ import { callHouse, rpc, UNREACHABLE, Unsettled } from './mcp.js';
12
+ import { refusalOf, retryable } from './refusals.js';
13
+ import { relayed, selectRelay } from './relay.js';
14
+ import { parse } from 'yaml';
15
+ const USAGE = "usage: house <tool> ['<arguments as JSON>']";
16
+ const PUSH_USAGE = 'usage: house push [commit] [--owner]';
17
+ const PUSH = "push [commit]: sends the Local copy's committed changes to House";
18
+ const FETCH_USAGE = 'usage: house fetch';
19
+ const FETCH = `fetch: records House's changes on each Local copy's ${HOUSE_REF}`;
20
+ const DOWNLOAD_USAGE = `usage: house download '{"path":"/rooms/<handle>/<path>","file":"<local file>"}', adding "ref" for a revision`;
21
+ const DOWNLOAD = 'download: writes a binary file of a Room to the local file named by file';
22
+ const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
23
+ const CLOSED = "this conversation's House connection is closed; nothing to do from here";
24
+ const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
25
+ const REVOKED = 'this conversation no longer has House access; nothing to do from here';
26
+ const UNCONNECTED = "this computer's own agent has no House connection; run kit login, or kit chatgpt --key <key> with a script key";
27
+ const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login, or kit chatgpt --key <key> with a script key";
28
+ const UNCONFIRMED = 'with no result; a write may or may not have taken effect, so read before you repeat it';
29
+ const socketPath = process.env.HOUSE_BRIDGE;
30
+ const MEDIA_TYPES = new Map([
31
+ ['avif', 'image/avif'],
32
+ ['csv', 'text/csv'],
33
+ ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
34
+ ['gif', 'image/gif'],
35
+ ['heic', 'image/heic'],
36
+ ['html', 'text/html'],
37
+ ['jpeg', 'image/jpeg'],
38
+ ['jpg', 'image/jpeg'],
39
+ ['json', 'application/json'],
40
+ ['m4a', 'audio/mp4'],
41
+ ['md', 'text/markdown'],
42
+ ['mov', 'video/quicktime'],
43
+ ['mp3', 'audio/mpeg'],
44
+ ['mp4', 'video/mp4'],
45
+ ['ogg', 'audio/ogg'],
46
+ ['pdf', 'application/pdf'],
47
+ ['png', 'image/png'],
48
+ ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
49
+ ['svg', 'image/svg+xml'],
50
+ ['txt', 'text/plain'],
51
+ ['wav', 'audio/wav'],
52
+ ['webm', 'video/webm'],
53
+ ['webp', 'image/webp'],
54
+ ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
55
+ ['zip', 'application/zip'],
56
+ ]);
57
+ function refused(path, status, text, local) {
58
+ const refusal = refusalOf(text);
59
+ if (refusal !== null)
60
+ return refusal.text;
61
+ if (status === 401)
62
+ return REVOKED;
63
+ if (status === 502 && local)
64
+ return text;
65
+ return path === '/' ? unconfirmed(status) : `${path} answered ${status}`;
66
+ }
67
+ function unconfirmed(status) {
68
+ return `House answered ${status} ${UNCONFIRMED}`;
69
+ }
70
+ function bridged(path, body, to = socketPath) {
71
+ return new Promise((resolve, reject) => {
72
+ const sent = request({ socketPath: to, path, method: 'POST', headers: { 'content-type': 'application/json' } }, (answer) => {
73
+ const chunks = [];
74
+ answer.on('data', (chunk) => chunks.push(chunk));
75
+ answer.on('end', () => {
76
+ const text = Buffer.concat(chunks).toString('utf8');
77
+ if (answer.statusCode === 200)
78
+ resolve(text);
79
+ else
80
+ reject(new Error(refused(path, answer.statusCode, text, answer.headers['content-type'] === undefined)));
81
+ });
82
+ });
83
+ sent.on('error', (error) => reject(new Error(error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED)));
84
+ sent.end(JSON.stringify(body));
85
+ });
86
+ }
87
+ async function direct(message) {
88
+ const ownAgent = await readOwnAgent();
89
+ if (ownAgent === null)
90
+ throw new Error(UNCONNECTED);
91
+ selectRelay(process.env.HOUSE_KIT_RELAY || ownAgent.relay);
92
+ setGlobalProxyFromEnv();
93
+ const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
94
+ throw new Unsettled(UNREACHABLE);
95
+ });
96
+ if (answer.status === 200)
97
+ return answer.text;
98
+ if (answer.status === 401)
99
+ throw new Error(DISCONNECTED);
100
+ const refusal = refusalOf(answer.text)?.text ?? unconfirmed(answer.status);
101
+ throw retryable(answer.text) === false ? new Error(refusal) : new Unsettled(refusal);
102
+ }
103
+ async function mcp(method, params) {
104
+ const message = rpc(method, params);
105
+ const answer = JSON.parse(socketPath === undefined ? await direct(message) : await bridged('/', message));
106
+ if (answer.error !== undefined)
107
+ throw new Error(answer.error.message);
108
+ return answer.result;
109
+ }
110
+ async function tools() {
111
+ return (await mcp('tools/list', {})).tools;
112
+ }
113
+ function unreadable(path, error) {
114
+ return new Error(error.code === 'EISDIR'
115
+ ? `${path} is a folder; upload one file at a time`
116
+ : `${path} is not a readable file`);
117
+ }
118
+ function opened(url, method, headers, body) {
119
+ return new Promise((answered, failed) => {
120
+ const local = socketPath !== undefined;
121
+ const target = local ? null : relayed(url);
122
+ if (!local)
123
+ setGlobalProxyFromEnv();
124
+ const sent = target === null
125
+ ? request({ socketPath, path: url, method, headers }, answered)
126
+ : (target.protocol === 'https:' ? httpsRequest : request)(target, { method, headers }, answered);
127
+ sent.on('error', (error) => failed(new Error(!local ? UNREACHABLE : error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED)));
128
+ if (body === undefined)
129
+ sent.end();
130
+ else
131
+ pipeline(body, sent).catch(() => undefined);
132
+ });
133
+ }
134
+ async function sentPart(url, file, start, end) {
135
+ const answer = await opened(url, 'PUT', { 'content-length': String(end - start) }, end === start ? undefined : createReadStream(file, { start, end: end - 1 }));
136
+ await answer.toArray();
137
+ if (answer.statusCode !== 200)
138
+ throw storeRefusal('upload', answer.statusCode);
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 written = resolve(file);
148
+ await downloaded(async () => {
149
+ const file = inspectedFile(await called('inspect', selected));
150
+ if (file === null)
151
+ throw new Error(`${String(selected.path)} holds no binary file; shell reads its text`);
152
+ return file;
153
+ }, async (url) => {
154
+ const answer = await opened(url, 'GET', {});
155
+ return { status: answer.statusCode, body: answer };
156
+ }, written, String(selected.path));
157
+ return written;
158
+ }
159
+ async function described(file) {
160
+ const digest = createHash('sha256');
161
+ let bytes = 0;
162
+ try {
163
+ for await (const chunk of createReadStream(file)) {
164
+ digest.update(chunk);
165
+ bytes += chunk.length;
166
+ }
167
+ }
168
+ catch (error) {
169
+ throw unreadable(file, error);
170
+ }
171
+ const mediaType = MEDIA_TYPES.get(extname(file).slice(1).toLowerCase());
172
+ return { bytes, sha256: digest.digest('hex'), ...(mediaType === undefined ? {} : { media_type: mediaType }) };
173
+ }
174
+ async function finished(upload, room) {
175
+ const text = await called('upload', { upload, room_ref: room });
176
+ const answer = parse(text);
177
+ return answer !== null && ('upload' in answer || 'checking' in answer) ? answer : { text };
178
+ }
179
+ async function upload({ file, ...destination }) {
180
+ if (typeof file !== 'string' || file === '')
181
+ throw new Error('upload needs "file", a local file');
182
+ const description = await described(file);
183
+ const answer = await called('upload', { ...destination, ...description });
184
+ const declared = parse(answer);
185
+ if (declared?.upload === undefined)
186
+ return answer;
187
+ const accepted = await uploaded(declared.upload, {
188
+ bytes: description.bytes,
189
+ send: (url, start, end) => sentPart(url, file, start, end),
190
+ finish: (id) => finished(id, destination.room_ref),
191
+ });
192
+ return accepted.text;
193
+ }
194
+ function unexpected(argument, usage) {
195
+ return new Error(`unexpected argument ${argument}; ${usage}`);
196
+ }
197
+ function accepted(args, flags, positionals, usage) {
198
+ const given = { flags: new Set(), positionals: [] };
199
+ for (const arg of args) {
200
+ if (flags.includes(arg))
201
+ given.flags.add(arg);
202
+ else if (!arg.startsWith('-') && given.positionals.length < positionals)
203
+ given.positionals.push(arg);
204
+ else
205
+ throw unexpected(arg, usage);
206
+ }
207
+ return given;
208
+ }
209
+ async function push(args) {
210
+ const { flags, positionals: [commit = 'HEAD'] } = accepted(args, ['--help', '--owner'], 1, PUSH_USAGE);
211
+ if (flags.has('--help'))
212
+ return PUSH_USAGE;
213
+ const owner = flags.has('--owner');
214
+ if (owner && socketPath !== undefined)
215
+ throw new Error('--owner is not for Agent conversations; run house push without it');
216
+ if (!owner && socketPath === undefined)
217
+ throw new Error('outside an Agent conversation, house push needs --owner');
218
+ const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, owner ? ownerSocket() : socketPath));
219
+ if (pushed.refused)
220
+ throw new Error(pushed.text);
221
+ return pushed.text;
222
+ }
223
+ async function fetched(args) {
224
+ if (accepted(args, ['--help'], 0, FETCH_USAGE).flags.has('--help'))
225
+ return FETCH_USAGE;
226
+ const answer = JSON.parse(await bridged('/git/fetch', {}, socketPath ?? ownerSocket()));
227
+ if (answer.refused)
228
+ throw new Error(answer.text);
229
+ return answer.text;
230
+ }
231
+ function argumentsOf(argument) {
232
+ if (argument === undefined)
233
+ return {};
234
+ let parsed;
235
+ try {
236
+ parsed = JSON.parse(argument);
237
+ }
238
+ catch {
239
+ throw new Error(ARGUMENTS);
240
+ }
241
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
242
+ throw new Error(ARGUMENTS);
243
+ return parsed;
244
+ }
245
+ async function house(args) {
246
+ const { flags, positionals: [verb, argument] } = accepted(args, ['--help'], 2, USAGE);
247
+ if (verb === 'help' && argument !== undefined)
248
+ throw unexpected(argument, USAGE);
249
+ if (flags.has('--help') && argument !== undefined)
250
+ throw unexpected('--help', USAGE);
251
+ if (verb === undefined || verb === 'help') {
252
+ return [USAGE, 'help', PUSH, FETCH, DOWNLOAD, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
253
+ }
254
+ if (flags.has('--help')) {
255
+ const tool = (await tools()).find((listed) => listed.name === verb);
256
+ if (tool === undefined)
257
+ throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
258
+ return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
259
+ }
260
+ const parsed = argumentsOf(argument);
261
+ return verb === 'upload' ? upload(parsed) : called(verb, parsed);
262
+ }
263
+ async function called(name, args) {
264
+ const result = await mcp('tools/call', { name, arguments: args });
265
+ const text = result.content.map((content) => content.text).join('\n');
266
+ if (result.isError === true)
267
+ throw new Error(text.replace(/\n+$/, ''));
268
+ return text;
269
+ }
270
+ const argv = process.argv.slice(2);
271
+ const named = argv.findIndex((arg) => !arg.startsWith('-'));
272
+ const rest = argv.filter((_arg, index) => index !== named);
273
+ (argv[named] === 'push'
274
+ ? push(rest)
275
+ : argv[named] === 'fetch'
276
+ ? fetched(rest)
277
+ : argv[named] === 'download'
278
+ ? download(rest)
279
+ : house(argv)).then((text) => {
280
+ process.stdout.write(`${text}\n`);
281
+ if (argv[0] === 'shell')
282
+ process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
283
+ }, (error) => {
284
+ process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
285
+ process.exitCode = 1;
286
+ });
@@ -1,192 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { createHash } from 'node:crypto';
3
- import { readFile } from 'node:fs/promises';
4
- import { request, setGlobalProxyFromEnv } from 'node:http';
5
- import { basename, join } from 'node:path';
6
- import { HOUSE_REF } from './git.js';
7
- import { kitHome, readEnrolment, readOwnAgent } from './home.js';
8
- import { callHouse, rpc, UNREACHABLE } from './mcp.js';
9
- import { refusalOf } from './refusals.js';
10
- import { relayed } from './relay.js';
11
- import { parse } from 'yaml';
12
- const USAGE = "usage: house <tool> ['<arguments as JSON>']";
13
- const PUSH_USAGE = 'usage: house push [commit] [--owner]';
14
- const PUSH = "push [commit]: sends the Local copy's committed changes to House";
15
- const FETCH_USAGE = 'usage: house fetch';
16
- const FETCH = `fetch: records House's changes on each Local copy's ${HOUSE_REF}`;
17
- const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
18
- const CLOSED = "this conversation's House connection is closed; nothing to do from here";
19
- const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
20
- const REVOKED = 'this conversation no longer has House access; nothing to do from here';
21
- const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
22
- const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login";
23
- const socketPath = process.env.HOUSE_BRIDGE;
24
- function refused(path, status, text) {
25
- const refusal = refusalOf(text);
26
- if (refusal !== null)
27
- return refusal.text;
28
- if (status === 401)
29
- return REVOKED;
30
- if (URL.canParse(path))
31
- return `the upload answered ${status}; upload the file again`;
32
- if (status === 502 && /^[A-Za-z]/.test(text))
33
- return text;
34
- return `${path} answered ${status}`;
35
- }
36
- function bridged(path, body, headers = { 'content-type': 'application/json' }, to = socketPath) {
37
- 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
- });
44
- answer.on('end', () => {
45
- if (answer.statusCode === 200)
46
- resolve(text);
47
- else
48
- reject(new Error(refused(path, answer.statusCode, text)));
49
- });
50
- });
51
- 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));
53
- });
54
- }
55
- async function direct(message) {
56
- const ownAgent = await readOwnAgent();
57
- if (ownAgent === null)
58
- throw new Error(UNCONNECTED);
59
- await readEnrolment();
60
- setGlobalProxyFromEnv();
61
- const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
62
- throw new Error(UNREACHABLE);
63
- });
64
- if (answer.status === 200)
65
- return answer.text;
66
- throw new Error(answer.status === 401 ? DISCONNECTED : (refusalOf(answer.text)?.text ?? `House answered ${answer.status}`));
67
- }
68
- async function mcp(method, params) {
69
- const message = rpc(method, params);
70
- const answer = JSON.parse(socketPath === undefined ? await direct(message) : await bridged('/', message));
71
- if (answer.error !== undefined)
72
- throw new Error(answer.error.message);
73
- return answer.result;
74
- }
75
- async function tools() {
76
- return (await mcp('tools/list', {})).tools;
77
- }
78
- async function localFile(path) {
79
- try {
80
- return await readFile(path);
81
- }
82
- catch (error) {
83
- throw new Error(error.code === 'EISDIR'
84
- ? `${path} is a folder; upload one file at a time`
85
- : `${path} is not a readable file`);
86
- }
87
- }
88
- async function sent(url, bytes, operation) {
89
- const headers = { 'content-type': 'application/octet-stream', 'x-house-byte-operation': operation };
90
- if (socketPath !== undefined)
91
- return bridged(url, bytes, headers);
92
- setGlobalProxyFromEnv();
93
- const answer = await fetch(relayed(url), { method: 'POST', headers, body: bytes }).catch(() => {
94
- throw new Error(UNREACHABLE);
95
- });
96
- const text = await answer.text();
97
- 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
- }));
111
- 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;
117
- }
118
- async function push(args) {
119
- if (args.includes('--help'))
120
- return PUSH_USAGE;
121
- const owner = args.includes('--owner');
122
- const commit = args.find((arg) => arg !== '--owner') ?? 'HEAD';
123
- if (owner && socketPath !== undefined)
124
- throw new Error('--owner is not for Agent conversations; run house push without it');
125
- if (!owner && socketPath === undefined)
126
- throw new Error('outside an Agent conversation, house push needs --owner');
127
- const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, undefined, owner ? join(kitHome(), 'owner.sock') : socketPath));
128
- if (pushed.refused)
129
- throw new Error(pushed.text);
130
- return pushed.text;
131
- }
132
- async function fetched(args) {
133
- if (args.includes('--help'))
134
- return FETCH_USAGE;
135
- const answer = JSON.parse(await bridged('/git/fetch', {}, undefined, socketPath ?? join(kitHome(), 'owner.sock')));
136
- if (answer.refused)
137
- throw new Error(answer.text);
138
- return answer.text;
139
- }
140
- function argumentsOf(argument) {
141
- if (argument === undefined)
142
- return {};
143
- let parsed;
144
- try {
145
- parsed = JSON.parse(argument);
146
- }
147
- catch {
148
- throw new Error(ARGUMENTS);
149
- }
150
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
151
- throw new Error(ARGUMENTS);
152
- return parsed;
153
- }
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');
157
- }
158
- if (argument === '--help') {
159
- const tool = (await tools()).find((listed) => listed.name === verb);
160
- if (tool === undefined)
161
- throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
162
- return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
163
- }
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);
2
+ const [major = 0, minor = 0] = process.versions.node.split('.').map(Number);
3
+ if (major < 24 || (major === 24 && minor < 14)) {
4
+ process.stderr.write(`house: the Kit needs Node 24.14.0 or newer; this is ${process.versions.node}\n`);
5
+ process.exitCode = 1;
176
6
  }
177
- async function called(name, args) {
178
- const result = await mcp('tools/call', { name, arguments: args });
179
- const text = result.content.map((content) => content.text).join('\n');
180
- if (result.isError === true)
181
- throw new Error(text.replace(/\n+$/, ''));
182
- return text;
7
+ else {
8
+ await import('./house-cli.js');
183
9
  }
184
- 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) => {
186
- process.stdout.write(`${text}\n`);
187
- if (argv[0] === 'shell')
188
- process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
189
- }, (error) => {
190
- process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
191
- process.exitCode = 1;
192
- });
10
+ export {};
@@ -1,10 +1,6 @@
1
+ import { agentInstructions } from '@agentshouse/skills';
1
2
  import { HOUSE_REF } from './git.js';
2
- import { HOW_WE_WORK } 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\`:`;
3
+ const HOW_WE_WORK = '/rooms/private/how-we-work.md';
8
4
  const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
9
5
  const FAILED = /^exit: [1-9]\d*$/;
10
6
  const CUT = /^stderr: shell: output_cut (\d+) of \d+ bytes; continue with: (.+)$/;
@@ -12,7 +8,7 @@ function cutOf(lines) {
12
8
  const cut = CUT.exec(lines[0] ?? '');
13
9
  return cut !== null && Buffer.byteLength(lines.slice(1).join('\n')) === Number(cut[1]) ? cut : null;
14
10
  }
15
- async function howWeWork(bridge) {
11
+ async function readHowWeWork(bridge) {
16
12
  let document = '';
17
13
  for (let command = `cat ${HOW_WE_WORK}`; command !== undefined;) {
18
14
  const read = await bridge.tool('shell', { command });
@@ -28,9 +24,9 @@ async function howWeWork(bridge) {
28
24
  document += lines.slice(cut === null ? 0 : 1).join('\n');
29
25
  command = cut?.[2];
30
26
  }
31
- return document.replace(/\n$/, '');
27
+ return document;
32
28
  }
33
29
  export async function instructions(bridge, base, copies) {
34
- 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');
30
+ const lines = agentInstructions(HOUSE_REF, copies);
31
+ return [lines.join('\n'), base, (await readHowWeWork(bridge)).replace(/\n$/, '')].filter((part) => part !== '').join('\n\n');
36
32
  }
@@ -0,0 +1,68 @@
1
+ import { setGlobalProxyFromEnv } from 'node:http';
2
+ import { parseArgs } from 'node:util';
3
+ import { answerGitCredential } from './app-git.js';
4
+ import { chatgpt } from './chatgpt.js';
5
+ import { login } from './login.js';
6
+ import { logout } from './logout.js';
7
+ import { resident } from './resident.js';
8
+ const USAGE = 'usage: kit <login|logout|resident|chatgpt>\n';
9
+ const COMMANDS = new Map([
10
+ [
11
+ 'logout',
12
+ {
13
+ usage: 'usage: kit logout',
14
+ about: "disconnects this computer, stops the Kit process and ends your own agent's connection",
15
+ operands: 0,
16
+ run: logout,
17
+ },
18
+ ],
19
+ [
20
+ 'resident',
21
+ {
22
+ usage: 'usage: kit resident',
23
+ about: "keeps this Environment connected; Kit's service runs it",
24
+ operands: 0,
25
+ run: resident,
26
+ },
27
+ ],
28
+ [
29
+ 'git-credential',
30
+ {
31
+ usage: 'usage: kit git-credential <get|store|erase>',
32
+ about: "answers git with your own agent's House credential; git runs it",
33
+ operands: 1,
34
+ run: ([operation]) => answerGitCredential(operation),
35
+ },
36
+ ],
37
+ ]);
38
+ const [command, ...argv] = process.argv.slice(2);
39
+ setGlobalProxyFromEnv();
40
+ async function run() {
41
+ if (command === 'login')
42
+ return login(argv);
43
+ if (command === 'chatgpt')
44
+ return chatgpt(argv);
45
+ if (command === '--help') {
46
+ parseArgs({ args: argv });
47
+ process.stdout.write(USAGE);
48
+ return;
49
+ }
50
+ const chosen = COMMANDS.get(command ?? '');
51
+ if (chosen === undefined) {
52
+ process.stderr.write(USAGE);
53
+ process.exitCode = 2;
54
+ return;
55
+ }
56
+ const { values, positionals } = parseArgs({ args: argv, options: { help: { type: 'boolean', default: false } }, allowPositionals: true });
57
+ if (positionals.length > chosen.operands)
58
+ throw new Error(`unexpected argument ${positionals[chosen.operands]}; ${chosen.usage}`);
59
+ if (values.help) {
60
+ process.stdout.write(`${chosen.usage}\n ${chosen.about}\n`);
61
+ return;
62
+ }
63
+ return chosen.run(positionals);
64
+ }
65
+ run().catch((error) => {
66
+ process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
67
+ process.exitCode = 1;
68
+ });