@agentshouse/kit 0.2.1-cf110d15f69c8 → 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 (147) hide show
  1. package/README.md +38 -44
  2. package/dist/acp.js +96 -22
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +221 -65
  5. package/dist/api.js +21 -3
  6. package/dist/app-git.js +10 -26
  7. package/dist/binaries.js +60 -0
  8. package/dist/bridge.js +101 -49
  9. package/dist/building.js +50 -0
  10. package/dist/calls.js +88 -0
  11. package/dist/chunks.js +54 -0
  12. package/dist/clis.js +80 -52
  13. package/dist/connect.js +121 -0
  14. package/dist/connection.js +120 -0
  15. package/dist/content.js +106 -0
  16. package/dist/conversations.js +711 -267
  17. package/dist/copies.js +1293 -595
  18. package/dist/earlier.js +273 -0
  19. package/dist/end.js +15 -3
  20. package/dist/events.js +553 -281
  21. package/dist/files.js +206 -32
  22. package/dist/git.js +2 -70
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +123 -15
  25. package/dist/house-cli.js +282 -0
  26. package/dist/house-main.js +7 -206
  27. package/dist/instructions.js +7 -13
  28. package/dist/keys.js +238 -0
  29. package/dist/kit-cli.js +78 -0
  30. package/dist/kit-main.js +8 -22
  31. package/dist/login.js +71 -39
  32. package/dist/logout.js +2 -4
  33. package/dist/manifest.js +75 -0
  34. package/dist/mcp.js +47 -7
  35. package/dist/owner.js +46 -0
  36. package/dist/placement.js +25 -0
  37. package/dist/refusals.js +50 -23
  38. package/dist/relay.js +22 -1
  39. package/dist/resident.js +153 -53
  40. package/dist/scope.js +15 -4
  41. package/dist/scripts.js +319 -0
  42. package/dist/secret-input.js +1 -1
  43. package/dist/settings.js +247 -0
  44. package/dist/sign-in.js +66 -38
  45. package/dist/silence.js +28 -0
  46. package/dist/skills.js +49 -35
  47. package/dist/supervisor.js +163 -0
  48. package/dist/transcription.js +90 -47
  49. package/dist/update.js +119 -102
  50. package/dist/wire.js +32 -0
  51. package/dist/work.js +30 -7
  52. package/dist/workspace.js +113 -0
  53. package/package.json +25 -21
  54. package/dist/authority-main.js +0 -22
  55. package/dist/bootstrap.json +0 -24
  56. package/dist/clis-main.js +0 -23
  57. package/dist/configure-main.js +0 -6
  58. package/dist/enrol-main.js +0 -10
  59. package/dist/git-main.js +0 -153
  60. package/dist/parts.js +0 -82
  61. package/dist/service-main.js +0 -9
  62. package/dist/service.js +0 -33
  63. package/dist/stream.js +0 -74
  64. package/dist/translate.js +0 -51
  65. package/how-we-work.md +0 -23
  66. package/skills/ask-matt/LICENSE +0 -21
  67. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  68. package/skills/ask-matt/SKILL.md +0 -91
  69. package/skills/ask-matt/agents/openai.yaml +0 -4
  70. package/skills/code-review/LICENSE +0 -21
  71. package/skills/code-review/SKILL.md +0 -89
  72. package/skills/code-review/agents/openai.yaml +0 -3
  73. package/skills/codebase-design/DEEPENING.md +0 -37
  74. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  75. package/skills/codebase-design/LICENSE +0 -21
  76. package/skills/codebase-design/SKILL.md +0 -116
  77. package/skills/codebase-design/agents/openai.yaml +0 -3
  78. package/skills/diagnosing-bugs/LICENSE +0 -21
  79. package/skills/diagnosing-bugs/SKILL.md +0 -140
  80. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  81. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  82. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  83. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  84. package/skills/domain-modeling/LICENSE +0 -21
  85. package/skills/domain-modeling/SKILL.md +0 -76
  86. package/skills/domain-modeling/agents/openai.yaml +0 -3
  87. package/skills/grill-me/LICENSE +0 -21
  88. package/skills/grill-me/SKILL.md +0 -8
  89. package/skills/grill-me/agents/openai.yaml +0 -4
  90. package/skills/grill-with-docs/LICENSE +0 -21
  91. package/skills/grill-with-docs/SKILL.md +0 -8
  92. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  93. package/skills/grilling/LICENSE +0 -21
  94. package/skills/grilling/SKILL.md +0 -30
  95. package/skills/grilling/agents/openai.yaml +0 -3
  96. package/skills/handoff/LICENSE +0 -21
  97. package/skills/handoff/SKILL.md +0 -17
  98. package/skills/handoff/agents/openai.yaml +0 -4
  99. package/skills/implement/LICENSE +0 -21
  100. package/skills/implement/SKILL.md +0 -16
  101. package/skills/implement/agents/openai.yaml +0 -4
  102. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  103. package/skills/improve-codebase-architecture/LICENSE +0 -21
  104. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  105. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  106. package/skills/prototype/LICENSE +0 -21
  107. package/skills/prototype/LOGIC.md +0 -67
  108. package/skills/prototype/SKILL.md +0 -28
  109. package/skills/prototype/UI.md +0 -112
  110. package/skills/prototype/agents/openai.yaml +0 -3
  111. package/skills/research/LICENSE +0 -21
  112. package/skills/research/SKILL.md +0 -14
  113. package/skills/research/agents/openai.yaml +0 -3
  114. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  115. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  116. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  117. package/skills/tdd/LICENSE +0 -21
  118. package/skills/tdd/SKILL.md +0 -40
  119. package/skills/tdd/agents/openai.yaml +0 -3
  120. package/skills/tdd/mocking.md +0 -59
  121. package/skills/tdd/tests.md +0 -77
  122. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  123. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  124. package/skills/teach/LICENSE +0 -21
  125. package/skills/teach/MISSION-FORMAT.md +0 -31
  126. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  127. package/skills/teach/SKILL.md +0 -141
  128. package/skills/teach/agents/openai.yaml +0 -4
  129. package/skills/to-questionnaire/LICENSE +0 -21
  130. package/skills/to-questionnaire/SKILL.md +0 -55
  131. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  132. package/skills/to-spec/LICENSE +0 -21
  133. package/skills/to-spec/SKILL.md +0 -76
  134. package/skills/to-spec/agents/openai.yaml +0 -4
  135. package/skills/to-tickets/LICENSE +0 -21
  136. package/skills/to-tickets/SKILL.md +0 -106
  137. package/skills/to-tickets/agents/openai.yaml +0 -4
  138. package/skills/wait-what/LICENSE +0 -21
  139. package/skills/wait-what/SKILL.md +0 -8
  140. package/skills/wait-what/agents/openai.yaml +0 -4
  141. package/skills/wayfinder/LICENSE +0 -21
  142. package/skills/wayfinder/SKILL.md +0 -129
  143. package/skills/wayfinder/agents/openai.yaml +0 -4
  144. package/skills/writing-for-agents/LICENSE +0 -21
  145. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  146. package/skills/writing-for-agents/SKILL.md +0 -83
  147. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/keys.js ADDED
@@ -0,0 +1,238 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { mkdir, readFile, realpath, rename, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { isDeepStrictEqual } from 'node:util';
7
+ import { parse } from 'smol-toml';
8
+ import { readHome, writeHome } from './home.js';
9
+ import { childEnvironment } from './relay.js';
10
+ function table(value) {
11
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};
12
+ }
13
+ function filled(value) {
14
+ return typeof value === 'string' && value !== '';
15
+ }
16
+ function hostOf(endpoint) {
17
+ if (typeof endpoint !== 'string')
18
+ return undefined;
19
+ try {
20
+ return new URL(endpoint).host || undefined;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ function keyed(apiKey, endpoint, maker) {
27
+ const host = hostOf(endpoint);
28
+ return { ...(apiKey ? { api_key: true } : {}), ...(host === undefined || host === maker ? {} : { provider: host }) };
29
+ }
30
+ function quietly(read) {
31
+ return () => read().catch(() => ({}));
32
+ }
33
+ async function readText(file) {
34
+ try {
35
+ return await readFile(file, 'utf8');
36
+ }
37
+ catch (error) {
38
+ if (error.code === 'ENOENT')
39
+ return null;
40
+ throw error;
41
+ }
42
+ }
43
+ async function replaceFile(file, text) {
44
+ const target = await realpath(file).catch(() => file);
45
+ await mkdir(dirname(target), { recursive: true });
46
+ const temporary = `${target}.${randomUUID()}`;
47
+ await writeFile(temporary, text, { mode: 0o600 });
48
+ await rename(temporary, target);
49
+ }
50
+ async function jsonSettings(file) {
51
+ const text = await readText(file);
52
+ if (text === null)
53
+ return {};
54
+ let settings;
55
+ try {
56
+ settings = JSON.parse(text);
57
+ }
58
+ catch {
59
+ settings = null;
60
+ }
61
+ if (typeof settings !== 'object' || settings === null || Array.isArray(settings))
62
+ throw new Error(`${file} holds no JSON object`);
63
+ return settings;
64
+ }
65
+ async function tomlSettings(file) {
66
+ return parse((await readText(file)) ?? '');
67
+ }
68
+ const BARE_KEY = /^[A-Za-z0-9_-]+$/;
69
+ function header(line, at) {
70
+ const trimmed = line.trim();
71
+ if (!trimmed.startsWith('['))
72
+ return null;
73
+ let value;
74
+ try {
75
+ value = parse(trimmed);
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ const path = [];
81
+ while (!Array.isArray(value)) {
82
+ const [name, ...more] = Object.keys(table(value));
83
+ if (name === undefined || more.length > 0)
84
+ return { at, path };
85
+ path.push(name);
86
+ value = table(value)[name];
87
+ }
88
+ return { at, path: [...path, '[]'] };
89
+ }
90
+ function editLines(lines, { table: path, key, value, kept }) {
91
+ const headers = lines.flatMap((line, at) => header(line, at) ?? []);
92
+ const found = path.length === 0 ? { at: -1, path } : headers.find((one) => isDeepStrictEqual(one.path, path));
93
+ const assignment = `${key} = ${JSON.stringify(value)}`;
94
+ if (found === undefined) {
95
+ if (value === null)
96
+ return lines;
97
+ const kept = lines.at(-1) === '' ? lines.slice(0, -1) : lines;
98
+ return [...kept, ...(kept.length === 0 ? [] : ['']), `[${path.map((name) => (BARE_KEY.test(name) ? name : JSON.stringify(name))).join('.')}]`, assignment, ''];
99
+ }
100
+ const end = headers.find((one) => one.at > found.at)?.at ?? lines.length;
101
+ const assigned = new RegExp(`^\\s*${key}\\s*=`);
102
+ const current = lines.findIndex((line, at) => at > found.at && at < end && assigned.test(line));
103
+ if (current !== -1 && kept)
104
+ return lines;
105
+ if (current !== -1)
106
+ return value === null ? lines.toSpliced(current, 1) : lines.toSpliced(current, 1, assignment);
107
+ if (value === null)
108
+ return lines;
109
+ const last = lines.findLastIndex((line, at) => at > found.at && at < end && line.trim() !== '');
110
+ return lines.toSpliced(Math.max(last, found.at) + 1, 0, assignment);
111
+ }
112
+ function editSettings(settings, { table: path, key, value, kept }) {
113
+ let at = settings;
114
+ for (const name of path) {
115
+ if (typeof at[name] !== 'object' || at[name] === null)
116
+ at[name] = Object.create(null);
117
+ at = at[name];
118
+ }
119
+ if (kept && key in at)
120
+ return;
121
+ if (value === null)
122
+ delete at[key];
123
+ else
124
+ at[key] = value;
125
+ }
126
+ async function editToml(file, edits) {
127
+ const text = (await readText(file)) ?? '';
128
+ let expected;
129
+ try {
130
+ expected = parse(text);
131
+ }
132
+ catch {
133
+ throw new Error(`${file} is not TOML`);
134
+ }
135
+ for (const edit of edits)
136
+ editSettings(expected, edit);
137
+ const edited = edits.reduce(editLines, text === '' ? [] : text.split('\n')).join('\n');
138
+ let written;
139
+ try {
140
+ written = parse(edited);
141
+ }
142
+ catch {
143
+ written = null;
144
+ }
145
+ if (!isDeepStrictEqual(written, expected))
146
+ throw new Error(`${file} could not take the key without changing its other settings`);
147
+ if (edited === text)
148
+ return async () => undefined;
149
+ return () => replaceFile(file, edited.endsWith('\n') ? edited : `${edited}\n`);
150
+ }
151
+ function claudeSettings() {
152
+ return join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'settings.json');
153
+ }
154
+ export const CLAUDE_KEY = {
155
+ read: quietly(async () => {
156
+ const env = table((await jsonSettings(claudeSettings())).env);
157
+ return keyed(filled(env.ANTHROPIC_API_KEY) || filled(env.ANTHROPIC_AUTH_TOKEN), env.ANTHROPIC_BASE_URL, 'api.anthropic.com');
158
+ }),
159
+ write: async (key, endpoint) => {
160
+ const file = claudeSettings();
161
+ const settings = await jsonSettings(file);
162
+ const { ANTHROPIC_API_KEY: _key, ANTHROPIC_AUTH_TOKEN: _token, ANTHROPIC_BASE_URL: _endpoint, ...env } = table(settings.env);
163
+ const written = endpoint === null
164
+ ? { ...env, ANTHROPIC_API_KEY: key }
165
+ : { ...env, ANTHROPIC_AUTH_TOKEN: key, ANTHROPIC_API_KEY: '', ANTHROPIC_BASE_URL: endpoint };
166
+ await replaceFile(file, `${JSON.stringify({ ...settings, env: written }, undefined, 2)}\n`);
167
+ },
168
+ };
169
+ const CODEX_PROVIDER = 'model_provider';
170
+ export function codexHome() {
171
+ return process.env.CODEX_HOME || join(homedir(), '.codex');
172
+ }
173
+ function codexLogin(cli, key, signal) {
174
+ return new Promise((resolve, reject) => {
175
+ const child = spawn(cli, ['login', '--with-api-key'], { stdio: ['pipe', 'ignore', 'pipe'], env: childEnvironment(), signal });
176
+ let output = '';
177
+ child.stderr.setEncoding('utf8').on('data', (chunk) => {
178
+ output = (output + chunk).slice(-4000);
179
+ });
180
+ child.on('error', reject);
181
+ child.on('close', (status) => {
182
+ const last = output.trim().split('\n').at(-1) ?? '';
183
+ if (status === 0)
184
+ resolve();
185
+ else
186
+ reject(new Error(`codex login --with-api-key exited with ${status ?? 'a signal'}${last === '' ? '' : `: ${last}`}`));
187
+ });
188
+ child.stdin.end(key);
189
+ });
190
+ }
191
+ export const CODEX_KEY = {
192
+ read: quietly(async () => {
193
+ const config = await tomlSettings(join(codexHome(), 'config.toml'));
194
+ const id = config[CODEX_PROVIDER];
195
+ if (typeof id === 'string' && id !== 'openai') {
196
+ const provider = table(table(config.model_providers)[id]);
197
+ const fromEnvironment = typeof provider.env_key === 'string' && filled(process.env[provider.env_key]);
198
+ return keyed(filled(provider.experimental_bearer_token) || fromEnvironment, provider.base_url, 'api.openai.com');
199
+ }
200
+ const auth = table(JSON.parse((await readText(join(codexHome(), 'auth.json'))) ?? '{}'));
201
+ return keyed(filled(auth.OPENAI_API_KEY) && (auth.tokens === undefined || auth.tokens === null), undefined, 'api.openai.com');
202
+ }),
203
+ write: async (key, endpoint, cli, signal) => {
204
+ const file = join(codexHome(), 'config.toml');
205
+ if (endpoint === null) {
206
+ const write = await editToml(file, [{ table: [], key: CODEX_PROVIDER, value: null }]);
207
+ await codexLogin(cli, key, signal);
208
+ await write();
209
+ return;
210
+ }
211
+ const host = new URL(endpoint).host;
212
+ const provider = ['model_providers', host];
213
+ const write = await editToml(file, [
214
+ { table: [], key: CODEX_PROVIDER, value: host },
215
+ { table: provider, key: 'name', value: host, kept: true },
216
+ { table: provider, key: 'base_url', value: endpoint },
217
+ { table: provider, key: 'experimental_bearer_token', value: key },
218
+ ]);
219
+ await write();
220
+ },
221
+ };
222
+ const GROK_HELD_KEY = 'grok-key.json';
223
+ export const GROK_KEY = {
224
+ read: quietly(async () => {
225
+ const held = await readHome(GROK_HELD_KEY);
226
+ if (held?.endpoint !== undefined)
227
+ return keyed(true, held.endpoint, 'api.x.ai');
228
+ const config = await tomlSettings(join(process.env.GROK_HOME || join(homedir(), '.grok'), 'config.toml'));
229
+ return keyed(held !== null, table(config.endpoints).models_base_url, 'api.x.ai');
230
+ }),
231
+ write: (key, endpoint) => writeHome(GROK_HELD_KEY, { key, ...(endpoint === null ? {} : { endpoint }) }),
232
+ environment: async () => {
233
+ const held = await readHome(GROK_HELD_KEY);
234
+ if (held === null)
235
+ return {};
236
+ return { XAI_API_KEY: held.key, ...(held.endpoint === undefined ? {} : { GROK_MODELS_BASE_URL: held.endpoint }) };
237
+ },
238
+ };
@@ -0,0 +1,78 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { answerGitCredential } from './app-git.js';
3
+ import { connect } from './connect.js';
4
+ import { login } from './login.js';
5
+ import { logout } from './logout.js';
6
+ import { proxyUnlessRelayed } from './relay.js';
7
+ import { resident } from './resident.js';
8
+ import { kitSettings, SETTINGS_USAGE } from './settings.js';
9
+ const USAGE = 'usage: kit <connect|login|logout|resident|settings>\n';
10
+ const COMMANDS = new Map([
11
+ [
12
+ 'logout',
13
+ {
14
+ usage: 'usage: kit logout',
15
+ about: "disconnects this computer, stops the Kit process and ends your own agent's connection",
16
+ operands: 0,
17
+ run: logout,
18
+ },
19
+ ],
20
+ [
21
+ 'resident',
22
+ {
23
+ usage: 'usage: kit resident',
24
+ about: "keeps this Environment connected; Kit's service runs it",
25
+ operands: 0,
26
+ run: resident,
27
+ },
28
+ ],
29
+ [
30
+ 'settings',
31
+ {
32
+ usage: SETTINGS_USAGE,
33
+ about: "prints Kit's settings, or changes whether Kit places House's Skills or where its workspace is",
34
+ operands: 2,
35
+ run: kitSettings,
36
+ },
37
+ ],
38
+ [
39
+ 'git-credential',
40
+ {
41
+ usage: 'usage: kit git-credential <get|store|erase>',
42
+ about: "answers git with your own agent's House credential; git runs it",
43
+ operands: 1,
44
+ run: ([operation]) => answerGitCredential(operation),
45
+ },
46
+ ],
47
+ ]);
48
+ const [command, ...argv] = process.argv.slice(2);
49
+ proxyUnlessRelayed();
50
+ async function run() {
51
+ if (command === 'connect')
52
+ return connect(argv);
53
+ if (command === 'login')
54
+ return login(argv);
55
+ if (command === '--help') {
56
+ parseArgs({ args: argv });
57
+ process.stdout.write(USAGE);
58
+ return;
59
+ }
60
+ const chosen = COMMANDS.get(command ?? '');
61
+ if (chosen === undefined) {
62
+ process.stderr.write(USAGE);
63
+ process.exitCode = 2;
64
+ return;
65
+ }
66
+ const { values, positionals } = parseArgs({ args: argv, options: { help: { type: 'boolean', default: false } }, allowPositionals: true });
67
+ if (positionals.length > chosen.operands)
68
+ throw new Error(`unexpected argument ${positionals[chosen.operands]}; ${chosen.usage}`);
69
+ if (values.help) {
70
+ process.stdout.write(`${chosen.usage}\n ${chosen.about}\n`);
71
+ return;
72
+ }
73
+ return chosen.run(positionals);
74
+ }
75
+ run().catch((error) => {
76
+ process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
77
+ process.exitCode = 1;
78
+ });
package/dist/kit-main.js CHANGED
@@ -1,24 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { setGlobalProxyFromEnv } from 'node:http';
3
- import { answerGitCredential } from './app-git.js';
4
- import { login } from './login.js';
5
- import { logout } from './logout.js';
6
- import { resident } from './resident.js';
7
- const [command, ...argv] = process.argv.slice(2);
8
- setGlobalProxyFromEnv();
9
- async function run() {
10
- if (command === 'login')
11
- return login(argv);
12
- if (command === 'logout')
13
- return logout();
14
- if (command === 'resident')
15
- return resident();
16
- if (command === 'git-credential')
17
- return answerGitCredential(argv[0]);
18
- process.stderr.write('usage: kit <login|logout|resident>\n');
19
- process.exitCode = 2;
20
- }
21
- run().catch((error) => {
22
- process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
2
+ const [major = 0, minor = 0, patch = 0] = process.versions.node.split('.').map(Number);
3
+ if (major < 24 || (major === 24 && (minor < 22 || (minor === 22 && patch < 1)))) {
4
+ process.stderr.write(`kit: the Kit needs Node 24.22.1 or newer; this is ${process.versions.node}\n`);
23
5
  process.exitCode = 1;
24
- });
6
+ }
7
+ else {
8
+ await import('./kit-cli.js');
9
+ }
10
+ export {};
package/dist/login.js CHANGED
@@ -1,20 +1,27 @@
1
+ import { KIT_LOGIN_PATHS, } from '@agentshouse/kit-wire';
1
2
  import { spawn } from 'node:child_process';
2
3
  import { createHash, randomBytes } from 'node:crypto';
3
- import { hostname } from 'node:os';
4
- import { delimiter, dirname } from 'node:path';
5
4
  import { parseArgs } from 'node:util';
6
- import { post, retrying } from './api.js';
5
+ import { HouseRefusal, post, retrying } from './api.js';
7
6
  import { placeAppGit } from './app-git.js';
8
- import { allowHouseInCodex, loginPath } from './clis.js';
9
- import { forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
7
+ import { writeCodexRule } from './clis.js';
8
+ import { forgetDisconnected, forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent, } from './home.js';
10
9
  import { callHouse, rpc } from './mcp.js';
10
+ import { refusalOf } from './refusals.js';
11
11
  import { selectRelay } from './relay.js';
12
- import { startService } from './service.js';
12
+ import { startService } from './supervisor.js';
13
13
  import { placeSkillSet } from './skills.js';
14
- const DEFAULT_HOUSE = 'https://agents.house';
14
+ import { endUnserved } from './wire.js';
15
+ export const DEFAULT_HOUSE = 'https://agents.house';
15
16
  const OPENER = process.platform === 'darwin' ? 'open' : 'xdg-open';
16
17
  // Polling every two seconds brings the User's confirmation to the waiting Kit moments after they give it.
17
18
  const POLL_INTERVAL_MS = 2000;
19
+ function startLogin(house, request) {
20
+ return post(house, KIT_LOGIN_PATHS.start, request);
21
+ }
22
+ function pollLogin(house, request) {
23
+ return post(house, KIT_LOGIN_PATHS.poll, request);
24
+ }
18
25
  function open(link) {
19
26
  spawn(OPENER, [link], { detached: true, stdio: 'ignore' })
20
27
  .on('error', () => undefined)
@@ -26,15 +33,27 @@ async function accepted(house, credential) {
26
33
  return true;
27
34
  if (checked.status === 401)
28
35
  return false;
36
+ endUnserved(checked.text);
29
37
  throw new Error(`House answered ${checked.status} when Kit checked this computer's own agent's connection: ${checked.text}`);
30
38
  }
31
- const USAGE = `usage: kit login [--house <origin>] [--environment <id>] [--rooms <ref>[,<ref>...] | --no-private] [--code <code>]
39
+ const USAGE = `usage: kit login [--house <origin>] [--environment <id>] [--rooms <ref>[,<ref>...] | --no-private]
40
+ kit login [--house <origin>] --code <code>
32
41
  --house <origin> the House to connect to, ${DEFAULT_HOUSE} unless one is stored
33
42
  --environment <id> reconnect this Environment
34
43
  --rooms <ref>[,<ref>...] give this Environment only these Rooms
35
44
  --no-private give this Environment every Room but your Private Room
36
45
  --code <code> connect this machine with a login code
37
46
  `;
47
+ function connected(house, named, environment) {
48
+ if (named === undefined)
49
+ return `Environment ${environment} is connected to ${house}.\n`;
50
+ if (named === environment)
51
+ return `Environment ${environment} is reconnected to ${house}.\n`;
52
+ return `Environment ${named} stays with its account; this computer is connected to ${house} as new Environment ${environment} of the account that confirmed.\n`;
53
+ }
54
+ function gone(error) {
55
+ return error instanceof HouseRefusal && refusalOf(error.text)?.code === 'kit_environment_not_found';
56
+ }
38
57
  function chosenRooms(rooms, noPrivate) {
39
58
  if (rooms !== undefined && noPrivate)
40
59
  throw new Error('--rooms and --no-private are two choices of Rooms; pass one');
@@ -58,6 +77,21 @@ export async function login(argv) {
58
77
  process.stdout.write(USAGE);
59
78
  return;
60
79
  }
80
+ const house = await enrol(values);
81
+ await placeConnection(house);
82
+ try {
83
+ startService();
84
+ }
85
+ catch (error) {
86
+ process.stderr.write(`kit: ${error.message}\n`);
87
+ }
88
+ }
89
+ export async function placeConnection(house) {
90
+ await placeSkillSet(house);
91
+ await writeCodexRule().catch((error) => process.stderr.write(`kit: ${error.message}\n`));
92
+ await placeAppGit(await readOwnAgent()).catch((error) => process.stderr.write(`kit: ${error.message}\n`));
93
+ }
94
+ export async function enrol(values) {
61
95
  if (values.code !== undefined && values.rooms !== undefined)
62
96
  throw new Error('--code cannot be used with --rooms');
63
97
  if (values.code !== undefined && values['no-private'])
@@ -72,62 +106,60 @@ export async function login(argv) {
72
106
  const relay = process.env.HOUSE_KIT_RELAY || undefined;
73
107
  selectRelay(relay);
74
108
  const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
75
- const replaces = process.env.HOUSE_KIT_REPLACES;
76
- const environment = replaces === undefined ? (values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined)) : undefined;
109
+ const remembered = values.environment === undefined && enrolled?.house === house ? enrolled.environment : undefined;
110
+ const environment = values.environment ?? remembered;
111
+ if (environment !== undefined && rooms.rooms !== undefined) {
112
+ throw new Error(`Environment ${environment} keeps its Rooms; change them on its page in House`);
113
+ }
77
114
  const ownAgent = await readOwnAgent();
78
115
  let held = false;
116
+ let named = environment;
79
117
  let exchanged;
80
118
  if (values.code !== undefined) {
81
- exchanged = await post(house, '/kit/token', { code: values.code, label: hostname() });
119
+ exchanged = await pollLogin(house, { code: values.code });
82
120
  }
83
121
  else {
84
122
  held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
85
123
  const verifier = randomBytes(32).toString('base64url');
86
- const started = await retrying(() => post(house, '/kit', {
87
- label: hostname(),
88
- ...(environment === undefined
89
- ? { act: 'new_environment', ...(replaces === undefined ? {} : { replaces }) }
90
- : { act: 'existing_environment', environment_id: environment }),
124
+ const start = () => retrying(() => startLogin(house, {
125
+ ...(named === undefined ? { act: 'new_environment' } : { act: 'existing_environment', environment_id: named }),
91
126
  ...rooms,
92
127
  code_challenge: createHash('sha256').update(verifier).digest('base64url'),
93
128
  ...(held ? {} : { headless: true }),
94
129
  }));
130
+ let started;
131
+ try {
132
+ started = await start();
133
+ }
134
+ catch (error) {
135
+ if (remembered === undefined || !gone(error))
136
+ throw error;
137
+ await forgetDisconnected();
138
+ process.stdout.write(`House no longer holds Environment ${remembered}; connecting this computer as a new one.\n`);
139
+ named = undefined;
140
+ started = await start();
141
+ }
95
142
  process.stdout.write(`Open this link and confirm: ${started.start_url}\n`);
96
143
  open(started.start_url);
97
- exchanged = await retrying(() => post(house, '/kit/token', { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
98
- }
99
- try {
100
- await placeSkillSet();
101
- }
102
- catch (error) {
103
- process.stderr.write(`kit: the skills could not be placed: ${error.message}\n`);
104
- }
105
- try {
106
- const shell = await loginPath().catch(() => '');
107
- await allowHouseInCodex([dirname(process.execPath), process.env.PATH ?? '', shell].join(delimiter));
108
- }
109
- catch (error) {
110
- process.stderr.write(`kit: Codex's rule for house could not be written: ${error.message}\n`);
144
+ exchanged = await retrying(() => pollLogin(house, { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
111
145
  }
146
+ const relayRecord = relay === undefined ? {} : { relay };
112
147
  await writeEnrolment({
113
148
  house,
114
- ...(relay === undefined ? {} : { relay }),
149
+ ...relayRecord,
115
150
  environment: exchanged.environment,
116
151
  credential: exchanged.credential,
117
152
  });
118
- process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
153
+ process.stdout.write(connected(house, named, exchanged.environment));
119
154
  if (exchanged.headless_credential !== undefined) {
120
- await writeOwnAgent({ house, user: exchanged.user, credential: exchanged.headless_credential });
155
+ await writeOwnAgent({ house, ...relayRecord, user: exchanged.user, credential: exchanged.headless_credential });
121
156
  }
122
157
  else if (held && ownAgent !== null && ownAgent.user !== exchanged.user) {
123
158
  await forgetOwnAgent();
124
159
  process.stdout.write("This computer's own agent was another User's; run kit login again to connect it to you.\n");
125
160
  }
126
- await placeAppGit(ownAgent, await readOwnAgent());
127
- try {
128
- startService();
129
- }
130
- catch (error) {
131
- process.stderr.write(`kit: ${error.message}\n`);
161
+ else if (held && ownAgent !== null) {
162
+ await writeOwnAgent({ house, ...relayRecord, user: ownAgent.user, credential: ownAgent.credential });
132
163
  }
164
+ return house;
133
165
  }
package/dist/logout.js CHANGED
@@ -1,11 +1,10 @@
1
- import { HouseRefusal, post } from './api.js';
2
- import { forgetAppGit } from './app-git.js';
1
+ import { HouseRefusal, kitAct } from './api.js';
3
2
  import { forgetEnrolment, forgetOwnAgent, readEnrolment } from './home.js';
4
3
  export async function logout() {
5
4
  const enrolled = await readEnrolment();
6
5
  if (enrolled !== null) {
7
6
  try {
8
- await post(enrolled.house, '/kit/logout', {}, enrolled.credential);
7
+ await kitAct(enrolled.house, 'kits/log-out', {}, enrolled.credential);
9
8
  }
10
9
  catch (error) {
11
10
  if (!(error instanceof HouseRefusal && error.status === 401))
@@ -13,7 +12,6 @@ export async function logout() {
13
12
  }
14
13
  await forgetEnrolment(enrolled);
15
14
  }
16
- await forgetAppGit();
17
15
  await forgetOwnAgent();
18
16
  process.stdout.write(enrolled === null
19
17
  ? 'This computer is not connected to House.\n'
@@ -0,0 +1,75 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { mkdir, readFile, readdir, rename, rm, rmdir, writeFile } from 'node:fs/promises';
4
+ import { dirname, join } from 'node:path';
5
+ export const MANIFEST = '.house';
6
+ const UNREAD = '.git';
7
+ const MARKER = /^(?:<{7}|={7}|>{7})(?: .*)?$/m;
8
+ export function digest(bytes) {
9
+ return createHash('sha256').update(bytes).digest('hex');
10
+ }
11
+ export async function fileDigest(file) {
12
+ const hash = createHash('sha256');
13
+ let bytes = 0;
14
+ for await (const chunk of createReadStream(file)) {
15
+ hash.update(chunk);
16
+ bytes += chunk.length;
17
+ }
18
+ return { sha256: hash.digest('hex'), bytes };
19
+ }
20
+ export async function hashed(file) {
21
+ try {
22
+ return await fileDigest(file);
23
+ }
24
+ catch (error) {
25
+ if (error.code === 'ENOENT' || error.code === 'EISDIR')
26
+ return null;
27
+ throw error;
28
+ }
29
+ }
30
+ export async function holding(repository, name, sha256) {
31
+ return (await hashed(join(repository, name)))?.sha256 === sha256;
32
+ }
33
+ export async function readManifest(repository) {
34
+ return JSON.parse(await readFile(join(repository, MANIFEST), 'utf8'));
35
+ }
36
+ export async function placed(staging, target, content) {
37
+ const temporary = `${staging}${randomUUID()}`;
38
+ await writeFile(temporary, content);
39
+ await mkdir(dirname(target), { recursive: true });
40
+ await rename(temporary, target);
41
+ }
42
+ export async function writeManifest(repository, staging, manifest) {
43
+ const files = Object.fromEntries(Object.entries(manifest.files).sort(([left], [right]) => (left < right ? -1 : 1)));
44
+ await placed(staging, join(repository, MANIFEST), `${JSON.stringify({ room_ref: manifest.room_ref, files })}\n`);
45
+ }
46
+ export async function removed(repository, name) {
47
+ await rm(join(repository, name), { force: true });
48
+ for (let folder = dirname(name); folder !== '.'; folder = dirname(folder)) {
49
+ if (!(await rmdir(join(repository, folder)).then(() => true, () => false)))
50
+ return;
51
+ }
52
+ }
53
+ export async function scanned(repository) {
54
+ const present = new Map();
55
+ const walk = async (folder) => {
56
+ for (const entry of await readdir(join(repository, folder), { withFileTypes: true })) {
57
+ const name = folder === '' ? entry.name : `${folder}/${entry.name}`;
58
+ if (folder === '' && (entry.name === MANIFEST || entry.name === UNREAD))
59
+ continue;
60
+ if (entry.isDirectory())
61
+ await walk(name);
62
+ else if (entry.isFile()) {
63
+ const file = await hashed(join(repository, name));
64
+ if (file !== null)
65
+ present.set(name.normalize('NFC'), { name, ...file });
66
+ }
67
+ }
68
+ };
69
+ await walk('');
70
+ return present;
71
+ }
72
+ export async function marked(repository, name) {
73
+ const text = await readFile(join(repository, name), 'utf8').catch(() => null);
74
+ return text !== null && MARKER.test(text);
75
+ }