@agentshouse/kit 0.2.1-alpha.8 → 0.2.1-c02dacffca87c

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 +49 -24
  2. package/dist/abort.js +9 -0
  3. package/dist/acp.js +102 -88
  4. package/dist/agents.js +356 -52
  5. package/dist/api.js +40 -4
  6. package/dist/app-git.js +48 -0
  7. package/dist/authority-main.js +2 -2
  8. package/dist/bridge.js +93 -78
  9. package/dist/building.js +50 -0
  10. package/dist/calls.js +71 -0
  11. package/dist/chatgpt.js +32 -0
  12. package/dist/chunks.js +49 -0
  13. package/dist/clis.js +224 -88
  14. package/dist/codex-main.js +58 -0
  15. package/dist/configure-main.js +6 -0
  16. package/dist/connection.js +105 -0
  17. package/dist/conversations.js +749 -268
  18. package/dist/copies.js +475 -260
  19. package/dist/end.js +33 -0
  20. package/dist/enrol-main.js +7 -1
  21. package/dist/events.js +546 -0
  22. package/dist/files.js +140 -17
  23. package/dist/git-main.js +2 -2
  24. package/dist/git.js +62 -22
  25. package/dist/home.js +134 -10
  26. package/dist/house-cli.js +299 -0
  27. package/dist/house-main.js +5 -102
  28. package/dist/instructions.js +17 -18
  29. package/dist/kit-cli.js +68 -0
  30. package/dist/kit-main.js +8 -16
  31. package/dist/login.js +130 -95
  32. package/dist/logout.js +19 -0
  33. package/dist/mcp.js +43 -0
  34. package/dist/operation.js +7 -4
  35. package/dist/parts.js +82 -0
  36. package/dist/placement.js +31 -0
  37. package/dist/refusals.js +53 -0
  38. package/dist/relay.js +41 -0
  39. package/dist/resident.js +145 -51
  40. package/dist/scope.js +214 -0
  41. package/dist/scripts.js +255 -0
  42. package/dist/secret-input.js +7 -2
  43. package/dist/service-main.js +9 -0
  44. package/dist/service.js +55 -0
  45. package/dist/shell.js +3 -0
  46. package/dist/sign-in.js +52 -32
  47. package/dist/silence.js +28 -0
  48. package/dist/skills.js +92 -0
  49. package/dist/transcription.js +210 -0
  50. package/dist/translate.js +2 -8
  51. package/dist/update.js +127 -0
  52. package/dist/wire.js +40 -0
  53. package/dist/work.js +346 -0
  54. package/package.json +20 -21
  55. package/dist/blocks.js +0 -51
  56. package/dist/bootstrap.json +0 -28
  57. package/dist/stream.js +0 -47
package/dist/clis.js CHANGED
@@ -1,114 +1,250 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { readFileSync } from 'node:fs';
3
- import { readFile } from 'node:fs/promises';
4
- import { join } from 'node:path';
5
- import { kitHome } from './home.js';
6
- const RUNNING_JOB = new Set(['running', 'paused']);
7
- function threadStatus({ method, params }) {
8
- if (method !== 'session/update' || params?.update?.sessionUpdate !== 'session_info_update')
9
- return undefined;
10
- return params.update._meta?.codex?.threadStatus?.type;
11
- }
12
- function asyncTask({ method, params }) {
13
- const update = params?.update;
14
- if (method !== 'session/update' || update?.asyncTaskId === undefined)
15
- return null;
16
- if (update.sessionUpdate === 'async_task_spawned')
17
- return { id: update.asyncTaskId, running: true };
18
- if (update.sessionUpdate === 'async_task_state_update' && !RUNNING_JOB.has(update.state ?? '')) {
19
- return { id: update.asyncTaskId, running: false };
2
+ import { randomUUID } from 'node:crypto';
3
+ import { constants, readFileSync } from 'node:fs';
4
+ import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
5
+ import { homedir, userInfo } from 'node:os';
6
+ import { delimiter, dirname, isAbsolute, join } from 'node:path';
7
+ import { releaseDirectory } from './placement.js';
8
+ import { childEnvironment } from './relay.js';
9
+ const HOUSE_EXECUTABLES = /^host_executable\(name = "house", paths = (\[.*\])\)$/m;
10
+ function houseRule(houses) {
11
+ return `prefix_rule(pattern = ["house"], decision = "allow")\nhost_executable(name = "house", paths = ${JSON.stringify(houses)})\n`;
12
+ }
13
+ const RAW_SUBTYPES = [
14
+ 'background_tasks_changed',
15
+ 'task_started',
16
+ 'task_updated',
17
+ 'task_notification',
18
+ 'task_progress',
19
+ 'session_state_changed',
20
+ 'hook_started',
21
+ 'hook_response',
22
+ ];
23
+ async function executable(path) {
24
+ try {
25
+ await access(path, constants.X_OK);
26
+ return true;
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
32
+ async function listedHouses(file) {
33
+ let text;
34
+ try {
35
+ text = await readFile(file, 'utf8');
36
+ }
37
+ catch (error) {
38
+ if (error.code === 'ENOENT')
39
+ return [];
40
+ throw error;
41
+ }
42
+ try {
43
+ const listed = JSON.parse(HOUSE_EXECUTABLES.exec(text)?.[1] ?? '[]');
44
+ return Array.isArray(listed) ? listed.filter((house) => typeof house === 'string') : [];
45
+ }
46
+ catch {
47
+ return [];
48
+ }
49
+ }
50
+ export async function allowHouseInCodex(path) {
51
+ 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');
53
+ const file = join(rules, 'house.rules');
54
+ const houses = [];
55
+ for (const house of [...(await listedHouses(file)), ...candidates]) {
56
+ if (!houses.includes(house) && (await executable(house)))
57
+ houses.push(house);
20
58
  }
21
- return null;
59
+ await mkdir(rules, { recursive: true });
60
+ const temporary = `${file}.${randomUUID()}`;
61
+ await writeFile(temporary, houseRule(houses));
62
+ await rename(temporary, file);
63
+ }
64
+ async function nothing() { }
65
+ function answered(error) {
66
+ return typeof error === 'object' && error !== null ? error : {};
67
+ }
68
+ function bridgeInClaudeSandbox(bridge) {
69
+ return process.platform === 'darwin' ? { allowUnixSockets: [bridge] } : { allowAllUnixSockets: true };
22
70
  }
23
71
  export const CLIS = {
24
72
  'codex-acp': {
25
- package: '@agentclientprotocol/codex-acp',
26
- bin: 'codex-acp',
73
+ bin: 'codex',
74
+ minimum: '0.160.1',
75
+ install: 'curl -fsSL https://chatgpt.com/codex/install.sh | sh',
76
+ update: 'codex update',
77
+ adapter: {
78
+ package: '@agentclientprotocol/codex-acp',
79
+ bin: 'codex-acp',
80
+ executable: 'CODEX_PATH',
81
+ env: { CODEX_CONFIG: JSON.stringify({ features: { shell_zsh_fork: true } }) },
82
+ },
27
83
  args: [],
28
- signedIn: { command: ['cli', 'login', 'status'] },
29
- login: { args: ['cli', 'login', '--device-auth'], code: 'show' },
30
- queues: false,
31
- turnStarted: (notice) => threadStatus(notice) === 'active',
32
- turnEnded: (notice) => threadStatus(notice) === 'idle',
33
- job: asyncTask,
84
+ fullAccess: 'agent-full-access',
85
+ sessionMeta: () => ({}),
86
+ unknownSession: (error) => {
87
+ const { code, data } = answered(error);
88
+ return code === -32603 && typeof data?.details === 'string' && data.details.startsWith('no rollout found');
89
+ },
90
+ renames: true,
91
+ allowHouse: allowHouseInCodex,
92
+ signedIn: { command: ['login', 'status'] },
93
+ login: { args: ['login', '--device-auth'], code: 'show' },
94
+ air: ['asyncTasks', 'nativeSubagentSessions'],
34
95
  },
35
96
  'claude-agent-acp': {
36
- package: '@agentclientprotocol/claude-agent-acp',
37
- bin: 'claude-agent-acp',
97
+ bin: 'claude',
98
+ minimum: '2.1.303',
99
+ install: 'curl -fsSL https://claude.ai/install.sh | bash',
100
+ update: 'claude update',
101
+ adapter: {
102
+ package: '@agentclientprotocol/claude-agent-acp',
103
+ bin: 'claude-agent-acp',
104
+ executable: 'CLAUDE_CODE_EXECUTABLE',
105
+ env: { CLAUDE_CODE_ENTRYPOINT: 'claude-agent-acp', IS_SANDBOX: '1' },
106
+ },
38
107
  args: [],
39
- signedIn: { command: ['--cli', 'auth', 'status'] },
40
- login: { args: ['--cli', 'auth', 'login', '--claudeai'], code: 'collect' },
41
- queues: false,
42
- turnStarted: () => false,
43
- turnEnded: ({ method, params }) => method === 'session/update' &&
44
- params?.update?.sessionUpdate === 'usage_update' &&
45
- params.update._meta?.['_claude/origin'] !== undefined,
46
- job: asyncTask,
108
+ fullAccess: 'bypassPermissions',
109
+ sessionMeta: (bridge, title) => ({
110
+ claudeCode: {
111
+ options: {
112
+ allowedTools: ['Bash(house:*)'],
113
+ includeHookEvents: true,
114
+ title,
115
+ settings: { sandbox: { network: bridgeInClaudeSandbox(bridge) } },
116
+ },
117
+ emitRawSDKMessages: [...RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })), { type: 'result' }],
118
+ },
119
+ }),
120
+ unknownSession: (error) => answered(error).code === -32002,
121
+ renames: false,
122
+ allowHouse: nothing,
123
+ signedIn: { command: ['auth', 'status'] },
124
+ login: { args: ['auth', 'login', '--claudeai'], code: 'collect', rejected: 'Invalid code' },
125
+ air: ['asyncTasks', 'sessionFailure'],
47
126
  },
48
127
  'grok-build': {
49
- package: '@xai-official/grok',
50
128
  bin: 'grok',
51
- args: ['agent', '--no-leader', 'stdio'],
129
+ minimum: '1.0.46',
130
+ install: 'curl -fsSL https://x.ai/cli/install.sh | bash',
131
+ update: 'grok update',
132
+ adapter: null,
133
+ args: ['--sandbox', 'off', 'agent', '--always-approve', '--no-leader', 'stdio'],
134
+ fullAccess: null,
135
+ sessionMeta: () => ({}),
136
+ unknownSession: (error) => answered(error).data?.code === 'FS_NOT_FOUND',
137
+ renames: false,
138
+ allowHouse: nothing,
52
139
  signedIn: { initializeMeta: 'defaultAuthMethodId' },
53
140
  login: { args: ['login', '--device-auth'], code: 'show' },
54
- queues: true,
55
- turnStarted: ({ method, params }) => method === '_x.ai/queue/changed' && params?.runningPromptId !== undefined,
56
- turnEnded: ({ method, params }) => method === '_x.ai/session_notification' && params?.update?.sessionUpdate === 'turn_completed',
57
- job: ({ method, params }) => {
58
- if (method === '_x.ai/task_backgrounded')
59
- return { id: params.update.task_id, running: true };
60
- if (method === '_x.ai/task_completed')
61
- return { id: params.update.task_snapshot.task_id, running: false };
62
- return null;
63
- },
141
+ air: ['asyncTasks'],
64
142
  },
65
143
  };
66
144
  const KIT_PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
67
- export const KIT_VERSION = KIT_PACKAGE.version;
68
- const PROXY = /^https?_proxy$/i;
69
- export function pinned(kind) {
70
- return KIT_PACKAGE.peerDependencies[CLIS[kind].package];
71
- }
72
- function prefix(kind) {
73
- return join(kitHome(), 'agents', kind);
145
+ export const KIT_RELEASE = KIT_PACKAGE.version;
146
+ const VERSION = /\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?/;
147
+ // 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.
148
+ const INSTALL_MS = 15 * 60_000;
149
+ // A login shell or a version read is ended after half a minute, so a profile that waits for input cannot stall the report.
150
+ const READ_MS = 30_000;
151
+ const CAUSE_CHARACTERS = 4000;
152
+ export function adapterCommand(kind) {
153
+ return join(releaseDirectory(KIT_RELEASE), 'adapters', kind, 'node_modules', '.bin', CLIS[kind].adapter.bin);
74
154
  }
75
- export function cliCommand(kind) {
76
- return join(prefix(kind), 'node_modules', '.bin', CLIS[kind].bin);
77
- }
78
- export async function installedRelease(kind) {
79
- try {
80
- const manifest = join(prefix(kind), 'node_modules', CLIS[kind].package, 'package.json');
81
- return JSON.parse(await readFile(manifest, 'utf8')).version;
82
- }
83
- catch {
84
- return null;
85
- }
86
- }
87
- export function withoutProxy() {
88
- return Object.fromEntries(Object.entries(process.env).filter(([name]) => !PROXY.test(name)));
89
- }
90
- export function run(command, args, timeoutMs) {
155
+ export function run(command, args, timeoutMs, detached = false, signal) {
91
156
  return new Promise((resolve) => {
92
- const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], timeout: timeoutMs, env: withoutProxy() });
157
+ const child = spawn(command, args, {
158
+ stdio: ['ignore', 'pipe', 'pipe'],
159
+ timeout: timeoutMs,
160
+ env: childEnvironment(),
161
+ detached,
162
+ signal: detached ? undefined : signal,
163
+ });
164
+ const stop = () => {
165
+ try {
166
+ process.kill(-child.pid, 'SIGKILL');
167
+ }
168
+ catch { }
169
+ };
170
+ if (detached && signal?.aborted)
171
+ stop();
172
+ if (detached)
173
+ signal?.addEventListener('abort', stop, { once: true });
174
+ const ended = (ran) => {
175
+ signal?.removeEventListener('abort', stop);
176
+ resolve(ran);
177
+ };
178
+ let stdout = '';
93
179
  let output = '';
94
- child.stdout.on('data', (chunk) => {
95
- output += chunk.toString('utf8');
180
+ child.stdout.setEncoding('utf8').on('data', (chunk) => {
181
+ stdout += chunk;
182
+ output += chunk;
96
183
  });
97
- child.stderr.on('data', (chunk) => {
98
- output += chunk.toString('utf8');
184
+ child.stderr.setEncoding('utf8').on('data', (chunk) => {
185
+ output += chunk;
99
186
  });
100
- child.on('error', (error) => resolve({ status: null, output: error.message }));
101
- child.on('close', (status) => resolve({ status, output }));
187
+ child.on('error', (error) => ended({ status: null, stdout, output: error.message }));
188
+ child.on('close', (status) => ended({ status, stdout, output }));
189
+ });
190
+ }
191
+ export function failureOf(ran, program) {
192
+ return ran.output.trim().slice(-CAUSE_CHARACTERS) || `${program} exited with ${ran.status ?? 'a signal'}`;
193
+ }
194
+ export function adapterArchive(kind) {
195
+ return `${kind}-${KIT_PACKAGE.peerDependencies[CLIS[kind].adapter.package]}.tar.gz`;
196
+ }
197
+ async function bounded(program, work, signal) {
198
+ const deadline = AbortSignal.timeout(INSTALL_MS);
199
+ const ran = await work(signal === undefined ? deadline : AbortSignal.any([signal, deadline]));
200
+ if (deadline.aborted && signal?.aborted !== true)
201
+ return `${program} did not end within ${INSTALL_MS / 1000} seconds`;
202
+ return ran.status === 0 ? null : failureOf(ran, program);
203
+ }
204
+ export function installCli(kind, signal) {
205
+ return bounded('the install', (within) => run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true, within), signal);
206
+ }
207
+ function loginShell() {
208
+ return process.env.SHELL || userInfo().shell;
209
+ }
210
+ const FOUND = 'house-kit-cli ';
211
+ const LOOKUP = `found=$(command -v "$1") || exit 0; case $found in /*) ;; *) found=$(pwd -P)/$found ;; esac; printf "${FOUND}%s\\n" "$found"`;
212
+ const USER_BIN = 'case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) PATH="$PATH:$HOME/.local/bin" ;; esac; export PATH';
213
+ function inLoginShell(script, argument = '', signal, timeoutMs = READ_MS) {
214
+ return run(loginShell(), ['-l', '-i', '-c', `exec /bin/sh -c '${USER_BIN}; ${script}' sh ${argument}`], timeoutMs, true, signal);
215
+ }
216
+ export async function onLoginPath(program, signal) {
217
+ const ran = await inLoginShell(LOOKUP, program, signal);
218
+ return ran.stdout.split('\n').findLast((line) => line.startsWith(FOUND))?.slice(FOUND.length) ?? null;
219
+ }
220
+ export function locate(kind, signal) {
221
+ return onLoginPath(CLIS[kind].bin, signal);
222
+ }
223
+ export function updateCli(kind) {
224
+ return bounded('the update', (within) => inLoginShell(CLIS[kind].update, '', within, INSTALL_MS));
225
+ }
226
+ export async function loginPath() {
227
+ const marker = 'house-kit-path ';
228
+ const ran = await inLoginShell(`printf "${marker}%s\\n" "$PATH"`);
229
+ return ran.stdout.split('\n').findLast((line) => line.startsWith(marker)).slice(marker.length);
230
+ }
231
+ export async function writeCodexRule() {
232
+ const shell = await loginPath().catch(() => '');
233
+ await allowHouseInCodex([dirname(process.execPath), process.env.PATH ?? '', shell].join(delimiter)).catch((error) => {
234
+ throw new Error(`Codex's rule for house could not be written: ${error.message}`);
102
235
  });
103
236
  }
104
- export async function install(kind) {
105
- const release = pinned(kind);
106
- if ((await installedRelease(kind)) === release)
107
- return release;
108
- const ran = await run('npm', ['install', '--prefix', prefix(kind), '--no-save', '--no-audit', '--no-fund', `${CLIS[kind].package}@${release}`], 15 * 60_000);
109
- if (ran.status !== 0) {
110
- process.stderr.write(`kit: ${kind} did not install: ${ran.output.trim()}\n`);
111
- return null;
237
+ export async function versionOf(path, signal) {
238
+ return VERSION.exec((await run(path, ['--version'], READ_MS, false, signal)).stdout)?.[0] ?? null;
239
+ }
240
+ function numbers(version) {
241
+ return version.split(/[.-]/, 3).map(Number);
242
+ }
243
+ export function below(found, minimum) {
244
+ const [have, need] = [numbers(found), numbers(minimum)];
245
+ for (let index = 0; index < 3; index++) {
246
+ if (have[index] !== need[index])
247
+ return have[index] < need[index];
112
248
  }
113
- return installedRelease(kind);
249
+ return found.includes('-') && !minimum.includes('-');
114
250
  }
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { connect } from 'node:net';
4
+ const KIT_ANSWER = '"house-kit-';
5
+ const SYNC = 'house-kit/sync';
6
+ function lines(each) {
7
+ let buffer = '';
8
+ return (chunk) => {
9
+ buffer += chunk;
10
+ for (let index = buffer.indexOf('\n'); index >= 0; index = buffer.indexOf('\n')) {
11
+ each(buffer.slice(0, index + 1));
12
+ buffer = buffer.slice(index + 1);
13
+ }
14
+ };
15
+ }
16
+ function answersKit(line) {
17
+ if (!line.includes(KIT_ANSWER))
18
+ return false;
19
+ try {
20
+ const message = JSON.parse(line);
21
+ return message.method === undefined && typeof message.id === 'string' && message.id.startsWith(KIT_ANSWER.slice(1));
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ const args = process.argv.slice(2);
28
+ const serving = args[0] === 'app-server';
29
+ if (process.env.HOUSE_KIT_SANDBOX === '1' && serving)
30
+ args.push('--disable', 'memories');
31
+ const codex = spawn(process.env.HOUSE_KIT_CODEX, args, { stdio: ['pipe', 'pipe', 'inherit'] });
32
+ const stream = serving ? connect(process.env.HOUSE_KIT_CODEX_STREAM) : null;
33
+ stream?.on('error', () => undefined);
34
+ process.stdin.setEncoding('utf8').on('data', lines((line) => codex.stdin.write(line)));
35
+ process.stdin.on('end', () => codex.stdin.end());
36
+ stream?.setEncoding('utf8').on('data', lines((line) => {
37
+ const message = JSON.parse(line);
38
+ if (message.method === SYNC)
39
+ stream.write(`${JSON.stringify({ jsonrpc: '2.0', id: message.id, result: {} })}\n`);
40
+ else
41
+ codex.stdin.write(line);
42
+ }));
43
+ codex.stdout.setEncoding('utf8').on('data', lines((line) => {
44
+ stream?.write(line);
45
+ if (answersKit(line) || process.stdout.write(line))
46
+ return;
47
+ codex.stdout.pause();
48
+ process.stdout.once('drain', () => codex.stdout.resume());
49
+ }));
50
+ codex.stdin.on('error', () => undefined);
51
+ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'])
52
+ process.on(signal, () => codex.kill(signal));
53
+ codex.on('exit', (code, signal) => {
54
+ if (signal === null)
55
+ process.exit(code ?? 1);
56
+ process.removeAllListeners(signal);
57
+ process.kill(process.pid, signal);
58
+ });
@@ -0,0 +1,6 @@
1
+ import { readConfiguration, writeConfiguration } from './home.js';
2
+ const skills = !process.argv.slice(2).includes('--no-skills');
3
+ const stored = await readConfiguration();
4
+ await writeConfiguration({ skills });
5
+ if (stored.skills !== skills)
6
+ process.stdout.write('changed\n');
@@ -0,0 +1,105 @@
1
+ import { subscribe } from 'node:diagnostics_channel';
2
+ import { HouseRefusal, retryDelay } from './api.js';
3
+ import { end, REPLACED, signInAgain } from './end.js';
4
+ import { readEnrolment } from './home.js';
5
+ import { relayed } from './relay.js';
6
+ import { Silence } from './silence.js';
7
+ import { endUnserved, KIT_WIRE, unserved } from './wire.js';
8
+ const PATH = '/kit/stream';
9
+ const SUBPROTOCOL = `house.kit.stream.${KIT_WIRE}`;
10
+ const REFUSAL_HEADER = 'x-house-refusal';
11
+ // House beats each Kit connection every thirty seconds, so two silent beats mean this Kit process cannot hear House.
12
+ export const CONNECTION_SILENCE_MS = 60_000;
13
+ function connectionUrl(house) {
14
+ const url = new URL(PATH, house);
15
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
16
+ return url;
17
+ }
18
+ function header(headers, name) {
19
+ for (let index = 0; index < headers.length; index += 2) {
20
+ if (headers[index].toString('latin1').toLowerCase() === name)
21
+ return headers[index + 1].toString('latin1');
22
+ }
23
+ return '';
24
+ }
25
+ let refused = null;
26
+ subscribe('undici:request:headers', (message) => {
27
+ const { request, response } = message;
28
+ if (!request.path.endsWith(PATH))
29
+ return;
30
+ refused = new HouseRefusal(PATH, response.statusCode, header(response.headers, REFUSAL_HEADER) || response.statusText);
31
+ });
32
+ export function holdConnection(handlers) {
33
+ let connection = null;
34
+ let socket = null;
35
+ let failures = 0;
36
+ const connect = async () => {
37
+ const { house, credential } = (await readEnrolment());
38
+ if (socket !== null || unserved())
39
+ return;
40
+ refused = null;
41
+ const opening = new WebSocket(relayed(connectionUrl(house)), {
42
+ protocols: [SUBPROTOCOL],
43
+ headers: { authorization: `Bearer ${credential}` },
44
+ });
45
+ socket = opening;
46
+ let opened = false;
47
+ let silence = null;
48
+ const closed = (event) => {
49
+ silence?.stop();
50
+ silence = null;
51
+ if (socket === opening)
52
+ socket = null;
53
+ if (connection === opening)
54
+ connection = null;
55
+ handlers.closed();
56
+ process.stderr.write(`kit: connection closed ${event.code} ${event.reason}\n`);
57
+ if (event.reason === 'replaced')
58
+ end(REPLACED);
59
+ if (event.reason === 'credential_rejected' || refused?.status === 401) {
60
+ void signInAgain(credential);
61
+ return;
62
+ }
63
+ if (refused !== null)
64
+ endUnserved(refused.text);
65
+ if (!opened && refused !== null)
66
+ process.stderr.write(`kit: ${refused.message}\n`);
67
+ // A closed connection reopens in one to three seconds, spread so Kit processes one restart closed return apart; an opening House refused or left unanswered backs off on the jittered curve, retryable or not, since a resident outlives a House deploy.
68
+ setTimeout(() => void connect(), opened ? 1000 + Math.random() * 2000 : retryDelay(failures++));
69
+ };
70
+ opening.onopen = () => {
71
+ opened = true;
72
+ failures = 0;
73
+ connection = opening;
74
+ silence = new Silence(CONNECTION_SILENCE_MS, () => {
75
+ if (connection !== opening)
76
+ return;
77
+ connection = null;
78
+ opening.onclose = null;
79
+ opening.close();
80
+ closed(new CloseEvent('close', { code: 1006, reason: 'heartbeat_missed' }));
81
+ });
82
+ silence.heard();
83
+ handlers.opened();
84
+ };
85
+ opening.onmessage = (event) => {
86
+ silence?.heard();
87
+ const arrived = JSON.parse(String(event.data));
88
+ if (arrived.type === 'input')
89
+ handlers.call(arrived);
90
+ else if (arrived.type !== 'beat')
91
+ handlers.notification(arrived);
92
+ };
93
+ opening.onerror = () => undefined;
94
+ opening.onclose = closed;
95
+ };
96
+ void connect();
97
+ return {
98
+ send(notification) {
99
+ if (connection === null || connection.readyState !== WebSocket.OPEN)
100
+ return false;
101
+ connection.send(JSON.stringify(notification));
102
+ return true;
103
+ },
104
+ };
105
+ }