@agentshouse/kit 0.2.1-c3cf4b145dcda → 0.2.1-c46722ad48058

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.
package/README.md CHANGED
@@ -1,14 +1,12 @@
1
1
  # House Kit
2
2
 
3
- House Kit connects an Environment, a Linux computer or server, to
4
- [agents.house](https://agents.house). It runs your Agents' conversations
5
- through the agent CLIs you chose and gives each Agent the `house` command.
3
+ House Kit connects an Environment, a Linux computer or server, to [agents.house](https://agents.house). It runs
4
+ your Agents' conversations through the agent CLIs you chose and gives each Agent the `house` command.
6
5
 
7
6
  ## Install
8
7
 
9
- Run `curl -fsSL agents.house/kit | sh`, or `irm agents.house/kit.ps1 | iex` on
10
- Windows, and again to update; options follow `sh -s --`. On macOS and Linux it
11
- installs House Kit natively under your own account, without an admin password,
8
+ Run `curl -fsSL agents.house/kit | sh`, or `irm agents.house/kit.ps1 | iex` on Windows, and again to update;
9
+ options follow `sh -s --`. On macOS and Linux it installs House Kit natively under your own account, without an admin password,
12
10
  as a service that runs while you are logged in. `kit` and `house` are then on
13
11
  your login shell's `PATH`, and your workspace is `~/AgentsHouse` unless you
14
12
  pass `--workspace <path>`.
@@ -33,21 +31,24 @@ them out; running it again without the flag brings them back.
33
31
 
34
32
  ## Commands
35
33
 
36
- `kit login` opens a link you confirm in your browser and keeps the
37
- Environment's credential in `~/.house-kit`, or in `$HOUSE_KIT_HOME` when it is
38
- set. Pass `--manual` to paste the code by hand on a machine without a browser,
39
- and `--environment <id>` to reconnect an Environment you already have. It also
40
- connects your own agent: outside an Agent conversation, `house <tool>` calls
34
+ `kit login` opens or prints a link you confirm in any browser, on this computer
35
+ or another, continues on its own and keeps the Environment's credential in
36
+ `~/.house-kit`, or in `$HOUSE_KIT_HOME` when it is set. `--environment <id>`
37
+ reconnects an Environment you already have; `--rooms <ref>[,<ref>...]` gives it
38
+ only those Rooms and `--no-private` every Room but your Private Room;
39
+ `--code <code>` connects immediately without a link.
40
+ A login also connects your own agent: outside an Agent conversation, `house <tool>` calls
41
41
  House as you and `git` clones and pushes your Apps at `<house>/app/` as you,
42
42
  until you revoke that connection on Connections. `house help` lists the Tools.
43
- `kit logout` disconnects this computer, stops House Kit and ends that Git
44
- access; a later `kit login` reconnects the same Environment.
45
-
46
- `kit resident` keeps the Environment connected, and keeps the Rooms you chose
47
- for this Environment as Git repositories under `local-copies` in the
48
- workspace. Commit in one and run `house push --owner` there to send the
49
- commit to House; in the container, run it through the install command from the
50
- copy's directory. Inside an Agent conversation the Agent runs `house push`.
43
+ `kit logout` disconnects this computer, stops House Kit and ends your own
44
+ agent's connection, so `house` and `git` no longer act as you here; a later
45
+ `kit login` reconnects the same Environment.
46
+
47
+ `kit resident` keeps the Environment connected and, as it connects, copies each
48
+ Room you chose for it as a Git repository in the workspace's `local-copies`.
49
+ `house fetch` records House's changes on each copy's `refs/house/received`;
50
+ rebase onto it, commit and run `house push --owner` in the copy, through the
51
+ install command in the container. An Agent runs both, without `--owner`.
51
52
 
52
53
  House Kit turns each audio file of your message to an Agent into text on this
53
54
  computer before the Agent reads it. While transcription is on, the speech
package/dist/acp.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { ndJsonStream, PROTOCOL_VERSION, } from '@agentclientprotocol/sdk';
2
- import { execFileSync, spawn } from 'node:child_process';
3
- import { readdirSync, readFileSync } from 'node:fs';
2
+ import { spawn } from 'node:child_process';
4
3
  import { Readable, Writable } from 'node:stream';
5
4
  import { CLIS, KIT_VERSION, adapterCommand, withoutProxy } from './clis.js';
6
- export async function startAdapter(kind, cli, cwd, app, events = () => undefined, added = {}, signal) {
5
+ import { killTree } from './scope.js';
6
+ export async function startAdapter(kind, cli, cwd, app, events = () => undefined, added = {}, signal, scope = null) {
7
7
  const adapter = CLIS[kind].adapter;
8
- const child = spawn(adapter === null ? cli : adapterCommand(kind), CLIS[kind].args, {
8
+ const started = [adapter === null ? cli : adapterCommand(kind), CLIS[kind].args];
9
+ const [command, args] = scope?.command(...started) ?? started;
10
+ const child = spawn(command, args, {
9
11
  cwd,
10
12
  env: { ...withoutProxy(), ...(adapter === null ? {} : { ...adapter.env, [adapter.executable]: cli }), ...added },
11
13
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -51,6 +53,7 @@ export async function startAdapter(kind, cli, cwd, app, events = () => undefined
51
53
  },
52
54
  clientInfo: { name: '@agentshouse/kit', version: KIT_VERSION },
53
55
  });
56
+ scope?.entered(child.pid);
54
57
  return { child, connection, initialized, exited };
55
58
  }
56
59
  catch (error) {
@@ -58,96 +61,3 @@ export async function startAdapter(kind, cli, cwd, app, events = () => undefined
58
61
  throw error;
59
62
  }
60
63
  }
61
- const LISTING_BYTES = 1 << 28;
62
- function listed(options) {
63
- return execFileSync('ps', [options, '-o', 'pid=,ppid=,command='], { encoding: 'utf8', maxBuffer: LISTING_BYTES })
64
- .split('\n')
65
- .flatMap((line) => {
66
- const fields = /^\s*(\d+)\s+(\d+)\s?(.*)$/.exec(line);
67
- return fields === null ? [] : [[Number(fields[1]), Number(fields[2]), fields[3]]];
68
- });
69
- }
70
- function parents() {
71
- const children = new Map();
72
- const adopt = (pid, parent) => children.set(parent, [...(children.get(parent) ?? []), pid]);
73
- if (process.platform === 'darwin') {
74
- for (const [pid, parent] of listed('-Aww'))
75
- adopt(pid, parent);
76
- return children;
77
- }
78
- for (const entry of readdirSync('/proc')) {
79
- if (!/^\d+$/.test(entry))
80
- continue;
81
- try {
82
- const stat = readFileSync(`/proc/${entry}/stat`, 'utf8');
83
- adopt(Number(entry), Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]));
84
- }
85
- catch { }
86
- }
87
- return children;
88
- }
89
- function descendants(roots) {
90
- const children = parents();
91
- const tree = [];
92
- const pending = roots.flatMap((root) => children.get(root) ?? []);
93
- while (pending.length > 0) {
94
- const pid = pending.pop();
95
- tree.push(pid);
96
- pending.push(...(children.get(pid) ?? []));
97
- }
98
- return tree;
99
- }
100
- function killAll(pids) {
101
- for (const pid of pids) {
102
- for (const target of [-pid, pid]) {
103
- try {
104
- process.kill(target, 'SIGKILL');
105
- }
106
- catch { }
107
- }
108
- }
109
- }
110
- function marked(marker) {
111
- if (process.platform === 'darwin') {
112
- return listed('-AEww')
113
- .filter(([, , command]) => ` ${command} `.includes(` ${marker} `))
114
- .map(([pid]) => pid);
115
- }
116
- return readdirSync('/proc')
117
- .filter((entry) => {
118
- try {
119
- return /^\d+$/.test(entry) && readFileSync(`/proc/${entry}/environ`, 'utf8').split('\0').includes(marker);
120
- }
121
- catch {
122
- return false;
123
- }
124
- })
125
- .map(Number);
126
- }
127
- function commandLine(pid) {
128
- try {
129
- return readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').join(' ').trim();
130
- }
131
- catch {
132
- return '';
133
- }
134
- }
135
- export function processes(marker) {
136
- const pids = marked(marker);
137
- const tree = [...pids, ...descendants(pids)];
138
- const commands = process.platform === 'darwin'
139
- ? new Map(listed('-Aww').map(([pid, , command]) => [pid, command]))
140
- : new Map(tree.map((pid) => [pid, commandLine(pid)]));
141
- return new Set(tree.flatMap((pid) => (commands.get(pid) ? [`${pid} ${commands.get(pid)}`] : [])));
142
- }
143
- export function killTree(child) {
144
- killAll([child.pid, ...descendants([child.pid])]);
145
- }
146
- export function killMarked(marker) {
147
- const pids = marked(marker);
148
- killAll([...pids, ...descendants(pids)]);
149
- }
150
- export function killDescendants() {
151
- const pids = marked(`HOUSE_KIT_RESIDENT=${process.pid}`);
152
- killAll([...pids, ...descendants([process.pid, ...pids])]);
153
- }
package/dist/agents.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { client } from '@agentclientprotocol/sdk';
2
2
  import { readFile, realpath } from 'node:fs/promises';
3
- import { killTree, startAdapter } from './acp.js';
3
+ import { startAdapter } from './acp.js';
4
4
  import { CLIS, KIT_VERSION, below, installAdapter, installCli, locate, run, versionOf } from './clis.js';
5
5
  import { agentBase, kitHome } from './home.js';
6
+ import { killTree } from './scope.js';
6
7
  import { holdTranscription, transcriptionReport } from './transcription.js';
7
8
  const SIGNED_OUT = { signed_in: false, models: [], modes: [] };
8
9
  function select(options, category) {
package/dist/api.js CHANGED
@@ -19,7 +19,7 @@ export function retryDelay(attempt) {
19
19
  // Full jitter, doubling from one second to a 30-second cap, spreads the Kits one outage dropped and retries within half a minute of House's return.
20
20
  return Math.random() * Math.min(30_000, 1000 * 2 ** attempt);
21
21
  }
22
- export async function retrying(sent, signal) {
22
+ export async function retrying(sent, signal, pause = retryDelay) {
23
23
  for (let attempt = 0;; attempt++) {
24
24
  try {
25
25
  return await sent();
@@ -28,8 +28,8 @@ export async function retrying(sent, signal) {
28
28
  if (!(error instanceof HouseRefusal) || retryable(error.text) !== true)
29
29
  throw error;
30
30
  }
31
- // A request House refused as retryable is sent again on the jittered curve.
32
- await delay(retryDelay(attempt), undefined, { signal });
31
+ // A request House refused as retryable is sent again after the caller's pause, the jittered curve unless it names its own.
32
+ await delay(pause(attempt), undefined, { signal });
33
33
  }
34
34
  }
35
35
  export async function post(house, path, body, credential, signal) {
@@ -1,23 +1,23 @@
1
1
  {
2
2
  "schemaVersion": 2,
3
- "version": "0.2.1-c3cf4b145dcda",
3
+ "version": "0.2.1-c46722ad48058",
4
4
  "hosts": {
5
5
  "macos": {
6
6
  "asset": {
7
7
  "name": "connect-linux.sh",
8
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c3cf4b145dcda/connect-linux.sh"
8
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c46722ad48058/connect-linux.sh"
9
9
  }
10
10
  },
11
11
  "linux": {
12
12
  "asset": {
13
13
  "name": "connect-linux.sh",
14
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c3cf4b145dcda/connect-linux.sh"
14
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c46722ad48058/connect-linux.sh"
15
15
  }
16
16
  },
17
17
  "windows": {
18
18
  "asset": {
19
19
  "name": "connect-windows.ps1",
20
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c3cf4b145dcda/connect-windows.ps1"
20
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-c46722ad48058/connect-windows.ps1"
21
21
  }
22
22
  }
23
23
  }
package/dist/bridge.js CHANGED
@@ -11,11 +11,10 @@ import { loginPath } from './clis.js';
11
11
  import { changedPaths, } from './copies.js';
12
12
  import { kitHome, readEnrolment } from './home.js';
13
13
  import { callHouse, mcpBody, rpc, UNREACHABLE } from './mcp.js';
14
- import { operationId, uuidOf } from './operation.js';
14
+ import { operationId } from './operation.js';
15
15
  import { refusalOf, retryable } from './refusals.js';
16
16
  import { relayed } from './relay.js';
17
17
  const MCP_REQUEST_BYTES = 4 * 1024 * 1024;
18
- const ATTACHMENTS = '/kit/attachments/upload';
19
18
  export async function received(request) {
20
19
  let text = '';
21
20
  request.setEncoding('utf8');
@@ -68,11 +67,6 @@ function resendAfter(forwarded, attempt) {
68
67
  const seconds = pendingSeconds(forwarded);
69
68
  return seconds === null ? null : seconds * 1000;
70
69
  }
71
- function versioned(conversationId, text) {
72
- const file = JSON.parse(text);
73
- const identity = JSON.stringify([conversationId, file.room_ref ?? null, file.name, file.sha256]);
74
- return JSON.stringify({ ...file, version: uuidOf(createHash('sha256').update(identity).digest(), 8) });
75
- }
76
70
  function editAnswer(forwarded) {
77
71
  const answer = answered(forwarded);
78
72
  if ('refused' in answer)
@@ -103,7 +97,7 @@ export async function openBridge(house, copies, conversationId, signal) {
103
97
  const after = resendAfter(forwarded, attempt);
104
98
  if (after === null)
105
99
  return forwarded;
106
- // A write House did not settle is sent again on the jittered curve, or after the wait House names for a pending one.
100
+ // A Tool call House did not settle is sent again on the jittered curve, or after the wait House names for a pending one.
107
101
  await delay(after, undefined, { signal: closed.signal });
108
102
  }
109
103
  };
@@ -141,32 +135,9 @@ export async function openBridge(house, copies, conversationId, signal) {
141
135
  const held = JSON.parse(text).transfer;
142
136
  return { url: held.url, operation: held.operation, bytes: bytes.length, sha256 };
143
137
  };
144
- let mutations = null;
145
- const writes = async (tool) => {
146
- mutations ??= house
147
- .post('/kit/tools/mutations', {}, closed.signal)
148
- .then(({ tools }) => new Set(tools.filter((listed) => listed.writes).map((listed) => listed.name)));
149
- try {
150
- return (await mutations).has(tool);
151
- }
152
- catch (error) {
153
- mutations = null;
154
- throw error;
155
- }
156
- };
157
- const forward = async (path, text) => {
158
- if (path === '/') {
159
- const message = JSON.parse(text);
160
- const tool = message.method === 'tools/call' ? String(message.params.name) : null;
161
- return send(message, tool !== null && (await writes(tool)) ? operationId() : null);
162
- }
163
- const answer = await fetch(relayed(new URL(path, origin)), {
164
- method: 'POST',
165
- headers: { 'content-type': 'application/json', authorization: `Bearer ${credential}` },
166
- body: versioned(conversationId, text),
167
- signal: closed.signal,
168
- });
169
- return { status: answer.status, text: await answer.text() };
138
+ const forward = (text) => {
139
+ const message = JSON.parse(text);
140
+ return send(message, message.method === 'tools/call' ? operationId() : null);
170
141
  };
171
142
  const caller = {
172
143
  key: `conversation:${conversationId}`,
@@ -188,11 +159,13 @@ export async function openBridge(house, copies, conversationId, signal) {
188
159
  const { cwd, commit } = JSON.parse(text);
189
160
  return { status: 200, text: JSON.stringify(await copies.push(cwd, commit, caller)) };
190
161
  }
162
+ if (path === '/git/fetch')
163
+ return { status: 200, text: JSON.stringify(await copies.fetch()) };
191
164
  if (path === '/git/observed') {
192
165
  await copies.observed(JSON.parse(text));
193
166
  return { status: 200, text: '{}' };
194
167
  }
195
- return path === '/' || path === ATTACHMENTS ? forward(path, text) : { status: 404, text: '' };
168
+ return path === '/' ? forward(text) : { status: 404, text: '' };
196
169
  };
197
170
  const sockets = join(kitHome(), 'bridges');
198
171
  await mkdir(sockets, { recursive: true, mode: 0o700 });
@@ -212,7 +185,8 @@ export async function openBridge(house, copies, conversationId, signal) {
212
185
  response.writeHead(error.status, { 'content-type': 'application/json' }).end(error.text);
213
186
  return;
214
187
  }
215
- response.writeHead(502).end(request.url === '/git/push' && error instanceof Error ? error.message : UNREACHABLE);
188
+ const verb = request.url === '/git/push' || request.url === '/git/fetch';
189
+ response.writeHead(502).end(verb && error instanceof Error ? error.message : UNREACHABLE);
216
190
  }
217
191
  });
218
192
  bridge.listen(socketPath);
@@ -239,7 +213,7 @@ export async function openBridge(house, copies, conversationId, signal) {
239
213
  GIT_CONFIG_VALUE_0: app,
240
214
  },
241
215
  tool: async (name, args) => {
242
- const forwarded = await forward('/', JSON.stringify(call(name, args)));
216
+ const forwarded = await forward(JSON.stringify(call(name, args)));
243
217
  if (forwarded.status !== 200)
244
218
  throw new Error(`House refused ${name} with ${forwarded.status}: ${forwarded.text}`);
245
219
  const answer = JSON.parse(forwarded.text);
package/dist/clis.js CHANGED
@@ -1,24 +1,56 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { readFileSync } from 'node:fs';
3
- import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { constants, readFileSync } from 'node:fs';
3
+ import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
4
4
  import { homedir, userInfo } from 'node:os';
5
- import { join } from 'node:path';
5
+ import { delimiter, isAbsolute, join } from 'node:path';
6
6
  import { kitHome } from './home.js';
7
- async function allowHouseInCodex() {
7
+ const RAW_SUBTYPES = [
8
+ 'background_tasks_changed',
9
+ 'task_started',
10
+ 'task_updated',
11
+ 'task_notification',
12
+ 'session_state_changed',
13
+ 'hook_started',
14
+ 'hook_response',
15
+ ];
16
+ async function executable(path) {
17
+ try {
18
+ await access(path, constants.X_OK);
19
+ return true;
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ async function allowHouseInCodex(path) {
26
+ const candidates = [...new Set(path.split(delimiter).filter((directory) => isAbsolute(directory)))].map((directory) => join(directory, 'house'));
27
+ const houses = [];
28
+ for (const candidate of candidates)
29
+ if (await executable(candidate))
30
+ houses.push(candidate);
8
31
  const rules = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'rules');
9
32
  await mkdir(rules, { recursive: true });
10
- await writeFile(join(rules, 'house.rules'), 'prefix_rule(pattern = ["house"], decision = "allow")\n');
33
+ await writeFile(join(rules, 'house.rules'), `prefix_rule(pattern = ["house"], decision = "allow")\nhost_executable(name = "house", paths = ${JSON.stringify(houses)})\n`);
11
34
  }
12
35
  async function nothing() { }
36
+ function bridgeInClaudeSandbox(bridge) {
37
+ return process.platform === 'darwin' ? { allowUnixSockets: [bridge] } : { allowAllUnixSockets: true };
38
+ }
13
39
  export const CLIS = {
14
40
  'codex-acp': {
15
41
  bin: 'codex',
16
42
  minimum: '0.159.1',
17
43
  install: 'curl -fsSL https://chatgpt.com/codex/install.sh | sh',
18
- adapter: { package: '@agentclientprotocol/codex-acp', bin: 'codex-acp', executable: 'CODEX_PATH', env: {} },
44
+ adapter: {
45
+ package: '@agentclientprotocol/codex-acp',
46
+ bin: 'codex-acp',
47
+ executable: 'CODEX_PATH',
48
+ env: { CODEX_CONFIG: JSON.stringify({ features: { shell_zsh_fork: true } }) },
49
+ },
19
50
  args: [],
20
51
  fullAccess: 'agent-full-access',
21
- sessionMeta: {},
52
+ sessionMeta: () => ({}),
53
+ renames: true,
22
54
  allowHouse: allowHouseInCodex,
23
55
  signedIn: { command: ['login', 'status'] },
24
56
  login: { args: ['login', '--device-auth'], code: 'show' },
@@ -36,12 +68,18 @@ export const CLIS = {
36
68
  },
37
69
  args: [],
38
70
  fullAccess: 'bypassPermissions',
39
- sessionMeta: {
71
+ sessionMeta: (bridge, title) => ({
40
72
  claudeCode: {
41
- options: { allowedTools: ['Bash(house:*)'] },
42
- emitRawSDKMessages: ['background_tasks_changed', 'session_state_changed', 'task_started', 'task_notification'].map((subtype) => ({ type: 'system', subtype })),
73
+ options: {
74
+ allowedTools: ['Bash(house:*)'],
75
+ includeHookEvents: true,
76
+ title,
77
+ settings: { sandbox: { network: bridgeInClaudeSandbox(bridge) } },
78
+ },
79
+ emitRawSDKMessages: RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })),
43
80
  },
44
- },
81
+ }),
82
+ renames: false,
45
83
  allowHouse: nothing,
46
84
  signedIn: { command: ['auth', 'status'] },
47
85
  login: { args: ['auth', 'login', '--claudeai'], code: 'collect', rejected: 'Invalid code' },
@@ -52,9 +90,10 @@ export const CLIS = {
52
90
  minimum: '1.0.46',
53
91
  install: 'curl -fsSL https://x.ai/cli/install.sh | bash',
54
92
  adapter: null,
55
- args: ['agent', '--always-approve', '--no-leader', 'stdio'],
93
+ args: ['--sandbox', 'off', 'agent', '--always-approve', '--no-leader', 'stdio'],
56
94
  fullAccess: null,
57
- sessionMeta: {},
95
+ sessionMeta: () => ({}),
96
+ renames: false,
58
97
  allowHouse: nothing,
59
98
  signedIn: { initializeMeta: 'defaultAuthMethodId' },
60
99
  login: { args: ['login', '--device-auth'], code: 'show' },
@@ -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
+ });