@agentshouse/kit 0.2.1-c3fc787e93f0e → 0.2.1-c4823db4ff116

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 (77) hide show
  1. package/README.md +2 -1
  2. package/dist/agents.js +49 -2
  3. package/dist/bootstrap.json +4 -4
  4. package/dist/chatgpt.js +7 -1
  5. package/dist/clis.js +2 -1
  6. package/dist/conversations.js +20 -4
  7. package/dist/copies.js +16 -8
  8. package/dist/events.js +3 -0
  9. package/dist/git.js +2 -3
  10. package/dist/home.js +5 -1
  11. package/dist/house-cli.js +291 -0
  12. package/dist/house-main.js +7 -262
  13. package/dist/instructions.js +2 -27
  14. package/dist/kit-cli.js +68 -0
  15. package/dist/kit-main.js +8 -67
  16. package/dist/login.js +32 -7
  17. package/dist/skills.js +71 -12
  18. package/dist/stream.js +57 -11
  19. package/dist/transcription.js +3 -3
  20. package/how-we-work.md +13 -3
  21. package/package.json +2 -1
  22. package/skills/ask-matt/SKILL.md +17 -11
  23. package/skills/ask-matt/agents/openai.yaml +1 -0
  24. package/skills/code-review/SKILL.md +5 -5
  25. package/skills/codebase-design/DESIGN-IT-TWICE.md +1 -1
  26. package/skills/codebase-design/SKILL.md +0 -2
  27. package/skills/diagnosing-bugs/SKILL.md +2 -4
  28. package/skills/domain-modeling/{CONTEXT-FORMAT.md → GLOSSARY-FORMAT.md} +10 -10
  29. package/skills/domain-modeling/SKILL.md +12 -14
  30. package/skills/grill-me/SKILL.md +1 -2
  31. package/skills/grill-me/agents/openai.yaml +1 -0
  32. package/skills/grill-with-docs/SKILL.md +1 -2
  33. package/skills/grill-with-docs/agents/openai.yaml +1 -0
  34. package/skills/grilling/SKILL.md +2 -2
  35. package/skills/handoff/SKILL.md +2 -3
  36. package/skills/handoff/agents/openai.yaml +1 -0
  37. package/skills/implement/SKILL.md +5 -4
  38. package/skills/implement/agents/openai.yaml +1 -0
  39. package/skills/implement-spec/SKILL.md +40 -0
  40. package/skills/implement-spec/agents/openai.yaml +5 -0
  41. package/skills/improve-codebase-architecture/SKILL.md +6 -7
  42. package/skills/improve-codebase-architecture/agents/openai.yaml +1 -0
  43. package/skills/pr/CREDITS.md +3 -0
  44. package/skills/pr/LICENSE +21 -0
  45. package/skills/pr/SKILL.md +170 -0
  46. package/skills/pr/agents/openai.yaml +3 -0
  47. package/skills/prototype/SKILL.md +0 -2
  48. package/skills/research/SKILL.md +0 -2
  49. package/skills/retro/LICENSE +21 -0
  50. package/skills/retro/SKILL.md +44 -0
  51. package/skills/retro/agents/openai.yaml +5 -0
  52. package/skills/tdd/SKILL.md +2 -4
  53. package/skills/teach/SKILL.md +3 -4
  54. package/skills/teach/agents/openai.yaml +1 -0
  55. package/skills/to-questionnaire/SKILL.md +1 -2
  56. package/skills/to-questionnaire/agents/openai.yaml +1 -0
  57. package/skills/to-spec/SKILL.md +1 -2
  58. package/skills/to-spec/agents/openai.yaml +1 -0
  59. package/skills/to-tickets/SKILL.md +3 -4
  60. package/skills/to-tickets/agents/openai.yaml +1 -0
  61. package/skills/triage/AGENT-BRIEF.md +207 -0
  62. package/skills/triage/LICENSE +21 -0
  63. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  64. package/skills/triage/SKILL.md +112 -0
  65. package/skills/triage/agents/openai.yaml +5 -0
  66. package/skills/wait-what/SKILL.md +2 -3
  67. package/skills/wait-what/agents/openai.yaml +1 -0
  68. package/skills/wayfinder/SKILL.md +5 -6
  69. package/skills/wayfinder/agents/openai.yaml +1 -0
  70. package/skills/wizard/LICENSE +21 -0
  71. package/skills/wizard/SKILL.md +44 -0
  72. package/skills/wizard/agents/openai.yaml +3 -0
  73. package/skills/wizard/template.sh +223 -0
  74. package/skills/writing-for-agents/SKILL.md +0 -2
  75. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  76. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  77. /package/skills/{resolving-merge-conflicts → implement-spec}/LICENSE +0 -0
package/README.md CHANGED
@@ -41,7 +41,8 @@ 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
48
  `kit resident` keeps the Environment connected and, as it connects, copies the text of each Room
package/dist/agents.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { client } from '@agentclientprotocol/sdk';
2
2
  import { readFile, realpath } from 'node:fs/promises';
3
+ import { setTimeout as delay } from 'node:timers/promises';
3
4
  import { startAdapter } from './acp.js';
4
5
  import { CLIS, KIT_VERSION, below, installAdapter, installCli, locate, run, versionOf } from './clis.js';
5
6
  import { agentBase, kitHome } from './home.js';
@@ -7,6 +8,8 @@ import { updatesItself } from './placement.js';
7
8
  import { killTree } from './scope.js';
8
9
  import { holdTranscription, transcriptionReport } from './transcription.js';
9
10
  import { KIT_WIRE } from './wire.js';
11
+ // Two quiet seconds let a fresh conversation start before background model discovery competes for its CPU.
12
+ const MODEL_PROBE_QUIET_MS = 2_000;
10
13
  const SIGNED_OUT = { signed_in: false, models: [], modes: [] };
11
14
  function select(options, category) {
12
15
  const option = options.find((candidate) => candidate.category === category);
@@ -24,6 +27,22 @@ function causeOf(error) {
24
27
  function logged(error) {
25
28
  process.stderr.write(`kit: ${causeOf(error)}\n`);
26
29
  }
30
+ const LAPTOP_CHASSIS = new Set(['8', '9', '10', '14', '30', '31', '32']);
31
+ const DESKTOP_CHASSIS = new Set(['3', '4', '5', '6', '7', '15', '16']);
32
+ const SERVER_CHASSIS = new Set(['17', '18', '19', '20', '21', '22', '23', '24']);
33
+ export function chassisForm(value) {
34
+ const chassis = value.trim();
35
+ if (LAPTOP_CHASSIS.has(chassis))
36
+ return 'laptop';
37
+ if (DESKTOP_CHASSIS.has(chassis))
38
+ return 'desktop';
39
+ if (SERVER_CHASSIS.has(chassis))
40
+ return 'server';
41
+ return undefined;
42
+ }
43
+ export function hostVm(version) {
44
+ return /docker desktop|microsoft|wsl|linuxkit/i.test(version);
45
+ }
27
46
  async function models(kind, adapter, known) {
28
47
  const agent = adapter.connection.agent;
29
48
  const opened = await agent.request('session/new', { cwd: kitHome(), mcpServers: [] });
@@ -122,6 +141,22 @@ async function operatingSystem() {
122
141
  const release = await readFile('/etc/os-release', 'utf8');
123
142
  return /^PRETTY_NAME="?([^"\n]*)"?$/m.exec(release)?.[1] ?? release;
124
143
  }
144
+ async function hostForm() {
145
+ if (process.platform === 'darwin') {
146
+ const battery = await run('pmset', ['-g', 'batt'], 10_000);
147
+ return battery.status === 0 && battery.output.includes('InternalBattery') ? 'laptop' : 'desktop';
148
+ }
149
+ if (process.platform !== 'linux')
150
+ return undefined;
151
+ const [container, version, chassis] = await Promise.all([
152
+ readFile('/.dockerenv', 'utf8').then(() => true).catch(() => false),
153
+ readFile('/proc/version', 'utf8').catch(() => ''),
154
+ readFile('/sys/class/dmi/id/chassis_type', 'utf8').catch(() => ''),
155
+ ]);
156
+ if (container && hostVm(version))
157
+ return undefined;
158
+ return chassisForm(chassis);
159
+ }
125
160
  export class Agents {
126
161
  desired = { agents: [], routes: [], transcribe: false };
127
162
  house;
@@ -130,6 +165,7 @@ export class Agents {
130
165
  installing = Promise.resolve();
131
166
  readings = new Map();
132
167
  reads = new Map();
168
+ starts = 0;
133
169
  sending = Promise.resolve();
134
170
  sent = null;
135
171
  refreshing = 0;
@@ -172,6 +208,7 @@ export class Agents {
172
208
  return reading.then(() => undefined);
173
209
  }
174
210
  cli(kind) {
211
+ this.starts += 1;
175
212
  return this.queue(kind, async () => {
176
213
  const resolved = await this.resolve(kind);
177
214
  if (!('cli' in resolved)) {
@@ -185,7 +222,7 @@ export class Agents {
185
222
  this.update(kind, { release, failure: null, signed_in: kept.signed_in, models: kept.models, modes: kept.modes });
186
223
  }
187
224
  const read = this.nextRead(kind);
188
- offer(kind, cli, kept)
225
+ this.quietOffer(kind, cli, kept)
189
226
  .then((offered) => {
190
227
  const current = this.readings.get(kind);
191
228
  if (this.reads.get(kind) === read && current?.release === release)
@@ -272,11 +309,19 @@ export class Agents {
272
309
  if (this.reads.get(kind) === current && !signal?.aborted)
273
310
  this.readings.set(kind, reading);
274
311
  }
312
+ async quietOffer(kind, cli, known) {
313
+ for (let seen = -1; seen !== this.starts;) {
314
+ seen = this.starts;
315
+ await delay(MODEL_PROBE_QUIET_MS);
316
+ }
317
+ return offer(kind, cli, known);
318
+ }
275
319
  async load(kind) {
276
320
  const known = this.readings.get(kind);
277
321
  if (known !== undefined && known.failure === null && known.minimum === undefined)
278
322
  return;
279
- await this.examine(kind, SIGNED_OUT, offer);
323
+ await this.examine(kind, SIGNED_OUT, (kind, cli, known) => this.quietOffer(kind, cli, known));
324
+ await this.report();
280
325
  }
281
326
  async send() {
282
327
  const agents = this.desired.agents.flatMap((kind) => {
@@ -284,8 +329,10 @@ export class Agents {
284
329
  return reading === undefined ? [] : [reported(kind, reading)];
285
330
  });
286
331
  const hostKey = await sshHostKey();
332
+ const form = await hostForm();
287
333
  const body = {
288
334
  os: await operatingSystem(),
335
+ ...(form === undefined ? {} : { form }),
289
336
  kit_version: KIT_VERSION,
290
337
  wire: KIT_WIRE,
291
338
  updates_itself: await updatesItself(),
@@ -1,23 +1,23 @@
1
1
  {
2
2
  "schemaVersion": 2,
3
- "version": "0.2.1-c3fc787e93f0e",
3
+ "version": "0.2.1-c4823db4ff116",
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-c3fc787e93f0e/connect-linux.sh"
8
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c4823db4ff116/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-c3fc787e93f0e/connect-linux.sh"
14
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c4823db4ff116/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-c3fc787e93f0e/connect-windows.ps1"
20
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c4823db4ff116/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,10 +18,15 @@ 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
25
  const relay = process.env.HOUSE_KIT_RELAY || undefined;
24
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`));
28
+ if (before !== null && before.credential !== values.key) {
29
+ process.stdout.write('This replaced the key this Kit home held; give each session its own HOUSE_KIT_HOME to keep its own key.\n');
30
+ }
25
31
  process.stdout.write(`house now calls ${house} as you, with the key kept in ${kitHome()}.\n`);
26
32
  }
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
  }
@@ -6,7 +6,7 @@ import { unlessAborted } from './abort.js';
6
6
  import { startAdapter } from './acp.js';
7
7
  import { openBridge } from './bridge.js';
8
8
  import { CLIS } from './clis.js';
9
- import { readerFor } from './events.js';
9
+ import { answeredFailure, readerFor } from './events.js';
10
10
  import { placeFiles, uploadBytes } from './files.js';
11
11
  import { agentBase } from './home.js';
12
12
  import { instructions } from './instructions.js';
@@ -17,6 +17,15 @@ 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 REFUSED = 'the CLI refused the prompt';
21
+ const EXIT_PLAN_MODE = {
22
+ parse(value) {
23
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
24
+ throw new Error('_x.ai/exit_plan_mode needs an object');
25
+ }
26
+ return value;
27
+ },
28
+ };
20
29
  export const CONVERSATION_INPUTS = new Set(['open', 'message', 'interrupt', 'kill', 'option', 'answer']);
21
30
  function causeOf(error) {
22
31
  return error instanceof Error ? error.message : String(error);
@@ -348,7 +357,8 @@ export class Conversations {
348
357
  reader.session = sessionId;
349
358
  const app = client({ name: '@agentshouse/kit' })
350
359
  .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));
360
+ .onRequest('elicitation/create', ({ params, signal }) => this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
361
+ .onRequest('_x.ai/exit_plan_mode', EXIT_PLAN_MODE, ({ params, signal }) => this.ask(conversation, '_x.ai/exit_plan_mode', params, false, signal));
352
362
  const cli = await unlessAborted(this.kit.agents.cli(route.kind), conversation.killed.signal);
353
363
  const bridge = await openBridge(this.kit.house, this.kit.copies, conversation.id, conversation.killed.signal);
354
364
  if (conversation.kills > 0) {
@@ -491,13 +501,15 @@ export class Conversations {
491
501
  this.kit.changed();
492
502
  return turn;
493
503
  }
494
- end(conversation, turn, failed) {
504
+ end(conversation, turn, failed, notice = null) {
495
505
  if (turn.ended)
496
506
  return;
497
507
  if (conversation.turn === turn) {
498
508
  for (const event of conversation.running?.reader.closeTurn() ?? [])
499
509
  this.apply(conversation, turn, event);
500
510
  }
511
+ if (notice !== null)
512
+ turn.parts.start({ type: 'marker', marker: 'retry', text: notice });
501
513
  turn.ended = true;
502
514
  conversation.open--;
503
515
  if (conversation.turn === turn)
@@ -515,7 +527,11 @@ export class Conversations {
515
527
  const running = conversation.running;
516
528
  const turn = this.begin(conversation);
517
529
  turn.prompted = true;
518
- running.adapter.connection.agent.request('session/prompt', { sessionId: running.sessionId, prompt }).then(() => this.end(conversation, turn, null), async (error) => {
530
+ running.adapter.connection.agent.request('session/prompt', { sessionId: running.sessionId, prompt }).then((answer) => {
531
+ const notice = answeredFailure(answer);
532
+ const failed = notice ?? (answer.stopReason === 'refusal' ? REFUSED : null);
533
+ this.end(conversation, turn, failed === null ? null : { failed }, notice);
534
+ }, async (error) => {
519
535
  if (running.adapter.connection.signal.aborted) {
520
536
  this.end(conversation, turn, { failed: running.killed ? KILLED : await running.adapter.exited });
521
537
  }
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
  }
@@ -261,7 +264,7 @@ export class LocalCopies {
261
264
  }
262
265
  catch (error) {
263
266
  refused = true;
264
- said.push(error instanceof HouseRefusal ? (refusalOf(error.text)?.text ?? causeOf(error)) : causeOf(error));
267
+ said.push(houseCause(error));
265
268
  }
266
269
  }
267
270
  return { refused, text: said.length === 0 ? 'Nothing new from House.' : said.join('\n') };
@@ -549,7 +552,7 @@ export class LocalCopies {
549
552
  changes = await this.derived(copy, base, commit);
550
553
  }
551
554
  catch (error) {
552
- return { refused: true, text: causeOf(error) };
555
+ return { refused: true, text: houseCause(error) };
553
556
  }
554
557
  if (changes.length === 0)
555
558
  return { refused: false, text: `Nothing to submit: ${short(commit)} matches House.` };
@@ -576,12 +579,17 @@ export class LocalCopies {
576
579
  const after = await tree(copy.repository, commit);
577
580
  const moved = movedPaths(copy.moves, before, after);
578
581
  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));
582
+ const arriving = [...after].filter(([path, entry]) => before.get(path) !== entry);
583
+ if (arriving.length > 0) {
584
+ const { bounds } = await this.house.post('/kit/door/discover', { prefixes: [root] });
585
+ const binary = [];
586
+ for (const [path, entry] of arriving) {
587
+ if (!(await isText(copy.repository, entry, bounds.max_authored_file_bytes)))
588
+ binary.push(path);
589
+ }
590
+ if (binary.length > 0)
591
+ throw new Error(textOnly(binary));
592
+ }
585
593
  const text = (entry) => blobText(copy.repository, entry);
586
594
  const changes = [];
587
595
  for (const path of [...new Set([...before.keys(), ...after.keys()])].sort()) {
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,3 +1,4 @@
1
+ import { randomUUID } from 'node:crypto';
1
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
4
  import { homedir, tmpdir } from 'node:os';
@@ -63,7 +64,7 @@ export async function readHome(name) {
63
64
  export async function writeHome(name, value) {
64
65
  const home = kitHome();
65
66
  await mkdir(home, { recursive: true, mode: 0o700 });
66
- const temporary = join(home, `${name}.${process.pid}`);
67
+ const temporary = join(home, `${name}.${randomUUID()}`);
67
68
  await writeFile(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600 });
68
69
  await rename(temporary, join(home, name));
69
70
  }
@@ -80,6 +81,9 @@ export async function writeEnrolment(enrolment) {
80
81
  export function readDisconnected() {
81
82
  return readHome(DISCONNECTED);
82
83
  }
84
+ export function forgetDisconnected() {
85
+ return rm(join(kitHome(), DISCONNECTED), { force: true });
86
+ }
83
87
  export async function forgetEnrolment({ house, environment }) {
84
88
  await writeHome(DISCONNECTED, { house, environment });
85
89
  await rm(join(kitHome(), ENROLMENT), { force: true });
@@ -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 { kitHome, 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 ? join(kitHome(), 'owner.sock') : 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 ?? join(kitHome(), 'owner.sock')));
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
+ });