@agentshouse/kit 0.2.1-ccb257fa8a318 → 0.2.1-ccffb3f637815

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 (57) hide show
  1. package/README.md +27 -31
  2. package/dist/acp.js +17 -10
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +121 -52
  5. package/dist/api.js +11 -6
  6. package/dist/binaries.js +89 -0
  7. package/dist/bridge.js +28 -27
  8. package/dist/building.js +7 -3
  9. package/dist/calls.js +18 -1
  10. package/dist/chunks.js +49 -0
  11. package/dist/clis.js +52 -63
  12. package/dist/connect.js +108 -0
  13. package/dist/connection.js +24 -20
  14. package/dist/content.js +106 -0
  15. package/dist/conversations.js +255 -134
  16. package/dist/copies.js +748 -248
  17. package/dist/earlier.js +263 -0
  18. package/dist/end.js +9 -6
  19. package/dist/events.js +549 -281
  20. package/dist/files.js +77 -11
  21. package/dist/git-main.js +24 -29
  22. package/dist/git.js +87 -12
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +80 -29
  25. package/dist/house-cli.js +106 -123
  26. package/dist/instructions.js +2 -4
  27. package/dist/keys.js +238 -0
  28. package/dist/kit-cli.js +14 -4
  29. package/dist/login.js +34 -20
  30. package/dist/logout.js +2 -2
  31. package/dist/mcp.js +38 -3
  32. package/dist/old-references.js +27 -0
  33. package/dist/owner.js +46 -0
  34. package/dist/placement.js +9 -23
  35. package/dist/refusals.js +37 -21
  36. package/dist/resident.js +107 -72
  37. package/dist/scope.js +12 -4
  38. package/dist/scripts.js +59 -11
  39. package/dist/secret-input.js +1 -1
  40. package/dist/settings.js +188 -0
  41. package/dist/sign-in.js +49 -4
  42. package/dist/supervisor.js +163 -0
  43. package/dist/transcription.js +5 -2
  44. package/dist/translate.js +18 -11
  45. package/dist/update.js +115 -160
  46. package/dist/wire.js +19 -9
  47. package/dist/work.js +27 -2
  48. package/dist/workspace.js +103 -0
  49. package/package.json +13 -8
  50. package/dist/authority-main.js +0 -22
  51. package/dist/chatgpt.js +0 -32
  52. package/dist/clis-main.js +0 -23
  53. package/dist/configure-main.js +0 -6
  54. package/dist/enrol-main.js +0 -10
  55. package/dist/parts.js +0 -82
  56. package/dist/service-main.js +0 -9
  57. package/dist/service.js +0 -55
package/dist/files.js CHANGED
@@ -1,38 +1,104 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { createWriteStream } from 'node:fs';
2
+ import { createReadStream, createWriteStream } from 'node:fs';
3
3
  import { mkdir, rename, rm } from 'node:fs/promises';
4
- import { basename, dirname, join } from 'node:path';
4
+ import { request } from 'node:http';
5
+ import { request as httpsRequest } from 'node:https';
6
+ import { basename, dirname, extname, join } from 'node:path';
5
7
  import { Readable, Transform } from 'node:stream';
6
8
  import { pipeline } from 'node:stream/promises';
7
9
  import { parseDocument } from 'yaml';
8
10
  import { retryDelay } from './api.js';
9
11
  import { Unsettled } from './mcp.js';
10
- import { relayed } from './relay.js';
12
+ import { proxyUnlessRelayed, relayed } from './relay.js';
11
13
  const STALLED_ROUNDS = 8;
12
14
  const PART_CHECKSUM = 'x-amz-checksum-sha256';
13
15
  const LINK = /\]\((\/rooms\/[^/)\s]+\/[^)\s]+)\)/gu;
16
+ const MEDIA_TYPES = new Map([
17
+ ['avif', 'image/avif'],
18
+ ['csv', 'text/csv'],
19
+ ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
20
+ ['gif', 'image/gif'],
21
+ ['heic', 'image/heic'],
22
+ ['html', 'text/html'],
23
+ ['jpeg', 'image/jpeg'],
24
+ ['jpg', 'image/jpeg'],
25
+ ['json', 'application/json'],
26
+ ['m4a', 'audio/mp4'],
27
+ ['md', 'text/markdown'],
28
+ ['mov', 'video/quicktime'],
29
+ ['mp3', 'audio/mpeg'],
30
+ ['mp4', 'video/mp4'],
31
+ ['ogg', 'audio/ogg'],
32
+ ['pdf', 'application/pdf'],
33
+ ['png', 'image/png'],
34
+ ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
35
+ ['svg', 'image/svg+xml'],
36
+ ['txt', 'text/plain'],
37
+ ['wav', 'audio/wav'],
38
+ ['webm', 'video/webm'],
39
+ ['webp', 'image/webp'],
40
+ ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
41
+ ['zip', 'application/zip'],
42
+ ]);
43
+ export function mediaTypeOf(path) {
44
+ return MEDIA_TYPES.get(extname(path).slice(1).toLowerCase());
45
+ }
14
46
  export function linkedPaths(text) {
15
47
  return [...new Set(Array.from(text.matchAll(LINK), (link) => link[1]))];
16
48
  }
17
- export function inspectedFile(answer) {
49
+ export function fileInfo(answer) {
18
50
  const document = parseDocument(answer);
19
51
  if (document.errors.length > 0)
20
52
  return null;
21
- const inspected = document.toJS();
22
- if (typeof inspected?.download !== 'string')
53
+ const details = document.toJS();
54
+ if (typeof details?.download !== 'string')
23
55
  return null;
24
56
  return {
25
- download: inspected.download,
26
- sha256: String(inspected.sha256),
27
- media_type: typeof inspected.media_type === 'string' ? inspected.media_type : null,
57
+ download: details.download,
58
+ sha256: String(details.sha256),
59
+ revision: String(details.revision),
60
+ bytes: Number(details.bytes),
61
+ media_type: typeof details.media_type === 'string' ? details.media_type : null,
28
62
  };
29
63
  }
30
- function paused(milliseconds) {
64
+ export function paused(milliseconds) {
31
65
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
32
66
  }
33
67
  export function storeRefusal(act, status) {
34
68
  return new Error(`the ${act} answered ${status}; ${act} the file again`);
35
69
  }
70
+ export function opened(url, method, headers, way, body) {
71
+ return new Promise((answered, failed) => {
72
+ const target = way.socketPath === undefined ? relayed(url) : null;
73
+ if (target !== null)
74
+ proxyUnlessRelayed();
75
+ const sent = target === null
76
+ ? request({ socketPath: way.socketPath, path: url, method, headers }, answered)
77
+ : (target.protocol === 'https:' ? httpsRequest : request)(target, { method, headers }, answered);
78
+ sent.on('error', (error) => failed(way.unreached(error)));
79
+ if (body === undefined)
80
+ sent.end();
81
+ else
82
+ pipeline(body, sent).catch(() => undefined);
83
+ });
84
+ }
85
+ function ranged(file, start, end) {
86
+ return end === start ? undefined : createReadStream(file, { start, end: end - 1 });
87
+ }
88
+ export async function* fileRange(file, start, end, unreadable) {
89
+ try {
90
+ yield* ranged(file, start, end) ?? [];
91
+ }
92
+ catch (error) {
93
+ throw unreadable(error);
94
+ }
95
+ }
96
+ export async function sentPart(url, file, start, end, headers, way) {
97
+ const answer = await opened(url, 'PUT', { ...headers, 'content-length': String(end - start) }, way, ranged(file, start, end));
98
+ await answer.toArray();
99
+ if (answer.statusCode !== 200)
100
+ throw way.refused(answer.statusCode);
101
+ }
36
102
  async function partDigests(uploading, partBytes) {
37
103
  const whole = createHash('sha256');
38
104
  const digests = [];
@@ -140,5 +206,5 @@ export async function downloaded(address, fetching, destination, name) {
140
206
  }
141
207
  export async function fetched(url, signal) {
142
208
  const answer = await fetch(relayed(url), { signal });
143
- return { status: answer.status, body: answer.body ?? Readable.from([]) };
209
+ return { status: answer.status, body: answer.body === null ? Readable.from([]) : Readable.fromWeb(answer.body) };
144
210
  }
package/dist/git-main.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn, spawnSync } from 'node:child_process';
3
- import { accessSync, constants, realpathSync, statSync } from 'node:fs';
3
+ import { accessSync, constants, mkdtempSync, realpathSync, rmSync, statSync } from 'node:fs';
4
4
  import { request } from 'node:http';
5
5
  import { constants as system } from 'node:os';
6
6
  import { delimiter, dirname, join } from 'node:path';
@@ -52,11 +52,12 @@ function nativeGit() {
52
52
  }
53
53
  return null;
54
54
  }
55
- function captured(git, args) {
55
+ function captured(git, args, { input, index } = {}) {
56
56
  const ran = spawnSync(git, args, {
57
- stdio: ['ignore', 'pipe', 'ignore'],
57
+ input,
58
+ stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'],
58
59
  maxBuffer: Infinity,
59
- env: { ...process.env, LC_ALL: 'C' },
60
+ env: { ...process.env, LC_ALL: 'C', ...(index === undefined ? {} : { GIT_INDEX_FILE: index }) },
60
61
  });
61
62
  return ran.status === 0 ? ran.stdout.toString('utf8') : null;
62
63
  }
@@ -78,30 +79,25 @@ function delegated(git, args) {
78
79
  child.once('close', (status, signal) => settle({ status, signal }));
79
80
  });
80
81
  }
81
- function staged(listing) {
82
- const entries = new Map();
83
- for (const record of (listing ?? '').split('\0')) {
84
- const tab = record.indexOf('\t');
85
- if (tab >= 0)
86
- entries.set(record.slice(tab + 1), record.slice(0, tab).split(' ')[1]);
82
+ function merged(git, copy, common) {
83
+ const staged = (captured(git, [...copy, 'ls-files', '--stage', '-z']) ?? '').split('\0');
84
+ const input = staged.filter((entry) => /^\d+ [0-9a-f]+ 0\t/.test(entry)).map((entry) => `${entry}\0`).join('');
85
+ const scratch = mkdtempSync(join(common, 'house-index-'));
86
+ try {
87
+ const index = join(scratch, 'index');
88
+ captured(git, [...copy, 'update-index', '-z', '--index-info'], { input, index });
89
+ return captured(git, [...copy, 'write-tree'], { index })?.trim();
90
+ }
91
+ finally {
92
+ rmSync(scratch, { recursive: true, force: true });
87
93
  }
88
- return entries;
89
94
  }
90
- function moved(planned, before, after) {
95
+ function moved(git, copy, before) {
96
+ const renames = ['diff-index', '--cached', '-z', '--name-status', '--find-renames=100%', '--diff-filter=R', before];
97
+ const fields = (captured(git, [...copy, ...renames]) ?? '').split('\0');
91
98
  const moves = [];
92
- for (const line of planned.split('\n')) {
93
- if (!line.startsWith('Renaming '))
94
- continue;
95
- const renaming = line.slice('Renaming '.length);
96
- for (let at = renaming.indexOf(' to '); at >= 0; at = renaming.indexOf(' to ', at + 1)) {
97
- const from = renaming.slice(0, at);
98
- const to = renaming.slice(at + 4);
99
- if (before.has(from) && !after.has(from) && after.get(to) === before.get(from)) {
100
- moves.push({ from, to });
101
- break;
102
- }
103
- }
104
- }
99
+ for (let at = 0; at + 2 < fields.length; at += 3)
100
+ moves.push({ from: fields[at + 1], to: fields[at + 2] });
105
101
  return moves;
106
102
  }
107
103
  function reported(socketPath, body) {
@@ -128,11 +124,10 @@ async function observed(git, args) {
128
124
  if (common === undefined || worktree === undefined || !dirname(common).startsWith(`${localCopies()}/`)) {
129
125
  return delegated(git, args);
130
126
  }
131
- const listing = [...globals, '-C', worktree, 'ls-files', '--stage', '-z'];
132
- const before = name === 'mv' ? staged(captured(git, listing)) : null;
133
- const planned = name === 'mv' ? (captured(git, [...globals, 'mv', '--dry-run', ...args.slice(index + 1)]) ?? '') : '';
127
+ const copy = [...globals, '-C', worktree];
128
+ const before = name === 'mv' ? merged(git, copy, common) : undefined;
134
129
  const outcome = await delegated(git, args);
135
- const moves = before !== null && outcome.status === 0 ? moved(planned, before, staged(captured(git, listing))) : [];
130
+ const moves = before !== undefined && outcome.status === 0 ? moved(git, copy, before) : [];
136
131
  await reported(bridge, { common, worktree, moves });
137
132
  return outcome;
138
133
  }
package/dist/git.js CHANGED
@@ -55,11 +55,50 @@ async function blob(repository, object) {
55
55
  export async function blobText(repository, object) {
56
56
  return (await blob(repository, object)).toString('utf8');
57
57
  }
58
- export async function isText(repository, object, maxBytes) {
58
+ export async function blobSizes(repository, objects) {
59
+ if (objects.length === 0)
60
+ return new Map();
61
+ const listed = await git(repository, ['cat-file', '--batch-check=%(objectname) %(objectsize)'], `${[...new Set(objects)].join('\n')}\n`);
62
+ return new Map(listed
63
+ .split('\n')
64
+ .filter((line) => line !== '')
65
+ .map((line) => {
66
+ const [object, size] = line.split(' ');
67
+ return [object, Number(size)];
68
+ }));
69
+ }
70
+ export async function isText(repository, object, size, maxBytes) {
71
+ if (size > maxBytes)
72
+ return false;
59
73
  const bytes = await blob(repository, object);
60
- return bytes.length <= maxBytes && isUtf8(bytes) && !bytes.includes(0);
74
+ return isUtf8(bytes) && !bytes.includes(0);
75
+ }
76
+ export async function* blobBytes(repository, object) {
77
+ const child = spawn('git', ['cat-file', 'blob', object], { cwd: repository, env: childEnvironment(), stdio: ['ignore', 'pipe', 'pipe'] });
78
+ let stderr = '';
79
+ child.stderr.on('data', (chunk) => {
80
+ stderr += chunk.toString('utf8');
81
+ });
82
+ const closed = new Promise((resolve, reject) => {
83
+ child.on('error', reject);
84
+ child.on('close', resolve);
85
+ });
86
+ try {
87
+ yield* child.stdout;
88
+ }
89
+ finally {
90
+ if (child.exitCode === null)
91
+ child.kill();
92
+ }
93
+ if ((await closed) !== 0)
94
+ throw new Error(`git cat-file failed: ${stderr.trim()}`);
95
+ }
96
+ export async function storedFile(repository, file) {
97
+ return (await git(repository, ['hash-object', '-w', '--no-filters', '--', file])).trim();
61
98
  }
62
99
  export function blobId(content) {
100
+ if (typeof content !== 'string')
101
+ return content.blob;
63
102
  const bytes = Buffer.from(content, 'utf8');
64
103
  return createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
65
104
  }
@@ -70,18 +109,54 @@ function data(text) {
70
109
  const bytes = Buffer.from(text, 'utf8');
71
110
  return [Buffer.from(`data ${bytes.length}\n`), bytes, Buffer.from('\n')];
72
111
  }
73
- export async function importCommits(repository, commits) {
74
- const stream = [];
112
+ function written(stream, bytes) {
113
+ return new Promise((resolve, reject) => {
114
+ stream.write(bytes, (error) => (error ? reject(error) : resolve()));
115
+ });
116
+ }
117
+ async function imported(stream, commits) {
118
+ await written(stream, Buffer.from('feature done\n'));
75
119
  for (const [index, commit] of commits.entries()) {
76
- 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')] : []));
77
- for (const [path, content] of commit.files) {
78
- if (content === null)
79
- stream.push(Buffer.from(`D ${quoted(path)}\n`));
80
- else
81
- stream.push(Buffer.from(`M 100644 inline ${quoted(path)}\n`), ...data(content));
120
+ await written(stream, Buffer.concat([
121
+ Buffer.from(`commit ${HOUSE_REF}\nmark :${index + 1}\ncommitter ${COMMITTER} ${Math.floor(Date.now() / 1000)} +0000\n`),
122
+ ...data(commit.message),
123
+ ...(commit.from === null ? [] : [Buffer.from(`from ${commit.from}\n`)]),
124
+ ...(commit.merge === undefined ? [] : [Buffer.from(`merge ${commit.merge}\n`)]),
125
+ ...(commit.replaces === true ? [Buffer.from('deleteall\n')] : []),
126
+ ]));
127
+ for await (const [path, content] of commit.files) {
128
+ await written(stream, content === null
129
+ ? Buffer.from(`D ${quoted(path)}\n`)
130
+ : typeof content === 'string'
131
+ ? Buffer.concat([Buffer.from(`M 100644 inline ${quoted(path)}\n`), ...data(content)])
132
+ : Buffer.from(`M 100644 ${content.blob} ${quoted(path)}\n`));
82
133
  }
83
- stream.push(Buffer.from('\n'));
134
+ await written(stream, Buffer.from('\n'));
135
+ }
136
+ await written(stream, Buffer.from('done\n'));
137
+ }
138
+ export async function importCommits(repository, commits) {
139
+ const child = spawn('git', ['fast-import', '--quiet', '--force'], { cwd: repository, env: childEnvironment() });
140
+ let stderr = '';
141
+ child.stdout.resume();
142
+ child.stderr.on('data', (chunk) => {
143
+ stderr += chunk.toString('utf8');
144
+ });
145
+ child.stdin.on('error', () => undefined);
146
+ const closed = new Promise((resolve, reject) => {
147
+ child.on('error', reject);
148
+ child.on('close', resolve);
149
+ });
150
+ try {
151
+ await imported(child.stdin, commits);
152
+ child.stdin.end();
153
+ }
154
+ catch (error) {
155
+ child.stdin.destroy();
156
+ await closed;
157
+ throw error.code === 'EPIPE' ? new Error(`git fast-import failed: ${stderr.trim()}`) : error;
84
158
  }
85
- await git(repository, ['fast-import', '--quiet', '--force'], Buffer.concat(stream));
159
+ if ((await closed) !== 0)
160
+ throw new Error(`git fast-import failed: ${stderr.trim()}`);
86
161
  return revision(repository, HOUSE_REF);
87
162
  }
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,24 +1,15 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { accessSync, chmodSync, constants, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync } from 'node:fs';
2
+ import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
3
3
  import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
4
- import { homedir, tmpdir } from 'node:os';
4
+ import { homedir } from 'node:os';
5
5
  import { join, resolve } from 'node:path';
6
6
  import { selectRelay } from './relay.js';
7
7
  const ENROLMENT = 'credential.json';
8
8
  const DISCONNECTED = 'disconnected.json';
9
9
  const CONFIGURATION = 'kit.json';
10
10
  const OWN_AGENT = 'own-agent.json';
11
- const RESTART = 'restart';
12
- let defaulted;
13
- function writable(directory) {
14
- try {
15
- accessSync(directory, constants.W_OK | constants.X_OK);
16
- return true;
17
- }
18
- catch {
19
- return false;
20
- }
21
- }
11
+ const PLANNED_RESTART = 'planned-restart';
12
+ const EARLIER_PREFIXES = ['/kit-home/kit', '/opt/house-kit'];
22
13
  function privateDirectory(path) {
23
14
  try {
24
15
  mkdirSync(path, { mode: 0o700 });
@@ -37,15 +28,39 @@ function privateDirectory(path) {
37
28
  chmodSync(path, 0o700);
38
29
  return path;
39
30
  }
40
- function ownTemporaryHome() {
41
- return privateDirectory(join(tmpdir(), `house-kit-${process.getuid()}`));
31
+ export function oneFolder(account = homedir()) {
32
+ return join(account, '.agents', 'house');
33
+ }
34
+ export function desktopPrefix() {
35
+ return join(homedir(), '.local', 'share', 'house-kit');
36
+ }
37
+ export function earlierPrefix() {
38
+ const prefix = process.env.HOUSE_KIT_PREFIX;
39
+ if (prefix === undefined || prefix === '')
40
+ return null;
41
+ return [...EARLIER_PREFIXES, desktopPrefix()].includes(resolve(prefix)) ? resolve(prefix) : null;
42
+ }
43
+ export function awaitsTakeover() {
44
+ const prefix = earlierPrefix();
45
+ return prefix === EARLIER_PREFIXES[0] || (prefix === EARLIER_PREFIXES[1] && process.getuid() !== 0);
46
+ }
47
+ export function earlierHome() {
48
+ return process.env.HOUSE_KIT_HOME || join(homedir(), '.house-kit');
42
49
  }
43
- function defaultHome() {
44
- const home = join(homedir(), '.house-kit');
45
- return existsSync(home) || writable(homedir()) ? home : ownTemporaryHome();
50
+ export function reinstall() {
51
+ if (!awaitsTakeover())
52
+ return undefined;
53
+ try {
54
+ return readFileSync(join(earlierHome(), 'placement'), 'utf8').trim() === 'windows' ? 'windows' : 'linux';
55
+ }
56
+ catch (error) {
57
+ if (error.code === 'ENOENT')
58
+ return 'linux';
59
+ throw error;
60
+ }
46
61
  }
47
62
  export function kitHome() {
48
- return process.env.HOUSE_KIT_HOME || (defaulted ??= defaultHome());
63
+ return earlierPrefix() === null ? oneFolder() : earlierHome();
49
64
  }
50
65
  export function socketDirectory() {
51
66
  const sockets = privateDirectory(join(realpathSync('/tmp'), `hk-${process.geteuid()}`));
@@ -60,20 +75,32 @@ export function ownerLock() {
60
75
  return join(socketDirectory(), 'owner.lock');
61
76
  }
62
77
  export function workspaceRoot() {
63
- return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
78
+ if (earlierPrefix() !== null)
79
+ return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
80
+ return configuredWorkspace() ?? kitHome();
64
81
  }
65
82
  export function agentBase() {
66
83
  return join(workspaceRoot(), 'agents');
67
84
  }
85
+ function parsed(name, text) {
86
+ try {
87
+ return JSON.parse(text);
88
+ }
89
+ catch {
90
+ throw new Error(`${name} in Kit home holds no JSON`);
91
+ }
92
+ }
68
93
  export async function readHome(name) {
94
+ let text;
69
95
  try {
70
- return JSON.parse(await readFile(join(kitHome(), name), 'utf8'));
96
+ text = await readFile(join(kitHome(), name), 'utf8');
71
97
  }
72
98
  catch (error) {
73
99
  if (error.code === 'ENOENT')
74
100
  return null;
75
101
  throw error;
76
102
  }
103
+ return parsed(name, text);
77
104
  }
78
105
  export async function writeHome(name, value) {
79
106
  const home = kitHome();
@@ -117,7 +144,7 @@ export async function forgetRejected(rejected) {
117
144
  return;
118
145
  throw error;
119
146
  }
120
- if (JSON.parse(readFileSync(taken, 'utf8')).credential !== rejected) {
147
+ if (parsed(ENROLMENT, readFileSync(taken, 'utf8')).credential !== rejected) {
121
148
  try {
122
149
  linkSync(taken, enrolment);
123
150
  }
@@ -129,14 +156,22 @@ export async function forgetRejected(rejected) {
129
156
  }
130
157
  rmSync(taken);
131
158
  }
132
- export function enrolled() {
133
- return existsSync(join(kitHome(), ENROLMENT));
159
+ export function recordPlannedRestart() {
160
+ writeFileSync(join(kitHome(), PLANNED_RESTART), '', { mode: 0o600 });
134
161
  }
135
- export function restartAsked() {
136
- return existsSync(join(kitHome(), RESTART));
162
+ export function takePlannedRestart() {
163
+ try {
164
+ unlinkSync(join(kitHome(), PLANNED_RESTART));
165
+ return true;
166
+ }
167
+ catch (error) {
168
+ if (error.code === 'ENOENT')
169
+ return false;
170
+ throw error;
171
+ }
137
172
  }
138
- export function forgetRestart() {
139
- return rm(join(kitHome(), RESTART), { force: true });
173
+ export function enrolled() {
174
+ return existsSync(join(kitHome(), ENROLMENT));
140
175
  }
141
176
  export function readOwnAgent() {
142
177
  return readHome(OWN_AGENT);
@@ -147,8 +182,24 @@ export function writeOwnAgent(ownAgent) {
147
182
  export function forgetOwnAgent() {
148
183
  return rm(join(kitHome(), OWN_AGENT), { force: true });
149
184
  }
185
+ function configuredWorkspace() {
186
+ let text;
187
+ try {
188
+ text = readFileSync(join(kitHome(), CONFIGURATION), 'utf8');
189
+ }
190
+ catch (error) {
191
+ if (error.code === 'ENOENT')
192
+ return undefined;
193
+ throw error;
194
+ }
195
+ return parsed(CONFIGURATION, text).workspace;
196
+ }
150
197
  export async function readConfiguration() {
151
- return { skills: (await readHome(CONFIGURATION))?.skills !== false };
198
+ const stored = await readHome(CONFIGURATION);
199
+ return { skills: stored?.skills !== false, workspace: stored?.workspace ?? kitHome() };
200
+ }
201
+ export async function storedConfiguration() {
202
+ return (await readHome(CONFIGURATION)) ?? {};
152
203
  }
153
204
  export function writeConfiguration(configuration) {
154
205
  return writeHome(CONFIGURATION, configuration);