@agentshouse/kit 0.2.1-c073f4e9391b2 → 0.2.1-c0b0ffa6c025b

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 (75) hide show
  1. package/README.md +9 -8
  2. package/dist/agents.js +35 -0
  3. package/dist/bootstrap.json +4 -4
  4. package/dist/chatgpt.js +6 -2
  5. package/dist/clis.js +3 -2
  6. package/dist/conversations.js +10 -1
  7. package/dist/copies.js +18 -8
  8. package/dist/files.js +7 -1
  9. package/dist/git.js +11 -8
  10. package/dist/home.js +41 -4
  11. package/dist/house-main.js +99 -38
  12. package/dist/instructions.js +2 -27
  13. package/dist/login.js +30 -15
  14. package/dist/skills.js +81 -12
  15. package/dist/stream.js +57 -11
  16. package/dist/transcription.js +3 -3
  17. package/dist/update.js +1 -0
  18. package/how-we-work.md +13 -3
  19. package/package.json +2 -1
  20. package/skills/ask-matt/SKILL.md +17 -11
  21. package/skills/ask-matt/agents/openai.yaml +1 -0
  22. package/skills/code-review/SKILL.md +5 -5
  23. package/skills/codebase-design/DESIGN-IT-TWICE.md +1 -1
  24. package/skills/codebase-design/SKILL.md +0 -2
  25. package/skills/diagnosing-bugs/SKILL.md +2 -4
  26. package/skills/domain-modeling/{CONTEXT-FORMAT.md → GLOSSARY-FORMAT.md} +10 -10
  27. package/skills/domain-modeling/SKILL.md +12 -14
  28. package/skills/grill-me/SKILL.md +1 -2
  29. package/skills/grill-me/agents/openai.yaml +1 -0
  30. package/skills/grill-with-docs/SKILL.md +1 -2
  31. package/skills/grill-with-docs/agents/openai.yaml +1 -0
  32. package/skills/grilling/SKILL.md +2 -2
  33. package/skills/handoff/SKILL.md +2 -3
  34. package/skills/handoff/agents/openai.yaml +1 -0
  35. package/skills/implement/SKILL.md +5 -4
  36. package/skills/implement/agents/openai.yaml +1 -0
  37. package/skills/implement-spec/SKILL.md +40 -0
  38. package/skills/implement-spec/agents/openai.yaml +5 -0
  39. package/skills/improve-codebase-architecture/SKILL.md +6 -7
  40. package/skills/improve-codebase-architecture/agents/openai.yaml +1 -0
  41. package/skills/pr/CREDITS.md +3 -0
  42. package/skills/pr/LICENSE +21 -0
  43. package/skills/pr/SKILL.md +170 -0
  44. package/skills/pr/agents/openai.yaml +3 -0
  45. package/skills/prototype/SKILL.md +0 -2
  46. package/skills/research/SKILL.md +0 -2
  47. package/skills/retro/LICENSE +21 -0
  48. package/skills/retro/SKILL.md +44 -0
  49. package/skills/retro/agents/openai.yaml +5 -0
  50. package/skills/tdd/SKILL.md +2 -4
  51. package/skills/teach/SKILL.md +3 -4
  52. package/skills/teach/agents/openai.yaml +1 -0
  53. package/skills/to-questionnaire/SKILL.md +1 -2
  54. package/skills/to-questionnaire/agents/openai.yaml +1 -0
  55. package/skills/to-spec/SKILL.md +1 -2
  56. package/skills/to-spec/agents/openai.yaml +1 -0
  57. package/skills/to-tickets/SKILL.md +3 -4
  58. package/skills/to-tickets/agents/openai.yaml +1 -0
  59. package/skills/triage/AGENT-BRIEF.md +207 -0
  60. package/skills/triage/LICENSE +21 -0
  61. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  62. package/skills/triage/SKILL.md +112 -0
  63. package/skills/triage/agents/openai.yaml +5 -0
  64. package/skills/wait-what/SKILL.md +2 -3
  65. package/skills/wait-what/agents/openai.yaml +1 -0
  66. package/skills/wayfinder/SKILL.md +5 -6
  67. package/skills/wayfinder/agents/openai.yaml +1 -0
  68. package/skills/wizard/LICENSE +21 -0
  69. package/skills/wizard/SKILL.md +44 -0
  70. package/skills/wizard/agents/openai.yaml +3 -0
  71. package/skills/wizard/template.sh +223 -0
  72. package/skills/writing-for-agents/SKILL.md +0 -2
  73. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  74. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  75. /package/skills/{resolving-merge-conflicts → implement-spec}/LICENSE +0 -0
package/README.md CHANGED
@@ -33,7 +33,7 @@ them out; running it again without the flag brings them back.
33
33
 
34
34
  `kit login` opens or prints a link you confirm in any browser, on this computer
35
35
  or another, continues on its own and keeps the Environment's credential in
36
- `~/.house-kit`, or in `$HOUSE_KIT_HOME` when it is set. `--environment <id>`
36
+ `$HOUSE_KIT_HOME` when it is set, else in `~/.house-kit`, or in `house-kit-<uid>` under the temporary directory when your home is read-only. `--environment <id>`
37
37
  reconnects an Environment you already have; `--rooms <ref>[,<ref>...]` gives it
38
38
  only those Rooms and `--no-private` every Room but your Private Room; `--code <code>` connects immediately without a link.
39
39
  A login also connects your own agent: outside an Agent conversation, `house <tool>` calls
@@ -41,18 +41,19 @@ House as you and `git` clones and pushes your Apps at `<house>/app/` as you, unt
41
41
  that connection on Connections. `house help` lists the Tools. Codex sessions started after a
42
42
  login run a lone `house` command outside their sandbox. `kit logout` disconnects this
43
43
  computer, stops House Kit and ends your own agent's connection, so `house` and `git` no
44
- longer act as you here; a later `kit login` reconnects the same Environment.
44
+ longer act as you here; a later `kit login` reconnects the same Environment, or connects
45
+ this computer as a new one when House no longer holds it.
45
46
  In a container you do not control, such as ChatGPT's, `npm i -g @agentshouse/kit` and `kit chatgpt --key <key>` with a key made on Connections let `house <tool>` act as you, starting and configuring nothing else.
46
47
 
47
- `kit resident` keeps the Environment connected and, as it connects, copies each
48
- Room you chose for it as a Git repository in the workspace's `local-copies`.
49
- `house fetch` records House's changes on each copy's `refs/house/received`;
50
- rebase onto it, commit and run `house push --owner` in the copy, through the
51
- install command in the container. An Agent runs both, without `--owner`.
48
+ `kit resident` keeps the Environment connected and, as it connects, copies the text of each Room
49
+ you chose for it as a Git repository in the workspace's `local-copies`. `house fetch` records
50
+ House's changes on each copy's `refs/house/received`; rebase onto it, commit and run
51
+ `house push --owner` in the copy, through the install command in the container. An Agent runs
52
+ both, without `--owner`. `house upload` and `house download` move a Room's other files.
52
53
 
53
54
  House Kit turns each audio file of your message to an Agent into text on this
54
55
  computer before the Agent reads it. While transcription is on, the speech
55
- engine and model use about 425 MB in `~/.house-kit`; turning it off deletes them.
56
+ engine and model use about 425 MB beside the Environment's credential; turning it off deletes them.
56
57
 
57
58
  ## License
58
59
 
package/dist/agents.js CHANGED
@@ -24,6 +24,22 @@ function causeOf(error) {
24
24
  function logged(error) {
25
25
  process.stderr.write(`kit: ${causeOf(error)}\n`);
26
26
  }
27
+ const LAPTOP_CHASSIS = new Set(['8', '9', '10', '14', '30', '31', '32']);
28
+ const DESKTOP_CHASSIS = new Set(['3', '4', '5', '6', '7', '15', '16']);
29
+ const SERVER_CHASSIS = new Set(['17', '18', '19', '20', '21', '22', '23', '24']);
30
+ export function chassisForm(value) {
31
+ const chassis = value.trim();
32
+ if (LAPTOP_CHASSIS.has(chassis))
33
+ return 'laptop';
34
+ if (DESKTOP_CHASSIS.has(chassis))
35
+ return 'desktop';
36
+ if (SERVER_CHASSIS.has(chassis))
37
+ return 'server';
38
+ return undefined;
39
+ }
40
+ export function hostVm(version) {
41
+ return /docker desktop|microsoft|wsl|linuxkit/i.test(version);
42
+ }
27
43
  async function models(kind, adapter, known) {
28
44
  const agent = adapter.connection.agent;
29
45
  const opened = await agent.request('session/new', { cwd: kitHome(), mcpServers: [] });
@@ -122,6 +138,22 @@ async function operatingSystem() {
122
138
  const release = await readFile('/etc/os-release', 'utf8');
123
139
  return /^PRETTY_NAME="?([^"\n]*)"?$/m.exec(release)?.[1] ?? release;
124
140
  }
141
+ async function hostForm() {
142
+ if (process.platform === 'darwin') {
143
+ const battery = await run('pmset', ['-g', 'batt'], 10_000);
144
+ return battery.status === 0 && battery.output.includes('InternalBattery') ? 'laptop' : 'desktop';
145
+ }
146
+ if (process.platform !== 'linux')
147
+ return undefined;
148
+ const [container, version, chassis] = await Promise.all([
149
+ readFile('/.dockerenv', 'utf8').then(() => true).catch(() => false),
150
+ readFile('/proc/version', 'utf8').catch(() => ''),
151
+ readFile('/sys/class/dmi/id/chassis_type', 'utf8').catch(() => ''),
152
+ ]);
153
+ if (container && hostVm(version))
154
+ return undefined;
155
+ return chassisForm(chassis);
156
+ }
125
157
  export class Agents {
126
158
  desired = { agents: [], routes: [], transcribe: false };
127
159
  house;
@@ -277,6 +309,7 @@ export class Agents {
277
309
  if (known !== undefined && known.failure === null && known.minimum === undefined)
278
310
  return;
279
311
  await this.examine(kind, SIGNED_OUT, offer);
312
+ await this.report();
280
313
  }
281
314
  async send() {
282
315
  const agents = this.desired.agents.flatMap((kind) => {
@@ -284,8 +317,10 @@ export class Agents {
284
317
  return reading === undefined ? [] : [reported(kind, reading)];
285
318
  });
286
319
  const hostKey = await sshHostKey();
320
+ const form = await hostForm();
287
321
  const body = {
288
322
  os: await operatingSystem(),
323
+ ...(form === undefined ? {} : { form }),
289
324
  kit_version: KIT_VERSION,
290
325
  wire: KIT_WIRE,
291
326
  updates_itself: await updatesItself(),
@@ -1,23 +1,23 @@
1
1
  {
2
2
  "schemaVersion": 2,
3
- "version": "0.2.1-c073f4e9391b2",
3
+ "version": "0.2.1-c0b0ffa6c025b",
4
4
  "hosts": {
5
5
  "macos": {
6
6
  "asset": {
7
7
  "name": "connect-linux.sh",
8
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c073f4e9391b2/connect-linux.sh"
8
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c0b0ffa6c025b/connect-linux.sh"
9
9
  }
10
10
  },
11
11
  "linux": {
12
12
  "asset": {
13
13
  "name": "connect-linux.sh",
14
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c073f4e9391b2/connect-linux.sh"
14
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c0b0ffa6c025b/connect-linux.sh"
15
15
  }
16
16
  },
17
17
  "windows": {
18
18
  "asset": {
19
19
  "name": "connect-windows.ps1",
20
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c073f4e9391b2/connect-windows.ps1"
20
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c0b0ffa6c025b/connect-windows.ps1"
21
21
  }
22
22
  }
23
23
  }
package/dist/chatgpt.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { parseArgs } from 'node:util';
2
+ import { placeAppGit } from './app-git.js';
2
3
  import { kitHome, readOwnAgent, writeOwnAgent } from './home.js';
3
4
  import { accepted, DEFAULT_HOUSE } from './login.js';
4
5
  const KEY_SOURCE = 'New key for a script on Connections';
@@ -17,9 +18,12 @@ export async function chatgpt(argv) {
17
18
  }
18
19
  if (values.key === undefined)
19
20
  throw new Error(`pass --key with a key from ${KEY_SOURCE}`);
20
- const house = values.house ?? (await readOwnAgent())?.house ?? DEFAULT_HOUSE;
21
+ const before = await readOwnAgent();
22
+ const house = values.house ?? before?.house ?? DEFAULT_HOUSE;
21
23
  if (!(await accepted(house, values.key)))
22
24
  throw new Error(`${house} does not accept this key; pass one from ${KEY_SOURCE}`);
23
- await writeOwnAgent({ house, credential: values.key });
25
+ const relay = process.env.HOUSE_KIT_RELAY || undefined;
26
+ await writeOwnAgent({ house, ...(relay === undefined ? {} : { relay }), credential: values.key });
27
+ await placeAppGit(before, await readOwnAgent()).catch((error) => process.stderr.write(`kit: ${error.message}\n`));
24
28
  process.stdout.write(`house now calls ${house} as you, with the key kept in ${kitHome()}.\n`);
25
29
  }
package/dist/clis.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
2
3
  import { constants, readFileSync } from 'node:fs';
3
4
  import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
4
5
  import { homedir, userInfo } from 'node:os';
@@ -54,7 +55,7 @@ export async function allowHouseInCodex(path) {
54
55
  houses.push(house);
55
56
  }
56
57
  await mkdir(rules, { recursive: true });
57
- const temporary = `${file}.${process.pid}`;
58
+ const temporary = `${file}.${randomUUID()}`;
58
59
  await writeFile(temporary, houseRule(houses));
59
60
  await rename(temporary, file);
60
61
  }
@@ -199,7 +200,7 @@ export async function installAdapter(kind, signal) {
199
200
  const release = KIT_PACKAGE.peerDependencies[adapter.package];
200
201
  if ((await installedAdapter(kind)) === release)
201
202
  return null;
202
- const ran = await run('npm', ['install', '--prefix', prefix(kind), '--no-save', '--no-audit', '--no-fund', '--omit=optional', `${adapter.package}@${release}`], INSTALL_MS, true, signal);
203
+ const ran = await run('npm', ['install', '--prefix', prefix(kind), '--cache', join(kitHome(), 'npm-cache'), '--no-save', '--no-audit', '--no-fund', '--omit=optional', `${adapter.package}@${release}`], INSTALL_MS, true, signal);
203
204
  return ran.status === 0 ? null : failureOf(ran, 'npm');
204
205
  }
205
206
  export async function installCli(kind, signal) {
@@ -17,6 +17,14 @@ import { createHowWeWork } from './skills.js';
17
17
  import { transcribe } from './transcription.js';
18
18
  import { workFor } from './work.js';
19
19
  const KILLED = 'the conversation was killed';
20
+ const EXIT_PLAN_MODE = {
21
+ parse(value) {
22
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
23
+ throw new Error('_x.ai/exit_plan_mode needs an object');
24
+ }
25
+ return value;
26
+ },
27
+ };
20
28
  export const CONVERSATION_INPUTS = new Set(['open', 'message', 'interrupt', 'kill', 'option', 'answer']);
21
29
  function causeOf(error) {
22
30
  return error instanceof Error ? error.message : String(error);
@@ -348,7 +356,8 @@ export class Conversations {
348
356
  reader.session = sessionId;
349
357
  const app = client({ name: '@agentshouse/kit' })
350
358
  .onRequest('session/request_permission', ({ params, signal }) => this.ask(conversation, 'session/request_permission', params, false, signal))
351
- .onRequest('elicitation/create', ({ params, signal }) => this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal));
359
+ .onRequest('elicitation/create', ({ params, signal }) => this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
360
+ .onRequest('_x.ai/exit_plan_mode', EXIT_PLAN_MODE, ({ params, signal }) => this.ask(conversation, '_x.ai/exit_plan_mode', params, false, signal));
352
361
  const cli = await unlessAborted(this.kit.agents.cli(route.kind), conversation.killed.signal);
353
362
  const bridge = await openBridge(this.kit.house, this.kit.copies, conversation.id, conversation.killed.signal);
354
363
  if (conversation.kills > 0) {
package/dist/copies.js CHANGED
@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';
3
3
  import { mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { finalRefusal, HouseRefusal, retrying } from './api.js';
6
- import { blobId, blobText, git, HOUSE_REF, importCommits, localCopies, revision, run, succeeded, tree, } from './git.js';
6
+ import { blobId, blobText, git, isText, HOUSE_REF, importCommits, localCopies, revision, run, succeeded, tree, } from './git.js';
7
7
  import { kitHome } from './home.js';
8
8
  import { operationId } from './operation.js';
9
9
  import { refusalOf } from './refusals.js';
@@ -29,6 +29,10 @@ const REBASED = new Set([
29
29
  function rebaseFixes(refusal) {
30
30
  return refusal.code === 'edit_conflict' && refusal.conflicts.some((code) => REBASED.has(code));
31
31
  }
32
+ function textOnly(paths) {
33
+ const [named, them] = paths.length === 1 ? [`${paths[0]} is`, 'it'] : [`${paths.join(', ')} are`, 'them'];
34
+ return `${named} not text, and house push sends text only; remove ${them} from the commit and place ${them} with house upload`;
35
+ }
32
36
  function short(commit) {
33
37
  return commit.slice(0, 12);
34
38
  }
@@ -572,7 +576,13 @@ export class LocalCopies {
572
576
  const after = await tree(copy.repository, commit);
573
577
  const moved = movedPaths(copy.moves, before, after);
574
578
  const arrived = new Set(moved.values());
575
- const text = (entry, path) => blobText(copy.repository, entry, path);
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));
585
+ const text = (entry) => blobText(copy.repository, entry);
576
586
  const changes = [];
577
587
  for (const path of [...new Set([...before.keys(), ...after.keys()])].sort()) {
578
588
  if (arrived.has(path))
@@ -585,7 +595,7 @@ export class LocalCopies {
585
595
  changes.push({ op: 'rename', path: `${root}/${path}`, to: `${root}/${to}`, base: known });
586
596
  const moving = after.get(to);
587
597
  if (moving !== prior) {
588
- changes.push({ op: 'replace', path: `${root}/${to}`, base: known, content: await text(moving, to) });
598
+ changes.push({ op: 'replace', path: `${root}/${to}`, base: known, content: await text(moving) });
589
599
  }
590
600
  continue;
591
601
  }
@@ -594,9 +604,9 @@ export class LocalCopies {
594
604
  if (next === undefined)
595
605
  changes.push({ op: 'remove', path: `${root}/${path}`, base: known });
596
606
  else if (prior === undefined)
597
- changes.push({ op: 'create', path: `${root}/${path}`, content: await text(next, path) });
607
+ changes.push({ op: 'create', path: `${root}/${path}`, content: await text(next) });
598
608
  else
599
- changes.push(...changed(`${root}/${path}`, path, known, await text(prior, path), await text(next, path)));
609
+ changes.push(...changed(`${root}/${path}`, path, known, await text(prior), await text(next)));
600
610
  }
601
611
  return changes;
602
612
  }
@@ -663,7 +673,7 @@ export class LocalCopies {
663
673
  written.push({
664
674
  path: `${root}/${path}`,
665
675
  revision: entry === undefined ? null : (revisionAt(current, current.house, path) ?? null),
666
- content: entry === undefined ? null : await blobText(copy.repository, entry, path),
676
+ content: entry === undefined ? null : await blobText(copy.repository, entry),
667
677
  });
668
678
  }
669
679
  return this.finished(await this.save({ ...current, push: { ...push, state: 'accepted', written } }));
@@ -707,7 +717,7 @@ export class LocalCopies {
707
717
  {
708
718
  path: `${rootOf(copy.room_handle)}/${path}`,
709
719
  revision: entry === undefined ? null : (revisionAt(copy, copy.house, path) ?? null),
710
- content: entry === undefined ? null : await blobText(copy.repository, entry, path),
720
+ content: entry === undefined ? null : await blobText(copy.repository, entry),
711
721
  },
712
722
  ];
713
723
  }
@@ -752,7 +762,7 @@ export class LocalCopies {
752
762
  async landed(repository, changes, house, selected) {
753
763
  const text = async (path) => {
754
764
  const entry = house.get(relative(path));
755
- return entry === undefined ? undefined : blobText(repository, entry, path);
765
+ return entry === undefined ? undefined : blobText(repository, entry);
756
766
  };
757
767
  for (const change of changes) {
758
768
  const current = await text(change.path);
package/dist/files.js CHANGED
@@ -1,7 +1,13 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { mkdir, writeFile } from 'node:fs/promises';
2
3
  import { join } from 'node:path';
3
4
  import { HouseRefusal, retrying } from './api.js';
4
5
  import { relayed } from './relay.js';
6
+ export function verified(bytes, sha256, name) {
7
+ if (createHash('sha256').update(bytes).digest('hex') !== sha256)
8
+ throw new Error(`${name} did not arrive whole; download it again`);
9
+ return bytes;
10
+ }
5
11
  export async function placeFiles(house, directory, files, signal) {
6
12
  const paths = [];
7
13
  for (const file of files) {
@@ -16,7 +22,7 @@ export async function placeFiles(house, directory, files, signal) {
16
22
  });
17
23
  await mkdir(folder, { recursive: true });
18
24
  const path = join(folder, file.name);
19
- await writeFile(path, Buffer.from(await answer.arrayBuffer()));
25
+ await writeFile(path, verified(Buffer.from(await answer.arrayBuffer()), file.sha256, file.name));
20
26
  paths.push(path);
21
27
  }
22
28
  return paths;
package/dist/git.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { isUtf8 } from 'node:buffer';
2
3
  import { createHash } from 'node:crypto';
3
4
  import { join } from 'node:path';
4
5
  import { withoutProxy } from './clis.js';
@@ -48,14 +49,16 @@ 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
+ const TEXT_MAX_BYTES = 16 * 1024 * 1024;
53
+ async function blob(repository, object) {
54
+ return (await run(repository, ['cat-file', 'blob', object])).stdout;
55
+ }
56
+ export async function blobText(repository, object) {
57
+ return (await blob(repository, object)).toString('utf8');
58
+ }
59
+ export async function isText(repository, object) {
60
+ const bytes = await blob(repository, object);
61
+ return bytes.length <= TEXT_MAX_BYTES && isUtf8(bytes) && !bytes.includes(0);
59
62
  }
60
63
  export function blobId(content) {
61
64
  const bytes = Buffer.from(content, 'utf8');
package/dist/home.js CHANGED
@@ -1,6 +1,7 @@
1
- import { existsSync, linkSync, readFileSync, renameSync, rmSync } from 'node:fs';
1
+ import { randomUUID } from 'node:crypto';
2
+ import { accessSync, chmodSync, constants, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, 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 { homedir, tmpdir } from 'node:os';
4
5
  import { join } from 'node:path';
5
6
  import { selectRelay } from './relay.js';
6
7
  const ENROLMENT = 'credential.json';
@@ -8,8 +9,41 @@ const DISCONNECTED = 'disconnected.json';
8
9
  const CONFIGURATION = 'kit.json';
9
10
  const OWN_AGENT = 'own-agent.json';
10
11
  const RESTART = 'restart';
12
+ let defaulted;
13
+ function writable(directory) {
14
+ try {
15
+ accessSync(directory, constants.W_OK | constants.X_OK);
16
+ return true;
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ function ownTemporaryHome() {
23
+ const home = join(tmpdir(), `house-kit-${process.getuid()}`);
24
+ try {
25
+ mkdirSync(home, { mode: 0o700 });
26
+ }
27
+ catch (error) {
28
+ if (error.code !== 'EEXIST')
29
+ throw error;
30
+ }
31
+ const found = lstatSync(home);
32
+ if (found.isSymbolicLink())
33
+ throw new Error(`${home} is a symbolic link`);
34
+ 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;
40
+ }
41
+ function defaultHome() {
42
+ const home = join(homedir(), '.house-kit');
43
+ return existsSync(home) || writable(homedir()) ? home : ownTemporaryHome();
44
+ }
11
45
  export function kitHome() {
12
- return process.env.HOUSE_KIT_HOME ?? join(homedir(), '.house-kit');
46
+ return process.env.HOUSE_KIT_HOME || (defaulted ??= defaultHome());
13
47
  }
14
48
  export function workspaceRoot() {
15
49
  return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
@@ -30,7 +64,7 @@ export async function readHome(name) {
30
64
  export async function writeHome(name, value) {
31
65
  const home = kitHome();
32
66
  await mkdir(home, { recursive: true, mode: 0o700 });
33
- const temporary = join(home, `${name}.${process.pid}`);
67
+ const temporary = join(home, `${name}.${randomUUID()}`);
34
68
  await writeFile(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600 });
35
69
  await rename(temporary, join(home, name));
36
70
  }
@@ -47,6 +81,9 @@ export async function writeEnrolment(enrolment) {
47
81
  export function readDisconnected() {
48
82
  return readHome(DISCONNECTED);
49
83
  }
84
+ export function forgetDisconnected() {
85
+ return rm(join(kitHome(), DISCONNECTED), { force: true });
86
+ }
50
87
  export async function forgetEnrolment({ house, environment }) {
51
88
  await writeHome(DISCONNECTED, { house, environment });
52
89
  await rm(join(kitHome(), ENROLMENT), { force: true });
@@ -1,25 +1,29 @@
1
1
  #!/usr/bin/env node
2
2
  import { createHash } from 'node:crypto';
3
- import { readFile } from 'node:fs/promises';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
4
  import { request, setGlobalProxyFromEnv } from 'node:http';
5
- import { extname, join } from 'node:path';
5
+ import { basename, dirname, extname, join, resolve } from 'node:path';
6
+ import { verified } from './files.js';
6
7
  import { HOUSE_REF } from './git.js';
7
- import { kitHome, readEnrolment, readOwnAgent } from './home.js';
8
+ import { kitHome, readOwnAgent } from './home.js';
8
9
  import { callHouse, rpc, UNREACHABLE } from './mcp.js';
9
10
  import { refusalOf } from './refusals.js';
10
- import { relayed } from './relay.js';
11
+ import { relayed, selectRelay } from './relay.js';
11
12
  import { parse, stringify } from 'yaml';
12
13
  const USAGE = "usage: house <tool> ['<arguments as JSON>']";
13
14
  const PUSH_USAGE = 'usage: house push [commit] [--owner]';
14
15
  const PUSH = "push [commit]: sends the Local copy's committed changes to House";
15
16
  const FETCH_USAGE = 'usage: house fetch';
16
17
  const FETCH = `fetch: records House's changes on each Local copy's ${HOUSE_REF}`;
18
+ const DOWNLOAD_USAGE = `usage: house download '{"path":"/rooms/<handle>/<path>","file":"<local file>"}', adding "ref" for a revision`;
19
+ const DOWNLOAD = 'download: writes a binary file of a Room to the local file named by file';
17
20
  const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
18
21
  const CLOSED = "this conversation's House connection is closed; nothing to do from here";
19
22
  const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
20
23
  const REVOKED = 'this conversation no longer has House access; nothing to do from here';
21
24
  const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
22
25
  const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login";
26
+ const UNCONFIRMED = 'with no result; a write may or may not have taken effect, so read before you repeat it';
23
27
  const socketPath = process.env.HOUSE_BRIDGE;
24
28
  const MEDIA_TYPES = new Map([
25
29
  ['avif', 'image/avif'],
@@ -48,49 +52,54 @@ const MEDIA_TYPES = new Map([
48
52
  ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
49
53
  ['zip', 'application/zip'],
50
54
  ]);
51
- function refused(path, status, text) {
55
+ function refused(path, method, status, text, local) {
52
56
  const refusal = refusalOf(text);
53
57
  if (refusal !== null)
54
58
  return refusal.text;
55
59
  if (status === 401)
56
60
  return REVOKED;
61
+ const act = method === 'GET' ? 'download' : 'upload';
57
62
  if (URL.canParse(path))
58
- return `the upload answered ${status}; upload the file again`;
59
- if (status === 502 && /^[A-Za-z]/.test(text))
63
+ return `the ${act} answered ${status}; ${act} the file again`;
64
+ if (status === 502 && local)
60
65
  return text;
61
- return `${path} answered ${status}`;
66
+ return path === '/' ? unconfirmed(status) : `${path} answered ${status}`;
62
67
  }
63
- function bridged(path, body, headers = { 'content-type': 'application/json' }, to = socketPath) {
68
+ function unconfirmed(status) {
69
+ return `House answered ${status} ${UNCONFIRMED}`;
70
+ }
71
+ function exchanged(path, method, body, headers = { 'content-type': 'application/json' }, to = socketPath) {
64
72
  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
- });
73
+ const sent = request({ socketPath: to, path, method, headers }, (answer) => {
74
+ const chunks = [];
75
+ answer.on('data', (chunk) => chunks.push(chunk));
71
76
  answer.on('end', () => {
77
+ const bytes = Buffer.concat(chunks);
72
78
  if (answer.statusCode === 200)
73
- resolve(text);
79
+ resolve(bytes);
74
80
  else
75
- reject(new Error(refused(path, answer.statusCode, text)));
81
+ reject(new Error(refused(path, method, answer.statusCode, bytes.toString('utf8'), answer.headers['content-type'] === undefined)));
76
82
  });
77
83
  });
78
84
  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));
85
+ sent.end(body === undefined ? undefined : body instanceof Buffer ? body : JSON.stringify(body));
80
86
  });
81
87
  }
88
+ async function bridged(path, body, headers, to = socketPath) {
89
+ return (await exchanged(path, 'POST', body, headers, to)).toString('utf8');
90
+ }
82
91
  async function direct(message) {
83
92
  const ownAgent = await readOwnAgent();
84
93
  if (ownAgent === null)
85
94
  throw new Error(UNCONNECTED);
86
- await readEnrolment();
95
+ selectRelay(process.env.HOUSE_KIT_RELAY || ownAgent.relay);
87
96
  setGlobalProxyFromEnv();
88
97
  const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
89
98
  throw new Error(UNREACHABLE);
90
99
  });
91
100
  if (answer.status === 200)
92
101
  return answer.text;
93
- throw new Error(answer.status === 401 ? DISCONNECTED : (refusalOf(answer.text)?.text ?? `House answered ${answer.status}`));
102
+ throw new Error(answer.status === 401 ? DISCONNECTED : (refusalOf(answer.text)?.text ?? unconfirmed(answer.status)));
94
103
  }
95
104
  async function mcp(method, params) {
96
105
  const message = rpc(method, params);
@@ -112,36 +121,82 @@ async function localFile(path) {
112
121
  : `${path} is not a readable file`);
113
122
  }
114
123
  }
115
- async function sent(url, bytes, operation) {
116
- const headers = { 'content-type': 'application/octet-stream', 'x-house-byte-operation': operation };
124
+ async function transferred(url, method, bytes, headers) {
117
125
  if (socketPath !== undefined)
118
- return bridged(url, bytes, headers);
126
+ return exchanged(url, method, bytes, headers);
119
127
  setGlobalProxyFromEnv();
120
- const answer = await fetch(relayed(url), { method: 'POST', headers, body: bytes }).catch(() => {
128
+ const answer = await fetch(relayed(url), { method, ...(headers === undefined ? {} : { headers }), ...(bytes === undefined ? {} : { body: bytes }) }).catch(() => {
121
129
  throw new Error(UNREACHABLE);
122
130
  });
123
- const text = await answer.text();
131
+ const received = Buffer.from(await answer.arrayBuffer());
124
132
  if (answer.status === 200)
125
- return text;
126
- throw new Error(refused(url, answer.status, text));
133
+ return received;
134
+ throw new Error(refused(url, method, answer.status, received.toString('utf8'), false));
127
135
  }
128
- async function upload({ file, ...destination }) {
136
+ async function sent(url, bytes, operation) {
137
+ const headers = { 'content-type': 'application/octet-stream', 'x-house-byte-operation': operation };
138
+ return (await transferred(url, 'POST', bytes, headers)).toString('utf8');
139
+ }
140
+ async function download(args) {
141
+ const { flags, positionals: [argument] } = accepted(args, ['--help'], 1, DOWNLOAD_USAGE);
142
+ if (flags.has('--help'))
143
+ return DOWNLOAD_USAGE;
144
+ const { file, ...selected } = argumentsOf(argument);
129
145
  if (typeof file !== 'string' || file === '')
130
- throw new Error('upload needs "file", a local file');
146
+ throw new Error('download needs "file", the local file to write');
147
+ const inspected = parse(await called('inspect', selected));
148
+ if (typeof inspected?.download !== 'string')
149
+ throw new Error(`${String(selected.path)} holds no binary file; shell reads its text`);
150
+ const bytes = verified(await transferred(inspected.download, 'GET'), String(inspected.sha256), String(selected.path));
151
+ const written = resolve(file);
152
+ await mkdir(dirname(written), { recursive: true });
153
+ await writeFile(written, bytes);
154
+ return written;
155
+ }
156
+ async function described(file) {
131
157
  const bytes = await localFile(file);
132
158
  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
- });
159
+ return {
160
+ bytes,
161
+ description: {
162
+ bytes: bytes.length,
163
+ sha256: createHash('sha256').update(bytes).digest('hex'),
164
+ ...(mediaType === undefined ? {} : { media_type: mediaType }),
165
+ },
166
+ };
167
+ }
168
+ async function upload({ file, ...destination }) {
169
+ if (typeof file !== 'string' || file === '')
170
+ throw new Error('upload needs "file", a local file');
171
+ const { bytes, description } = await described(file);
172
+ const answer = await called('upload', { ...destination, ...description });
139
173
  const declared = parse(answer);
140
174
  if (declared.upload === undefined)
141
175
  return answer;
142
176
  const written = JSON.parse(await sent(declared.upload.url, bytes, declared.upload.operation));
143
177
  return stringify(written, { lineWidth: 0 }).trimEnd();
144
178
  }
179
+ async function appendRecord(args) {
180
+ const held = new Map();
181
+ const attachments = Array.isArray(args.attachments)
182
+ ? await Promise.all(args.attachments.map(async (attachment) => {
183
+ if (typeof attachment !== 'string')
184
+ return attachment;
185
+ const { bytes, description } = await described(attachment);
186
+ held.set(description.sha256, bytes);
187
+ return { name: basename(attachment), ...description };
188
+ }))
189
+ : args.attachments;
190
+ const record = { ...args, attachments };
191
+ for (;;) {
192
+ const answer = await called('append_record', record);
193
+ const { upload } = parse(answer);
194
+ if (upload === undefined)
195
+ return answer;
196
+ for (const grant of upload)
197
+ await sent(grant.url, held.get(grant.sha256), grant.operation);
198
+ }
199
+ }
145
200
  function unexpected(argument, usage) {
146
201
  return new Error(`unexpected argument ${argument}; ${usage}`);
147
202
  }
@@ -200,7 +255,7 @@ async function house(args) {
200
255
  if (flags.has('--help') && argument !== undefined)
201
256
  throw unexpected('--help', USAGE);
202
257
  if (verb === undefined || verb === 'help') {
203
- return [USAGE, 'help', PUSH, FETCH, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
258
+ return [USAGE, 'help', PUSH, FETCH, DOWNLOAD, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
204
259
  }
205
260
  if (flags.has('--help')) {
206
261
  const tool = (await tools()).find((listed) => listed.name === verb);
@@ -209,7 +264,7 @@ async function house(args) {
209
264
  return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
210
265
  }
211
266
  const parsed = argumentsOf(argument);
212
- return verb === 'upload' ? upload(parsed) : called(verb, parsed);
267
+ return verb === 'upload' ? upload(parsed) : verb === 'append_record' ? appendRecord(parsed) : called(verb, parsed);
213
268
  }
214
269
  async function called(name, args) {
215
270
  const result = await mcp('tools/call', { name, arguments: args });
@@ -221,7 +276,13 @@ async function called(name, args) {
221
276
  const argv = process.argv.slice(2);
222
277
  const named = argv.findIndex((arg) => !arg.startsWith('-'));
223
278
  const rest = argv.filter((_arg, index) => index !== named);
224
- (argv[named] === 'push' ? push(rest) : argv[named] === 'fetch' ? fetched(rest) : house(argv)).then((text) => {
279
+ (argv[named] === 'push'
280
+ ? push(rest)
281
+ : argv[named] === 'fetch'
282
+ ? fetched(rest)
283
+ : argv[named] === 'download'
284
+ ? download(rest)
285
+ : house(argv)).then((text) => {
225
286
  process.stdout.write(`${text}\n`);
226
287
  if (argv[0] === 'shell')
227
288
  process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);