@agentshouse/kit 0.2.1-cf268dff1869b → 0.2.1-cf2c570b41f24

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 (54) hide show
  1. package/README.md +18 -25
  2. package/dist/acp.js +12 -9
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +72 -26
  5. package/dist/api.js +18 -4
  6. package/dist/binaries.js +60 -0
  7. package/dist/bridge.js +99 -44
  8. package/dist/calls.js +18 -1
  9. package/dist/chunks.js +54 -0
  10. package/dist/clis.js +33 -15
  11. package/dist/connect.js +121 -0
  12. package/dist/connection.js +25 -10
  13. package/dist/content.js +106 -0
  14. package/dist/conversations.js +251 -158
  15. package/dist/copies.js +1260 -599
  16. package/dist/earlier.js +273 -0
  17. package/dist/end.js +6 -9
  18. package/dist/events.js +544 -297
  19. package/dist/files.js +77 -11
  20. package/dist/git.js +0 -70
  21. package/dist/grok.js +39 -0
  22. package/dist/home.js +86 -22
  23. package/dist/house-cli.js +145 -162
  24. package/dist/instructions.js +2 -4
  25. package/dist/keys.js +238 -0
  26. package/dist/kit-cli.js +14 -4
  27. package/dist/login.js +34 -20
  28. package/dist/logout.js +2 -2
  29. package/dist/manifest.js +75 -0
  30. package/dist/mcp.js +43 -7
  31. package/dist/owner.js +46 -0
  32. package/dist/placement.js +0 -6
  33. package/dist/refusals.js +50 -23
  34. package/dist/resident.js +117 -76
  35. package/dist/scripts.js +79 -15
  36. package/dist/secret-input.js +1 -1
  37. package/dist/settings.js +247 -0
  38. package/dist/sign-in.js +49 -4
  39. package/dist/supervisor.js +163 -0
  40. package/dist/transcription.js +5 -2
  41. package/dist/update.js +31 -22
  42. package/dist/wire.js +2 -10
  43. package/dist/work.js +27 -2
  44. package/dist/workspace.js +113 -0
  45. package/package.json +12 -8
  46. package/dist/authority-main.js +0 -22
  47. package/dist/chatgpt.js +0 -32
  48. package/dist/configure-main.js +0 -6
  49. package/dist/enrol-main.js +0 -10
  50. package/dist/git-main.js +0 -153
  51. package/dist/parts.js +0 -82
  52. package/dist/service-main.js +0 -9
  53. package/dist/service.js +0 -55
  54. package/dist/translate.js +0 -45
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.js CHANGED
@@ -1,14 +1,5 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { isUtf8 } from 'node:buffer';
3
- import { createHash } from 'node:crypto';
4
- import { join } from 'node:path';
5
- import { workspaceRoot } from './home.js';
6
2
  import { childEnvironment } from './relay.js';
7
- export function localCopies() {
8
- return join(workspaceRoot(), 'local-copies');
9
- }
10
- export const HOUSE_REF = 'refs/house/received';
11
- const COMMITTER = 'Kit <house-kit@localhost>';
12
3
  export function run(cwd, args, input, env = {}) {
13
4
  return new Promise((resolve, reject) => {
14
5
  const child = spawn('git', args, { cwd, env: { ...childEnvironment(), ...env } });
@@ -24,64 +15,3 @@ export function run(cwd, args, input, env = {}) {
24
15
  child.stdin.end(input);
25
16
  });
26
17
  }
27
- export async function git(cwd, args, input, env) {
28
- const ran = await run(cwd, args, input, env);
29
- if (ran.status !== 0)
30
- throw new Error(`git ${args[0]} failed: ${ran.stderr.trim()}`);
31
- return ran.stdout.toString('utf8');
32
- }
33
- export async function succeeded(cwd, args, env) {
34
- return (await run(cwd, args, undefined, env)).status === 0;
35
- }
36
- export async function revision(cwd, name) {
37
- return (await git(cwd, ['rev-parse', '--verify', `${name}^{commit}`])).trim();
38
- }
39
- export async function tree(repository, commit) {
40
- const listed = await git(repository, ['ls-tree', '-r', '-z', commit]);
41
- const entries = new Map();
42
- for (const entry of listed.split('\0')) {
43
- const tab = entry.indexOf('\t');
44
- if (tab < 0)
45
- continue;
46
- const [, type, object] = entry.slice(0, tab).split(' ');
47
- if (type === 'blob')
48
- entries.set(entry.slice(tab + 1), object);
49
- }
50
- return entries;
51
- }
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);
61
- }
62
- export function blobId(content) {
63
- const bytes = Buffer.from(content, 'utf8');
64
- return createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
65
- }
66
- function quoted(path) {
67
- return `"${path.replace(/[\\"]/g, '\\$&').replace(/\n/g, '\\n')}"`;
68
- }
69
- function data(text) {
70
- const bytes = Buffer.from(text, 'utf8');
71
- return [Buffer.from(`data ${bytes.length}\n`), bytes, Buffer.from('\n')];
72
- }
73
- export async function importCommits(repository, commits) {
74
- const stream = [];
75
- 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));
82
- }
83
- stream.push(Buffer.from('\n'));
84
- }
85
- await git(repository, ['fast-import', '--quiet', '--force'], Buffer.concat(stream));
86
- return revision(repository, HOUSE_REF);
87
- }
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,23 +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
- let defaulted;
12
- function writable(directory) {
13
- try {
14
- accessSync(directory, constants.W_OK | constants.X_OK);
15
- return true;
16
- }
17
- catch {
18
- return false;
19
- }
20
- }
11
+ const PLANNED_RESTART = 'planned-restart';
12
+ const EARLIER_PREFIXES = ['/kit-home/kit', '/opt/house-kit'];
21
13
  function privateDirectory(path) {
22
14
  try {
23
15
  mkdirSync(path, { mode: 0o700 });
@@ -36,15 +28,42 @@ function privateDirectory(path) {
36
28
  chmodSync(path, 0o700);
37
29
  return path;
38
30
  }
39
- function ownTemporaryHome() {
40
- return privateDirectory(join(tmpdir(), `house-kit-${process.getuid()}`));
31
+ export function oneFolder(account = homedir()) {
32
+ return join(account, '.agents', 'house');
33
+ }
34
+ export function houseFolder(account = homedir()) {
35
+ return join(account, 'house');
36
+ }
37
+ export function desktopPrefix() {
38
+ return join(homedir(), '.local', 'share', 'house-kit');
39
+ }
40
+ export function earlierPrefix() {
41
+ const prefix = process.env.HOUSE_KIT_PREFIX;
42
+ if (prefix === undefined || prefix === '')
43
+ return null;
44
+ return [...EARLIER_PREFIXES, desktopPrefix()].includes(resolve(prefix)) ? resolve(prefix) : null;
45
+ }
46
+ export function awaitsTakeover() {
47
+ const prefix = earlierPrefix();
48
+ return prefix === EARLIER_PREFIXES[0] || (prefix === EARLIER_PREFIXES[1] && process.getuid() !== 0);
41
49
  }
42
- function defaultHome() {
43
- const home = join(homedir(), '.house-kit');
44
- return existsSync(home) || writable(homedir()) ? home : ownTemporaryHome();
50
+ export function earlierHome() {
51
+ return process.env.HOUSE_KIT_HOME || join(homedir(), '.house-kit');
52
+ }
53
+ export function reinstall() {
54
+ if (!awaitsTakeover())
55
+ return undefined;
56
+ try {
57
+ return readFileSync(join(earlierHome(), 'placement'), 'utf8').trim() === 'windows' ? 'windows' : 'linux';
58
+ }
59
+ catch (error) {
60
+ if (error.code === 'ENOENT')
61
+ return 'linux';
62
+ throw error;
63
+ }
45
64
  }
46
65
  export function kitHome() {
47
- return process.env.HOUSE_KIT_HOME || (defaulted ??= defaultHome());
66
+ return earlierPrefix() === null ? oneFolder() : earlierHome();
48
67
  }
49
68
  export function socketDirectory() {
50
69
  const sockets = privateDirectory(join(realpathSync('/tmp'), `hk-${process.geteuid()}`));
@@ -59,20 +78,35 @@ export function ownerLock() {
59
78
  return join(socketDirectory(), 'owner.lock');
60
79
  }
61
80
  export function workspaceRoot() {
62
- return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
81
+ if (earlierPrefix() !== null)
82
+ return process.env.HOUSE_KIT_WORKSPACE ?? '/agents/house';
83
+ return configuredWorkspace() ?? houseFolder();
63
84
  }
64
85
  export function agentBase() {
65
86
  return join(workspaceRoot(), 'agents');
66
87
  }
88
+ export function roomsFolder() {
89
+ return join(workspaceRoot(), 'rooms');
90
+ }
91
+ function parsed(name, text) {
92
+ try {
93
+ return JSON.parse(text);
94
+ }
95
+ catch {
96
+ throw new Error(`${name} in Kit home holds no JSON`);
97
+ }
98
+ }
67
99
  export async function readHome(name) {
100
+ let text;
68
101
  try {
69
- return JSON.parse(await readFile(join(kitHome(), name), 'utf8'));
102
+ text = await readFile(join(kitHome(), name), 'utf8');
70
103
  }
71
104
  catch (error) {
72
105
  if (error.code === 'ENOENT')
73
106
  return null;
74
107
  throw error;
75
108
  }
109
+ return parsed(name, text);
76
110
  }
77
111
  export async function writeHome(name, value) {
78
112
  const home = kitHome();
@@ -116,7 +150,7 @@ export async function forgetRejected(rejected) {
116
150
  return;
117
151
  throw error;
118
152
  }
119
- if (JSON.parse(readFileSync(taken, 'utf8')).credential !== rejected) {
153
+ if (parsed(ENROLMENT, readFileSync(taken, 'utf8')).credential !== rejected) {
120
154
  try {
121
155
  linkSync(taken, enrolment);
122
156
  }
@@ -128,6 +162,20 @@ export async function forgetRejected(rejected) {
128
162
  }
129
163
  rmSync(taken);
130
164
  }
165
+ export function recordPlannedRestart() {
166
+ writeFileSync(join(kitHome(), PLANNED_RESTART), '', { mode: 0o600 });
167
+ }
168
+ export function takePlannedRestart() {
169
+ try {
170
+ unlinkSync(join(kitHome(), PLANNED_RESTART));
171
+ return true;
172
+ }
173
+ catch (error) {
174
+ if (error.code === 'ENOENT')
175
+ return false;
176
+ throw error;
177
+ }
178
+ }
131
179
  export function enrolled() {
132
180
  return existsSync(join(kitHome(), ENROLMENT));
133
181
  }
@@ -140,8 +188,24 @@ export function writeOwnAgent(ownAgent) {
140
188
  export function forgetOwnAgent() {
141
189
  return rm(join(kitHome(), OWN_AGENT), { force: true });
142
190
  }
191
+ function configuredWorkspace() {
192
+ let text;
193
+ try {
194
+ text = readFileSync(join(kitHome(), CONFIGURATION), 'utf8');
195
+ }
196
+ catch (error) {
197
+ if (error.code === 'ENOENT')
198
+ return undefined;
199
+ throw error;
200
+ }
201
+ return parsed(CONFIGURATION, text).workspace;
202
+ }
143
203
  export async function readConfiguration() {
144
- return { skills: (await readHome(CONFIGURATION))?.skills !== false };
204
+ const stored = await readHome(CONFIGURATION);
205
+ return { skills: stored?.skills !== false, workspace: stored?.workspace ?? houseFolder() };
206
+ }
207
+ export async function storedConfiguration() {
208
+ return (await readHome(CONFIGURATION)) ?? {};
145
209
  }
146
210
  export function writeConfiguration(configuration) {
147
211
  return writeHome(CONFIGURATION, configuration);