@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/house-cli.js CHANGED
@@ -1,59 +1,33 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { createReadStream } from 'node:fs';
3
3
  import { request } from 'node:http';
4
- import { request as httpsRequest } from 'node:https';
5
- import { extname, join, resolve } from 'node:path';
6
- import { Readable } from 'node:stream';
7
- import { pipeline } from 'node:stream/promises';
8
- import { downloaded, inspectedFile, storeRefusal, uploaded } from './files.js';
4
+ import { resolve } from 'node:path';
5
+ import { text as textOf } from 'node:stream/consumers';
6
+ import { downloaded, fileInfo, fileRange, mediaTypeOf, opened, sentPart, storeRefusal, uploaded, } from './files.js';
9
7
  import { HOUSE_REF } from './git.js';
10
- import { ownerSocket, readOwnAgent } from './home.js';
11
- import { callHouse, rpc, UNREACHABLE, Unsettled } from './mcp.js';
12
- import { refusalOf, retryable } from './refusals.js';
13
- import { proxyUnlessRelayed, relayed, selectRelay } from './relay.js';
8
+ import { ownerSocket } from './home.js';
9
+ import { ownAgentCall, rpc, unconfirmed, UNREACHABLE } from './mcp.js';
10
+ import { refusalOf } from './refusals.js';
14
11
  import { parse } from 'yaml';
15
- const USAGE = "usage: house <tool> ['<arguments as JSON>']";
12
+ const USAGE = "usage: house <tool> ['<arguments as JSON>'], or house <tool> - to read them from stdin; house help <tool>: its arguments";
13
+ const HELP = 'help [tool]';
16
14
  const PUSH_USAGE = 'usage: house push [commit] [--owner]';
17
- const PUSH = "push [commit]: sends the Local copy's committed changes to House";
15
+ const PUSH = "push [commit]: sends the Local copy's committed changes to House in one push, each .md file as document text and every other file as an attachment";
18
16
  const FETCH_USAGE = 'usage: house fetch';
19
17
  const FETCH = `fetch: records House's changes on each Local copy's ${HOUSE_REF}`;
20
18
  const DOWNLOAD_USAGE = `usage: house download '{"path":"/rooms/<handle>/<path>","file":"<local file>"}', adding "ref" for a revision`;
21
19
  const DOWNLOAD = 'download: writes a binary file of a Room to the local file named by file';
22
- const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
20
+ const UPLOAD_USAGE = `usage: house upload '{"file":"<local file>","room_ref":"r_…","path":"<path in the Room>"}', adding "base", the revision it replaces`;
21
+ const ARGUMENTS = `the arguments are one JSON object, in single quotes or on stdin after -, like house search '{"query":"invoice"}'`;
23
22
  const CLOSED = "this conversation's House connection is closed; nothing to do from here";
24
23
  const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
25
24
  const REVOKED = 'this conversation no longer has House access; nothing to do from here';
26
- const UNCONNECTED = "this computer's own agent has no House connection; run kit login, or kit chatgpt --key <key> with a script key";
27
- const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login, or kit chatgpt --key <key> with a script key";
28
- const UNCONFIRMED = 'with no result; a write may or may not have taken effect, so read before you repeat it';
29
25
  const socketPath = process.env.HOUSE_BRIDGE;
30
- const MEDIA_TYPES = new Map([
31
- ['avif', 'image/avif'],
32
- ['csv', 'text/csv'],
33
- ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
34
- ['gif', 'image/gif'],
35
- ['heic', 'image/heic'],
36
- ['html', 'text/html'],
37
- ['jpeg', 'image/jpeg'],
38
- ['jpg', 'image/jpeg'],
39
- ['json', 'application/json'],
40
- ['m4a', 'audio/mp4'],
41
- ['md', 'text/markdown'],
42
- ['mov', 'video/quicktime'],
43
- ['mp3', 'audio/mpeg'],
44
- ['mp4', 'video/mp4'],
45
- ['ogg', 'audio/ogg'],
46
- ['pdf', 'application/pdf'],
47
- ['png', 'image/png'],
48
- ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
49
- ['svg', 'image/svg+xml'],
50
- ['txt', 'text/plain'],
51
- ['wav', 'audio/wav'],
52
- ['webm', 'video/webm'],
53
- ['webp', 'image/webp'],
54
- ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
55
- ['zip', 'application/zip'],
56
- ]);
26
+ const WAY = {
27
+ ...(socketPath === undefined ? {} : { socketPath }),
28
+ unreached: (error) => new Error(socketPath === undefined ? UNREACHABLE : error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED),
29
+ refused: (status) => storeRefusal('upload', status),
30
+ };
57
31
  function refused(path, status, text, local) {
58
32
  const refusal = refusalOf(text);
59
33
  if (refusal !== null)
@@ -64,9 +38,6 @@ function refused(path, status, text, local) {
64
38
  return text;
65
39
  return path === '/' ? unconfirmed(status) : `${path} answered ${status}`;
66
40
  }
67
- function unconfirmed(status) {
68
- return `House answered ${status} ${UNCONFIRMED}`;
69
- }
70
41
  function bridged(path, body, to = socketPath) {
71
42
  return new Promise((resolve, reject) => {
72
43
  const sent = request({ socketPath: to, path, method: 'POST', headers: { 'content-type': 'application/json' } }, (answer) => {
@@ -84,24 +55,9 @@ function bridged(path, body, to = socketPath) {
84
55
  sent.end(JSON.stringify(body));
85
56
  });
86
57
  }
87
- async function direct(message) {
88
- const ownAgent = await readOwnAgent();
89
- if (ownAgent === null)
90
- throw new Error(UNCONNECTED);
91
- selectRelay(process.env.HOUSE_KIT_RELAY || ownAgent.relay);
92
- const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
93
- throw new Unsettled(UNREACHABLE);
94
- });
95
- if (answer.status === 200)
96
- return answer.text;
97
- if (answer.status === 401)
98
- throw new Error(DISCONNECTED);
99
- const refusal = refusalOf(answer.text)?.text ?? unconfirmed(answer.status);
100
- throw retryable(answer.text) === false ? new Error(refusal) : new Unsettled(refusal);
101
- }
102
58
  async function mcp(method, params) {
103
59
  const message = rpc(method, params);
104
- const answer = JSON.parse(socketPath === undefined ? await direct(message) : await bridged('/', message));
60
+ const answer = JSON.parse(socketPath === undefined ? await ownAgentCall(message) : await bridged('/', message));
105
61
  if (answer.error !== undefined)
106
62
  throw new Error(answer.error.message);
107
63
  return answer.result;
@@ -114,54 +70,21 @@ function unreadable(path, error) {
114
70
  ? `${path} is a folder; upload one file at a time`
115
71
  : `${path} is not a readable file`);
116
72
  }
117
- function opened(url, method, headers, body) {
118
- return new Promise((answered, failed) => {
119
- const local = socketPath !== undefined;
120
- const target = local ? null : relayed(url);
121
- if (!local)
122
- proxyUnlessRelayed();
123
- const sent = target === null
124
- ? request({ socketPath, path: url, method, headers }, answered)
125
- : (target.protocol === 'https:' ? httpsRequest : request)(target, { method, headers }, answered);
126
- sent.on('error', (error) => failed(new Error(!local ? UNREACHABLE : error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED)));
127
- if (body === undefined)
128
- sent.end();
129
- else
130
- pipeline(body, sent).catch(() => undefined);
131
- });
132
- }
133
- function ranged(file, start, end) {
134
- return end === start ? undefined : createReadStream(file, { start, end: end - 1 });
135
- }
136
- async function* read(file, start, end) {
137
- try {
138
- yield* ranged(file, start, end) ?? [];
139
- }
140
- catch (error) {
141
- throw unreadable(file, error);
142
- }
143
- }
144
- async function sentPart(url, file, start, end, headers) {
145
- const answer = await opened(url, 'PUT', { ...headers, 'content-length': String(end - start) }, ranged(file, start, end));
146
- await answer.toArray();
147
- if (answer.statusCode !== 200)
148
- throw storeRefusal('upload', answer.statusCode);
149
- }
150
73
  async function download(args) {
151
74
  const { flags, positionals: [argument] } = accepted(args, ['--help'], 1, DOWNLOAD_USAGE);
152
75
  if (flags.has('--help'))
153
76
  return DOWNLOAD_USAGE;
154
- const { file, ...selected } = argumentsOf(argument);
77
+ const { file, ...selected } = await argumentsOf(argument);
155
78
  if (typeof file !== 'string' || file === '')
156
79
  throw new Error('download needs "file", the local file to write');
157
80
  const written = resolve(file);
158
81
  await downloaded(async () => {
159
- const file = inspectedFile(await called('inspect', selected));
82
+ const file = fileInfo(await called('info', selected));
160
83
  if (file === null)
161
84
  throw new Error(`${String(selected.path)} holds no binary file; shell reads its text`);
162
85
  return file;
163
86
  }, async (url) => {
164
- const answer = await opened(url, 'GET', {});
87
+ const answer = await opened(url, 'GET', {}, WAY);
165
88
  return { status: answer.statusCode, body: answer };
166
89
  }, written, String(selected.path));
167
90
  return written;
@@ -178,7 +101,7 @@ async function described(file) {
178
101
  catch (error) {
179
102
  throw unreadable(file, error);
180
103
  }
181
- const mediaType = MEDIA_TYPES.get(extname(file).slice(1).toLowerCase());
104
+ const mediaType = mediaTypeOf(file);
182
105
  return { bytes, sha256: digest.digest('hex'), ...(mediaType === undefined ? {} : { media_type: mediaType }) };
183
106
  }
184
107
  async function finished(upload, room, partSha256) {
@@ -198,8 +121,8 @@ async function upload({ file, ...destination }) {
198
121
  name: file,
199
122
  bytes: description.bytes,
200
123
  sha256: description.sha256,
201
- read: (start, end) => read(file, start, end),
202
- send: (url, start, end, headers) => sentPart(url, file, start, end, headers),
124
+ read: (start, end) => fileRange(file, start, end, (error) => unreadable(file, error)),
125
+ send: (url, start, end, headers) => sentPart(url, file, start, end, headers, WAY),
203
126
  finish: (id, partSha256) => finished(id, destination.room_ref, partSha256),
204
127
  });
205
128
  return accepted.text;
@@ -212,7 +135,7 @@ function accepted(args, flags, positionals, usage) {
212
135
  for (const arg of args) {
213
136
  if (flags.includes(arg))
214
137
  given.flags.add(arg);
215
- else if (!arg.startsWith('-') && given.positionals.length < positionals)
138
+ else if ((arg === '-' || !arg.startsWith('-')) && given.positionals.length < positionals)
216
139
  given.positionals.push(arg);
217
140
  else
218
141
  throw unexpected(arg, usage);
@@ -222,7 +145,7 @@ function accepted(args, flags, positionals, usage) {
222
145
  async function push(args) {
223
146
  const { flags, positionals: [commit = 'HEAD'] } = accepted(args, ['--help', '--owner'], 1, PUSH_USAGE);
224
147
  if (flags.has('--help'))
225
- return PUSH_USAGE;
148
+ return `${PUSH_USAGE}\n${PUSH}`;
226
149
  const owner = flags.has('--owner');
227
150
  if (owner && socketPath !== undefined)
228
151
  throw new Error('--owner is not for Agent conversations; run house push without it');
@@ -241,12 +164,13 @@ async function fetched(args) {
241
164
  throw new Error(answer.text);
242
165
  return answer.text;
243
166
  }
244
- function argumentsOf(argument) {
167
+ async function argumentsOf(argument) {
245
168
  if (argument === undefined)
246
169
  return {};
170
+ const given = argument === '-' ? await textOf(process.stdin) : argument;
247
171
  let parsed;
248
172
  try {
249
- parsed = JSON.parse(argument);
173
+ parsed = JSON.parse(given);
250
174
  }
251
175
  catch {
252
176
  throw new Error(ARGUMENTS);
@@ -255,22 +179,78 @@ function argumentsOf(argument) {
255
179
  throw new Error(ARGUMENTS);
256
180
  return parsed;
257
181
  }
182
+ // The schema a $ref points to inside the Tool's own inputSchema, or an empty one when it points elsewhere.
183
+ function resolved(schema, root) {
184
+ if (schema.$ref === undefined)
185
+ return schema;
186
+ if (!schema.$ref.startsWith('#'))
187
+ return {};
188
+ let found = root;
189
+ for (const key of schema.$ref.split('/').slice(1)) {
190
+ found = typeof found === 'object' && found !== null ? found[key.replaceAll('~1', '/').replaceAll('~0', '~')] : undefined;
191
+ }
192
+ return typeof found === 'object' && found !== null ? found : {};
193
+ }
194
+ // The schema a $ref resolves to, with that $ref added to the open ones, or null when it is open already,
195
+ // so a schema that holds itself is expanded once.
196
+ function expanded(schema, root, refs) {
197
+ if (schema.$ref === undefined)
198
+ return { schema, refs };
199
+ return refs.has(schema.$ref) ? null : { schema: resolved(schema, root), refs: new Set([...refs, schema.$ref]) };
200
+ }
201
+ // One line per argument: its name, its value when it has one or a few, whether it is required, and its
202
+ // description. When deep, the arguments its value holds follow it.
203
+ function argumentLines(schema, root, indent, deep, refs = new Set()) {
204
+ const required = new Set(schema.required ?? []);
205
+ return Object.entries(schema.properties ?? {}).flatMap(([name, property]) => {
206
+ const value = resolved(property, root);
207
+ const values = value.const !== undefined ? [value.const] : (value.enum ?? []);
208
+ const words = [name, ...(values.length === 0 ? [] : [values.map((one) => JSON.stringify(one)).join(' | ')]), ...(required.has(name) ? ['(required)'] : [])];
209
+ const description = property.description ?? value.description;
210
+ const line = `${indent}${words.join(' ')}${description === undefined ? '' : `: ${description}`}`;
211
+ return deep ? [line, ...held(property, root, `${indent} `, refs)] : [line];
212
+ });
213
+ }
214
+ // The arguments a value holds: its own, its items', and those of each alternative of a oneOf or anyOf,
215
+ // each alternative a "- " entry when more than one has arguments.
216
+ function held(schema, root, indent, refs) {
217
+ const value = expanded(schema, root, refs);
218
+ if (value === null)
219
+ return [];
220
+ const alternatives = (value.schema.oneOf ?? value.schema.anyOf ?? [])
221
+ .map((alternative) => held(alternative, root, indent, value.refs))
222
+ .filter((lines) => lines.length > 0);
223
+ return [
224
+ ...argumentLines(value.schema, root, indent, true, value.refs),
225
+ ...(value.schema.items === undefined ? [] : held(value.schema.items, root, indent, value.refs)),
226
+ ...(alternatives.length === 1
227
+ ? alternatives[0]
228
+ : alternatives.flatMap((lines) => lines.map((line, index) => (index === 0 ? `${indent}- ${line.slice(indent.length)}` : ` ${line}`)))),
229
+ ];
230
+ }
231
+ function listed(tool) {
232
+ return tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`;
233
+ }
234
+ async function toolHelp(name) {
235
+ const tool = (await tools()).find((one) => one.name === name);
236
+ if (tool === undefined)
237
+ throw new Error(`${name} is no Tool; house find_command '{"query":"${name}"}' finds Commands`);
238
+ return [listed(tool), ...argumentLines(tool.inputSchema, tool.inputSchema, ' ', true)].join('\n');
239
+ }
258
240
  async function house(args) {
259
241
  const { flags, positionals: [verb, argument] } = accepted(args, ['--help'], 2, USAGE);
260
- if (verb === 'help' && argument !== undefined)
261
- throw unexpected(argument, USAGE);
262
242
  if (flags.has('--help') && argument !== undefined)
263
243
  throw unexpected('--help', USAGE);
244
+ // house help <name> runs as house <name> --help, so both forms answer alike.
245
+ if (verb === 'help' && argument !== undefined)
246
+ return run([argument, '--help']);
264
247
  if (verb === undefined || verb === 'help') {
265
- return [USAGE, 'help', PUSH, FETCH, DOWNLOAD, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
248
+ const listing = (await tools()).flatMap((tool) => tool.description === undefined ? [tool.name, ...argumentLines(tool.inputSchema, tool.inputSchema, ' ', false)] : [listed(tool)]);
249
+ return [USAGE, HELP, PUSH, FETCH, DOWNLOAD, ...listing].join('\n');
266
250
  }
267
- if (flags.has('--help')) {
268
- const tool = (await tools()).find((listed) => listed.name === verb);
269
- if (tool === undefined)
270
- throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
271
- return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
272
- }
273
- const parsed = argumentsOf(argument);
251
+ if (flags.has('--help'))
252
+ return verb === 'upload' ? UPLOAD_USAGE : toolHelp(verb);
253
+ const parsed = await argumentsOf(argument);
274
254
  return verb === 'upload' ? upload(parsed) : called(verb, parsed);
275
255
  }
276
256
  async function called(name, args) {
@@ -280,16 +260,19 @@ async function called(name, args) {
280
260
  throw new Error(text.replace(/\n+$/, ''));
281
261
  return text;
282
262
  }
263
+ function run(argv) {
264
+ const named = argv.findIndex((arg) => !arg.startsWith('-'));
265
+ const rest = argv.filter((_arg, index) => index !== named);
266
+ if (argv[named] === 'push')
267
+ return push(rest);
268
+ if (argv[named] === 'fetch')
269
+ return fetched(rest);
270
+ if (argv[named] === 'download')
271
+ return download(rest);
272
+ return house(argv);
273
+ }
283
274
  const argv = process.argv.slice(2);
284
- const named = argv.findIndex((arg) => !arg.startsWith('-'));
285
- const rest = argv.filter((_arg, index) => index !== named);
286
- (argv[named] === 'push'
287
- ? push(rest)
288
- : argv[named] === 'fetch'
289
- ? fetched(rest)
290
- : argv[named] === 'download'
291
- ? download(rest)
292
- : house(argv)).then((text) => {
275
+ run(argv).then((text) => {
293
276
  process.stdout.write(`${text}\n`);
294
277
  if (argv[0] === 'shell')
295
278
  process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
@@ -1,5 +1,4 @@
1
1
  import { agentInstructions } from '@agentshouse/skills';
2
- import { HOUSE_REF } from './git.js';
3
2
  const OWNER_RULES = '/rooms/private/owner-rules.md';
4
3
  const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
5
4
  const FAILED = /^exit: [1-9]\d*$/;
@@ -26,7 +25,6 @@ async function readOwnerRules(bridge) {
26
25
  }
27
26
  return document;
28
27
  }
29
- export async function instructions(bridge, base, copies) {
30
- const lines = agentInstructions(HOUSE_REF, copies);
31
- return [lines.join('\n'), base, (await readOwnerRules(bridge)).replace(/\n$/, '')].filter((part) => part !== '').join('\n\n');
28
+ export async function instructions(bridge, base) {
29
+ return [agentInstructions().join('\n'), base, (await readOwnerRules(bridge)).replace(/\n$/, '')].filter((part) => part !== '').join('\n\n');
32
30
  }
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
+ };
package/dist/kit-cli.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { parseArgs } from 'node:util';
2
2
  import { answerGitCredential } from './app-git.js';
3
- import { chatgpt } from './chatgpt.js';
3
+ import { connect } from './connect.js';
4
4
  import { login } from './login.js';
5
5
  import { logout } from './logout.js';
6
6
  import { proxyUnlessRelayed } from './relay.js';
7
7
  import { resident } from './resident.js';
8
- const USAGE = 'usage: kit <login|logout|resident|chatgpt>\n';
8
+ import { kitSettings, SETTINGS_USAGE } from './settings.js';
9
+ const USAGE = 'usage: kit <connect|login|logout|resident|settings>\n';
9
10
  const COMMANDS = new Map([
10
11
  [
11
12
  'logout',
@@ -25,6 +26,15 @@ const COMMANDS = new Map([
25
26
  run: resident,
26
27
  },
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
+ ],
28
38
  [
29
39
  'git-credential',
30
40
  {
@@ -38,10 +48,10 @@ const COMMANDS = new Map([
38
48
  const [command, ...argv] = process.argv.slice(2);
39
49
  proxyUnlessRelayed();
40
50
  async function run() {
51
+ if (command === 'connect')
52
+ return connect(argv);
41
53
  if (command === 'login')
42
54
  return login(argv);
43
- if (command === 'chatgpt')
44
- return chatgpt(argv);
45
55
  if (command === '--help') {
46
56
  parseArgs({ args: argv });
47
57
  process.stdout.write(USAGE);