@agentshouse/kit 0.2.1-cf110d15f69c8 → 0.2.1-cf268dff1869b

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