@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/bridge.js CHANGED
@@ -8,10 +8,11 @@ import { parse } from 'yaml';
8
8
  import { finalRefusal, HouseRefusal, retryDelay, retrying } from './api.js';
9
9
  import { loginPath } from './clis.js';
10
10
  import { changedPaths, } from './copies.js';
11
+ import { fileInfo } from './files.js';
11
12
  import { kitHome, readEnrolment, socketDirectory } from './home.js';
12
- import { callHouse, mcpBody, rpc, UNREACHABLE } from './mcp.js';
13
+ import { callHouse, mcpBody, refusalIn, rpc, toolAnswer, UNREACHABLE } from './mcp.js';
13
14
  import { operationId } from './operation.js';
14
- import { refusalOf, retryable } from './refusals.js';
15
+ import { refusalOf, retryable, stopsPush } from './refusals.js';
15
16
  import { relayed } from './relay.js';
16
17
  const MCP_REQUEST_BYTES = 4_000_000;
17
18
  export async function received(request) {
@@ -34,18 +35,6 @@ function relay(request, response, house, authorization) {
34
35
  forwarded.on('error', () => response.destroy());
35
36
  request.pipe(forwarded);
36
37
  }
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
38
  function pendingSeconds(forwarded) {
50
39
  if (forwarded.status !== 200)
51
40
  return null;
@@ -58,16 +47,19 @@ function pendingSeconds(forwarded) {
58
47
  const seconds = JSON.parse(text).pending.retry_after;
59
48
  return typeof seconds === 'number' ? seconds : null;
60
49
  }
61
- function resendAfter(forwarded, attempt) {
50
+ function resendAfter(forwarded, attempt, pushing) {
62
51
  if (forwarded === null)
63
52
  return retryDelay(attempt);
64
- if (forwarded.status !== 200)
53
+ if (forwarded.status !== 200) {
54
+ if (pushing && stopsPush(refusalOf(forwarded.text)))
55
+ return null;
65
56
  return retryable(forwarded.text) === false ? null : retryDelay(attempt);
57
+ }
66
58
  const seconds = pendingSeconds(forwarded);
67
59
  return seconds === null ? null : seconds * 1000;
68
60
  }
69
61
  function editAnswer(forwarded) {
70
- const answer = answered(forwarded);
62
+ const answer = toolAnswer(forwarded);
71
63
  if ('refused' in answer)
72
64
  return answer;
73
65
  const { results } = parse(answer.text);
@@ -81,10 +73,10 @@ function editAnswer(forwarded) {
81
73
  export async function openBridge(house, copies, conversationId, signal) {
82
74
  const path = [join(kitHome(), 'shim'), dirname(process.execPath), await loginPath()].join(delimiter);
83
75
  const origin = (await readEnrolment()).house;
84
- const { credential } = await retrying(() => house.post(`/kit/conversations/${conversationId}/credential`, {}, signal), signal);
76
+ const { credential } = await retrying(() => house.act('conversations/credentials/issue', { conversation: conversationId }, signal), signal);
85
77
  const closed = new AbortController();
86
78
  const sent = (message, operation) => callHouse(origin, credential, message, operation, closed.signal);
87
- const send = async (message, operation) => {
79
+ const send = async (message, operation, pushing = false) => {
88
80
  if (operation === null)
89
81
  return sent(message, null);
90
82
  for (let attempt = 0;; attempt++) {
@@ -93,7 +85,7 @@ export async function openBridge(house, copies, conversationId, signal) {
93
85
  throw error;
94
86
  return null;
95
87
  });
96
- const after = resendAfter(forwarded, attempt);
88
+ const after = resendAfter(forwarded, attempt, pushing);
97
89
  if (after === null)
98
90
  return forwarded;
99
91
  // 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 +96,7 @@ export async function openBridge(house, copies, conversationId, signal) {
104
96
  const staged = async (operation, changes) => {
105
97
  const bytes = Buffer.from(JSON.stringify({ changes }));
106
98
  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));
99
+ const prepared = toolAnswer(await send(call('update', { op: 'stage', paths: changedPaths(changes), bytes: bytes.length, sha256 }), operation));
111
100
  if ('refused' in prepared)
112
101
  return prepared;
113
102
  const { transfer } = parse(prepared.text);
@@ -141,7 +130,7 @@ export async function openBridge(house, copies, conversationId, signal) {
141
130
  const caller = {
142
131
  key: `conversation:${conversationId}`,
143
132
  submit: async (operation, changes, held, retain) => {
144
- const inline = call('edit', { changes });
133
+ const inline = call('update', { changes });
145
134
  let upload = held;
146
135
  if (upload === undefined && Buffer.byteLength(mcpBody(inline, operation)) > MCP_REQUEST_BYTES) {
147
136
  const prepared = await staged(operation, changes);
@@ -150,7 +139,19 @@ export async function openBridge(house, copies, conversationId, signal) {
150
139
  upload = prepared;
151
140
  await retain(upload);
152
141
  }
153
- return editAnswer(await send(upload === undefined ? inline : call('edit', { paths: changedPaths(changes), upload }), operation));
142
+ return editAnswer(await send(upload === undefined ? inline : call('update', { paths: changedPaths(changes), upload }), operation, true));
143
+ },
144
+ finish: async (upload, room, partSha256) => {
145
+ const answer = toolAnswer(await send(call('upload', { upload, room_ref: room, part_sha256: partSha256 }), operationId(), true));
146
+ if ('refused' in answer)
147
+ throw new Error(answer.refused.text);
148
+ return parse(answer.text);
149
+ },
150
+ info: async (path, revision) => {
151
+ const answer = toolAnswer(await send(call('info', { path, ...(revision === undefined ? {} : { ref: revision }) }), operationId()));
152
+ if ('refused' in answer)
153
+ throw new Error(answer.refused.text);
154
+ return fileInfo(answer.text);
154
155
  },
155
156
  };
156
157
  const local = async (path, text) => {
@@ -159,7 +160,7 @@ export async function openBridge(house, copies, conversationId, signal) {
159
160
  return { status: 200, text: JSON.stringify(await copies.push(cwd, commit, caller)) };
160
161
  }
161
162
  if (path === '/git/fetch')
162
- return { status: 200, text: JSON.stringify(await copies.fetch()) };
163
+ return { status: 200, text: JSON.stringify(await copies.fetch(caller)) };
163
164
  if (path === '/git/observed') {
164
165
  await copies.observed(JSON.parse(text));
165
166
  return { status: 200, text: '{}' };
package/dist/building.js CHANGED
@@ -16,10 +16,14 @@ async function served(name, signal) {
16
16
  await answer.body?.cancel();
17
17
  throw new Error(`House answered ${answer.status} for ${name}`);
18
18
  }
19
- export async function servedDigest(name, signal) {
19
+ export async function servedRelease(signal) {
20
20
  const manifest = (await (await served(MANIFEST, signal)).json());
21
- const sha256 = manifest.files?.[name]?.sha256;
22
- return typeof sha256 === 'string' ? sha256 : null;
21
+ const installer = manifest.hosts?.linux;
22
+ const sha256 = typeof installer === 'string' ? manifest.files?.[installer]?.sha256 : undefined;
23
+ if (typeof manifest.version !== 'string' || typeof installer !== 'string' || typeof sha256 !== 'string') {
24
+ throw new Error(`House serves no Kit release in ${MANIFEST}`);
25
+ }
26
+ return { version: manifest.version, installer, sha256 };
23
27
  }
24
28
  export async function downloadServed(name, sha256, destination, signal, most = Infinity) {
25
29
  const answer = await served(name, signal);
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,49 @@
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
+ yield* models;
38
+ for (const { hash } of chunks) {
39
+ const file = join(directory, hash);
40
+ for (const line of (await readFile(file, 'utf8')).split('\n')) {
41
+ if (line === '')
42
+ continue;
43
+ const entry = JSON.parse(line);
44
+ if (!('folder' in entry))
45
+ yield entry;
46
+ }
47
+ await rm(file);
48
+ }
49
+ }
package/dist/clis.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { constants, readFileSync } from 'node:fs';
4
- import { access, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
5
- import { homedir, userInfo } from 'node:os';
4
+ import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
5
+ import { userInfo } from 'node:os';
6
6
  import { delimiter, dirname, isAbsolute, join } from 'node:path';
7
- import { downloadServed, servedDigest } from './building.js';
8
- import { kitHome } from './home.js';
7
+ import { CLAUDE_KEY, CODEX_KEY, GROK_KEY, codexHome } from './keys.js';
8
+ import { releaseDirectory } from './placement.js';
9
9
  import { childEnvironment } from './relay.js';
10
10
  const HOUSE_EXECUTABLES = /^host_executable\(name = "house", paths = (\[.*\])\)$/m;
11
11
  function houseRule(houses) {
@@ -16,10 +16,12 @@ const RAW_SUBTYPES = [
16
16
  'task_started',
17
17
  'task_updated',
18
18
  'task_notification',
19
+ 'task_progress',
19
20
  'session_state_changed',
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,9 +80,11 @@ 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',
87
+ update: 'codex update',
76
88
  adapter: {
77
89
  package: '@agentclientprotocol/codex-acp',
78
90
  bin: 'codex-acp',
@@ -86,16 +98,19 @@ export const CLIS = {
86
98
  const { code, data } = answered(error);
87
99
  return code === -32603 && typeof data?.details === 'string' && data.details.startsWith('no rollout found');
88
100
  },
89
- renames: true,
90
101
  allowHouse: allowHouseInCodex,
102
+ questionFields: codexQuestionFields,
91
103
  signedIn: { command: ['login', 'status'] },
92
104
  login: { args: ['login', '--device-auth'], code: 'show' },
105
+ key: CODEX_KEY,
93
106
  air: ['asyncTasks', 'nativeSubagentSessions'],
94
107
  },
95
108
  'claude-agent-acp': {
109
+ name: 'Claude Code',
96
110
  bin: 'claude',
97
- minimum: '2.1.303',
111
+ minimum: '2.1.316',
98
112
  install: 'curl -fsSL https://claude.ai/install.sh | bash',
113
+ update: 'claude update',
99
114
  adapter: {
100
115
  package: '@agentclientprotocol/claude-agent-acp',
101
116
  bin: 'claude-agent-acp',
@@ -104,69 +119,63 @@ export const CLIS = {
104
119
  },
105
120
  args: [],
106
121
  fullAccess: 'bypassPermissions',
107
- sessionMeta: (bridge, title) => ({
122
+ sessionMeta: (bridge) => ({
108
123
  claudeCode: {
109
124
  options: {
110
125
  allowedTools: ['Bash(house:*)'],
111
126
  includeHookEvents: true,
112
- title,
113
127
  settings: { sandbox: { network: bridgeInClaudeSandbox(bridge) } },
114
128
  },
115
- emitRawSDKMessages: RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })),
129
+ emitRawSDKMessages: [...RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })), ...RAW_TYPES.map((type) => ({ type }))],
116
130
  },
117
131
  }),
118
132
  unknownSession: (error) => answered(error).code === -32002,
119
- renames: false,
120
133
  allowHouse: nothing,
134
+ questionFields: claudeQuestionFields,
121
135
  signedIn: { command: ['auth', 'status'] },
122
136
  login: { args: ['auth', 'login', '--claudeai'], code: 'collect', rejected: 'Invalid code' },
137
+ key: CLAUDE_KEY,
123
138
  air: ['asyncTasks', 'sessionFailure'],
124
139
  },
125
140
  'grok-build': {
141
+ name: 'Grok Build',
126
142
  bin: 'grok',
127
143
  minimum: '1.0.46',
128
144
  install: 'curl -fsSL https://x.ai/cli/install.sh | bash',
145
+ update: 'grok update',
129
146
  adapter: null,
130
147
  args: ['--sandbox', 'off', 'agent', '--always-approve', '--no-leader', 'stdio'],
131
148
  fullAccess: null,
132
149
  sessionMeta: () => ({}),
133
150
  unknownSession: (error) => answered(error).data?.code === 'FS_NOT_FOUND',
134
- renames: false,
135
151
  allowHouse: nothing,
136
- signedIn: { initializeMeta: 'defaultAuthMethodId' },
152
+ questionFields: () => [],
153
+ signedIn: { initializeMeta: 'defaultAuthMethodId', apiKey: 'xai.api_key' },
137
154
  login: { args: ['login', '--device-auth'], code: 'show' },
155
+ key: GROK_KEY,
138
156
  air: ['asyncTasks'],
139
157
  },
140
158
  };
141
159
  const KIT_PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
142
160
  export const KIT_RELEASE = KIT_PACKAGE.version;
143
161
  const VERSION = /\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?/;
144
- // An install still running after fifteen minutes is ended and reported as failed, so a hung download cannot hold its CLI's report.
162
+ // An install or update still running after fifteen minutes is ended as failed, so a hung download can neither hold its CLI's report nor keep the Kit busy.
145
163
  const INSTALL_MS = 15 * 60_000;
146
164
  // A login shell or a version read is ended after half a minute, so a profile that waits for input cannot stall the report.
147
165
  const READ_MS = 30_000;
148
166
  const CAUSE_CHARACTERS = 4000;
149
- function prefix(kind) {
150
- return join(kitHome(), 'agents', kind);
151
- }
152
167
  export function adapterCommand(kind) {
153
- return join(prefix(kind), 'node_modules', '.bin', CLIS[kind].adapter.bin);
168
+ return join(releaseDirectory(KIT_RELEASE), 'adapters', kind, 'node_modules', '.bin', CLIS[kind].adapter.bin);
154
169
  }
155
- async function installedAdapter(kind) {
156
- try {
157
- const manifest = join(prefix(kind), 'node_modules', CLIS[kind].adapter.package, 'package.json');
158
- return JSON.parse(await readFile(manifest, 'utf8')).version;
159
- }
160
- catch {
161
- return null;
162
- }
170
+ export async function cliEnvironment(kind) {
171
+ return { ...childEnvironment(), ...(await CLIS[kind].key.environment?.()) };
163
172
  }
164
- export function run(command, args, timeoutMs, detached = false, signal) {
173
+ export function run(command, args, timeoutMs, detached = false, signal, env = childEnvironment()) {
165
174
  return new Promise((resolve) => {
166
175
  const child = spawn(command, args, {
167
176
  stdio: ['ignore', 'pipe', 'pipe'],
168
177
  timeout: timeoutMs,
169
- env: childEnvironment(),
178
+ env,
170
179
  detached,
171
180
  signal: detached ? undefined : signal,
172
181
  });
@@ -203,38 +212,15 @@ export function failureOf(ran, program) {
203
212
  export function adapterArchive(kind) {
204
213
  return `${kind}-${KIT_PACKAGE.peerDependencies[CLIS[kind].adapter.package]}.tar.gz`;
205
214
  }
206
- export async function installAdapter(kind, signal) {
207
- const adapter = CLIS[kind].adapter;
208
- if (adapter === null)
209
- return null;
210
- if ((await installedAdapter(kind)) === KIT_PACKAGE.peerDependencies[adapter.package])
211
- return null;
212
- const name = adapterArchive(kind);
213
- const archive = `${prefix(kind)}.tar.gz`;
215
+ async function bounded(program, work, signal) {
214
216
  const deadline = AbortSignal.timeout(INSTALL_MS);
215
- const bounded = signal === undefined ? deadline : AbortSignal.any([signal, deadline]);
216
- try {
217
- const sha256 = await servedDigest(name, bounded);
218
- if (sha256 === null)
219
- return `House serves no ${name}`;
220
- await rm(prefix(kind), { recursive: true, force: true });
221
- await mkdir(prefix(kind), { recursive: true });
222
- await downloadServed(name, sha256, archive, bounded);
223
- const ran = await run('tar', ['-xzf', archive, '-C', prefix(kind)], INSTALL_MS, true, signal);
224
- return ran.status === 0 ? null : failureOf(ran, 'tar');
225
- }
226
- catch (error) {
227
- if (deadline.aborted && signal?.aborted !== true)
228
- return `${name} did not arrive within ${INSTALL_MS / 1000} seconds`;
229
- return error instanceof Error ? error.message : String(error);
230
- }
231
- finally {
232
- await rm(archive, { force: true });
233
- }
217
+ const ran = await work(signal === undefined ? deadline : AbortSignal.any([signal, deadline]));
218
+ if (deadline.aborted && signal?.aborted !== true)
219
+ return `${program} did not end within ${INSTALL_MS / 1000} seconds`;
220
+ return ran.status === 0 ? null : failureOf(ran, program);
234
221
  }
235
- export async function installCli(kind, signal) {
236
- const ran = await run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true, signal);
237
- return ran.status === 0 ? null : failureOf(ran, 'the install');
222
+ export function installCli(kind, signal) {
223
+ return bounded('the install', (within) => run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true, within), signal);
238
224
  }
239
225
  function loginShell() {
240
226
  return process.env.SHELL || userInfo().shell;
@@ -242,8 +228,8 @@ function loginShell() {
242
228
  const FOUND = 'house-kit-cli ';
243
229
  const LOOKUP = `found=$(command -v "$1") || exit 0; case $found in /*) ;; *) found=$(pwd -P)/$found ;; esac; printf "${FOUND}%s\\n" "$found"`;
244
230
  const USER_BIN = 'case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) PATH="$PATH:$HOME/.local/bin" ;; esac; export PATH';
245
- function inLoginShell(script, argument = '', signal) {
246
- return run(loginShell(), ['-l', '-i', '-c', `exec /bin/sh -c '${USER_BIN}; ${script}' sh ${argument}`], READ_MS, true, signal);
231
+ function inLoginShell(script, argument = '', signal, timeoutMs = READ_MS) {
232
+ return run(loginShell(), ['-l', '-i', '-c', `exec /bin/sh -c '${USER_BIN}; ${script}' sh ${argument}`], timeoutMs, true, signal);
247
233
  }
248
234
  export async function onLoginPath(program, signal) {
249
235
  const ran = await inLoginShell(LOOKUP, program, signal);
@@ -252,6 +238,9 @@ export async function onLoginPath(program, signal) {
252
238
  export function locate(kind, signal) {
253
239
  return onLoginPath(CLIS[kind].bin, signal);
254
240
  }
241
+ export function updateCli(kind) {
242
+ return bounded('the update', (within) => inLoginShell(CLIS[kind].update, '', within, INSTALL_MS));
243
+ }
255
244
  export async function loginPath() {
256
245
  const marker = 'house-kit-path ';
257
246
  const ran = await inLoginShell(`printf "${marker}%s\\n" "$PATH"`);
@@ -263,8 +252,8 @@ export async function writeCodexRule() {
263
252
  throw new Error(`Codex's rule for house could not be written: ${error.message}`);
264
253
  });
265
254
  }
266
- export async function versionOf(path, signal) {
267
- 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;
268
257
  }
269
258
  function numbers(version) {
270
259
  return version.split(/[.-]/, 3).map(Number);
@@ -0,0 +1,108 @@
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 { takeOverEarlier } from './earlier.js';
8
+ import { kitHome, readEnrolment, storedConfiguration, writeConfiguration } from './home.js';
9
+ import { DEFAULT_HOUSE, enrol, placeConnection } from './login.js';
10
+ import { runningRelease } from './owner.js';
11
+ import { quoted } from './shell.js';
12
+ import { defineSupervisor, launcher, supervise, systemd } from './supervisor.js';
13
+ const USAGE = `usage: kit connect [--house <origin>] [--code <code>]
14
+ --house <origin> the Building this account's Kit serves, ${DEFAULT_HOUSE} unless one is stored
15
+ --code <code> connect this computer with a login code when Kit holds no credential House accepts
16
+ `;
17
+ const HELD = 'held-enrolment';
18
+ const RECORDS = ['credential.json', 'disconnected.json'];
19
+ const ENDS = ['SIGHUP', 'SIGINT', 'SIGTERM'];
20
+ function unanswered(error) {
21
+ return error instanceof HouseRefusal ? error.status >= 500 : error instanceof TypeError && error.message === 'fetch failed';
22
+ }
23
+ async function standing(house, credential) {
24
+ try {
25
+ await kitAct(house, 'agents/desired/list', {}, credential);
26
+ return true;
27
+ }
28
+ catch (error) {
29
+ if (!unanswered(error))
30
+ return false;
31
+ process.stderr.write(`kit: House did not answer, so the stored credential stands: ${error.message}\n`);
32
+ return true;
33
+ }
34
+ }
35
+ function settleHeld() {
36
+ const held = join(kitHome(), HELD);
37
+ if (!existsSync(held))
38
+ return;
39
+ if (!existsSync(join(kitHome(), RECORDS[0]))) {
40
+ for (const record of RECORDS)
41
+ if (existsSync(join(held, record)))
42
+ renameSync(join(held, record), join(kitHome(), record));
43
+ }
44
+ rmSync(held, { recursive: true, force: true });
45
+ }
46
+ async function heldWhile(work) {
47
+ const held = join(kitHome(), HELD);
48
+ mkdirSync(held, { mode: 0o700 });
49
+ const ended = () => {
50
+ settleHeld();
51
+ process.exit(130);
52
+ };
53
+ for (const signal of ENDS)
54
+ process.once(signal, ended);
55
+ try {
56
+ for (const record of RECORDS)
57
+ if (existsSync(join(kitHome(), record)))
58
+ renameSync(join(kitHome(), record), join(held, record));
59
+ await work();
60
+ }
61
+ finally {
62
+ for (const signal of ENDS)
63
+ process.off(signal, ended);
64
+ settleHeld();
65
+ }
66
+ }
67
+ export async function connect(argv) {
68
+ const { values } = parseArgs({
69
+ args: argv,
70
+ options: { house: { type: 'string' }, code: { type: 'string' }, help: { type: 'boolean', default: false } },
71
+ });
72
+ if (values.help) {
73
+ process.stdout.write(USAGE);
74
+ return;
75
+ }
76
+ await takeOverEarlier();
77
+ settleHeld();
78
+ const stored = await readEnrolment();
79
+ const house = values.house ?? stored?.house ?? DEFAULT_HOUSE;
80
+ if (stored !== null && stored.house !== house) {
81
+ throw new Error(`this account's Kit serves ${stored.house}; kit logout disconnects it from there, then this command connects it to ${house}`);
82
+ }
83
+ const install = process.env.HOUSE_KIT_INSTALL_COMMAND;
84
+ if (install !== undefined && install !== '')
85
+ await writeFile(join(kitHome(), 'install-command'), `${install}\n`, { mode: 0o600 });
86
+ if (stored === null || !(await standing(stored.house, stored.credential))) {
87
+ if (values.code === undefined)
88
+ await enrol({ house, 'no-private': false });
89
+ else
90
+ await heldWhile(() => enrol({ house, code: values.code, 'no-private': false }));
91
+ if ((await readEnrolment()) === null)
92
+ throw new Error('kit login connected no Environment');
93
+ }
94
+ const settings = await storedConfiguration();
95
+ if (settings.skills === undefined || settings.workspace === undefined) {
96
+ await writeConfiguration({ skills: true, workspace: kitHome(), ...settings });
97
+ }
98
+ await placeConnection(house);
99
+ const { environment } = (await readEnrolment());
100
+ if (process.platform !== 'darwin' && !systemd()) {
101
+ 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`);
102
+ return;
103
+ }
104
+ const changed = await defineSupervisor();
105
+ const running = await runningRelease();
106
+ await supervise(changed, running !== null && running !== KIT_RELEASE);
107
+ process.stdout.write(`Kit connected for Environment ${environment}.\n`);
108
+ }