@agentshouse/kit 0.2.1-alpha.8 → 0.2.1-c05cd91c26b1d

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 (150) hide show
  1. package/README.md +46 -21
  2. package/dist/abort.js +9 -0
  3. package/dist/acp.js +48 -85
  4. package/dist/agents.js +312 -53
  5. package/dist/api.js +40 -4
  6. package/dist/app-git.js +48 -0
  7. package/dist/bootstrap.json +10 -14
  8. package/dist/bridge.js +92 -77
  9. package/dist/chatgpt.js +32 -0
  10. package/dist/clis-main.js +23 -0
  11. package/dist/clis.js +213 -71
  12. package/dist/codex-main.js +58 -0
  13. package/dist/configure-main.js +6 -0
  14. package/dist/conversations.js +429 -232
  15. package/dist/copies.js +233 -171
  16. package/dist/end.js +23 -0
  17. package/dist/enrol-main.js +7 -1
  18. package/dist/events.js +525 -0
  19. package/dist/files.js +24 -3
  20. package/dist/git-main.js +2 -2
  21. package/dist/git.js +15 -9
  22. package/dist/home.js +141 -10
  23. package/dist/house-cli.js +291 -0
  24. package/dist/house-main.js +5 -102
  25. package/dist/inputs.js +37 -0
  26. package/dist/instructions.js +10 -31
  27. package/dist/kit-cli.js +68 -0
  28. package/dist/kit-main.js +8 -16
  29. package/dist/login.js +129 -94
  30. package/dist/logout.js +19 -0
  31. package/dist/mcp.js +39 -0
  32. package/dist/operation.js +7 -4
  33. package/dist/parts.js +82 -0
  34. package/dist/placement.js +30 -0
  35. package/dist/refusals.js +53 -0
  36. package/dist/relay.js +20 -0
  37. package/dist/resident.js +123 -40
  38. package/dist/scope.js +203 -0
  39. package/dist/secret-input.js +7 -2
  40. package/dist/service-main.js +9 -0
  41. package/dist/service.js +33 -0
  42. package/dist/shell.js +3 -0
  43. package/dist/sign-in.js +47 -28
  44. package/dist/skills.js +147 -0
  45. package/dist/stream.js +89 -13
  46. package/dist/transcription.js +170 -0
  47. package/dist/update.js +138 -0
  48. package/dist/wire.js +6 -0
  49. package/dist/work.js +346 -0
  50. package/how-we-work.md +33 -0
  51. package/package.json +8 -8
  52. package/skills/ask-matt/LICENSE +21 -0
  53. package/skills/ask-matt/PHASE-BOUNDARIES.md +55 -0
  54. package/skills/ask-matt/SKILL.md +97 -0
  55. package/skills/ask-matt/agents/openai.yaml +5 -0
  56. package/skills/code-review/LICENSE +21 -0
  57. package/skills/code-review/SKILL.md +89 -0
  58. package/skills/code-review/agents/openai.yaml +3 -0
  59. package/skills/codebase-design/DEEPENING.md +37 -0
  60. package/skills/codebase-design/DESIGN-IT-TWICE.md +44 -0
  61. package/skills/codebase-design/LICENSE +21 -0
  62. package/skills/codebase-design/SKILL.md +114 -0
  63. package/skills/codebase-design/agents/openai.yaml +3 -0
  64. package/skills/diagnosing-bugs/LICENSE +21 -0
  65. package/skills/diagnosing-bugs/SKILL.md +138 -0
  66. package/skills/diagnosing-bugs/agents/openai.yaml +3 -0
  67. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +44 -0
  68. package/skills/domain-modeling/ADR-FORMAT.md +47 -0
  69. package/skills/domain-modeling/GLOSSARY-FORMAT.md +60 -0
  70. package/skills/domain-modeling/LICENSE +21 -0
  71. package/skills/domain-modeling/SKILL.md +74 -0
  72. package/skills/domain-modeling/agents/openai.yaml +3 -0
  73. package/skills/grill-me/LICENSE +21 -0
  74. package/skills/grill-me/SKILL.md +7 -0
  75. package/skills/grill-me/agents/openai.yaml +5 -0
  76. package/skills/grill-with-docs/LICENSE +21 -0
  77. package/skills/grill-with-docs/SKILL.md +7 -0
  78. package/skills/grill-with-docs/agents/openai.yaml +5 -0
  79. package/skills/grilling/LICENSE +21 -0
  80. package/skills/grilling/SKILL.md +30 -0
  81. package/skills/grilling/agents/openai.yaml +3 -0
  82. package/skills/handoff/LICENSE +21 -0
  83. package/skills/handoff/SKILL.md +16 -0
  84. package/skills/handoff/agents/openai.yaml +5 -0
  85. package/skills/implement/LICENSE +21 -0
  86. package/skills/implement/SKILL.md +17 -0
  87. package/skills/implement/agents/openai.yaml +5 -0
  88. package/skills/implement-spec/LICENSE +21 -0
  89. package/skills/implement-spec/SKILL.md +40 -0
  90. package/skills/implement-spec/agents/openai.yaml +5 -0
  91. package/skills/improve-codebase-architecture/HTML-REPORT.md +123 -0
  92. package/skills/improve-codebase-architecture/LICENSE +21 -0
  93. package/skills/improve-codebase-architecture/SKILL.md +71 -0
  94. package/skills/improve-codebase-architecture/agents/openai.yaml +5 -0
  95. package/skills/pr/CREDITS.md +3 -0
  96. package/skills/pr/LICENSE +21 -0
  97. package/skills/pr/SKILL.md +170 -0
  98. package/skills/pr/agents/openai.yaml +3 -0
  99. package/skills/prototype/LICENSE +21 -0
  100. package/skills/prototype/LOGIC.md +67 -0
  101. package/skills/prototype/SKILL.md +26 -0
  102. package/skills/prototype/UI.md +112 -0
  103. package/skills/prototype/agents/openai.yaml +3 -0
  104. package/skills/research/LICENSE +21 -0
  105. package/skills/research/SKILL.md +12 -0
  106. package/skills/research/agents/openai.yaml +3 -0
  107. package/skills/retro/LICENSE +21 -0
  108. package/skills/retro/SKILL.md +44 -0
  109. package/skills/retro/agents/openai.yaml +5 -0
  110. package/skills/tdd/LICENSE +21 -0
  111. package/skills/tdd/SKILL.md +38 -0
  112. package/skills/tdd/agents/openai.yaml +3 -0
  113. package/skills/tdd/mocking.md +59 -0
  114. package/skills/tdd/tests.md +77 -0
  115. package/skills/teach/GLOSSARY-FORMAT.md +35 -0
  116. package/skills/teach/LEARNING-RECORD-FORMAT.md +46 -0
  117. package/skills/teach/LICENSE +21 -0
  118. package/skills/teach/MISSION-FORMAT.md +31 -0
  119. package/skills/teach/RESOURCES-FORMAT.md +32 -0
  120. package/skills/teach/SKILL.md +140 -0
  121. package/skills/teach/agents/openai.yaml +5 -0
  122. package/skills/to-questionnaire/LICENSE +21 -0
  123. package/skills/to-questionnaire/SKILL.md +54 -0
  124. package/skills/to-questionnaire/agents/openai.yaml +5 -0
  125. package/skills/to-spec/LICENSE +21 -0
  126. package/skills/to-spec/SKILL.md +75 -0
  127. package/skills/to-spec/agents/openai.yaml +5 -0
  128. package/skills/to-tickets/LICENSE +21 -0
  129. package/skills/to-tickets/SKILL.md +105 -0
  130. package/skills/to-tickets/agents/openai.yaml +5 -0
  131. package/skills/triage/AGENT-BRIEF.md +207 -0
  132. package/skills/triage/LICENSE +21 -0
  133. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  134. package/skills/triage/SKILL.md +112 -0
  135. package/skills/triage/agents/openai.yaml +5 -0
  136. package/skills/wait-what/LICENSE +21 -0
  137. package/skills/wait-what/SKILL.md +7 -0
  138. package/skills/wait-what/agents/openai.yaml +5 -0
  139. package/skills/wayfinder/LICENSE +21 -0
  140. package/skills/wayfinder/SKILL.md +128 -0
  141. package/skills/wayfinder/agents/openai.yaml +5 -0
  142. package/skills/wizard/LICENSE +21 -0
  143. package/skills/wizard/SKILL.md +44 -0
  144. package/skills/wizard/agents/openai.yaml +3 -0
  145. package/skills/wizard/template.sh +223 -0
  146. package/skills/writing-for-agents/LICENSE +21 -0
  147. package/skills/writing-for-agents/SKILL-MECHANICS.md +22 -0
  148. package/skills/writing-for-agents/SKILL.md +81 -0
  149. package/skills/writing-for-agents/agents/openai.yaml +3 -0
  150. package/dist/blocks.js +0 -51
package/dist/home.js CHANGED
@@ -1,13 +1,73 @@
1
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
- import { homedir } from 'node:os';
3
- import { join } from 'node:path';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { accessSync, chmodSync, constants, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync } from 'node:fs';
3
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { homedir, tmpdir } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ import { selectRelay } from './relay.js';
4
7
  const ENROLMENT = 'credential.json';
8
+ const DISCONNECTED = 'disconnected.json';
9
+ const CONFIGURATION = 'kit.json';
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
+ }
5
47
  export function kitHome() {
6
- return process.env.HOUSE_KIT_HOME ?? join(homedir(), '.house-kit');
48
+ return process.env.HOUSE_KIT_HOME || (defaulted ??= defaultHome());
7
49
  }
8
- export async function readEnrolment() {
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');
61
+ }
62
+ export function workspaceRoot() {
63
+ return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
64
+ }
65
+ export function agentBase() {
66
+ return join(workspaceRoot(), 'agents');
67
+ }
68
+ export async function readHome(name) {
9
69
  try {
10
- return JSON.parse(await readFile(join(kitHome(), ENROLMENT), 'utf8'));
70
+ return JSON.parse(await readFile(join(kitHome(), name), 'utf8'));
11
71
  }
12
72
  catch (error) {
13
73
  if (error.code === 'ENOENT')
@@ -15,10 +75,81 @@ export async function readEnrolment() {
15
75
  throw error;
16
76
  }
17
77
  }
18
- export async function writeEnrolment(enrolment) {
78
+ export async function writeHome(name, value) {
19
79
  const home = kitHome();
20
80
  await mkdir(home, { recursive: true, mode: 0o700 });
21
- const temporary = join(home, `${ENROLMENT}.${process.pid}`);
22
- await writeFile(temporary, `${JSON.stringify(enrolment)}\n`, { mode: 0o600 });
23
- await rename(temporary, join(home, ENROLMENT));
81
+ const temporary = join(home, `${name}.${randomUUID()}`);
82
+ await writeFile(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600 });
83
+ await rename(temporary, join(home, name));
84
+ }
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;
90
+ }
91
+ export async function writeEnrolment(enrolment) {
92
+ await writeHome(ENROLMENT, enrolment);
93
+ await rm(join(kitHome(), DISCONNECTED), { force: true });
94
+ }
95
+ export function readDisconnected() {
96
+ return readHome(DISCONNECTED);
97
+ }
98
+ export function forgetDisconnected() {
99
+ return rm(join(kitHome(), DISCONNECTED), { force: true });
100
+ }
101
+ export async function forgetEnrolment({ house, environment }) {
102
+ await writeHome(DISCONNECTED, { house, environment });
103
+ await rm(join(kitHome(), ENROLMENT), { force: true });
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
+ }
132
+ export function enrolled() {
133
+ return existsSync(join(kitHome(), ENROLMENT));
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
+ }
141
+ export function readOwnAgent() {
142
+ return readHome(OWN_AGENT);
143
+ }
144
+ export function writeOwnAgent(ownAgent) {
145
+ return writeHome(OWN_AGENT, ownAgent);
146
+ }
147
+ export function forgetOwnAgent() {
148
+ return rm(join(kitHome(), OWN_AGENT), { force: true });
149
+ }
150
+ export async function readConfiguration() {
151
+ return { skills: (await readHome(CONFIGURATION))?.skills !== false };
152
+ }
153
+ export function writeConfiguration(configuration) {
154
+ return writeHome(CONFIGURATION, configuration);
24
155
  }
@@ -0,0 +1,291 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { request, setGlobalProxyFromEnv } from 'node:http';
4
+ import { basename, dirname, extname, join, resolve } from 'node:path';
5
+ import { verified } from './files.js';
6
+ import { HOUSE_REF } from './git.js';
7
+ import { ownerSocket, readOwnAgent } from './home.js';
8
+ import { callHouse, rpc, UNREACHABLE } from './mcp.js';
9
+ import { refusalOf } from './refusals.js';
10
+ import { relayed, selectRelay } 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 DOWNLOAD_USAGE = `usage: house download '{"path":"/rooms/<handle>/<path>","file":"<local file>"}', adding "ref" for a revision`;
18
+ const DOWNLOAD = 'download: writes a binary file of a Room to the local file named by file';
19
+ const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
20
+ const CLOSED = "this conversation's House connection is closed; nothing to do from here";
21
+ const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
22
+ const REVOKED = 'this conversation no longer has House access; nothing to do from here';
23
+ const UNCONNECTED = "this computer's own agent has no House connection; run kit login, or kit chatgpt --key <key> with a script key";
24
+ const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login, or kit chatgpt --key <key> with a script key";
25
+ const UNCONFIRMED = 'with no result; a write may or may not have taken effect, so read before you repeat it';
26
+ const socketPath = process.env.HOUSE_BRIDGE;
27
+ const MEDIA_TYPES = new Map([
28
+ ['avif', 'image/avif'],
29
+ ['csv', 'text/csv'],
30
+ ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
31
+ ['gif', 'image/gif'],
32
+ ['heic', 'image/heic'],
33
+ ['html', 'text/html'],
34
+ ['jpeg', 'image/jpeg'],
35
+ ['jpg', 'image/jpeg'],
36
+ ['json', 'application/json'],
37
+ ['m4a', 'audio/mp4'],
38
+ ['md', 'text/markdown'],
39
+ ['mov', 'video/quicktime'],
40
+ ['mp3', 'audio/mpeg'],
41
+ ['mp4', 'video/mp4'],
42
+ ['ogg', 'audio/ogg'],
43
+ ['pdf', 'application/pdf'],
44
+ ['png', 'image/png'],
45
+ ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
46
+ ['svg', 'image/svg+xml'],
47
+ ['txt', 'text/plain'],
48
+ ['wav', 'audio/wav'],
49
+ ['webm', 'video/webm'],
50
+ ['webp', 'image/webp'],
51
+ ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
52
+ ['zip', 'application/zip'],
53
+ ]);
54
+ function refused(path, method, status, text, local) {
55
+ const refusal = refusalOf(text);
56
+ if (refusal !== null)
57
+ return refusal.text;
58
+ if (status === 401)
59
+ return REVOKED;
60
+ const act = method === 'GET' ? 'download' : 'upload';
61
+ if (URL.canParse(path))
62
+ return `the ${act} answered ${status}; ${act} the file again`;
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 exchanged(path, method, body, headers = { 'content-type': 'application/json' }, to = socketPath) {
71
+ return new Promise((resolve, reject) => {
72
+ const sent = request({ socketPath: to, path, method, headers }, (answer) => {
73
+ const chunks = [];
74
+ answer.on('data', (chunk) => chunks.push(chunk));
75
+ answer.on('end', () => {
76
+ const bytes = Buffer.concat(chunks);
77
+ if (answer.statusCode === 200)
78
+ resolve(bytes);
79
+ else
80
+ reject(new Error(refused(path, method, answer.statusCode, bytes.toString('utf8'), 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(body === undefined ? undefined : body instanceof Buffer ? body : JSON.stringify(body));
85
+ });
86
+ }
87
+ async function bridged(path, body, headers, to = socketPath) {
88
+ return (await exchanged(path, 'POST', body, headers, to)).toString('utf8');
89
+ }
90
+ async function direct(message) {
91
+ const ownAgent = await readOwnAgent();
92
+ if (ownAgent === null)
93
+ throw new Error(UNCONNECTED);
94
+ selectRelay(process.env.HOUSE_KIT_RELAY || ownAgent.relay);
95
+ setGlobalProxyFromEnv();
96
+ const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
97
+ throw new Error(UNREACHABLE);
98
+ });
99
+ if (answer.status === 200)
100
+ return answer.text;
101
+ throw new Error(answer.status === 401 ? DISCONNECTED : (refusalOf(answer.text)?.text ?? unconfirmed(answer.status)));
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
+ async function localFile(path) {
114
+ try {
115
+ return await readFile(path);
116
+ }
117
+ catch (error) {
118
+ throw new Error(error.code === 'EISDIR'
119
+ ? `${path} is a folder; upload one file at a time`
120
+ : `${path} is not a readable file`);
121
+ }
122
+ }
123
+ async function transferred(url, method, bytes, headers) {
124
+ if (socketPath !== undefined)
125
+ return exchanged(url, method, bytes, headers);
126
+ setGlobalProxyFromEnv();
127
+ const answer = await fetch(relayed(url), { method, ...(headers === undefined ? {} : { headers }), ...(bytes === undefined ? {} : { body: bytes }) }).catch(() => {
128
+ throw new Error(UNREACHABLE);
129
+ });
130
+ const received = Buffer.from(await answer.arrayBuffer());
131
+ if (answer.status === 200)
132
+ return received;
133
+ throw new Error(refused(url, method, answer.status, received.toString('utf8'), false));
134
+ }
135
+ async function sent(url, bytes, operation) {
136
+ const headers = { 'content-type': 'application/octet-stream', 'x-house-byte-operation': operation };
137
+ return (await transferred(url, 'POST', bytes, headers)).toString('utf8');
138
+ }
139
+ async function download(args) {
140
+ const { flags, positionals: [argument] } = accepted(args, ['--help'], 1, DOWNLOAD_USAGE);
141
+ if (flags.has('--help'))
142
+ return DOWNLOAD_USAGE;
143
+ const { file, ...selected } = argumentsOf(argument);
144
+ if (typeof file !== 'string' || file === '')
145
+ throw new Error('download needs "file", the local file to write');
146
+ const inspected = parse(await called('inspect', selected));
147
+ if (typeof inspected?.download !== 'string')
148
+ throw new Error(`${String(selected.path)} holds no binary file; shell reads its text`);
149
+ const bytes = verified(await transferred(inspected.download, 'GET'), String(inspected.sha256), String(selected.path));
150
+ const written = resolve(file);
151
+ await mkdir(dirname(written), { recursive: true });
152
+ await writeFile(written, bytes);
153
+ return written;
154
+ }
155
+ async function described(file) {
156
+ const bytes = await localFile(file);
157
+ const mediaType = MEDIA_TYPES.get(extname(file).slice(1).toLowerCase());
158
+ return {
159
+ bytes,
160
+ description: {
161
+ bytes: bytes.length,
162
+ sha256: createHash('sha256').update(bytes).digest('hex'),
163
+ ...(mediaType === undefined ? {} : { media_type: mediaType }),
164
+ },
165
+ };
166
+ }
167
+ async function upload({ file, ...destination }) {
168
+ if (typeof file !== 'string' || file === '')
169
+ throw new Error('upload needs "file", a local file');
170
+ const { bytes, description } = await described(file);
171
+ const answer = await called('upload', { ...destination, ...description });
172
+ const declared = parse(answer);
173
+ if (declared.upload === undefined)
174
+ return answer;
175
+ const written = JSON.parse(await sent(declared.upload.url, bytes, declared.upload.operation));
176
+ return stringify(written, { lineWidth: 0 }).trimEnd();
177
+ }
178
+ async function appendRecord(args) {
179
+ const held = new Map();
180
+ const attachments = Array.isArray(args.attachments)
181
+ ? await Promise.all(args.attachments.map(async (attachment) => {
182
+ if (typeof attachment !== 'string')
183
+ return attachment;
184
+ const { bytes, description } = await described(attachment);
185
+ held.set(description.sha256, bytes);
186
+ return { name: basename(attachment), ...description };
187
+ }))
188
+ : args.attachments;
189
+ const record = { ...args, attachments };
190
+ for (;;) {
191
+ const answer = await called('append_record', record);
192
+ const { upload } = parse(answer);
193
+ if (upload === undefined)
194
+ return answer;
195
+ for (const grant of upload)
196
+ await sent(grant.url, held.get(grant.sha256), grant.operation);
197
+ }
198
+ }
199
+ function unexpected(argument, usage) {
200
+ return new Error(`unexpected argument ${argument}; ${usage}`);
201
+ }
202
+ function accepted(args, flags, positionals, usage) {
203
+ const given = { flags: new Set(), positionals: [] };
204
+ for (const arg of args) {
205
+ if (flags.includes(arg))
206
+ given.flags.add(arg);
207
+ else if (!arg.startsWith('-') && given.positionals.length < positionals)
208
+ given.positionals.push(arg);
209
+ else
210
+ throw unexpected(arg, usage);
211
+ }
212
+ return given;
213
+ }
214
+ async function push(args) {
215
+ const { flags, positionals: [commit = 'HEAD'] } = accepted(args, ['--help', '--owner'], 1, PUSH_USAGE);
216
+ if (flags.has('--help'))
217
+ return PUSH_USAGE;
218
+ const owner = flags.has('--owner');
219
+ if (owner && socketPath !== undefined)
220
+ throw new Error('--owner is not for Agent conversations; run house push without it');
221
+ if (!owner && socketPath === undefined)
222
+ throw new Error('outside an Agent conversation, house push needs --owner');
223
+ const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, undefined, owner ? ownerSocket() : socketPath));
224
+ if (pushed.refused)
225
+ throw new Error(pushed.text);
226
+ return pushed.text;
227
+ }
228
+ async function fetched(args) {
229
+ if (accepted(args, ['--help'], 0, FETCH_USAGE).flags.has('--help'))
230
+ return FETCH_USAGE;
231
+ const answer = JSON.parse(await bridged('/git/fetch', {}, undefined, socketPath ?? ownerSocket()));
232
+ if (answer.refused)
233
+ throw new Error(answer.text);
234
+ return answer.text;
235
+ }
236
+ function argumentsOf(argument) {
237
+ if (argument === undefined)
238
+ return {};
239
+ let parsed;
240
+ try {
241
+ parsed = JSON.parse(argument);
242
+ }
243
+ catch {
244
+ throw new Error(ARGUMENTS);
245
+ }
246
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
247
+ throw new Error(ARGUMENTS);
248
+ return parsed;
249
+ }
250
+ async function house(args) {
251
+ const { flags, positionals: [verb, argument] } = accepted(args, ['--help'], 2, USAGE);
252
+ if (verb === 'help' && argument !== undefined)
253
+ throw unexpected(argument, USAGE);
254
+ if (flags.has('--help') && argument !== undefined)
255
+ throw unexpected('--help', USAGE);
256
+ if (verb === undefined || verb === 'help') {
257
+ return [USAGE, 'help', PUSH, FETCH, DOWNLOAD, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
258
+ }
259
+ if (flags.has('--help')) {
260
+ const tool = (await tools()).find((listed) => listed.name === verb);
261
+ if (tool === undefined)
262
+ throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
263
+ return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
264
+ }
265
+ const parsed = argumentsOf(argument);
266
+ return verb === 'upload' ? upload(parsed) : verb === 'append_record' ? appendRecord(parsed) : called(verb, parsed);
267
+ }
268
+ async function called(name, args) {
269
+ const result = await mcp('tools/call', { name, arguments: args });
270
+ const text = result.content.map((content) => content.text).join('\n');
271
+ if (result.isError === true)
272
+ throw new Error(text.replace(/\n+$/, ''));
273
+ return text;
274
+ }
275
+ const argv = process.argv.slice(2);
276
+ const named = argv.findIndex((arg) => !arg.startsWith('-'));
277
+ const rest = argv.filter((_arg, index) => index !== named);
278
+ (argv[named] === 'push'
279
+ ? push(rest)
280
+ : argv[named] === 'fetch'
281
+ ? fetched(rest)
282
+ : argv[named] === 'download'
283
+ ? download(rest)
284
+ : house(argv)).then((text) => {
285
+ process.stdout.write(`${text}\n`);
286
+ if (argv[0] === 'shell')
287
+ process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
288
+ }, (error) => {
289
+ process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
290
+ process.exitCode = 1;
291
+ });
@@ -1,107 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { createHash, randomUUID } from 'node:crypto';
3
- import { readFile } from 'node:fs/promises';
4
- import { request } from 'node:http';
5
- import { basename, join } from 'node:path';
6
- import { kitHome } from './home.js';
7
- const USAGE = "usage: house <tool> ['<arguments as JSON>']";
8
- const GIT_HELP = 'Submit a Room commit to House; default HEAD. Use --owner only outside an Agent conversation. Native git push is not a House remote.';
9
- const GIT_USAGE = `usage: house git push [commit] [--owner]\n${GIT_HELP}`;
10
- const socketPath = process.env.HOUSE_BRIDGE;
11
- function bridged(path, body, headers = { 'content-type': 'application/json' }, to = socketPath) {
12
- return new Promise((resolve, reject) => {
13
- const sent = request({ socketPath: to, path, method: 'POST', headers }, (answer) => {
14
- let text = '';
15
- answer.setEncoding('utf8');
16
- answer.on('data', (chunk) => {
17
- text += chunk;
18
- });
19
- answer.on('end', () => {
20
- if (answer.statusCode === 200)
21
- resolve(text);
22
- else
23
- reject(new Error(`${path} answered ${answer.statusCode}: ${text}`));
24
- });
25
- });
26
- sent.on('error', reject);
27
- sent.end(body instanceof Buffer ? body : JSON.stringify(body));
28
- });
29
- }
30
- async function mcp(method, params) {
31
- const answer = JSON.parse(await bridged('/', { jsonrpc: '2.0', id: 1, method, params }));
32
- if (answer.error !== undefined)
33
- throw new Error(answer.error.message);
34
- return answer.result;
35
- }
36
- async function tools() {
37
- return (await mcp('tools/list', {})).tools;
38
- }
39
- async function upload(path, roomRef) {
40
- const bytes = await readFile(path);
41
- const declared = JSON.parse(await bridged('/kit/attachments/upload', {
42
- ...(roomRef === undefined ? {} : { room_ref: roomRef }),
43
- version: randomUUID(),
44
- name: basename(path),
45
- bytes: bytes.length,
46
- sha256: createHash('sha256').update(bytes).digest('hex'),
47
- }));
48
- return bridged(declared.upload.url, bytes, {
49
- 'content-type': 'application/octet-stream',
50
- 'x-house-byte-operation': declared.upload.operation,
51
- });
52
- }
53
- async function gitPush(args) {
54
- if (args.includes('--help'))
55
- return GIT_USAGE;
56
- if (args[0] !== 'push')
57
- throw new Error(GIT_USAGE);
58
- const owner = args.includes('--owner');
59
- const commit = args.slice(1).find((arg) => arg !== '--owner') ?? 'HEAD';
60
- if (owner && socketPath !== undefined)
61
- throw new Error('house git push --owner runs outside an Agent conversation');
62
- if (!owner && socketPath === undefined)
63
- throw new Error('outside an Agent conversation, house git push needs --owner');
64
- const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, undefined, owner ? join(kitHome(), 'owner.sock') : socketPath));
65
- if (pushed.refused)
66
- throw new Error(pushed.text);
67
- return pushed.text;
68
- }
69
- async function house([verb, argument]) {
70
- if (verb === undefined || verb === '--help') {
71
- return [USAGE, `git push [commit]: ${GIT_HELP}`, ...(await tools()).map((tool) => `${tool.name}: ${tool.description}`)].join('\n');
72
- }
73
- if (argument === '--help') {
74
- const tool = (await tools()).find((listed) => listed.name === verb);
75
- if (tool === undefined)
76
- throw new Error(`House has no tool ${verb}`);
77
- return `${tool.description}\n${JSON.stringify(tool.inputSchema, null, 2)}`;
78
- }
79
- const args = (argument === undefined ? {} : JSON.parse(argument));
80
- if (verb === 'upload_attachment')
81
- return upload(String(args.path), args.room_ref);
82
- if (verb === 'append_record' && Array.isArray(args.attachments)) {
83
- const attachments = [];
84
- for (const path of args.attachments) {
85
- attachments.push(JSON.parse(await upload(String(path), args.room_ref)).attachment);
86
- }
87
- args.attachments = attachments;
88
- }
89
- const result = await mcp('tools/call', { name: verb, arguments: args });
90
- const text = result.content.map((content) => content.text).join('\n');
91
- if (result.isError === true)
92
- throw new Error(text);
93
- return text;
94
- }
95
- const argv = process.argv.slice(2);
96
- if (argv[0] !== 'git' && socketPath === undefined) {
97
- process.stderr.write('house: house runs inside an Agent conversation\n');
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`);
98
5
  process.exitCode = 1;
99
6
  }
100
7
  else {
101
- (argv[0] === 'git' ? gitPush(argv.slice(1)) : house(argv)).then((text) => {
102
- process.stdout.write(`${text}\n`);
103
- }, (error) => {
104
- process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
105
- process.exitCode = 1;
106
- });
8
+ await import('./house-cli.js');
107
9
  }
10
+ export {};
package/dist/inputs.js ADDED
@@ -0,0 +1,37 @@
1
+ function logged(error) {
2
+ process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
3
+ }
4
+ export class Inputs {
5
+ house;
6
+ changed;
7
+ carried = new Map();
8
+ open = 0;
9
+ constructor(house, changed) {
10
+ this.house = house;
11
+ this.changed = changed;
12
+ }
13
+ idle() {
14
+ return this.open === 0;
15
+ }
16
+ carry(inputId, work) {
17
+ const known = this.carried.get(inputId);
18
+ const carried = known ?? work();
19
+ if (known === undefined) {
20
+ this.carried.set(inputId, carried);
21
+ carried.catch(() => this.carried.delete(inputId));
22
+ }
23
+ this.open++;
24
+ this.changed();
25
+ return carried
26
+ .then(async ({ ack, acknowledged }) => {
27
+ await this.house.deliver(`/kit/inputs/${inputId}/ack`, ack);
28
+ if (known === undefined)
29
+ await acknowledged?.();
30
+ })
31
+ .catch(logged)
32
+ .finally(() => {
33
+ this.open--;
34
+ this.changed();
35
+ });
36
+ }
37
+ }
@@ -1,33 +1,12 @@
1
- import { readEnrolment } from './home.js';
2
- const HOUSE_LINE = 'Work with House through the `house` CLI: run `house --help`.';
3
- const FILE_LINE = 'To give the User a file, upload it with `house upload_attachment` and link it in your answer.';
4
- const COPIES_LINE = 'These House paths are Git working copies here; commit in one and run `house git push` to send the commit to House:';
5
- const HOW_WE_WORK = '/private/library/how-we-work.md';
6
- const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
7
- const CUT = /^stderr: shell: output_cut (\d+) of \d+ bytes; continue with: (.+)$/;
8
- async function howWeWork(bridge) {
9
- let document = '';
10
- for (let command = `cat ${HOW_WE_WORK}`; command !== undefined;) {
11
- const read = await bridge.tool('shell', { command });
12
- const text = read.content.map((content) => content.text).join('\n');
13
- const lines = text.split('\n');
14
- let at = lines[5]?.startsWith('authority: ') ? 6 : 5;
15
- if (read.isError === true || lines[2] !== 'exit: 0') {
16
- const refusal = read.isError === true ? text : lines.slice(at).join('\n').replace(/^stderr: /gm, '');
17
- if (UNREADABLE.test(refusal))
18
- return '';
19
- throw new Error(refusal);
20
- }
21
- const cut = lines[3] === 'truncation: egress' ? CUT.exec(lines[at++] ?? '') : null;
22
- const shown = Buffer.from(`${lines.slice(at).join('\n')}\n`);
23
- document += (cut === null ? shown : shown.subarray(0, Number(cut[1]))).toString();
24
- command = cut?.[2];
25
- }
26
- return document.replace(/\n$/, '');
27
- }
1
+ import { HOUSE_REF } from './git.js';
2
+ import { readHowWeWork } from './skills.js';
3
+ const SOURCE_LINE = "From House:";
4
+ const HOUSE_LINE = "Work with House through the `house` CLI: run `house --help`, and `house find_command` for House's guides and formats.";
5
+ const FILE_LINE = 'To give the User a file, upload it with `house upload` and link it; for an App, a Site or a website, follow `house find_command \'{"query":"app"}\'`. Never start a server.';
6
+ const READ_LINE = "Optional per-Room instructions: `/rooms/private/rooms/<handle>/AGENTS.md`.";
7
+ const WAIT_LINE = 'To get what another Agent will write into a Room, `create_trigger` on where it will land with a `conversation` action, then end your turn: this conversation continues when it lands.';
8
+ const COPIES_LINE = `House Local copies; before work run \`house fetch\` and rebase onto \`${HOUSE_REF}\`; after it commit, then \`house push\`:`;
28
9
  export async function instructions(bridge, base, copies) {
29
- const app = new URL('/app/new.git', (await readEnrolment()).house).href;
30
- const appLine = `To show the User a page, upload it or push it to an App instead of starting a server; \`git clone ${app}\` starts a new App.`;
31
- const lines = [HOUSE_LINE, FILE_LINE, appLine, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
32
- return [lines.join('\n'), base, await howWeWork(bridge)].filter((part) => part !== '').join('\n\n');
10
+ const lines = [SOURCE_LINE, HOUSE_LINE, FILE_LINE, READ_LINE, WAIT_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
11
+ return [lines.join('\n'), base, (await readHowWeWork(bridge)).replace(/\n$/, '')].filter((part) => part !== '').join('\n\n');
33
12
  }