@agentshouse/kit 0.2.1-cd646adba3f64 → 0.2.1-cdc381ebf021f

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 (141) hide show
  1. package/README.md +42 -48
  2. package/dist/acp.js +102 -108
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +227 -68
  5. package/dist/api.js +19 -10
  6. package/dist/app-git.js +10 -26
  7. package/dist/bridge.js +18 -47
  8. package/dist/building.js +50 -0
  9. package/dist/calls.js +88 -0
  10. package/dist/chunks.js +49 -0
  11. package/dist/clis.js +157 -100
  12. package/dist/codex-main.js +58 -0
  13. package/dist/connect.js +108 -0
  14. package/dist/connection.js +120 -0
  15. package/dist/content.js +106 -0
  16. package/dist/conversations.js +815 -335
  17. package/dist/copies.js +439 -232
  18. package/dist/earlier.js +263 -0
  19. package/dist/end.js +23 -5
  20. package/dist/events.js +793 -0
  21. package/dist/files.js +139 -17
  22. package/dist/git.js +57 -21
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +122 -8
  25. package/dist/house-cli.js +359 -0
  26. package/dist/house-main.js +7 -159
  27. package/dist/instructions.js +7 -11
  28. package/dist/kit-cli.js +78 -0
  29. package/dist/kit-main.js +8 -22
  30. package/dist/login.js +132 -107
  31. package/dist/logout.js +15 -17
  32. package/dist/mcp.js +6 -2
  33. package/dist/owner.js +46 -0
  34. package/dist/placement.js +25 -0
  35. package/dist/relay.js +33 -2
  36. package/dist/resident.js +160 -58
  37. package/dist/scope.js +214 -0
  38. package/dist/scripts.js +303 -0
  39. package/dist/secret-input.js +1 -1
  40. package/dist/settings.js +188 -0
  41. package/dist/sign-in.js +40 -33
  42. package/dist/silence.js +28 -0
  43. package/dist/skills.js +49 -35
  44. package/dist/supervisor.js +163 -0
  45. package/dist/transcription.js +90 -47
  46. package/dist/translate.js +19 -16
  47. package/dist/update.js +119 -102
  48. package/dist/wire.js +32 -0
  49. package/dist/work.js +353 -0
  50. package/dist/workspace.js +103 -0
  51. package/package.json +25 -21
  52. package/dist/authority-main.js +0 -22
  53. package/dist/blocks.js +0 -51
  54. package/dist/bootstrap.json +0 -24
  55. package/dist/clis-main.js +0 -23
  56. package/dist/configure-main.js +0 -6
  57. package/dist/enrol-main.js +0 -4
  58. package/dist/stream.js +0 -72
  59. package/how-we-work.md +0 -23
  60. package/skills/ask-matt/LICENSE +0 -21
  61. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  62. package/skills/ask-matt/SKILL.md +0 -91
  63. package/skills/ask-matt/agents/openai.yaml +0 -4
  64. package/skills/code-review/LICENSE +0 -21
  65. package/skills/code-review/SKILL.md +0 -89
  66. package/skills/code-review/agents/openai.yaml +0 -3
  67. package/skills/codebase-design/DEEPENING.md +0 -37
  68. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  69. package/skills/codebase-design/LICENSE +0 -21
  70. package/skills/codebase-design/SKILL.md +0 -116
  71. package/skills/codebase-design/agents/openai.yaml +0 -3
  72. package/skills/diagnosing-bugs/LICENSE +0 -21
  73. package/skills/diagnosing-bugs/SKILL.md +0 -140
  74. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  75. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  76. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  77. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  78. package/skills/domain-modeling/LICENSE +0 -21
  79. package/skills/domain-modeling/SKILL.md +0 -76
  80. package/skills/domain-modeling/agents/openai.yaml +0 -3
  81. package/skills/grill-me/LICENSE +0 -21
  82. package/skills/grill-me/SKILL.md +0 -8
  83. package/skills/grill-me/agents/openai.yaml +0 -4
  84. package/skills/grill-with-docs/LICENSE +0 -21
  85. package/skills/grill-with-docs/SKILL.md +0 -8
  86. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  87. package/skills/grilling/LICENSE +0 -21
  88. package/skills/grilling/SKILL.md +0 -30
  89. package/skills/grilling/agents/openai.yaml +0 -3
  90. package/skills/handoff/LICENSE +0 -21
  91. package/skills/handoff/SKILL.md +0 -17
  92. package/skills/handoff/agents/openai.yaml +0 -4
  93. package/skills/implement/LICENSE +0 -21
  94. package/skills/implement/SKILL.md +0 -16
  95. package/skills/implement/agents/openai.yaml +0 -4
  96. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  97. package/skills/improve-codebase-architecture/LICENSE +0 -21
  98. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  99. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  100. package/skills/prototype/LICENSE +0 -21
  101. package/skills/prototype/LOGIC.md +0 -67
  102. package/skills/prototype/SKILL.md +0 -28
  103. package/skills/prototype/UI.md +0 -112
  104. package/skills/prototype/agents/openai.yaml +0 -3
  105. package/skills/research/LICENSE +0 -21
  106. package/skills/research/SKILL.md +0 -14
  107. package/skills/research/agents/openai.yaml +0 -3
  108. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  109. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  110. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  111. package/skills/tdd/LICENSE +0 -21
  112. package/skills/tdd/SKILL.md +0 -40
  113. package/skills/tdd/agents/openai.yaml +0 -3
  114. package/skills/tdd/mocking.md +0 -59
  115. package/skills/tdd/tests.md +0 -77
  116. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  117. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  118. package/skills/teach/LICENSE +0 -21
  119. package/skills/teach/MISSION-FORMAT.md +0 -31
  120. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  121. package/skills/teach/SKILL.md +0 -141
  122. package/skills/teach/agents/openai.yaml +0 -4
  123. package/skills/to-questionnaire/LICENSE +0 -21
  124. package/skills/to-questionnaire/SKILL.md +0 -55
  125. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  126. package/skills/to-spec/LICENSE +0 -21
  127. package/skills/to-spec/SKILL.md +0 -76
  128. package/skills/to-spec/agents/openai.yaml +0 -4
  129. package/skills/to-tickets/LICENSE +0 -21
  130. package/skills/to-tickets/SKILL.md +0 -106
  131. package/skills/to-tickets/agents/openai.yaml +0 -4
  132. package/skills/wait-what/LICENSE +0 -21
  133. package/skills/wait-what/SKILL.md +0 -8
  134. package/skills/wait-what/agents/openai.yaml +0 -4
  135. package/skills/wayfinder/LICENSE +0 -21
  136. package/skills/wayfinder/SKILL.md +0 -129
  137. package/skills/wayfinder/agents/openai.yaml +0 -4
  138. package/skills/writing-for-agents/LICENSE +0 -21
  139. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  140. package/skills/writing-for-agents/SKILL.md +0 -83
  141. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/files.js CHANGED
@@ -1,22 +1,144 @@
1
- import { mkdir, writeFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { createWriteStream } from 'node:fs';
3
+ import { mkdir, rename, rm } from 'node:fs/promises';
4
+ import { basename, dirname, join } from 'node:path';
5
+ import { Readable, Transform } from 'node:stream';
6
+ import { pipeline } from 'node:stream/promises';
7
+ import { parseDocument } from 'yaml';
8
+ import { retryDelay } from './api.js';
9
+ import { Unsettled } from './mcp.js';
3
10
  import { relayed } from './relay.js';
4
- export async function placeFiles(house, directory, files, signal) {
5
- const paths = [];
6
- for (const file of files) {
7
- const original = await house.post('/kit/conversation/originals/get', { version: file.version, download: true }, signal);
8
- const answer = await fetch(relayed(original.download.url), { signal });
9
- if (!answer.ok)
10
- throw new Error(`${file.name} did not download: ${answer.status}`);
11
- const folder = join(directory, '.house', 'files', original.message, file.version);
12
- await mkdir(join(directory, '.house')).catch((error) => {
13
- if (error.code !== 'EEXIST')
11
+ const STALLED_ROUNDS = 8;
12
+ const PART_CHECKSUM = 'x-amz-checksum-sha256';
13
+ const LINK = /\]\((\/rooms\/[^/)\s]+\/[^)\s]+)\)/gu;
14
+ export function linkedPaths(text) {
15
+ return [...new Set(Array.from(text.matchAll(LINK), (link) => link[1]))];
16
+ }
17
+ export function inspectedFile(answer) {
18
+ const document = parseDocument(answer);
19
+ if (document.errors.length > 0)
20
+ return null;
21
+ const inspected = document.toJS();
22
+ if (typeof inspected?.download !== 'string')
23
+ return null;
24
+ return {
25
+ download: inspected.download,
26
+ sha256: String(inspected.sha256),
27
+ media_type: typeof inspected.media_type === 'string' ? inspected.media_type : null,
28
+ };
29
+ }
30
+ export function paused(milliseconds) {
31
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
32
+ }
33
+ export function storeRefusal(act, status) {
34
+ return new Error(`the ${act} answered ${status}; ${act} the file again`);
35
+ }
36
+ async function partDigests(uploading, partBytes) {
37
+ const whole = createHash('sha256');
38
+ const digests = [];
39
+ for (let start = 0; digests.length === 0 || start < uploading.bytes; start += partBytes) {
40
+ const end = Math.min(start + partBytes, uploading.bytes);
41
+ const digest = createHash('sha256');
42
+ for await (const chunk of uploading.read(start, end)) {
43
+ digest.update(chunk);
44
+ whole.update(chunk);
45
+ }
46
+ digests.push(digest.digest());
47
+ }
48
+ if (whole.digest('hex') !== uploading.sha256)
49
+ throw new Error(`${uploading.name} changed while it was uploaded; upload it again`);
50
+ return digests;
51
+ }
52
+ export async function uploaded(declared, uploading) {
53
+ const partBytes = declared.part_bytes;
54
+ const digests = await partDigests(uploading, partBytes);
55
+ const partSha256 = digests.map((digest) => digest.toString('hex'));
56
+ let answer = await finishing(uploading, declared.id, partSha256);
57
+ let idle = 0;
58
+ let stalled = 0;
59
+ while ('upload' in answer) {
60
+ const { id, parts } = answer.upload;
61
+ let sent = 0;
62
+ let failure = null;
63
+ for (const { part, url } of parts ?? []) {
64
+ const start = (part - 1) * partBytes;
65
+ try {
66
+ await uploading.send(url, start, Math.min(start + partBytes, uploading.bytes), {
67
+ [PART_CHECKSUM]: digests[part - 1].toString('base64'),
68
+ });
69
+ sent++;
70
+ }
71
+ catch (error) {
72
+ failure = error;
73
+ break;
74
+ }
75
+ }
76
+ if (sent > 0) {
77
+ idle = 0;
78
+ stalled = 0;
79
+ }
80
+ else {
81
+ if (failure !== null && ++stalled >= STALLED_ROUNDS)
82
+ throw failure;
83
+ // A round that sent no part, its store unreachable, is followed by the next finishing call on the jittered curve.
84
+ await paused(retryDelay(idle++));
85
+ }
86
+ answer = await finishing(uploading, id, partSha256);
87
+ }
88
+ return answer;
89
+ }
90
+ async function finishing(uploading, upload, partSha256) {
91
+ for (let unsettled = 1;; unsettled++) {
92
+ try {
93
+ return await uploading.finish(upload, partSha256);
94
+ }
95
+ catch (error) {
96
+ if (!(error instanceof Unsettled) || unsettled === STALLED_ROUNDS)
14
97
  throw error;
98
+ }
99
+ // A finishing call House did not settle, unreached or refused short of final, is sent again on the jittered curve as a conversation resends it, so a dropped connection or a House restart resumes the upload instead of ending it.
100
+ await paused(retryDelay(unsettled - 1));
101
+ }
102
+ }
103
+ async function drained(body) {
104
+ for await (const _chunk of body)
105
+ ;
106
+ }
107
+ export async function downloaded(address, fetching, destination, name) {
108
+ for (let asked = 1;; asked++) {
109
+ const { download, sha256 } = await address();
110
+ const answer = await fetching(download);
111
+ if (answer.status === 403 && asked === 1) {
112
+ await drained(answer.body);
113
+ continue;
114
+ }
115
+ if (answer.status !== 200) {
116
+ await drained(answer.body);
117
+ throw storeRefusal('download', answer.status);
118
+ }
119
+ await mkdir(dirname(destination), { recursive: true });
120
+ const partial = join(dirname(destination), `.${basename(destination)}.${randomUUID()}`);
121
+ const digest = createHash('sha256');
122
+ const hashed = new Transform({
123
+ transform(chunk, _encoding, done) {
124
+ digest.update(chunk);
125
+ done(null, chunk);
126
+ },
15
127
  });
16
- await mkdir(folder, { recursive: true });
17
- const path = join(folder, file.name);
18
- await writeFile(path, Buffer.from(await answer.arrayBuffer()));
19
- paths.push(path);
128
+ try {
129
+ await pipeline(answer.body, hashed, createWriteStream(partial, { flags: 'wx' }));
130
+ if (digest.digest('hex') !== sha256)
131
+ throw new Error(`${name} did not arrive whole; download it again`);
132
+ await rename(partial, destination);
133
+ }
134
+ catch (error) {
135
+ await rm(partial, { force: true });
136
+ throw error;
137
+ }
138
+ return;
20
139
  }
21
- return paths;
140
+ }
141
+ export async function fetched(url, signal) {
142
+ const answer = await fetch(relayed(url), { signal });
143
+ return { status: answer.status, body: answer.body === null ? Readable.from([]) : Readable.fromWeb(answer.body) };
22
144
  }
package/dist/git.js CHANGED
@@ -1,16 +1,17 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { isUtf8 } from 'node:buffer';
2
3
  import { createHash } from 'node:crypto';
3
4
  import { join } from 'node:path';
4
- import { withoutProxy } from './clis.js';
5
5
  import { workspaceRoot } from './home.js';
6
+ import { childEnvironment } from './relay.js';
6
7
  export function localCopies() {
7
8
  return join(workspaceRoot(), 'local-copies');
8
9
  }
9
10
  export const HOUSE_REF = 'refs/house/received';
10
- const COMMITTER = 'House Kit <house-kit@localhost>';
11
+ const COMMITTER = 'Kit <house-kit@localhost>';
11
12
  export function run(cwd, args, input, env = {}) {
12
13
  return new Promise((resolve, reject) => {
13
- const child = spawn('git', args, { cwd, env: { ...withoutProxy(), ...env } });
14
+ const child = spawn('git', args, { cwd, env: { ...childEnvironment(), ...env } });
14
15
  const stdout = [];
15
16
  let stderr = '';
16
17
  child.stdout.on('data', (chunk) => stdout.push(chunk));
@@ -48,14 +49,15 @@ export async function tree(repository, commit) {
48
49
  }
49
50
  return entries;
50
51
  }
51
- export async function blobText(repository, object, path) {
52
- const bytes = (await run(repository, ['cat-file', 'blob', object])).stdout;
53
- try {
54
- return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
55
- }
56
- catch {
57
- throw new Error(`${path} is binary and House stores only text; remove it from the commit`);
58
- }
52
+ async function blob(repository, object) {
53
+ return (await run(repository, ['cat-file', 'blob', object])).stdout;
54
+ }
55
+ export async function blobText(repository, object) {
56
+ return (await blob(repository, object)).toString('utf8');
57
+ }
58
+ export async function isText(repository, object, maxBytes) {
59
+ const bytes = await blob(repository, object);
60
+ return bytes.length <= maxBytes && isUtf8(bytes) && !bytes.includes(0);
59
61
  }
60
62
  export function blobId(content) {
61
63
  const bytes = Buffer.from(content, 'utf8');
@@ -68,18 +70,52 @@ function data(text) {
68
70
  const bytes = Buffer.from(text, 'utf8');
69
71
  return [Buffer.from(`data ${bytes.length}\n`), bytes, Buffer.from('\n')];
70
72
  }
71
- export async function importCommits(repository, commits) {
72
- const stream = [];
73
+ function written(stream, bytes) {
74
+ return new Promise((resolve, reject) => {
75
+ stream.write(bytes, (error) => (error ? reject(error) : resolve()));
76
+ });
77
+ }
78
+ async function imported(stream, commits) {
79
+ await written(stream, Buffer.from('feature done\n'));
73
80
  for (const [index, commit] of commits.entries()) {
74
- stream.push(Buffer.from(`commit ${HOUSE_REF}\nmark :${index + 1}\ncommitter ${COMMITTER} ${Math.floor(Date.now() / 1000)} +0000\n`), ...data(commit.message), ...(commit.from === null ? [] : [Buffer.from(`from ${commit.from}\n`)]), ...(commit.merge === undefined ? [] : [Buffer.from(`merge ${commit.merge}\n`)]), ...(commit.replaces === true ? [Buffer.from('deleteall\n')] : []));
75
- for (const [path, content] of commit.files) {
76
- if (content === null)
77
- stream.push(Buffer.from(`D ${quoted(path)}\n`));
78
- else
79
- stream.push(Buffer.from(`M 100644 inline ${quoted(path)}\n`), ...data(content));
81
+ await written(stream, Buffer.concat([
82
+ Buffer.from(`commit ${HOUSE_REF}\nmark :${index + 1}\ncommitter ${COMMITTER} ${Math.floor(Date.now() / 1000)} +0000\n`),
83
+ ...data(commit.message),
84
+ ...(commit.from === null ? [] : [Buffer.from(`from ${commit.from}\n`)]),
85
+ ...(commit.merge === undefined ? [] : [Buffer.from(`merge ${commit.merge}\n`)]),
86
+ ...(commit.replaces === true ? [Buffer.from('deleteall\n')] : []),
87
+ ]));
88
+ for await (const [path, content] of commit.files) {
89
+ await written(stream, content === null
90
+ ? Buffer.from(`D ${quoted(path)}\n`)
91
+ : Buffer.concat([Buffer.from(`M 100644 inline ${quoted(path)}\n`), ...data(content)]));
80
92
  }
81
- stream.push(Buffer.from('\n'));
93
+ await written(stream, Buffer.from('\n'));
94
+ }
95
+ await written(stream, Buffer.from('done\n'));
96
+ }
97
+ export async function importCommits(repository, commits) {
98
+ const child = spawn('git', ['fast-import', '--quiet', '--force'], { cwd: repository, env: childEnvironment() });
99
+ let stderr = '';
100
+ child.stdout.resume();
101
+ child.stderr.on('data', (chunk) => {
102
+ stderr += chunk.toString('utf8');
103
+ });
104
+ child.stdin.on('error', () => undefined);
105
+ const closed = new Promise((resolve, reject) => {
106
+ child.on('error', reject);
107
+ child.on('close', resolve);
108
+ });
109
+ try {
110
+ await imported(child.stdin, commits);
111
+ child.stdin.end();
112
+ }
113
+ catch (error) {
114
+ child.stdin.destroy();
115
+ await closed;
116
+ throw error.code === 'EPIPE' ? new Error(`git fast-import failed: ${stderr.trim()}`) : error;
82
117
  }
83
- await git(repository, ['fast-import', '--quiet', '--force'], Buffer.concat(stream));
118
+ if ((await closed) !== 0)
119
+ throw new Error(`git fast-import failed: ${stderr.trim()}`);
84
120
  return revision(repository, HOUSE_REF);
85
121
  }
package/dist/grok.js ADDED
@@ -0,0 +1,39 @@
1
+ const PLAN = 'plan';
2
+ const PLAN_ABANDONED = 'abandoned';
3
+ const PLAN_FIELD = {
4
+ type: 'string',
5
+ title: 'Approve this plan?',
6
+ oneOf: [
7
+ { const: 'approved', title: 'Approve' },
8
+ { const: PLAN_ABANDONED, title: 'Abandon' },
9
+ ],
10
+ };
11
+ function form(sessionId, message, properties) {
12
+ return { mode: 'form', sessionId, message, requestedSchema: { type: 'object', properties } };
13
+ }
14
+ function questionField({ options, multiSelect }, title) {
15
+ const choices = options.map(({ label, description }) => ({ const: label, title: label, description }));
16
+ return multiSelect === true ? { type: 'array', title, items: { anyOf: choices } } : { type: 'string', title, oneOf: choices };
17
+ }
18
+ export function grokQuestionForm({ sessionId, questions }) {
19
+ const lone = questions.length === 1;
20
+ return form(sessionId, questions.map(({ question }) => question).join('\n\n'), Object.fromEntries(questions.map((one) => [one.question, questionField(one, lone ? 'Answer' : one.question)])));
21
+ }
22
+ function answerText(value) {
23
+ return Array.isArray(value) ? value.join(', ') : String(value);
24
+ }
25
+ function contentOf(response) {
26
+ return response.action === 'accept' ? (response.content ?? {}) : {};
27
+ }
28
+ export function grokQuestionAnswer(response) {
29
+ if (response.action !== 'accept')
30
+ return { outcome: 'cancelled' };
31
+ const answers = Object.entries(contentOf(response)).map(([question, value]) => [question, answerText(value)]);
32
+ return { outcome: 'accepted', answers: Object.fromEntries(answers) };
33
+ }
34
+ export function grokPlanForm({ sessionId, planContent }) {
35
+ return form(sessionId, planContent, { [PLAN]: PLAN_FIELD });
36
+ }
37
+ export function grokPlanAnswer(response) {
38
+ return { outcome: contentOf(response)[PLAN] ?? PLAN_ABANDONED };
39
+ }
package/dist/home.js CHANGED
@@ -1,16 +1,82 @@
1
- import { existsSync } from 'node:fs';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync } from 'node:fs';
2
3
  import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
4
  import { homedir } from 'node:os';
4
- import { join } from 'node:path';
5
+ import { join, resolve } from 'node:path';
6
+ import { selectRelay } from './relay.js';
5
7
  const ENROLMENT = 'credential.json';
6
8
  const DISCONNECTED = 'disconnected.json';
7
9
  const CONFIGURATION = 'kit.json';
8
10
  const OWN_AGENT = 'own-agent.json';
11
+ const EARLIER_PREFIXES = ['/kit-home/kit', '/opt/house-kit'];
12
+ function privateDirectory(path) {
13
+ try {
14
+ mkdirSync(path, { mode: 0o700 });
15
+ }
16
+ catch (error) {
17
+ if (error.code !== 'EEXIST')
18
+ throw error;
19
+ }
20
+ const found = lstatSync(path);
21
+ if (found.isSymbolicLink())
22
+ throw new Error(`${path} is a symbolic link`);
23
+ if (!found.isDirectory())
24
+ throw new Error(`${path} is not a directory`);
25
+ if (found.uid !== process.geteuid())
26
+ throw new Error(`${path} is not owned by this User`);
27
+ chmodSync(path, 0o700);
28
+ return path;
29
+ }
30
+ export function oneFolder(account = homedir()) {
31
+ return join(account, '.agents', 'house');
32
+ }
33
+ export function desktopPrefix() {
34
+ return join(homedir(), '.local', 'share', 'house-kit');
35
+ }
36
+ export function earlierPrefix() {
37
+ const prefix = process.env.HOUSE_KIT_PREFIX;
38
+ if (prefix === undefined || prefix === '')
39
+ return null;
40
+ return [...EARLIER_PREFIXES, desktopPrefix()].includes(resolve(prefix)) ? resolve(prefix) : null;
41
+ }
42
+ export function awaitsTakeover() {
43
+ const prefix = earlierPrefix();
44
+ return prefix === EARLIER_PREFIXES[0] || (prefix === EARLIER_PREFIXES[1] && process.getuid() !== 0);
45
+ }
46
+ export function earlierHome() {
47
+ return process.env.HOUSE_KIT_HOME || join(homedir(), '.house-kit');
48
+ }
49
+ export function reinstall() {
50
+ if (!awaitsTakeover())
51
+ return undefined;
52
+ try {
53
+ return readFileSync(join(earlierHome(), 'placement'), 'utf8').trim() === 'windows' ? 'windows' : 'linux';
54
+ }
55
+ catch (error) {
56
+ if (error.code === 'ENOENT')
57
+ return 'linux';
58
+ throw error;
59
+ }
60
+ }
9
61
  export function kitHome() {
10
- return process.env.HOUSE_KIT_HOME ?? join(homedir(), '.house-kit');
62
+ return earlierPrefix() === null ? oneFolder() : earlierHome();
63
+ }
64
+ export function socketDirectory() {
65
+ const sockets = privateDirectory(join(realpathSync('/tmp'), `hk-${process.geteuid()}`));
66
+ const home = kitHome();
67
+ const physical = existsSync(home) ? realpathSync(home) : resolve(home);
68
+ return privateDirectory(join(sockets, createHash('sha256').update(physical).digest('hex').slice(0, 12)));
69
+ }
70
+ export function ownerSocket() {
71
+ return join(socketDirectory(), 'owner.sock');
72
+ }
73
+ export function ownerLock() {
74
+ return join(socketDirectory(), 'owner.lock');
11
75
  }
12
76
  export function workspaceRoot() {
13
- return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
77
+ if (earlierPrefix() !== null)
78
+ return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
79
+ return configuredWorkspace() ?? kitHome();
14
80
  }
15
81
  export function agentBase() {
16
82
  return join(workspaceRoot(), 'agents');
@@ -28,12 +94,15 @@ export async function readHome(name) {
28
94
  export async function writeHome(name, value) {
29
95
  const home = kitHome();
30
96
  await mkdir(home, { recursive: true, mode: 0o700 });
31
- const temporary = join(home, `${name}.${process.pid}`);
97
+ const temporary = join(home, `${name}.${randomUUID()}`);
32
98
  await writeFile(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600 });
33
99
  await rename(temporary, join(home, name));
34
100
  }
35
- export function readEnrolment() {
36
- return readHome(ENROLMENT);
101
+ export async function readEnrolment() {
102
+ const enrolment = await readHome(ENROLMENT);
103
+ if (enrolment !== null)
104
+ selectRelay(process.env.HOUSE_KIT_RELAY || enrolment.relay);
105
+ return enrolment;
37
106
  }
38
107
  export async function writeEnrolment(enrolment) {
39
108
  await writeHome(ENROLMENT, enrolment);
@@ -42,10 +111,40 @@ export async function writeEnrolment(enrolment) {
42
111
  export function readDisconnected() {
43
112
  return readHome(DISCONNECTED);
44
113
  }
114
+ export function forgetDisconnected() {
115
+ return rm(join(kitHome(), DISCONNECTED), { force: true });
116
+ }
45
117
  export async function forgetEnrolment({ house, environment }) {
46
118
  await writeHome(DISCONNECTED, { house, environment });
47
119
  await rm(join(kitHome(), ENROLMENT), { force: true });
48
120
  }
121
+ export async function forgetRejected(rejected) {
122
+ const held = await readHome(ENROLMENT);
123
+ if (held?.credential !== rejected)
124
+ return;
125
+ await writeHome(DISCONNECTED, { house: held.house, environment: held.environment });
126
+ const enrolment = join(kitHome(), ENROLMENT);
127
+ const taken = `${enrolment}.${process.pid}`;
128
+ try {
129
+ renameSync(enrolment, taken);
130
+ }
131
+ catch (error) {
132
+ if (error.code === 'ENOENT')
133
+ return;
134
+ throw error;
135
+ }
136
+ if (JSON.parse(readFileSync(taken, 'utf8')).credential !== rejected) {
137
+ try {
138
+ linkSync(taken, enrolment);
139
+ }
140
+ catch (error) {
141
+ if (error.code !== 'EEXIST')
142
+ throw error;
143
+ }
144
+ rmSync(join(kitHome(), DISCONNECTED), { force: true });
145
+ }
146
+ rmSync(taken);
147
+ }
49
148
  export function enrolled() {
50
149
  return existsSync(join(kitHome(), ENROLMENT));
51
150
  }
@@ -58,8 +157,23 @@ export function writeOwnAgent(ownAgent) {
58
157
  export function forgetOwnAgent() {
59
158
  return rm(join(kitHome(), OWN_AGENT), { force: true });
60
159
  }
160
+ function configuredWorkspace() {
161
+ try {
162
+ const { workspace } = JSON.parse(readFileSync(join(kitHome(), CONFIGURATION), 'utf8'));
163
+ return workspace;
164
+ }
165
+ catch (error) {
166
+ if (error.code === 'ENOENT')
167
+ return undefined;
168
+ throw error;
169
+ }
170
+ }
61
171
  export async function readConfiguration() {
62
- return { skills: (await readHome(CONFIGURATION))?.skills !== false };
172
+ const stored = await readHome(CONFIGURATION);
173
+ return { skills: stored?.skills !== false, workspace: stored?.workspace ?? kitHome() };
174
+ }
175
+ export async function storedConfiguration() {
176
+ return (await readHome(CONFIGURATION)) ?? {};
63
177
  }
64
178
  export function writeConfiguration(configuration) {
65
179
  return writeHome(CONFIGURATION, configuration);