@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/house-cli.js CHANGED
@@ -1,59 +1,31 @@
1
- import { createHash } from 'node:crypto';
2
- import { createReadStream } from 'node:fs';
3
1
  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';
9
- 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';
2
+ import { resolve } from 'node:path';
3
+ import { text as textOf } from 'node:stream/consumers';
4
+ import { downloaded, fileInfo, fileRange, mediaTypeOf, opened, sentPart, storeRefusal, uploaded, } from './files.js';
5
+ import { DEFAULT_MAX_SIZE, UPLOAD_NEEDS_OWNER } from './copies.js';
6
+ import { ownerSocket } from './home.js';
7
+ import { fileDigest } from './manifest.js';
8
+ import { ownAgentCall, rpc, unconfirmed, UNREACHABLE } from './mcp.js';
9
+ import { refusalOf } from './refusals.js';
14
10
  import { parse } from 'yaml';
15
- const USAGE = "usage: house <tool> ['<arguments as JSON>']";
16
- const PUSH_USAGE = 'usage: house push [commit] [--owner]';
17
- const PUSH = "push [commit]: sends the Local copy's committed changes to House";
18
- const FETCH_USAGE = 'usage: house fetch';
19
- const FETCH = `fetch: records House's changes on each Local copy's ${HOUSE_REF}`;
20
- const DOWNLOAD_USAGE = `usage: house download '{"path":"/rooms/<handle>/<path>","file":"<local file>"}', adding "ref" for a revision`;
21
- 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"}'`;
23
- const CLOSED = "this conversation's House connection is closed; nothing to do from here";
11
+ const USAGE = "usage: house <tool> ['<arguments as JSON>'], or house <tool> - to read them from stdin; house help <tool>: its arguments";
12
+ const HELP = 'help [tool]';
13
+ const UPLOAD_USAGE = `usage: house upload [--owner], or house upload '{"file":"<local file>","path":"/rooms/<handle>/<path>"}', adding "base", the revision it replaces`;
14
+ const UPLOAD = "upload: in a Room's Local copy, sends every file changed, added or deleted there since it last matched House, each .md file as document text and every other file as an attachment, with --owner outside an Agent conversation; with JSON, sends one local file to the Room path it names";
15
+ const DOWNLOAD_USAGE = `usage: house download [--with-attachments] [--max-size <MB>], or house download '{"path":"/rooms/<handle>/<path>","file":"<local file>"}', adding "ref" for a revision`;
16
+ const DOWNLOAD = `download: brings House's changes into every Local copy, leaving each file changed here for the next house upload, and with --with-attachments each attachment it lacks up to --max-size megabytes, ${DEFAULT_MAX_SIZE} by default; with JSON, writes one attachment of a Room to the local file named by file`;
17
+ const MAX_SIZE = `--max-size takes a number of megabytes; ${DOWNLOAD_USAGE}`;
18
+ const MEGABYTES = /^\d+(?:\.\d+)?$/;
19
+ const ARGUMENTS = `the arguments are one JSON object, in single quotes or on stdin after -, like house search '{"query":"invoice"}'`;
20
+ const CLOSED = 'this House connection is closed; nothing to do from here';
24
21
  const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
25
22
  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
23
  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
- ]);
24
+ const WAY = {
25
+ ...(socketPath === undefined ? {} : { socketPath }),
26
+ unreached: (error) => new Error(socketPath === undefined ? UNREACHABLE : error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED),
27
+ refused: (status) => storeRefusal('upload', status),
28
+ };
57
29
  function refused(path, status, text, local) {
58
30
  const refusal = refusalOf(text);
59
31
  if (refusal !== null)
@@ -64,9 +36,6 @@ function refused(path, status, text, local) {
64
36
  return text;
65
37
  return path === '/' ? unconfirmed(status) : `${path} answered ${status}`;
66
38
  }
67
- function unconfirmed(status) {
68
- return `House answered ${status} ${UNCONFIRMED}`;
69
- }
70
39
  function bridged(path, body, to = socketPath) {
71
40
  return new Promise((resolve, reject) => {
72
41
  const sent = request({ socketPath: to, path, method: 'POST', headers: { 'content-type': 'application/json' } }, (answer) => {
@@ -84,24 +53,9 @@ function bridged(path, body, to = socketPath) {
84
53
  sent.end(JSON.stringify(body));
85
54
  });
86
55
  }
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
56
  async function mcp(method, params) {
103
57
  const message = rpc(method, params);
104
- const answer = JSON.parse(socketPath === undefined ? await direct(message) : await bridged('/', message));
58
+ const answer = JSON.parse(socketPath === undefined ? await ownAgentCall(message) : await bridged('/', message));
105
59
  if (answer.error !== undefined)
106
60
  throw new Error(answer.error.message);
107
61
  return answer.result;
@@ -114,75 +68,49 @@ function unreadable(path, error) {
114
68
  ? `${path} is a folder; upload one file at a time`
115
69
  : `${path} is not a readable file`);
116
70
  }
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
71
  async function download(args) {
151
- const { flags, positionals: [argument] } = accepted(args, ['--help'], 1, DOWNLOAD_USAGE);
72
+ const valued = args.indexOf('--max-size');
73
+ const size = valued === -1 ? undefined : args[valued + 1];
74
+ const rest = valued === -1 ? args : args.filter((_arg, index) => index !== valued && index !== valued + 1);
75
+ const { flags, positionals: [argument] } = accepted(rest, ['--help', '--with-attachments'], 1, DOWNLOAD_USAGE);
152
76
  if (flags.has('--help'))
153
- return DOWNLOAD_USAGE;
154
- const { file, ...selected } = argumentsOf(argument);
77
+ return `${DOWNLOAD_USAGE}\n${DOWNLOAD}`;
78
+ if (argument === undefined) {
79
+ if (valued !== -1 && !MEGABYTES.test(size ?? ''))
80
+ throw new Error(MAX_SIZE);
81
+ const maxSize = size === undefined ? DEFAULT_MAX_SIZE : Number(size);
82
+ return copyVerb('/copy/download', { attachments: flags.has('--with-attachments'), max_size: maxSize });
83
+ }
84
+ if (valued !== -1 || flags.has('--with-attachments'))
85
+ throw unexpected(valued !== -1 ? '--max-size' : '--with-attachments', DOWNLOAD_USAGE);
86
+ const { file, ...selected } = await argumentsOf(argument);
155
87
  if (typeof file !== 'string' || file === '')
156
88
  throw new Error('download needs "file", the local file to write');
157
89
  const written = resolve(file);
158
90
  await downloaded(async () => {
159
- const file = inspectedFile(await called('inspect', selected));
91
+ const file = fileInfo(await called('info', selected));
160
92
  if (file === null)
161
93
  throw new Error(`${String(selected.path)} holds no binary file; shell reads its text`);
162
94
  return file;
163
95
  }, async (url) => {
164
- const answer = await opened(url, 'GET', {});
96
+ const answer = await opened(url, 'GET', {}, WAY);
165
97
  return { status: answer.statusCode, body: answer };
166
98
  }, written, String(selected.path));
167
99
  return written;
168
100
  }
169
101
  async function described(file) {
170
- const digest = createHash('sha256');
171
- let bytes = 0;
102
+ let held;
172
103
  try {
173
- for await (const chunk of createReadStream(file)) {
174
- digest.update(chunk);
175
- bytes += chunk.length;
176
- }
104
+ held = await fileDigest(file);
177
105
  }
178
106
  catch (error) {
179
107
  throw unreadable(file, error);
180
108
  }
181
- const mediaType = MEDIA_TYPES.get(extname(file).slice(1).toLowerCase());
182
- return { bytes, sha256: digest.digest('hex'), ...(mediaType === undefined ? {} : { media_type: mediaType }) };
109
+ const mediaType = mediaTypeOf(file);
110
+ return { bytes: held.bytes, sha256: held.sha256, ...(mediaType === undefined ? {} : { media_type: mediaType }) };
183
111
  }
184
- async function finished(upload, room, partSha256) {
185
- const text = await called('upload', { upload, room_ref: room, part_sha256: partSha256 });
112
+ async function finished(upload, path, partSha256) {
113
+ const text = await called('upload', { upload, path, part_sha256: partSha256 });
186
114
  const answer = parse(text);
187
115
  return answer !== null && 'upload' in answer ? answer : { text };
188
116
  }
@@ -198,9 +126,9 @@ async function upload({ file, ...destination }) {
198
126
  name: file,
199
127
  bytes: description.bytes,
200
128
  sha256: description.sha256,
201
- read: (start, end) => read(file, start, end),
202
- send: (url, start, end, headers) => sentPart(url, file, start, end, headers),
203
- finish: (id, partSha256) => finished(id, destination.room_ref, partSha256),
129
+ read: (start, end) => fileRange(file, start, end, (error) => unreadable(file, error)),
130
+ send: (url, start, end, headers) => sentPart(url, file, start, end, headers, WAY),
131
+ finish: (id, partSha256) => finished(id, destination.path, partSha256),
204
132
  });
205
133
  return accepted.text;
206
134
  }
@@ -212,41 +140,40 @@ function accepted(args, flags, positionals, usage) {
212
140
  for (const arg of args) {
213
141
  if (flags.includes(arg))
214
142
  given.flags.add(arg);
215
- else if (!arg.startsWith('-') && given.positionals.length < positionals)
143
+ else if ((arg === '-' || !arg.startsWith('-')) && given.positionals.length < positionals)
216
144
  given.positionals.push(arg);
217
145
  else
218
146
  throw unexpected(arg, usage);
219
147
  }
220
148
  return given;
221
149
  }
222
- async function push(args) {
223
- const { flags, positionals: [commit = 'HEAD'] } = accepted(args, ['--help', '--owner'], 1, PUSH_USAGE);
224
- if (flags.has('--help'))
225
- return PUSH_USAGE;
226
- const owner = flags.has('--owner');
227
- if (owner && socketPath !== undefined)
228
- throw new Error('--owner is not for Agent conversations; run house push without it');
229
- if (!owner && socketPath === undefined)
230
- throw new Error('outside an Agent conversation, house push needs --owner');
231
- const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, owner ? ownerSocket() : socketPath));
232
- if (pushed.refused)
233
- throw new Error(pushed.text);
234
- return pushed.text;
235
- }
236
- async function fetched(args) {
237
- if (accepted(args, ['--help'], 0, FETCH_USAGE).flags.has('--help'))
238
- return FETCH_USAGE;
239
- const answer = JSON.parse(await bridged('/git/fetch', {}, socketPath ?? ownerSocket()));
150
+ async function copyVerb(path, body) {
151
+ const answer = JSON.parse(await bridged(path, body, socketPath ?? ownerSocket()));
240
152
  if (answer.refused)
241
153
  throw new Error(answer.text);
242
154
  return answer.text;
243
155
  }
244
- function argumentsOf(argument) {
156
+ async function uploadVerb(args) {
157
+ const { flags, positionals: [argument] } = accepted(args, ['--help', '--owner'], 1, UPLOAD_USAGE);
158
+ if (flags.has('--help'))
159
+ return `${UPLOAD_USAGE}\n${UPLOAD}`;
160
+ if (argument !== undefined) {
161
+ if (flags.has('--owner'))
162
+ throw unexpected('--owner', UPLOAD_USAGE);
163
+ return upload(await argumentsOf(argument));
164
+ }
165
+ const owner = flags.has('--owner');
166
+ if (!owner && socketPath === undefined)
167
+ throw new Error(UPLOAD_NEEDS_OWNER);
168
+ return copyVerb('/copy/upload', { cwd: process.cwd(), owner });
169
+ }
170
+ async function argumentsOf(argument) {
245
171
  if (argument === undefined)
246
172
  return {};
173
+ const given = argument === '-' ? await textOf(process.stdin) : argument;
247
174
  let parsed;
248
175
  try {
249
- parsed = JSON.parse(argument);
176
+ parsed = JSON.parse(given);
250
177
  }
251
178
  catch {
252
179
  throw new Error(ARGUMENTS);
@@ -255,23 +182,78 @@ function argumentsOf(argument) {
255
182
  throw new Error(ARGUMENTS);
256
183
  return parsed;
257
184
  }
185
+ // The schema a $ref points to inside the Tool's own inputSchema, or an empty one when it points elsewhere.
186
+ function resolved(schema, root) {
187
+ if (schema.$ref === undefined)
188
+ return schema;
189
+ if (!schema.$ref.startsWith('#'))
190
+ return {};
191
+ let found = root;
192
+ for (const key of schema.$ref.split('/').slice(1)) {
193
+ found = typeof found === 'object' && found !== null ? found[key.replaceAll('~1', '/').replaceAll('~0', '~')] : undefined;
194
+ }
195
+ return typeof found === 'object' && found !== null ? found : {};
196
+ }
197
+ // The schema a $ref resolves to, with that $ref added to the open ones, or null when it is open already,
198
+ // so a schema that holds itself is expanded once.
199
+ function expanded(schema, root, refs) {
200
+ if (schema.$ref === undefined)
201
+ return { schema, refs };
202
+ return refs.has(schema.$ref) ? null : { schema: resolved(schema, root), refs: new Set([...refs, schema.$ref]) };
203
+ }
204
+ // One line per argument: its name, its value when it has one or a few, whether it is required, and its
205
+ // description. When deep, the arguments its value holds follow it.
206
+ function argumentLines(schema, root, indent, deep, refs = new Set()) {
207
+ const required = new Set(schema.required ?? []);
208
+ return Object.entries(schema.properties ?? {}).flatMap(([name, property]) => {
209
+ const value = resolved(property, root);
210
+ const values = value.const !== undefined ? [value.const] : (value.enum ?? []);
211
+ const words = [name, ...(values.length === 0 ? [] : [values.map((one) => JSON.stringify(one)).join(' | ')]), ...(required.has(name) ? ['(required)'] : [])];
212
+ const description = property.description ?? value.description;
213
+ const line = `${indent}${words.join(' ')}${description === undefined ? '' : `: ${description}`}`;
214
+ return deep ? [line, ...held(property, root, `${indent} `, refs)] : [line];
215
+ });
216
+ }
217
+ // The arguments a value holds: its own, its items', and those of each alternative of a oneOf or anyOf,
218
+ // each alternative a "- " entry when more than one has arguments.
219
+ function held(schema, root, indent, refs) {
220
+ const value = expanded(schema, root, refs);
221
+ if (value === null)
222
+ return [];
223
+ const alternatives = (value.schema.oneOf ?? value.schema.anyOf ?? [])
224
+ .map((alternative) => held(alternative, root, indent, value.refs))
225
+ .filter((lines) => lines.length > 0);
226
+ return [
227
+ ...argumentLines(value.schema, root, indent, true, value.refs),
228
+ ...(value.schema.items === undefined ? [] : held(value.schema.items, root, indent, value.refs)),
229
+ ...(alternatives.length === 1
230
+ ? alternatives[0]
231
+ : alternatives.flatMap((lines) => lines.map((line, index) => (index === 0 ? `${indent}- ${line.slice(indent.length)}` : ` ${line}`)))),
232
+ ];
233
+ }
234
+ function listed(tool) {
235
+ return tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`;
236
+ }
237
+ async function toolHelp(name) {
238
+ const tool = (await tools()).find((one) => one.name === name);
239
+ if (tool === undefined)
240
+ throw new Error(`${name} is no Tool; house find_command '{"query":"${name}"}' finds Commands`);
241
+ return [listed(tool), ...argumentLines(tool.inputSchema, tool.inputSchema, ' ', true)].join('\n');
242
+ }
258
243
  async function house(args) {
259
244
  const { flags, positionals: [verb, argument] } = accepted(args, ['--help'], 2, USAGE);
260
- if (verb === 'help' && argument !== undefined)
261
- throw unexpected(argument, USAGE);
262
245
  if (flags.has('--help') && argument !== undefined)
263
246
  throw unexpected('--help', USAGE);
247
+ // house help <name> runs as house <name> --help, so both forms answer alike.
248
+ if (verb === 'help' && argument !== undefined)
249
+ return run([argument, '--help']);
264
250
  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');
266
- }
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');
251
+ const listing = (await tools()).flatMap((tool) => tool.description === undefined ? [tool.name, ...argumentLines(tool.inputSchema, tool.inputSchema, ' ', false)] : [listed(tool)]);
252
+ return [USAGE, HELP, UPLOAD, DOWNLOAD, ...listing].join('\n');
272
253
  }
273
- const parsed = argumentsOf(argument);
274
- return verb === 'upload' ? upload(parsed) : called(verb, parsed);
254
+ if (flags.has('--help'))
255
+ return toolHelp(verb);
256
+ return called(verb, await argumentsOf(argument));
275
257
  }
276
258
  async function called(name, args) {
277
259
  const result = await mcp('tools/call', { name, arguments: args });
@@ -280,16 +262,17 @@ async function called(name, args) {
280
262
  throw new Error(text.replace(/\n+$/, ''));
281
263
  return text;
282
264
  }
265
+ function run(argv) {
266
+ const named = argv.findIndex((arg) => !arg.startsWith('-'));
267
+ const rest = argv.filter((_arg, index) => index !== named);
268
+ if (argv[named] === 'upload')
269
+ return uploadVerb(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
+ };