@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/bridge.js CHANGED
@@ -4,15 +4,20 @@ import { setTimeout as delay } from 'node:timers/promises';
4
4
  import { createServer, request as httpRequest } from 'node:http';
5
5
  import { request as httpsRequest } from 'node:https';
6
6
  import { delimiter, dirname, join } from 'node:path';
7
+ import { FUNCTION_RUN_META_KEY } from '@agentshouse/kit-wire';
7
8
  import { parse } from 'yaml';
8
9
  import { finalRefusal, HouseRefusal, retryDelay, retrying } from './api.js';
9
10
  import { loginPath } from './clis.js';
10
- import { changedPaths, } from './copies.js';
11
- import { kitHome, readEnrolment, socketDirectory } from './home.js';
12
- import { callHouse, mcpBody, rpc, UNREACHABLE } from './mcp.js';
11
+ import { changedPaths, DEFAULT_MAX_SIZE, UPLOAD_NEEDS_OWNER, } from './copies.js';
12
+ import { fileInfo } from './files.js';
13
+ import { readEnrolment, readOwnAgent, socketDirectory } from './home.js';
14
+ import { callHouse, DISCONNECTED, mcpBody, refusalIn, rpc, toolAnswer, UNREACHABLE } from './mcp.js';
13
15
  import { operationId } from './operation.js';
14
- import { refusalOf, retryable } from './refusals.js';
16
+ import { refusalOf, retryable, stopsPush } from './refusals.js';
15
17
  import { relayed } from './relay.js';
18
+ class Said extends Error {
19
+ }
20
+ const OWNER_IN_CONVERSATION = '--owner is not for Agent conversations; run house upload without it';
16
21
  const MCP_REQUEST_BYTES = 4_000_000;
17
22
  export async function received(request) {
18
23
  let text = '';
@@ -34,18 +39,6 @@ function relay(request, response, house, authorization) {
34
39
  forwarded.on('error', () => response.destroy());
35
40
  request.pipe(forwarded);
36
41
  }
37
- function refusalIn(text, status) {
38
- return refusalOf(text) ?? { code: '', text: text === '' ? `House refused it with ${status}` : text, conflicts: [] };
39
- }
40
- function answered(forwarded) {
41
- if (forwarded.status !== 200)
42
- return { refused: refusalIn(forwarded.text, forwarded.status) };
43
- const answer = JSON.parse(forwarded.text);
44
- if (answer.error !== undefined)
45
- return { refused: refusalIn(answer.error.message, forwarded.status) };
46
- const text = answer.result.content.map((content) => content.text).join('\n');
47
- return answer.result.isError === true ? { refused: refusalIn(text, forwarded.status) } : { text };
48
- }
49
42
  function pendingSeconds(forwarded) {
50
43
  if (forwarded.status !== 200)
51
44
  return null;
@@ -58,33 +51,77 @@ function pendingSeconds(forwarded) {
58
51
  const seconds = JSON.parse(text).pending.retry_after;
59
52
  return typeof seconds === 'number' ? seconds : null;
60
53
  }
61
- function resendAfter(forwarded, attempt) {
54
+ function resendAfter(forwarded, attempt, pushing) {
62
55
  if (forwarded === null)
63
56
  return retryDelay(attempt);
64
- if (forwarded.status !== 200)
57
+ if (forwarded.status !== 200) {
58
+ if (pushing && stopsPush(refusalOf(forwarded.text)))
59
+ return null;
65
60
  return retryable(forwarded.text) === false ? null : retryDelay(attempt);
61
+ }
66
62
  const seconds = pendingSeconds(forwarded);
67
63
  return seconds === null ? null : seconds * 1000;
68
64
  }
69
65
  function editAnswer(forwarded) {
70
- const answer = answered(forwarded);
66
+ const answer = toolAnswer(forwarded);
71
67
  if ('refused' in answer)
72
68
  return answer;
73
69
  const { results } = parse(answer.text);
74
70
  return {
75
71
  accepted: results.flatMap((result) => [
76
72
  ...(result.from === undefined ? [] : [{ path: result.from, revision: null, content: null }]),
77
- { path: result.path, revision: result.revision ?? null },
73
+ { path: result.path, revision: result.revision ?? null, ...(result.content === undefined ? {} : { content: result.content }) },
78
74
  ]),
79
75
  };
80
76
  }
81
77
  export async function openBridge(house, copies, conversationId, signal) {
82
- const path = [join(kitHome(), 'shim'), dirname(process.execPath), await loginPath()].join(delimiter);
78
+ const { credential } = await retrying(() => house.act('agent_update.credentials_issue', { conversation: conversationId }, signal), signal);
79
+ return bridgeFor(copies, {
80
+ key: `conversation:${conversationId}`,
81
+ origin: (await readEnrolment()).house,
82
+ credential,
83
+ named: {},
84
+ ownAgent: false,
85
+ owner: false,
86
+ path: [dirname(process.execPath), await loginPath()].join(delimiter),
87
+ });
88
+ }
89
+ async function runCredential(house, run, signal) {
90
+ try {
91
+ return (await retrying(() => house.act('agent_update.credentials_issue', { run }, signal), signal)).credential;
92
+ }
93
+ catch (error) {
94
+ if (finalRefusal(error))
95
+ return null;
96
+ throw error;
97
+ }
98
+ }
99
+ export async function openRunBridge(house, copies, run, signal) {
100
+ const named = { [FUNCTION_RUN_META_KEY]: run };
101
+ const ownAgent = await readOwnAgent();
102
+ if (ownAgent !== null) {
103
+ return bridgeFor(copies, {
104
+ key: `function-run:${run}`,
105
+ origin: ownAgent.house,
106
+ credential: ownAgent.credential,
107
+ named,
108
+ ownAgent: true,
109
+ owner: true,
110
+ path: null,
111
+ });
112
+ }
113
+ const credential = await runCredential(house, run, signal);
114
+ if (credential === null)
115
+ return null;
83
116
  const origin = (await readEnrolment()).house;
84
- const { credential } = await retrying(() => house.post(`/kit/conversations/${conversationId}/credential`, {}, signal), signal);
117
+ return bridgeFor(copies, { key: `function-run:${run}`, origin, credential, named, ownAgent: false, owner: true, path: null });
118
+ }
119
+ async function bridgeFor(copies, holder) {
120
+ const { origin, credential, named, path } = holder;
85
121
  const closed = new AbortController();
86
- const sent = (message, operation) => callHouse(origin, credential, message, operation, closed.signal);
87
- const send = async (message, operation) => {
122
+ const sent = (message, operation) => callHouse(origin, credential, message, { operation, named, signal: closed.signal });
123
+ const send = async (message, asked, pushing = false) => {
124
+ const operation = holder.ownAgent ? null : asked;
88
125
  if (operation === null)
89
126
  return sent(message, null);
90
127
  for (let attempt = 0;; attempt++) {
@@ -93,7 +130,7 @@ export async function openBridge(house, copies, conversationId, signal) {
93
130
  throw error;
94
131
  return null;
95
132
  });
96
- const after = resendAfter(forwarded, attempt);
133
+ const after = resendAfter(forwarded, attempt, pushing);
97
134
  if (after === null)
98
135
  return forwarded;
99
136
  // A Tool call House did not settle is sent again on the jittered curve, or after the wait House names for a pending one.
@@ -104,10 +141,7 @@ export async function openBridge(house, copies, conversationId, signal) {
104
141
  const staged = async (operation, changes) => {
105
142
  const bytes = Buffer.from(JSON.stringify({ changes }));
106
143
  const sha256 = createHash('sha256').update(bytes).digest('hex');
107
- const prepared = answered(await send(call('run_command', {
108
- command: 'prepare_edit_upload',
109
- arguments: { paths: changedPaths(changes), bytes: bytes.length, sha256 },
110
- }), operation));
144
+ const prepared = toolAnswer(await send(call('update', { op: 'stage', paths: changedPaths(changes), bytes: bytes.length, sha256 }), operation));
111
145
  if ('refused' in prepared)
112
146
  return prepared;
113
147
  const { transfer } = parse(prepared.text);
@@ -139,32 +173,49 @@ export async function openBridge(house, copies, conversationId, signal) {
139
173
  return send(message, message.method === 'tools/call' ? operationId() : null);
140
174
  };
141
175
  const caller = {
142
- key: `conversation:${conversationId}`,
176
+ key: holder.key,
143
177
  submit: async (operation, changes, held, retain) => {
144
- const inline = call('edit', { changes });
178
+ const inline = call('update', { changes });
145
179
  let upload = held;
146
- if (upload === undefined && Buffer.byteLength(mcpBody(inline, operation)) > MCP_REQUEST_BYTES) {
180
+ if (upload === undefined && Buffer.byteLength(mcpBody(inline, { operation, named })) > MCP_REQUEST_BYTES) {
147
181
  const prepared = await staged(operation, changes);
148
182
  if ('refused' in prepared)
149
183
  return prepared;
150
184
  upload = prepared;
151
185
  await retain(upload);
152
186
  }
153
- return editAnswer(await send(upload === undefined ? inline : call('edit', { paths: changedPaths(changes), upload }), operation));
187
+ return editAnswer(await send(upload === undefined ? inline : call('update', { paths: changedPaths(changes), upload }), operation, true));
188
+ },
189
+ finish: async (upload, path, partSha256) => {
190
+ const answer = toolAnswer(await send(call('upload', { upload, path, part_sha256: partSha256 }), operationId(), true));
191
+ if ('refused' in answer)
192
+ throw new Error(answer.refused.text);
193
+ return parse(answer.text);
194
+ },
195
+ info: async (path, revision) => {
196
+ const answer = toolAnswer(await send(call('info', { path, ...(revision === undefined ? {} : { ref: revision }) }), operationId()));
197
+ if ('refused' in answer)
198
+ throw new Error(answer.refused.text);
199
+ return fileInfo(answer.text);
154
200
  },
155
201
  };
202
+ const uploader = holder.owner ? copies.owner : caller;
156
203
  const local = async (path, text) => {
157
- if (path === '/git/push') {
158
- const { cwd, commit } = JSON.parse(text);
159
- return { status: 200, text: JSON.stringify(await copies.push(cwd, commit, caller)) };
204
+ if (path === '/copy/upload') {
205
+ const { cwd, owner } = JSON.parse(text);
206
+ const uploaded = owner === holder.owner ? await copies.upload(cwd, uploader) : { refused: true, text: owner ? OWNER_IN_CONVERSATION : UPLOAD_NEEDS_OWNER };
207
+ return { status: 200, text: JSON.stringify(uploaded) };
160
208
  }
161
- if (path === '/git/fetch')
162
- return { status: 200, text: JSON.stringify(await copies.fetch()) };
163
- if (path === '/git/observed') {
164
- await copies.observed(JSON.parse(text));
165
- return { status: 200, text: '{}' };
209
+ if (path === '/copy/download') {
210
+ const { attachments = false, max_size: maxSize = DEFAULT_MAX_SIZE } = JSON.parse(text);
211
+ return { status: 200, text: JSON.stringify(await copies.download(uploader, { attachments, maxSize })) };
166
212
  }
167
- return path === '/' ? forward(text) : { status: 404, text: '' };
213
+ if (path !== '/')
214
+ return { status: 404, text: '' };
215
+ const forwarded = await forward(text);
216
+ if (holder.ownAgent && forwarded.status === 401)
217
+ throw new Said(DISCONNECTED);
218
+ return forwarded;
168
219
  };
169
220
  const socketPath = join(socketDirectory(), `${randomUUID()}.sock`);
170
221
  const bridge = createServer(async (request, response) => {
@@ -178,11 +229,15 @@ export async function openBridge(house, copies, conversationId, signal) {
178
229
  response.writeHead(answered.status, { 'content-type': 'application/json' }).end(answered.text);
179
230
  }
180
231
  catch (error) {
232
+ if (error instanceof Said) {
233
+ response.writeHead(502).end(error.message);
234
+ return;
235
+ }
181
236
  if (error instanceof HouseRefusal) {
182
237
  response.writeHead(error.status, { 'content-type': 'application/json' }).end(error.text);
183
238
  return;
184
239
  }
185
- const verb = request.url === '/git/push' || request.url === '/git/fetch';
240
+ const verb = request.url === '/copy/upload' || request.url === '/copy/download';
186
241
  response.writeHead(502).end(verb && error instanceof Error ? error.message : UNREACHABLE);
187
242
  }
188
243
  });
@@ -204,7 +259,7 @@ export async function openBridge(house, copies, conversationId, signal) {
204
259
  return {
205
260
  env: {
206
261
  HOUSE_BRIDGE: socketPath,
207
- PATH: path,
262
+ ...(path === null ? {} : { PATH: path }),
208
263
  GIT_CONFIG_COUNT: '1',
209
264
  GIT_CONFIG_KEY_0: `url.${proxy}/app/.insteadOf`,
210
265
  GIT_CONFIG_VALUE_0: app,
package/dist/calls.js CHANGED
@@ -12,6 +12,8 @@ export class Calls {
12
12
  results;
13
13
  returned = new Set();
14
14
  released = new Set();
15
+ carrying = new Map();
16
+ settings = new Set();
15
17
  open = 0;
16
18
  constructor(house, changed) {
17
19
  this.house = house;
@@ -27,6 +29,13 @@ export class Calls {
27
29
  idle() {
28
30
  return this.open === 0;
29
31
  }
32
+ busy() {
33
+ return [...this.carrying.keys()].some((callId) => !this.settings.has(callId));
34
+ }
35
+ carrySettings(callId, work) {
36
+ this.settings.add(callId);
37
+ return this.carry(callId, work);
38
+ }
30
39
  carry(callId, work) {
31
40
  if (this.released.has(callId))
32
41
  return Promise.resolve();
@@ -38,11 +47,12 @@ export class Calls {
38
47
  carried.catch(() => this.carried.delete(callId));
39
48
  }
40
49
  this.open++;
50
+ this.carrying.set(callId, (this.carrying.get(callId) ?? 0) + 1);
41
51
  this.changed();
42
52
  return carried
43
53
  .then(async ({ result, returned, release }) => {
44
54
  try {
45
- await this.house.deliver(`/kit/inputs/${callId}/ack`, result);
55
+ await this.house.deliver('kit-calls/results/return', { call: callId, ...result });
46
56
  }
47
57
  finally {
48
58
  this.returned.add(callId);
@@ -60,6 +70,13 @@ export class Calls {
60
70
  .catch(logged)
61
71
  .finally(() => {
62
72
  this.open--;
73
+ const left = this.carrying.get(callId) - 1;
74
+ if (left === 0) {
75
+ this.carrying.delete(callId);
76
+ this.settings.delete(callId);
77
+ }
78
+ else
79
+ this.carrying.set(callId, left);
63
80
  this.changed();
64
81
  });
65
82
  }
package/dist/chunks.js ADDED
@@ -0,0 +1,54 @@
1
+ import { readFile, rm } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { downloaded, fetched } from './files.js';
4
+ const DOWNLOADS_AT_ONCE = 6;
5
+ // A chunk is about one megabyte, so a download still unfinished after two minutes holds every Room behind it on a dead connection.
6
+ const CHUNK_DOWNLOAD_MS = 120_000;
7
+ class AddressExpired extends Error {
8
+ constructor() {
9
+ super("House's store refused every chunk it asked for");
10
+ }
11
+ }
12
+ function once(chunk) {
13
+ let asked = false;
14
+ return async () => {
15
+ if (asked)
16
+ throw new AddressExpired();
17
+ asked = true;
18
+ return { download: chunk.download, sha256: chunk.hash };
19
+ };
20
+ }
21
+ export async function stagedChunks(directory, chunks) {
22
+ let next = 0;
23
+ let failure;
24
+ const downloading = async () => {
25
+ while (next < chunks.length && failure === undefined) {
26
+ const chunk = chunks[next++];
27
+ const reading = (url) => fetched(url, AbortSignal.timeout(CHUNK_DOWNLOAD_MS));
28
+ await downloaded(once(chunk), reading, join(directory, chunk.hash), 'A Room chunk').catch((error) => {
29
+ failure ??= error;
30
+ });
31
+ }
32
+ };
33
+ await Promise.all(Array.from({ length: DOWNLOADS_AT_ONCE }, downloading));
34
+ return failure;
35
+ }
36
+ export async function* chunkEntries(directory, chunks, models) {
37
+ for (const { hash } of chunks) {
38
+ for (const line of (await readFile(join(directory, hash), 'utf8')).split('\n'))
39
+ if (line !== '')
40
+ JSON.parse(line);
41
+ }
42
+ yield* models;
43
+ for (const { hash } of chunks) {
44
+ const file = join(directory, hash);
45
+ for (const line of (await readFile(file, 'utf8')).split('\n')) {
46
+ if (line === '')
47
+ continue;
48
+ const entry = JSON.parse(line);
49
+ if (!('folder' in entry))
50
+ yield entry;
51
+ }
52
+ await rm(file);
53
+ }
54
+ }
package/dist/clis.js CHANGED
@@ -2,8 +2,9 @@ import { spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { constants, readFileSync } from 'node:fs';
4
4
  import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
5
- import { homedir, userInfo } from 'node:os';
5
+ import { userInfo } from 'node:os';
6
6
  import { delimiter, dirname, isAbsolute, join } from 'node:path';
7
+ import { CLAUDE_KEY, CODEX_KEY, GROK_KEY, codexHome } from './keys.js';
7
8
  import { releaseDirectory } from './placement.js';
8
9
  import { childEnvironment } from './relay.js';
9
10
  const HOUSE_EXECUTABLES = /^host_executable\(name = "house", paths = (\[.*\])\)$/m;
@@ -20,6 +21,7 @@ const RAW_SUBTYPES = [
20
21
  'hook_started',
21
22
  'hook_response',
22
23
  ];
24
+ const RAW_TYPES = ['result', 'user', 'assistant', 'rate_limit_event', 'prompt_suggestion'];
23
25
  async function executable(path) {
24
26
  try {
25
27
  await access(path, constants.X_OK);
@@ -49,7 +51,7 @@ async function listedHouses(file) {
49
51
  }
50
52
  export async function allowHouseInCodex(path) {
51
53
  const candidates = [...new Set(path.split(delimiter).filter((directory) => isAbsolute(directory)))].map((directory) => join(directory, 'house'));
52
- const rules = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'rules');
54
+ const rules = join(codexHome(), 'rules');
53
55
  const file = join(rules, 'house.rules');
54
56
  const houses = [];
55
57
  for (const house of [...(await listedHouses(file)), ...candidates]) {
@@ -62,6 +64,14 @@ export async function allowHouseInCodex(path) {
62
64
  await rename(temporary, file);
63
65
  }
64
66
  async function nothing() { }
67
+ function claudeQuestionFields(request) {
68
+ const properties = request.requestedSchema?.properties ?? {};
69
+ return Object.keys(properties).filter((name) => properties[name]._meta?.jetbrains?.air?.customAnswer !== undefined);
70
+ }
71
+ function codexQuestionFields(request) {
72
+ const { _meta, requestedSchema } = request;
73
+ return _meta?.codex === undefined ? [] : (requestedSchema?.required ?? []);
74
+ }
65
75
  function answered(error) {
66
76
  return typeof error === 'object' && error !== null ? error : {};
67
77
  }
@@ -70,8 +80,9 @@ function bridgeInClaudeSandbox(bridge) {
70
80
  }
71
81
  export const CLIS = {
72
82
  'codex-acp': {
83
+ name: 'Codex',
73
84
  bin: 'codex',
74
- minimum: '0.160.1',
85
+ minimum: '0.165.0',
75
86
  install: 'curl -fsSL https://chatgpt.com/codex/install.sh | sh',
76
87
  update: 'codex update',
77
88
  adapter: {
@@ -87,15 +98,17 @@ export const CLIS = {
87
98
  const { code, data } = answered(error);
88
99
  return code === -32603 && typeof data?.details === 'string' && data.details.startsWith('no rollout found');
89
100
  },
90
- renames: true,
91
101
  allowHouse: allowHouseInCodex,
102
+ questionFields: codexQuestionFields,
92
103
  signedIn: { command: ['login', 'status'] },
93
104
  login: { args: ['login', '--device-auth'], code: 'show' },
105
+ key: CODEX_KEY,
94
106
  air: ['asyncTasks', 'nativeSubagentSessions'],
95
107
  },
96
108
  'claude-agent-acp': {
109
+ name: 'Claude Code',
97
110
  bin: 'claude',
98
- minimum: '2.1.303',
111
+ minimum: '2.1.316',
99
112
  install: 'curl -fsSL https://claude.ai/install.sh | bash',
100
113
  update: 'claude update',
101
114
  adapter: {
@@ -106,25 +119,26 @@ export const CLIS = {
106
119
  },
107
120
  args: [],
108
121
  fullAccess: 'bypassPermissions',
109
- sessionMeta: (bridge, title) => ({
122
+ sessionMeta: (bridge) => ({
110
123
  claudeCode: {
111
124
  options: {
112
125
  allowedTools: ['Bash(house:*)'],
113
126
  includeHookEvents: true,
114
- title,
115
127
  settings: { sandbox: { network: bridgeInClaudeSandbox(bridge) } },
116
128
  },
117
- emitRawSDKMessages: [...RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })), { type: 'result' }],
129
+ emitRawSDKMessages: [...RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })), ...RAW_TYPES.map((type) => ({ type }))],
118
130
  },
119
131
  }),
120
132
  unknownSession: (error) => answered(error).code === -32002,
121
- renames: false,
122
133
  allowHouse: nothing,
134
+ questionFields: claudeQuestionFields,
123
135
  signedIn: { command: ['auth', 'status'] },
124
136
  login: { args: ['auth', 'login', '--claudeai'], code: 'collect', rejected: 'Invalid code' },
137
+ key: CLAUDE_KEY,
125
138
  air: ['asyncTasks', 'sessionFailure'],
126
139
  },
127
140
  'grok-build': {
141
+ name: 'Grok Build',
128
142
  bin: 'grok',
129
143
  minimum: '1.0.46',
130
144
  install: 'curl -fsSL https://x.ai/cli/install.sh | bash',
@@ -134,10 +148,11 @@ export const CLIS = {
134
148
  fullAccess: null,
135
149
  sessionMeta: () => ({}),
136
150
  unknownSession: (error) => answered(error).data?.code === 'FS_NOT_FOUND',
137
- renames: false,
138
151
  allowHouse: nothing,
139
- signedIn: { initializeMeta: 'defaultAuthMethodId' },
152
+ questionFields: () => [],
153
+ signedIn: { initializeMeta: 'defaultAuthMethodId', apiKey: 'xai.api_key' },
140
154
  login: { args: ['login', '--device-auth'], code: 'show' },
155
+ key: GROK_KEY,
141
156
  air: ['asyncTasks'],
142
157
  },
143
158
  };
@@ -152,12 +167,15 @@ const CAUSE_CHARACTERS = 4000;
152
167
  export function adapterCommand(kind) {
153
168
  return join(releaseDirectory(KIT_RELEASE), 'adapters', kind, 'node_modules', '.bin', CLIS[kind].adapter.bin);
154
169
  }
155
- export function run(command, args, timeoutMs, detached = false, signal) {
170
+ export async function cliEnvironment(kind) {
171
+ return { ...childEnvironment(), ...(await CLIS[kind].key.environment?.()) };
172
+ }
173
+ export function run(command, args, timeoutMs, detached = false, signal, env = childEnvironment()) {
156
174
  return new Promise((resolve) => {
157
175
  const child = spawn(command, args, {
158
176
  stdio: ['ignore', 'pipe', 'pipe'],
159
177
  timeout: timeoutMs,
160
- env: childEnvironment(),
178
+ env,
161
179
  detached,
162
180
  signal: detached ? undefined : signal,
163
181
  });
@@ -234,8 +252,8 @@ export async function writeCodexRule() {
234
252
  throw new Error(`Codex's rule for house could not be written: ${error.message}`);
235
253
  });
236
254
  }
237
- export async function versionOf(path, signal) {
238
- return VERSION.exec((await run(path, ['--version'], READ_MS, false, signal)).stdout)?.[0] ?? null;
255
+ export async function versionOf(kind, path, signal) {
256
+ return VERSION.exec((await run(path, ['--version'], READ_MS, false, signal, await cliEnvironment(kind))).stdout)?.[0] ?? null;
239
257
  }
240
258
  function numbers(version) {
241
259
  return version.split(/[.-]/, 3).map(Number);
@@ -0,0 +1,121 @@
1
+ import { existsSync, mkdirSync, renameSync, rmSync } from 'node:fs';
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import { HouseRefusal, kitAct } from './api.js';
6
+ import { KIT_RELEASE } from './clis.js';
7
+ import { otherAccountKit, takeOverEarlier } from './earlier.js';
8
+ import { kitHome, readDisconnected, readEnrolment, storedConfiguration, writeConfiguration } from './home.js';
9
+ import { DEFAULT_HOUSE, enrol, placeConnection } from './login.js';
10
+ import { runningRelease } from './owner.js';
11
+ import { HOUSE_NOT_KITS, houseRoot } from './settings.js';
12
+ import { quoted } from './shell.js';
13
+ import { defineSupervisor, launcher, supervise, systemd } from './supervisor.js';
14
+ const USAGE = `usage: kit connect [--house <origin>] [--code <code>]
15
+ --house <origin> the Building this account's Kit serves, ${DEFAULT_HOUSE} unless one is stored
16
+ --code <code> connect this computer with a login code when Kit holds no credential House accepts
17
+ `;
18
+ const HELD = 'held-enrolment';
19
+ const RECORDS = ['credential.json', 'disconnected.json'];
20
+ const ENDS = ['SIGHUP', 'SIGINT', 'SIGTERM'];
21
+ function unanswered(error) {
22
+ return error instanceof HouseRefusal ? error.status >= 500 : error instanceof TypeError && error.message === 'fetch failed';
23
+ }
24
+ async function standing(house, credential) {
25
+ try {
26
+ await kitAct(house, 'agents/desired/list', {}, credential);
27
+ return true;
28
+ }
29
+ catch (error) {
30
+ if (error instanceof HouseRefusal && error.status === 401)
31
+ return false;
32
+ if (!unanswered(error))
33
+ throw error;
34
+ process.stderr.write(`kit: House did not answer, so the stored credential stands: ${error.message}\n`);
35
+ return true;
36
+ }
37
+ }
38
+ function settleHeld() {
39
+ const held = join(kitHome(), HELD);
40
+ if (!existsSync(held))
41
+ return;
42
+ if (!existsSync(join(kitHome(), RECORDS[0]))) {
43
+ for (const record of RECORDS)
44
+ if (existsSync(join(held, record)))
45
+ renameSync(join(held, record), join(kitHome(), record));
46
+ }
47
+ rmSync(held, { recursive: true, force: true });
48
+ }
49
+ async function heldWhile(work) {
50
+ const held = join(kitHome(), HELD);
51
+ mkdirSync(held, { mode: 0o700 });
52
+ const ended = () => {
53
+ settleHeld();
54
+ process.exit(130);
55
+ };
56
+ for (const signal of ENDS)
57
+ process.once(signal, ended);
58
+ try {
59
+ for (const record of RECORDS)
60
+ if (existsSync(join(kitHome(), record)))
61
+ renameSync(join(kitHome(), record), join(held, record));
62
+ await work();
63
+ }
64
+ finally {
65
+ for (const signal of ENDS)
66
+ process.off(signal, ended);
67
+ settleHeld();
68
+ }
69
+ }
70
+ export async function connect(argv) {
71
+ const { values } = parseArgs({
72
+ args: argv,
73
+ options: { house: { type: 'string' }, code: { type: 'string' }, help: { type: 'boolean', default: false } },
74
+ });
75
+ if (values.help) {
76
+ process.stdout.write(USAGE);
77
+ return;
78
+ }
79
+ await takeOverEarlier();
80
+ settleHeld();
81
+ const held = await storedConfiguration();
82
+ const workspace = held.workspace ?? (await houseRoot());
83
+ if (workspace === null)
84
+ throw new Error(HOUSE_NOT_KITS);
85
+ const stored = await readEnrolment();
86
+ const other = stored === null && (await readDisconnected()) === null ? otherAccountKit() : null;
87
+ if (other !== null)
88
+ throw new Error(`this computer's Kit runs as ${other}; run this command as ${other} to update it`);
89
+ const house = values.house ?? stored?.house ?? DEFAULT_HOUSE;
90
+ if (stored !== null && stored.house !== house) {
91
+ throw new Error(`this account's Kit serves ${stored.house}; kit logout disconnects it from there, then this command connects it to ${house}`);
92
+ }
93
+ if (stored === null || !(await standing(stored.house, stored.credential))) {
94
+ if (values.code === undefined)
95
+ await enrol({ house, 'no-private': false });
96
+ else
97
+ await heldWhile(() => enrol({ house, code: values.code, 'no-private': false }));
98
+ if ((await readEnrolment()) === null)
99
+ throw new Error('kit login connected no Environment');
100
+ }
101
+ else if (values.code !== undefined) {
102
+ process.stdout.write(`This computer is already connected as Environment ${stored.environment}; the login code was not used.\n`);
103
+ }
104
+ const install = process.env.HOUSE_KIT_INSTALL_COMMAND;
105
+ if (install !== undefined && install !== '')
106
+ await writeFile(join(kitHome(), 'install-command'), `${install}\n`, { mode: 0o600 });
107
+ const settings = await storedConfiguration();
108
+ if (settings.skills === undefined || settings.workspace === undefined) {
109
+ await writeConfiguration({ skills: true, workspace, ...settings });
110
+ }
111
+ await placeConnection(house);
112
+ const { environment } = (await readEnrolment());
113
+ if (process.platform !== 'darwin' && !systemd()) {
114
+ process.stdout.write(`Kit ${KIT_RELEASE} is installed for Environment ${environment}, but no systemd runs on this host to start it; run ${quoted(launcher())} resident under your own service manager, restarting it whenever it ends with a failure.\n`);
115
+ return;
116
+ }
117
+ const changed = await defineSupervisor();
118
+ const running = await runningRelease();
119
+ await supervise(changed, running !== null && running !== KIT_RELEASE);
120
+ process.stdout.write(`Kit connected for Environment ${environment}.\n`);
121
+ }