@agentshouse/kit 0.2.1-ce145e9aadbf6 → 0.2.1-ce3d2bb67177c

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 (105) hide show
  1. package/README.md +40 -39
  2. package/dist/acp.js +48 -105
  3. package/dist/agents.js +153 -43
  4. package/dist/api.js +34 -2
  5. package/dist/app-git.js +48 -0
  6. package/dist/bootstrap.json +4 -4
  7. package/dist/bridge.js +36 -57
  8. package/dist/calls.js +63 -0
  9. package/dist/chatgpt.js +32 -0
  10. package/dist/clis.js +127 -70
  11. package/dist/codex-main.js +58 -0
  12. package/dist/connection.js +125 -0
  13. package/dist/conversations.js +620 -323
  14. package/dist/copies.js +188 -128
  15. package/dist/end.js +27 -0
  16. package/dist/enrol-main.js +7 -1
  17. package/dist/events.js +525 -0
  18. package/dist/files.js +123 -17
  19. package/dist/git.js +11 -9
  20. package/dist/home.js +96 -7
  21. package/dist/house-cli.js +327 -0
  22. package/dist/house-main.js +7 -159
  23. package/dist/instructions.js +10 -32
  24. package/dist/kit-cli.js +68 -0
  25. package/dist/kit-main.js +8 -19
  26. package/dist/login.js +117 -104
  27. package/dist/logout.js +14 -13
  28. package/dist/mcp.js +4 -2
  29. package/dist/parts.js +82 -0
  30. package/dist/placement.js +39 -0
  31. package/dist/refusals.js +12 -0
  32. package/dist/relay.js +12 -2
  33. package/dist/resident.js +106 -50
  34. package/dist/scope.js +206 -0
  35. package/dist/secret-input.js +3 -2
  36. package/dist/service-main.js +9 -0
  37. package/dist/service.js +55 -0
  38. package/dist/shell.js +3 -0
  39. package/dist/sign-in.js +37 -31
  40. package/dist/skills.js +84 -15
  41. package/dist/transcription.js +100 -21
  42. package/dist/translate.js +2 -8
  43. package/dist/update.js +71 -50
  44. package/dist/wire.js +22 -0
  45. package/dist/work.js +346 -0
  46. package/how-we-work.md +13 -3
  47. package/package.json +4 -3
  48. package/skills/ask-matt/SKILL.md +17 -11
  49. package/skills/ask-matt/agents/openai.yaml +1 -0
  50. package/skills/code-review/SKILL.md +5 -5
  51. package/skills/codebase-design/DESIGN-IT-TWICE.md +1 -1
  52. package/skills/codebase-design/SKILL.md +0 -2
  53. package/skills/diagnosing-bugs/SKILL.md +2 -4
  54. package/skills/domain-modeling/{CONTEXT-FORMAT.md → GLOSSARY-FORMAT.md} +10 -10
  55. package/skills/domain-modeling/SKILL.md +12 -14
  56. package/skills/grill-me/SKILL.md +1 -2
  57. package/skills/grill-me/agents/openai.yaml +1 -0
  58. package/skills/grill-with-docs/SKILL.md +1 -2
  59. package/skills/grill-with-docs/agents/openai.yaml +1 -0
  60. package/skills/grilling/SKILL.md +2 -2
  61. package/skills/handoff/SKILL.md +2 -3
  62. package/skills/handoff/agents/openai.yaml +1 -0
  63. package/skills/implement/SKILL.md +5 -4
  64. package/skills/implement/agents/openai.yaml +1 -0
  65. package/skills/implement-spec/SKILL.md +40 -0
  66. package/skills/implement-spec/agents/openai.yaml +5 -0
  67. package/skills/improve-codebase-architecture/SKILL.md +6 -7
  68. package/skills/improve-codebase-architecture/agents/openai.yaml +1 -0
  69. package/skills/pr/CREDITS.md +3 -0
  70. package/skills/pr/LICENSE +21 -0
  71. package/skills/pr/SKILL.md +170 -0
  72. package/skills/pr/agents/openai.yaml +3 -0
  73. package/skills/prototype/SKILL.md +0 -2
  74. package/skills/research/SKILL.md +0 -2
  75. package/skills/retro/LICENSE +21 -0
  76. package/skills/retro/SKILL.md +44 -0
  77. package/skills/retro/agents/openai.yaml +5 -0
  78. package/skills/tdd/SKILL.md +2 -4
  79. package/skills/teach/SKILL.md +3 -4
  80. package/skills/teach/agents/openai.yaml +1 -0
  81. package/skills/to-questionnaire/SKILL.md +1 -2
  82. package/skills/to-questionnaire/agents/openai.yaml +1 -0
  83. package/skills/to-spec/SKILL.md +1 -2
  84. package/skills/to-spec/agents/openai.yaml +1 -0
  85. package/skills/to-tickets/SKILL.md +3 -4
  86. package/skills/to-tickets/agents/openai.yaml +1 -0
  87. package/skills/triage/AGENT-BRIEF.md +207 -0
  88. package/skills/triage/LICENSE +21 -0
  89. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  90. package/skills/triage/SKILL.md +112 -0
  91. package/skills/triage/agents/openai.yaml +5 -0
  92. package/skills/wait-what/SKILL.md +2 -3
  93. package/skills/wait-what/agents/openai.yaml +1 -0
  94. package/skills/wayfinder/SKILL.md +5 -6
  95. package/skills/wayfinder/agents/openai.yaml +1 -0
  96. package/skills/wizard/LICENSE +21 -0
  97. package/skills/wizard/SKILL.md +44 -0
  98. package/skills/wizard/agents/openai.yaml +3 -0
  99. package/skills/wizard/template.sh +223 -0
  100. package/skills/writing-for-agents/SKILL.md +0 -2
  101. package/dist/blocks.js +0 -51
  102. package/dist/stream.js +0 -47
  103. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  104. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  105. /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';
@@ -7,7 +8,7 @@ export function localCopies() {
7
8
  return join(workspaceRoot(), 'local-copies');
8
9
  }
9
10
  export const HOUSE_REF = 'refs/house/received';
10
- const COMMITTER = 'House Kit <house-kit@localhost>';
11
+ const COMMITTER = 'Kit <house-kit@localhost>';
11
12
  export function run(cwd, args, input, env = {}) {
12
13
  return new Promise((resolve, reject) => {
13
14
  const child = spawn('git', args, { cwd, env: { ...withoutProxy(), ...env } });
@@ -48,14 +49,15 @@ 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
+ async function blob(repository, object) {
53
+ return (await run(repository, ['cat-file', 'blob', object])).stdout;
54
+ }
55
+ export async function blobText(repository, object) {
56
+ return (await blob(repository, object)).toString('utf8');
57
+ }
58
+ export async function isText(repository, object, maxBytes) {
59
+ const bytes = await blob(repository, object);
60
+ return bytes.length <= maxBytes && isUtf8(bytes) && !bytes.includes(0);
59
61
  }
60
62
  export function blobId(content) {
61
63
  const bytes = Buffer.from(content, 'utf8');
package/dist/home.js CHANGED
@@ -1,13 +1,63 @@
1
- import { existsSync } 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';
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 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
+ }
9
47
  export function kitHome() {
10
- 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');
11
61
  }
12
62
  export function workspaceRoot() {
13
63
  return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
@@ -28,12 +78,15 @@ export async function readHome(name) {
28
78
  export async function writeHome(name, value) {
29
79
  const home = kitHome();
30
80
  await mkdir(home, { recursive: true, mode: 0o700 });
31
- const temporary = join(home, `${name}.${process.pid}`);
81
+ const temporary = join(home, `${name}.${randomUUID()}`);
32
82
  await writeFile(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600 });
33
83
  await rename(temporary, join(home, name));
34
84
  }
35
- export function readEnrolment() {
36
- return readHome(ENROLMENT);
85
+ export async function readEnrolment() {
86
+ const enrolment = await readHome(ENROLMENT);
87
+ if (enrolment !== null)
88
+ selectRelay(process.env.HOUSE_KIT_RELAY || enrolment.relay);
89
+ return enrolment;
37
90
  }
38
91
  export async function writeEnrolment(enrolment) {
39
92
  await writeHome(ENROLMENT, enrolment);
@@ -42,13 +95,49 @@ export async function writeEnrolment(enrolment) {
42
95
  export function readDisconnected() {
43
96
  return readHome(DISCONNECTED);
44
97
  }
98
+ export function forgetDisconnected() {
99
+ return rm(join(kitHome(), DISCONNECTED), { force: true });
100
+ }
45
101
  export async function forgetEnrolment({ house, environment }) {
46
102
  await writeHome(DISCONNECTED, { house, environment });
47
103
  await rm(join(kitHome(), ENROLMENT), { force: true });
48
104
  }
105
+ export async function forgetRejected(rejected) {
106
+ const held = await readHome(ENROLMENT);
107
+ if (held?.credential !== rejected)
108
+ return;
109
+ await writeHome(DISCONNECTED, { house: held.house, environment: held.environment });
110
+ const enrolment = join(kitHome(), ENROLMENT);
111
+ const taken = `${enrolment}.${process.pid}`;
112
+ try {
113
+ renameSync(enrolment, taken);
114
+ }
115
+ catch (error) {
116
+ if (error.code === 'ENOENT')
117
+ return;
118
+ throw error;
119
+ }
120
+ if (JSON.parse(readFileSync(taken, 'utf8')).credential !== rejected) {
121
+ try {
122
+ linkSync(taken, enrolment);
123
+ }
124
+ catch (error) {
125
+ if (error.code !== 'EEXIST')
126
+ throw error;
127
+ }
128
+ rmSync(join(kitHome(), DISCONNECTED), { force: true });
129
+ }
130
+ rmSync(taken);
131
+ }
49
132
  export function enrolled() {
50
133
  return existsSync(join(kitHome(), ENROLMENT));
51
134
  }
135
+ export function restartAsked() {
136
+ return existsSync(join(kitHome(), RESTART));
137
+ }
138
+ export function forgetRestart() {
139
+ return rm(join(kitHome(), RESTART), { force: true });
140
+ }
52
141
  export function readOwnAgent() {
53
142
  return readHome(OWN_AGENT);
54
143
  }
@@ -0,0 +1,327 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { request, setGlobalProxyFromEnv } from 'node:http';
5
+ import { request as httpsRequest } from 'node:https';
6
+ import { basename, extname, join, resolve } from 'node:path';
7
+ import { Readable } from 'node:stream';
8
+ import { pipeline } from 'node:stream/promises';
9
+ import { downloaded, inspectedFile, storeRefusal, uploaded } from './files.js';
10
+ import { HOUSE_REF } from './git.js';
11
+ import { ownerSocket, readOwnAgent } from './home.js';
12
+ import { callHouse, rpc, UNREACHABLE, Unsettled } from './mcp.js';
13
+ import { refusalOf, retryable } from './refusals.js';
14
+ import { relayed, selectRelay } from './relay.js';
15
+ import { parse } from 'yaml';
16
+ const USAGE = "usage: house <tool> ['<arguments as JSON>']";
17
+ const PUSH_USAGE = 'usage: house push [commit] [--owner]';
18
+ const PUSH = "push [commit]: sends the Local copy's committed changes to House";
19
+ const FETCH_USAGE = 'usage: house fetch';
20
+ const FETCH = `fetch: records House's changes on each Local copy's ${HOUSE_REF}`;
21
+ const DOWNLOAD_USAGE = `usage: house download '{"path":"/rooms/<handle>/<path>","file":"<local file>"}', adding "ref" for a revision`;
22
+ const DOWNLOAD = 'download: writes a binary file of a Room to the local file named by file';
23
+ const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
24
+ const CLOSED = "this conversation's House connection is closed; nothing to do from here";
25
+ const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
26
+ const REVOKED = 'this conversation no longer has House access; nothing to do from here';
27
+ const UNCONNECTED = "this computer's own agent has no House connection; run kit login, or kit chatgpt --key <key> with a script key";
28
+ const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login, or kit chatgpt --key <key> with a script key";
29
+ const UNCONFIRMED = 'with no result; a write may or may not have taken effect, so read before you repeat it';
30
+ const socketPath = process.env.HOUSE_BRIDGE;
31
+ const MEDIA_TYPES = new Map([
32
+ ['avif', 'image/avif'],
33
+ ['csv', 'text/csv'],
34
+ ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
35
+ ['gif', 'image/gif'],
36
+ ['heic', 'image/heic'],
37
+ ['html', 'text/html'],
38
+ ['jpeg', 'image/jpeg'],
39
+ ['jpg', 'image/jpeg'],
40
+ ['json', 'application/json'],
41
+ ['m4a', 'audio/mp4'],
42
+ ['md', 'text/markdown'],
43
+ ['mov', 'video/quicktime'],
44
+ ['mp3', 'audio/mpeg'],
45
+ ['mp4', 'video/mp4'],
46
+ ['ogg', 'audio/ogg'],
47
+ ['pdf', 'application/pdf'],
48
+ ['png', 'image/png'],
49
+ ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
50
+ ['svg', 'image/svg+xml'],
51
+ ['txt', 'text/plain'],
52
+ ['wav', 'audio/wav'],
53
+ ['webm', 'video/webm'],
54
+ ['webp', 'image/webp'],
55
+ ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
56
+ ['zip', 'application/zip'],
57
+ ]);
58
+ function refused(path, status, text, local) {
59
+ const refusal = refusalOf(text);
60
+ if (refusal !== null)
61
+ return refusal.text;
62
+ if (status === 401)
63
+ return REVOKED;
64
+ if (status === 502 && local)
65
+ return text;
66
+ return path === '/' ? unconfirmed(status) : `${path} answered ${status}`;
67
+ }
68
+ function unconfirmed(status) {
69
+ return `House answered ${status} ${UNCONFIRMED}`;
70
+ }
71
+ function bridged(path, body, to = socketPath) {
72
+ return new Promise((resolve, reject) => {
73
+ const sent = request({ socketPath: to, path, method: 'POST', headers: { 'content-type': 'application/json' } }, (answer) => {
74
+ const chunks = [];
75
+ answer.on('data', (chunk) => chunks.push(chunk));
76
+ answer.on('end', () => {
77
+ const text = Buffer.concat(chunks).toString('utf8');
78
+ if (answer.statusCode === 200)
79
+ resolve(text);
80
+ else
81
+ reject(new Error(refused(path, answer.statusCode, text, answer.headers['content-type'] === undefined)));
82
+ });
83
+ });
84
+ sent.on('error', (error) => reject(new Error(error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED)));
85
+ sent.end(JSON.stringify(body));
86
+ });
87
+ }
88
+ async function direct(message) {
89
+ const ownAgent = await readOwnAgent();
90
+ if (ownAgent === null)
91
+ throw new Error(UNCONNECTED);
92
+ selectRelay(process.env.HOUSE_KIT_RELAY || ownAgent.relay);
93
+ setGlobalProxyFromEnv();
94
+ const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
95
+ throw new Unsettled(UNREACHABLE);
96
+ });
97
+ if (answer.status === 200)
98
+ return answer.text;
99
+ if (answer.status === 401)
100
+ throw new Error(DISCONNECTED);
101
+ const refusal = refusalOf(answer.text)?.text ?? unconfirmed(answer.status);
102
+ throw retryable(answer.text) === false ? new Error(refusal) : new Unsettled(refusal);
103
+ }
104
+ async function mcp(method, params) {
105
+ const message = rpc(method, params);
106
+ const answer = JSON.parse(socketPath === undefined ? await direct(message) : await bridged('/', message));
107
+ if (answer.error !== undefined)
108
+ throw new Error(answer.error.message);
109
+ return answer.result;
110
+ }
111
+ async function tools() {
112
+ return (await mcp('tools/list', {})).tools;
113
+ }
114
+ function unreadable(path, error) {
115
+ return new Error(error.code === 'EISDIR'
116
+ ? `${path} is a folder; upload one file at a time`
117
+ : `${path} is not a readable file`);
118
+ }
119
+ async function localFile(path) {
120
+ try {
121
+ return await readFile(path);
122
+ }
123
+ catch (error) {
124
+ throw unreadable(path, error);
125
+ }
126
+ }
127
+ function opened(url, method, headers, body) {
128
+ return new Promise((answered, failed) => {
129
+ const local = socketPath !== undefined;
130
+ const target = local ? null : relayed(url);
131
+ if (!local)
132
+ setGlobalProxyFromEnv();
133
+ const sent = target === null
134
+ ? request({ socketPath, path: url, method, headers }, answered)
135
+ : (target.protocol === 'https:' ? httpsRequest : request)(target, { method, headers }, answered);
136
+ sent.on('error', (error) => failed(new Error(!local ? UNREACHABLE : error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED)));
137
+ if (body instanceof Readable)
138
+ pipeline(body, sent).catch(() => undefined);
139
+ else
140
+ sent.end(body);
141
+ });
142
+ }
143
+ async function textOf(answer) {
144
+ return Buffer.concat(await answer.toArray()).toString('utf8');
145
+ }
146
+ async function sent(url, bytes, operation) {
147
+ const headers = { 'content-type': 'application/octet-stream', 'x-house-byte-operation': operation };
148
+ const answer = await opened(url, 'POST', headers, bytes);
149
+ const text = await textOf(answer);
150
+ if (answer.statusCode === 200)
151
+ return text;
152
+ throw new Error(refusalOf(text)?.text ?? storeRefusal('upload', answer.statusCode).message);
153
+ }
154
+ async function sentPart(url, file, start, end) {
155
+ const answer = await opened(url, 'PUT', { 'content-length': String(end - start) }, end === start ? undefined : createReadStream(file, { start, end: end - 1 }));
156
+ await answer.toArray();
157
+ if (answer.statusCode !== 200)
158
+ throw storeRefusal('upload', answer.statusCode);
159
+ }
160
+ async function download(args) {
161
+ const { flags, positionals: [argument] } = accepted(args, ['--help'], 1, DOWNLOAD_USAGE);
162
+ if (flags.has('--help'))
163
+ return DOWNLOAD_USAGE;
164
+ const { file, ...selected } = argumentsOf(argument);
165
+ if (typeof file !== 'string' || file === '')
166
+ throw new Error('download needs "file", the local file to write');
167
+ const written = resolve(file);
168
+ await downloaded(async () => {
169
+ const file = inspectedFile(await called('inspect', selected));
170
+ if (file === null)
171
+ throw new Error(`${String(selected.path)} holds no binary file; shell reads its text`);
172
+ return file;
173
+ }, async (url) => {
174
+ const answer = await opened(url, 'GET', {});
175
+ return { status: answer.statusCode, body: answer };
176
+ }, written, String(selected.path));
177
+ return written;
178
+ }
179
+ async function described(file) {
180
+ const digest = createHash('sha256');
181
+ let bytes = 0;
182
+ try {
183
+ for await (const chunk of createReadStream(file)) {
184
+ digest.update(chunk);
185
+ bytes += chunk.length;
186
+ }
187
+ }
188
+ catch (error) {
189
+ throw unreadable(file, error);
190
+ }
191
+ const mediaType = MEDIA_TYPES.get(extname(file).slice(1).toLowerCase());
192
+ return { bytes, sha256: digest.digest('hex'), ...(mediaType === undefined ? {} : { media_type: mediaType }) };
193
+ }
194
+ async function finished(upload, room) {
195
+ const text = await called('upload', { upload, room_ref: room });
196
+ const answer = parse(text);
197
+ return answer !== null && ('upload' in answer || 'checking' in answer) ? answer : { text };
198
+ }
199
+ async function upload({ file, ...destination }) {
200
+ if (typeof file !== 'string' || file === '')
201
+ throw new Error('upload needs "file", a local file');
202
+ const description = await described(file);
203
+ const answer = await called('upload', { ...destination, ...description });
204
+ const declared = parse(answer);
205
+ if (declared?.upload === undefined)
206
+ return answer;
207
+ const accepted = await uploaded(declared.upload, {
208
+ bytes: description.bytes,
209
+ send: (url, start, end) => sentPart(url, file, start, end),
210
+ finish: (id) => finished(id, destination.room_ref),
211
+ });
212
+ return accepted.text;
213
+ }
214
+ async function appendRecord(args) {
215
+ const held = new Map();
216
+ const attachments = Array.isArray(args.attachments)
217
+ ? await Promise.all(args.attachments.map(async (attachment) => {
218
+ if (typeof attachment !== 'string')
219
+ return attachment;
220
+ const description = await described(attachment);
221
+ held.set(description.sha256, attachment);
222
+ return { name: basename(attachment), ...description };
223
+ }))
224
+ : args.attachments;
225
+ const record = { ...args, attachments };
226
+ for (;;) {
227
+ const answer = await called('append_record', record);
228
+ const { upload } = parse(answer);
229
+ if (upload === undefined)
230
+ return answer;
231
+ for (const grant of upload)
232
+ await sent(grant.url, await localFile(held.get(grant.sha256)), grant.operation);
233
+ }
234
+ }
235
+ function unexpected(argument, usage) {
236
+ return new Error(`unexpected argument ${argument}; ${usage}`);
237
+ }
238
+ function accepted(args, flags, positionals, usage) {
239
+ const given = { flags: new Set(), positionals: [] };
240
+ for (const arg of args) {
241
+ if (flags.includes(arg))
242
+ given.flags.add(arg);
243
+ else if (!arg.startsWith('-') && given.positionals.length < positionals)
244
+ given.positionals.push(arg);
245
+ else
246
+ throw unexpected(arg, usage);
247
+ }
248
+ return given;
249
+ }
250
+ async function push(args) {
251
+ const { flags, positionals: [commit = 'HEAD'] } = accepted(args, ['--help', '--owner'], 1, PUSH_USAGE);
252
+ if (flags.has('--help'))
253
+ return PUSH_USAGE;
254
+ const owner = flags.has('--owner');
255
+ if (owner && socketPath !== undefined)
256
+ throw new Error('--owner is not for Agent conversations; run house push without it');
257
+ if (!owner && socketPath === undefined)
258
+ throw new Error('outside an Agent conversation, house push needs --owner');
259
+ const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, owner ? ownerSocket() : socketPath));
260
+ if (pushed.refused)
261
+ throw new Error(pushed.text);
262
+ return pushed.text;
263
+ }
264
+ async function fetched(args) {
265
+ if (accepted(args, ['--help'], 0, FETCH_USAGE).flags.has('--help'))
266
+ return FETCH_USAGE;
267
+ const answer = JSON.parse(await bridged('/git/fetch', {}, socketPath ?? ownerSocket()));
268
+ if (answer.refused)
269
+ throw new Error(answer.text);
270
+ return answer.text;
271
+ }
272
+ function argumentsOf(argument) {
273
+ if (argument === undefined)
274
+ return {};
275
+ let parsed;
276
+ try {
277
+ parsed = JSON.parse(argument);
278
+ }
279
+ catch {
280
+ throw new Error(ARGUMENTS);
281
+ }
282
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
283
+ throw new Error(ARGUMENTS);
284
+ return parsed;
285
+ }
286
+ async function house(args) {
287
+ const { flags, positionals: [verb, argument] } = accepted(args, ['--help'], 2, USAGE);
288
+ if (verb === 'help' && argument !== undefined)
289
+ throw unexpected(argument, USAGE);
290
+ if (flags.has('--help') && argument !== undefined)
291
+ throw unexpected('--help', USAGE);
292
+ if (verb === undefined || verb === 'help') {
293
+ return [USAGE, 'help', PUSH, FETCH, DOWNLOAD, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
294
+ }
295
+ if (flags.has('--help')) {
296
+ const tool = (await tools()).find((listed) => listed.name === verb);
297
+ if (tool === undefined)
298
+ throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
299
+ return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
300
+ }
301
+ const parsed = argumentsOf(argument);
302
+ return verb === 'upload' ? upload(parsed) : verb === 'append_record' ? appendRecord(parsed) : called(verb, parsed);
303
+ }
304
+ async function called(name, args) {
305
+ const result = await mcp('tools/call', { name, arguments: args });
306
+ const text = result.content.map((content) => content.text).join('\n');
307
+ if (result.isError === true)
308
+ throw new Error(text.replace(/\n+$/, ''));
309
+ return text;
310
+ }
311
+ const argv = process.argv.slice(2);
312
+ const named = argv.findIndex((arg) => !arg.startsWith('-'));
313
+ const rest = argv.filter((_arg, index) => index !== named);
314
+ (argv[named] === 'push'
315
+ ? push(rest)
316
+ : argv[named] === 'fetch'
317
+ ? fetched(rest)
318
+ : argv[named] === 'download'
319
+ ? download(rest)
320
+ : house(argv)).then((text) => {
321
+ process.stdout.write(`${text}\n`);
322
+ if (argv[0] === 'shell')
323
+ process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
324
+ }, (error) => {
325
+ process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
326
+ process.exitCode = 1;
327
+ });
@@ -1,162 +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 { kitHome, readOwnAgent } from './home.js';
7
- import { callHouse, rpc, UNREACHABLE } from './mcp.js';
8
- import { refusalOf } from './refusals.js';
9
- const USAGE = "usage: house <tool> ['<arguments as JSON>']";
10
- const PUSH_USAGE = 'usage: house push [commit] [--owner]';
11
- const PUSH = "push [commit]: sends the Local copy's committed changes to House";
12
- const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
13
- const CLOSED = "this conversation's House connection is closed; nothing to do from here";
14
- const REVOKED = 'this conversation no longer has House access; nothing to do from here';
15
- const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
16
- const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login";
17
- const socketPath = process.env.HOUSE_BRIDGE;
18
- function refused(path, status, text) {
19
- const refusal = refusalOf(text);
20
- if (refusal !== null)
21
- return refusal.text;
22
- if (status === 401)
23
- return REVOKED;
24
- if (URL.canParse(path))
25
- return `the upload answered ${status}; upload the file again`;
26
- if (status === 502 && /^[A-Za-z]/.test(text))
27
- return text;
28
- return `${path} answered ${status}`;
29
- }
30
- function bridged(path, body, headers = { 'content-type': 'application/json' }, to = socketPath) {
31
- return new Promise((resolve, reject) => {
32
- const sent = request({ socketPath: to, path, method: 'POST', headers }, (answer) => {
33
- let text = '';
34
- answer.setEncoding('utf8');
35
- answer.on('data', (chunk) => {
36
- text += chunk;
37
- });
38
- answer.on('end', () => {
39
- if (answer.statusCode === 200)
40
- resolve(text);
41
- else
42
- reject(new Error(refused(path, answer.statusCode, text)));
43
- });
44
- });
45
- sent.on('error', () => reject(new Error(CLOSED)));
46
- sent.end(body instanceof Buffer ? body : JSON.stringify(body));
47
- });
48
- }
49
- async function direct(message) {
50
- const ownAgent = await readOwnAgent();
51
- if (ownAgent === null)
52
- throw new Error(UNCONNECTED);
53
- setGlobalProxyFromEnv();
54
- const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
55
- throw new Error(UNREACHABLE);
56
- });
57
- if (answer.status === 200)
58
- return answer.text;
59
- throw new Error(answer.status === 401 ? DISCONNECTED : (refusalOf(answer.text)?.text ?? `House answered ${answer.status}`));
60
- }
61
- async function mcp(method, params) {
62
- const message = rpc(method, params);
63
- const answer = JSON.parse(socketPath === undefined ? await direct(message) : await bridged('/', message));
64
- if (answer.error !== undefined)
65
- throw new Error(answer.error.message);
66
- return answer.result;
67
- }
68
- async function tools() {
69
- return (await mcp('tools/list', {})).tools;
70
- }
71
- async function localFile(path) {
72
- try {
73
- return await readFile(path);
74
- }
75
- catch (error) {
76
- throw new Error(error.code === 'EISDIR'
77
- ? `${path} is a folder; upload one file at a time`
78
- : `${path} is not a readable file`);
79
- }
80
- }
81
- async function upload(path, roomRef, missing) {
82
- if (typeof path !== 'string' || path === '')
83
- throw new Error(missing);
84
- const bytes = await localFile(path);
85
- const declared = JSON.parse(await bridged('/kit/attachments/upload', {
86
- ...(roomRef === undefined ? {} : { room_ref: roomRef }),
87
- name: basename(path),
88
- bytes: bytes.length,
89
- sha256: createHash('sha256').update(bytes).digest('hex'),
90
- }));
91
- if (declared.upload === undefined)
92
- return declared.attachment;
93
- const saved = JSON.parse(await bridged(declared.upload.url, bytes, {
94
- 'content-type': 'application/octet-stream',
95
- 'x-house-byte-operation': declared.upload.operation,
96
- }));
97
- if (saved.upload_failure !== undefined)
98
- throw new Error(`${path} was not saved: ${saved.upload_failure}; call again later`);
99
- return saved.attachment;
100
- }
101
- async function push(args) {
102
- if (args.includes('--help'))
103
- return PUSH_USAGE;
104
- const owner = args.includes('--owner');
105
- const commit = args.find((arg) => arg !== '--owner') ?? 'HEAD';
106
- if (owner && socketPath !== undefined)
107
- throw new Error('--owner is not for Agent conversations; run house push without it');
108
- if (!owner && socketPath === undefined)
109
- throw new Error('outside an Agent conversation, house push needs --owner');
110
- const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, undefined, owner ? join(kitHome(), 'owner.sock') : socketPath));
111
- if (pushed.refused)
112
- throw new Error(pushed.text);
113
- return pushed.text;
114
- }
115
- function argumentsOf(argument) {
116
- if (argument === undefined)
117
- return {};
118
- let parsed;
119
- try {
120
- parsed = JSON.parse(argument);
121
- }
122
- catch {
123
- throw new Error(ARGUMENTS);
124
- }
125
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
126
- throw new Error(ARGUMENTS);
127
- return parsed;
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;
128
6
  }
129
- async function house([verb, argument]) {
130
- if (verb === undefined || verb === '--help' || verb === 'help') {
131
- return [USAGE, 'help', PUSH, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
132
- }
133
- if (argument === '--help') {
134
- const tool = (await tools()).find((listed) => listed.name === verb);
135
- if (tool === undefined)
136
- throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
137
- return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
138
- }
139
- const args = argumentsOf(argument);
140
- if (socketPath !== undefined && verb === 'upload_attachment') {
141
- return JSON.stringify({ attachment: await upload(args.path, args.room_ref, 'upload_attachment needs "path", a local file') });
142
- }
143
- if (socketPath !== undefined && verb === 'append_record' && Array.isArray(args.attachments)) {
144
- const attachments = [];
145
- for (const path of args.attachments) {
146
- attachments.push(await upload(path, args.room_ref, 'each attachments entry is the path of a local file'));
147
- }
148
- args.attachments = attachments;
149
- }
150
- const result = await mcp('tools/call', { name: verb, arguments: args });
151
- const text = result.content.map((content) => content.text).join('\n');
152
- if (result.isError === true)
153
- throw new Error(text.replace(/\n+$/, ''));
154
- return text;
7
+ else {
8
+ await import('./house-cli.js');
155
9
  }
156
- const argv = process.argv.slice(2);
157
- (argv[0] === 'push' ? push(argv.slice(1)) : house(argv)).then((text) => {
158
- process.stdout.write(`${text}\n`);
159
- }, (error) => {
160
- process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
161
- process.exitCode = 1;
162
- });
10
+ export {};