@agentshouse/kit 0.2.1-ca18b01951c3b → 0.2.1-caf8b8e5a324f

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.
package/dist/copies.js CHANGED
@@ -15,6 +15,9 @@ const IDENTITY = { GIT_COMMITTER_NAME: 'House Kit', GIT_COMMITTER_EMAIL: 'house-
15
15
  function causeOf(error) {
16
16
  return error instanceof Error ? error.message : String(error);
17
17
  }
18
+ function houseCause(error) {
19
+ return error instanceof HouseRefusal ? (refusalOf(error.text)?.text ?? causeOf(error)) : causeOf(error);
20
+ }
18
21
  function logged(error) {
19
22
  process.stderr.write(`kit: ${causeOf(error)}\n`);
20
23
  }
@@ -33,6 +36,9 @@ function textOnly(paths) {
33
36
  const [named, them] = paths.length === 1 ? [`${paths[0]} is`, 'it'] : [`${paths.join(', ')} are`, 'them'];
34
37
  return `${named} not text, and house push sends text only; remove ${them} from the commit and place ${them} with house upload`;
35
38
  }
39
+ function outside(path) {
40
+ return { refused: true, text: `${path} is not a House Local copy; run house push inside one` };
41
+ }
36
42
  function short(commit) {
37
43
  return commit.slice(0, 12);
38
44
  }
@@ -60,6 +66,9 @@ function sidecar(path) {
60
66
  segments.splice(-1, 0, PROVENANCE);
61
67
  return segments.join('/');
62
68
  }
69
+ function recordOf(key) {
70
+ return join(kitHome(), 'local-copies', `${key}.json`);
71
+ }
63
72
  function rootOf(handle) {
64
73
  return `/rooms/${handle}`;
65
74
  }
@@ -206,7 +215,7 @@ export class LocalCopies {
206
215
  async mapping() {
207
216
  await this.answering;
208
217
  return [...this.copies.values()]
209
- .filter((copy) => copy.active)
218
+ .filter((copy) => copy.erasing === undefined)
210
219
  .map((copy) => `${rootOf(copy.room_handle)}: ${copy.repository}`)
211
220
  .sort();
212
221
  }
@@ -229,25 +238,30 @@ export class LocalCopies {
229
238
  return this.holding([...new Set([...this.copies.keys(), ...synced.keys()])].sort(), async () => {
230
239
  const said = [];
231
240
  let refused = false;
232
- for (const copy of this.copies.values()) {
233
- if (synced.has(copy.key) || !copy.active)
241
+ for (const copy of [...this.copies.values()]) {
242
+ const returned = synced.has(copy.key);
243
+ if (returned && copy.erasing === undefined)
234
244
  continue;
235
- await this.save({ ...copy, active: false });
236
- said.push(`${rootOf(copy.room_handle)}: no longer synced to this Environment; its files stay`);
245
+ try {
246
+ await this.erase(copy);
247
+ said.push(`${rootOf(copy.room_handle)}: ${returned ? '' : 'no longer synced to this Environment; '}erased from the Local copy`);
248
+ }
249
+ catch (error) {
250
+ refused = true;
251
+ said.push(`${rootOf(copy.room_handle)}: ${causeOf(error)}`);
252
+ }
237
253
  }
238
254
  const current = [];
239
255
  for (const [key, handle] of synced) {
240
256
  try {
241
257
  const held = this.copies.get(key);
258
+ if (held?.erasing)
259
+ continue;
242
260
  if (held === undefined || !(await exists(held.repository))) {
243
261
  said.push(await this.materialize(key, handle));
244
262
  continue;
245
263
  }
246
- const copy = held.room_handle === handle ? held : await this.save({ ...held, room_handle: handle });
247
- if (copy.active)
248
- current.push(copy);
249
- else
250
- said.push(...moved(copy, await this.save(await this.received({ ...copy, active: true }))));
264
+ current.push(held.room_handle === handle ? held : await this.save({ ...held, room_handle: handle }));
251
265
  }
252
266
  catch (error) {
253
267
  refused = true;
@@ -261,7 +275,7 @@ export class LocalCopies {
261
275
  }
262
276
  catch (error) {
263
277
  refused = true;
264
- said.push(error instanceof HouseRefusal ? (refusalOf(error.text)?.text ?? causeOf(error)) : causeOf(error));
278
+ said.push(houseCause(error));
265
279
  }
266
280
  }
267
281
  return { refused, text: said.length === 0 ? 'Nothing new from House.' : said.join('\n') };
@@ -273,6 +287,8 @@ export class LocalCopies {
273
287
  return;
274
288
  await this.exclusive(key, async () => {
275
289
  const copy = this.copies.get(key);
290
+ if (copy === undefined || copy.erasing)
291
+ return;
276
292
  let moves = copy.moves;
277
293
  for (const { from, to } of report.moves) {
278
294
  const held = moves.find((move) => move.worktree === report.worktree && move.to === from);
@@ -295,11 +311,11 @@ export class LocalCopies {
295
311
  async push(cwd, selector, caller) {
296
312
  const located = await run(cwd, ['rev-parse', '--path-format=absolute', '--git-common-dir', '--show-toplevel']);
297
313
  if (located.status !== 0)
298
- return { refused: true, text: `${cwd} is not a House Local copy; run house push inside one` };
314
+ return outside(cwd);
299
315
  const [common, worktree] = located.stdout.toString('utf8').split('\n');
300
316
  const key = await this.keyAt(dirname(common));
301
317
  if (key === undefined)
302
- return { refused: true, text: `${worktree} is not a House Local copy; run house push inside one` };
318
+ return outside(worktree);
303
319
  return this.exclusive(key, () => this.pushed(key, worktree, selector, caller));
304
320
  }
305
321
  async keyAt(repository) {
@@ -320,7 +336,7 @@ export class LocalCopies {
320
336
  return key === undefined ? work() : this.exclusive(key, () => this.holding(rest, work));
321
337
  }
322
338
  async save(copy) {
323
- const path = join(kitHome(), 'local-copies', `${copy.key}.json`);
339
+ const path = recordOf(copy.key);
324
340
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
325
341
  const temporary = `${path}.${process.pid}`;
326
342
  await writeFile(temporary, JSON.stringify(copy), { mode: 0o600 });
@@ -328,6 +344,12 @@ export class LocalCopies {
328
344
  this.copies.set(copy.key, copy);
329
345
  return copy;
330
346
  }
347
+ async erase(copy) {
348
+ await this.save({ ...copy, erasing: true });
349
+ await rm(copy.repository, { recursive: true, force: true });
350
+ await rm(recordOf(copy.key), { force: true });
351
+ this.copies.delete(copy.key);
352
+ }
331
353
  async read(handle) {
332
354
  const prefixes = [rootOf(handle)];
333
355
  const discovery = await this.house.post('/kit/door/discover', { prefixes });
@@ -394,7 +416,6 @@ export class LocalCopies {
394
416
  room_ref: read.anchor,
395
417
  room_handle: handle,
396
418
  repository,
397
- active: true,
398
419
  house,
399
420
  position: read.position,
400
421
  log_epoch: read.log_epoch,
@@ -523,6 +544,8 @@ export class LocalCopies {
523
544
  }
524
545
  async pushed(key, worktree, selector, caller) {
525
546
  let copy = this.copies.get(key);
547
+ if (copy === undefined || copy.erasing)
548
+ return outside(worktree);
526
549
  if (copy.push?.state === 'submitted')
527
550
  return this.settle(copy, caller);
528
551
  const selected = await run(worktree, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${selector}^{commit}`]);
@@ -536,9 +559,6 @@ export class LocalCopies {
536
559
  }
537
560
  copy = await this.save(without(copy));
538
561
  }
539
- if (!copy.active) {
540
- return { refused: true, text: `${rootOf(copy.room_handle)} is no longer synced to this Environment, so House takes no push from it` };
541
- }
542
562
  const listed = (await git(copy.repository, ['rev-list', '--topo-order', commit])).split('\n');
543
563
  const base = listed.find((ancestor) => ancestor in copy.manifests);
544
564
  if (base === undefined) {
@@ -549,7 +569,7 @@ export class LocalCopies {
549
569
  changes = await this.derived(copy, base, commit);
550
570
  }
551
571
  catch (error) {
552
- return { refused: true, text: causeOf(error) };
572
+ return { refused: true, text: houseCause(error) };
553
573
  }
554
574
  if (changes.length === 0)
555
575
  return { refused: false, text: `Nothing to submit: ${short(commit)} matches House.` };
@@ -576,12 +596,17 @@ export class LocalCopies {
576
596
  const after = await tree(copy.repository, commit);
577
597
  const moved = movedPaths(copy.moves, before, after);
578
598
  const arrived = new Set(moved.values());
579
- const binary = [];
580
- for (const [path, entry] of after)
581
- if (before.get(path) !== entry && !(await isText(copy.repository, entry)))
582
- binary.push(path);
583
- if (binary.length > 0)
584
- throw new Error(textOnly(binary));
599
+ const arriving = [...after].filter(([path, entry]) => before.get(path) !== entry);
600
+ if (arriving.length > 0) {
601
+ const { bounds } = await this.house.post('/kit/door/discover', { prefixes: [root] });
602
+ const binary = [];
603
+ for (const [path, entry] of arriving) {
604
+ if (!(await isText(copy.repository, entry, bounds.max_authored_file_bytes)))
605
+ binary.push(path);
606
+ }
607
+ if (binary.length > 0)
608
+ throw new Error(textOnly(binary));
609
+ }
585
610
  const text = (entry) => blobText(copy.repository, entry);
586
611
  const changes = [];
587
612
  for (const path of [...new Set([...before.keys(), ...after.keys()])].sort()) {
package/dist/end.js CHANGED
@@ -13,8 +13,9 @@ export function end(reason) {
13
13
  export function restart(reason) {
14
14
  exit(reason, 1);
15
15
  }
16
- export function updateRequired(house) {
17
- end(`This Kit is too old for House. Update it: ${installCommand(house)}`);
16
+ export function updateRequired() {
17
+ const command = installCommand();
18
+ end(command === null ? 'This Kit is too old for House; install it again.' : `This Kit is too old for House. Update it: ${command}`);
18
19
  }
19
20
  export async function signInAgain(rejected) {
20
21
  await forgetRejected(rejected);
package/dist/events.js CHANGED
@@ -512,6 +512,9 @@ class GrokReader extends Reader {
512
512
  return [];
513
513
  }
514
514
  }
515
+ export function answeredFailure(answer) {
516
+ return answer._meta?.jetbrains?.air?.sessionFailure?.title ?? null;
517
+ }
515
518
  export function readerFor(kind) {
516
519
  if (kind === 'claude-agent-acp')
517
520
  return new ClaudeReader();
package/dist/git.js CHANGED
@@ -49,16 +49,15 @@ export async function tree(repository, commit) {
49
49
  }
50
50
  return entries;
51
51
  }
52
- const TEXT_MAX_BYTES = 16 * 1024 * 1024;
53
52
  async function blob(repository, object) {
54
53
  return (await run(repository, ['cat-file', 'blob', object])).stdout;
55
54
  }
56
55
  export async function blobText(repository, object) {
57
56
  return (await blob(repository, object)).toString('utf8');
58
57
  }
59
- export async function isText(repository, object) {
58
+ export async function isText(repository, object, maxBytes) {
60
59
  const bytes = await blob(repository, object);
61
- return bytes.length <= TEXT_MAX_BYTES && isUtf8(bytes) && !bytes.includes(0);
60
+ return bytes.length <= maxBytes && isUtf8(bytes) && !bytes.includes(0);
62
61
  }
63
62
  export function blobId(content) {
64
63
  const bytes = Buffer.from(content, 'utf8');
package/dist/home.js CHANGED
@@ -1,8 +1,8 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { accessSync, chmodSync, constants, existsSync, linkSync, lstatSync, mkdirSync, 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';
3
3
  import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
4
4
  import { homedir, tmpdir } from 'node:os';
5
- import { join } from 'node:path';
5
+ import { join, resolve } from 'node:path';
6
6
  import { selectRelay } from './relay.js';
7
7
  const ENROLMENT = 'credential.json';
8
8
  const DISCONNECTED = 'disconnected.json';
@@ -19,24 +19,26 @@ function writable(directory) {
19
19
  return false;
20
20
  }
21
21
  }
22
- function ownTemporaryHome() {
23
- const home = join(tmpdir(), `house-kit-${process.getuid()}`);
22
+ function privateDirectory(path) {
24
23
  try {
25
- mkdirSync(home, { mode: 0o700 });
24
+ mkdirSync(path, { mode: 0o700 });
26
25
  }
27
26
  catch (error) {
28
27
  if (error.code !== 'EEXIST')
29
28
  throw error;
30
29
  }
31
- const found = lstatSync(home);
30
+ const found = lstatSync(path);
32
31
  if (found.isSymbolicLink())
33
- throw new Error(`${home} is a symbolic link`);
32
+ throw new Error(`${path} is a symbolic link`);
34
33
  if (!found.isDirectory())
35
- throw new Error(`${home} is not a directory`);
36
- if (found.uid !== process.getuid())
37
- throw new Error(`${home} is not owned by this User`);
38
- chmodSync(home, 0o700);
39
- return home;
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()}`));
40
42
  }
41
43
  function defaultHome() {
42
44
  const home = join(homedir(), '.house-kit');
@@ -45,6 +47,18 @@ function defaultHome() {
45
47
  export function kitHome() {
46
48
  return process.env.HOUSE_KIT_HOME || (defaulted ??= defaultHome());
47
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');
61
+ }
48
62
  export function workspaceRoot() {
49
63
  return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
50
64
  }
@@ -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
+ });