@agentshouse/kit 0.2.1-cde47fd72fe59 → 0.2.1-ce0af1aee9a57

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 (149) hide show
  1. package/README.md +28 -29
  2. package/dist/acp.js +59 -8
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +59 -33
  5. package/dist/api.js +5 -5
  6. package/dist/authority-main.js +3 -3
  7. package/dist/bridge.js +5 -5
  8. package/dist/building.js +50 -0
  9. package/dist/calls.js +71 -0
  10. package/dist/chunks.js +49 -0
  11. package/dist/clis.js +47 -45
  12. package/dist/{stream.js → connection.js} +46 -49
  13. package/dist/content.js +63 -0
  14. package/dist/conversations.js +614 -206
  15. package/dist/copies.js +308 -176
  16. package/dist/end.js +14 -4
  17. package/dist/events.js +742 -210
  18. package/dist/files.js +139 -37
  19. package/dist/git.js +47 -13
  20. package/dist/grok.js +39 -0
  21. package/dist/home.js +0 -7
  22. package/dist/house-cli.js +97 -89
  23. package/dist/house-main.js +3 -3
  24. package/dist/instructions.js +29 -11
  25. package/dist/kit-cli.js +5 -8
  26. package/dist/kit-main.js +3 -3
  27. package/dist/login.js +6 -6
  28. package/dist/logout.js +1 -1
  29. package/dist/mcp.js +6 -2
  30. package/dist/placement.js +21 -20
  31. package/dist/relay.js +21 -0
  32. package/dist/resident.js +69 -48
  33. package/dist/scope.js +15 -4
  34. package/dist/scripts.js +255 -0
  35. package/dist/secret-input.js +1 -1
  36. package/dist/service.js +1 -1
  37. package/dist/sign-in.js +22 -21
  38. package/dist/silence.js +28 -0
  39. package/dist/skills.js +42 -97
  40. package/dist/transcription.js +88 -45
  41. package/dist/translate.js +18 -9
  42. package/dist/update.js +113 -124
  43. package/dist/wire.js +37 -3
  44. package/dist/work.js +9 -2
  45. package/package.json +22 -21
  46. package/dist/bootstrap.json +0 -24
  47. package/dist/chatgpt.js +0 -32
  48. package/dist/clis-main.js +0 -23
  49. package/dist/inputs.js +0 -37
  50. package/dist/parts.js +0 -82
  51. package/how-we-work.md +0 -33
  52. package/skills/ask-matt/LICENSE +0 -21
  53. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  54. package/skills/ask-matt/SKILL.md +0 -97
  55. package/skills/ask-matt/agents/openai.yaml +0 -5
  56. package/skills/code-review/LICENSE +0 -21
  57. package/skills/code-review/SKILL.md +0 -89
  58. package/skills/code-review/agents/openai.yaml +0 -3
  59. package/skills/codebase-design/DEEPENING.md +0 -37
  60. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  61. package/skills/codebase-design/LICENSE +0 -21
  62. package/skills/codebase-design/SKILL.md +0 -114
  63. package/skills/codebase-design/agents/openai.yaml +0 -3
  64. package/skills/diagnosing-bugs/LICENSE +0 -21
  65. package/skills/diagnosing-bugs/SKILL.md +0 -138
  66. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  67. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  68. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  69. package/skills/domain-modeling/GLOSSARY-FORMAT.md +0 -60
  70. package/skills/domain-modeling/LICENSE +0 -21
  71. package/skills/domain-modeling/SKILL.md +0 -74
  72. package/skills/domain-modeling/agents/openai.yaml +0 -3
  73. package/skills/grill-me/LICENSE +0 -21
  74. package/skills/grill-me/SKILL.md +0 -7
  75. package/skills/grill-me/agents/openai.yaml +0 -5
  76. package/skills/grill-with-docs/LICENSE +0 -21
  77. package/skills/grill-with-docs/SKILL.md +0 -7
  78. package/skills/grill-with-docs/agents/openai.yaml +0 -5
  79. package/skills/grilling/LICENSE +0 -21
  80. package/skills/grilling/SKILL.md +0 -30
  81. package/skills/grilling/agents/openai.yaml +0 -3
  82. package/skills/handoff/LICENSE +0 -21
  83. package/skills/handoff/SKILL.md +0 -16
  84. package/skills/handoff/agents/openai.yaml +0 -5
  85. package/skills/implement/LICENSE +0 -21
  86. package/skills/implement/SKILL.md +0 -17
  87. package/skills/implement/agents/openai.yaml +0 -5
  88. package/skills/implement-spec/LICENSE +0 -21
  89. package/skills/implement-spec/SKILL.md +0 -40
  90. package/skills/implement-spec/agents/openai.yaml +0 -5
  91. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  92. package/skills/improve-codebase-architecture/LICENSE +0 -21
  93. package/skills/improve-codebase-architecture/SKILL.md +0 -71
  94. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
  95. package/skills/pr/CREDITS.md +0 -3
  96. package/skills/pr/LICENSE +0 -21
  97. package/skills/pr/SKILL.md +0 -170
  98. package/skills/pr/agents/openai.yaml +0 -3
  99. package/skills/prototype/LICENSE +0 -21
  100. package/skills/prototype/LOGIC.md +0 -67
  101. package/skills/prototype/SKILL.md +0 -26
  102. package/skills/prototype/UI.md +0 -112
  103. package/skills/prototype/agents/openai.yaml +0 -3
  104. package/skills/research/LICENSE +0 -21
  105. package/skills/research/SKILL.md +0 -12
  106. package/skills/research/agents/openai.yaml +0 -3
  107. package/skills/retro/LICENSE +0 -21
  108. package/skills/retro/SKILL.md +0 -44
  109. package/skills/retro/agents/openai.yaml +0 -5
  110. package/skills/tdd/LICENSE +0 -21
  111. package/skills/tdd/SKILL.md +0 -38
  112. package/skills/tdd/agents/openai.yaml +0 -3
  113. package/skills/tdd/mocking.md +0 -59
  114. package/skills/tdd/tests.md +0 -77
  115. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  116. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  117. package/skills/teach/LICENSE +0 -21
  118. package/skills/teach/MISSION-FORMAT.md +0 -31
  119. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  120. package/skills/teach/SKILL.md +0 -140
  121. package/skills/teach/agents/openai.yaml +0 -5
  122. package/skills/to-questionnaire/LICENSE +0 -21
  123. package/skills/to-questionnaire/SKILL.md +0 -54
  124. package/skills/to-questionnaire/agents/openai.yaml +0 -5
  125. package/skills/to-spec/LICENSE +0 -21
  126. package/skills/to-spec/SKILL.md +0 -75
  127. package/skills/to-spec/agents/openai.yaml +0 -5
  128. package/skills/to-tickets/LICENSE +0 -21
  129. package/skills/to-tickets/SKILL.md +0 -105
  130. package/skills/to-tickets/agents/openai.yaml +0 -5
  131. package/skills/triage/AGENT-BRIEF.md +0 -207
  132. package/skills/triage/LICENSE +0 -21
  133. package/skills/triage/OUT-OF-SCOPE.md +0 -105
  134. package/skills/triage/SKILL.md +0 -112
  135. package/skills/triage/agents/openai.yaml +0 -5
  136. package/skills/wait-what/LICENSE +0 -21
  137. package/skills/wait-what/SKILL.md +0 -7
  138. package/skills/wait-what/agents/openai.yaml +0 -5
  139. package/skills/wayfinder/LICENSE +0 -21
  140. package/skills/wayfinder/SKILL.md +0 -128
  141. package/skills/wayfinder/agents/openai.yaml +0 -5
  142. package/skills/wizard/LICENSE +0 -21
  143. package/skills/wizard/SKILL.md +0 -44
  144. package/skills/wizard/agents/openai.yaml +0 -3
  145. package/skills/wizard/template.sh +0 -223
  146. package/skills/writing-for-agents/LICENSE +0 -21
  147. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  148. package/skills/writing-for-agents/SKILL.md +0 -81
  149. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/calls.js ADDED
@@ -0,0 +1,71 @@
1
+ import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { kitHome } from './home.js';
4
+ function logged(error) {
5
+ process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
6
+ }
7
+ export class Calls {
8
+ house;
9
+ changed;
10
+ carried = new Map();
11
+ path = join(kitHome(), 'call-results.json');
12
+ results;
13
+ returned = new Set();
14
+ released = new Set();
15
+ open = 0;
16
+ constructor(house, changed) {
17
+ this.house = house;
18
+ this.changed = changed;
19
+ this.results = new Map(existsSync(this.path) ? Object.entries(JSON.parse(readFileSync(this.path, 'utf8'))) : []);
20
+ }
21
+ keepResult(callId, result) {
22
+ if (this.returned.has(callId))
23
+ return;
24
+ this.results.set(callId, result);
25
+ this.save();
26
+ }
27
+ idle() {
28
+ return this.open === 0;
29
+ }
30
+ carry(callId, work) {
31
+ if (this.released.has(callId))
32
+ return Promise.resolve();
33
+ const known = this.carried.get(callId);
34
+ const result = this.results.get(callId);
35
+ const carried = known ?? (result === undefined ? work() : Promise.resolve({ result }));
36
+ if (known === undefined) {
37
+ this.carried.set(callId, carried);
38
+ carried.catch(() => this.carried.delete(callId));
39
+ }
40
+ this.open++;
41
+ this.changed();
42
+ return carried
43
+ .then(async ({ result, returned, release }) => {
44
+ try {
45
+ await this.house.deliver('/kit/kit-calls/results/return', { call: callId, ...result });
46
+ }
47
+ finally {
48
+ this.returned.add(callId);
49
+ if (this.results.delete(callId))
50
+ this.save();
51
+ }
52
+ if (known !== undefined)
53
+ return;
54
+ if (release) {
55
+ this.carried.delete(callId);
56
+ this.released.add(callId);
57
+ }
58
+ await returned?.();
59
+ })
60
+ .catch(logged)
61
+ .finally(() => {
62
+ this.open--;
63
+ this.changed();
64
+ });
65
+ }
66
+ save() {
67
+ const temporary = `${this.path}.${process.pid}`;
68
+ writeFileSync(temporary, JSON.stringify(Object.fromEntries(this.results)), { mode: 0o600 });
69
+ renameSync(temporary, this.path);
70
+ }
71
+ }
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* chunkTexts(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 (entry.content !== undefined)
45
+ yield entry;
46
+ }
47
+ await rm(file);
48
+ }
49
+ }
package/dist/clis.js CHANGED
@@ -4,7 +4,8 @@ import { constants, readFileSync } from 'node:fs';
4
4
  import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
5
5
  import { homedir, userInfo } from 'node:os';
6
6
  import { delimiter, dirname, isAbsolute, join } from 'node:path';
7
- import { kitHome } from './home.js';
7
+ import { releaseDirectory } from './placement.js';
8
+ import { childEnvironment } from './relay.js';
8
9
  const HOUSE_EXECUTABLES = /^host_executable\(name = "house", paths = (\[.*\])\)$/m;
9
10
  function houseRule(houses) {
10
11
  return `prefix_rule(pattern = ["house"], decision = "allow")\nhost_executable(name = "house", paths = ${JSON.stringify(houses)})\n`;
@@ -14,10 +15,12 @@ const RAW_SUBTYPES = [
14
15
  'task_started',
15
16
  'task_updated',
16
17
  'task_notification',
18
+ 'task_progress',
17
19
  'session_state_changed',
18
20
  'hook_started',
19
21
  'hook_response',
20
22
  ];
23
+ const RAW_TYPES = ['result', 'user', 'assistant', 'rate_limit_event', 'prompt_suggestion'];
21
24
  async function executable(path) {
22
25
  try {
23
26
  await access(path, constants.X_OK);
@@ -60,6 +63,14 @@ export async function allowHouseInCodex(path) {
60
63
  await rename(temporary, file);
61
64
  }
62
65
  async function nothing() { }
66
+ function claudeQuestionFields(request) {
67
+ const properties = request.requestedSchema?.properties ?? {};
68
+ return Object.keys(properties).filter((name) => properties[name]._meta?.jetbrains?.air?.customAnswer !== undefined);
69
+ }
70
+ function codexQuestionFields(request) {
71
+ const { _meta, requestedSchema } = request;
72
+ return _meta?.codex === undefined ? [] : (requestedSchema?.required ?? []);
73
+ }
63
74
  function answered(error) {
64
75
  return typeof error === 'object' && error !== null ? error : {};
65
76
  }
@@ -69,8 +80,9 @@ function bridgeInClaudeSandbox(bridge) {
69
80
  export const CLIS = {
70
81
  'codex-acp': {
71
82
  bin: 'codex',
72
- minimum: '0.159.1',
83
+ minimum: '0.165.0',
73
84
  install: 'curl -fsSL https://chatgpt.com/codex/install.sh | sh',
85
+ update: 'codex update',
74
86
  adapter: {
75
87
  package: '@agentclientprotocol/codex-acp',
76
88
  bin: 'codex-acp',
@@ -84,16 +96,17 @@ export const CLIS = {
84
96
  const { code, data } = answered(error);
85
97
  return code === -32603 && typeof data?.details === 'string' && data.details.startsWith('no rollout found');
86
98
  },
87
- renames: true,
88
99
  allowHouse: allowHouseInCodex,
100
+ questionFields: codexQuestionFields,
89
101
  signedIn: { command: ['login', 'status'] },
90
102
  login: { args: ['login', '--device-auth'], code: 'show' },
91
103
  air: ['asyncTasks', 'nativeSubagentSessions'],
92
104
  },
93
105
  'claude-agent-acp': {
94
106
  bin: 'claude',
95
- minimum: '2.1.286',
107
+ minimum: '2.1.316',
96
108
  install: 'curl -fsSL https://claude.ai/install.sh | bash',
109
+ update: 'claude update',
97
110
  adapter: {
98
111
  package: '@agentclientprotocol/claude-agent-acp',
99
112
  bin: 'claude-agent-acp',
@@ -102,20 +115,19 @@ export const CLIS = {
102
115
  },
103
116
  args: [],
104
117
  fullAccess: 'bypassPermissions',
105
- sessionMeta: (bridge, title) => ({
118
+ sessionMeta: (bridge) => ({
106
119
  claudeCode: {
107
120
  options: {
108
121
  allowedTools: ['Bash(house:*)'],
109
122
  includeHookEvents: true,
110
- title,
111
123
  settings: { sandbox: { network: bridgeInClaudeSandbox(bridge) } },
112
124
  },
113
- emitRawSDKMessages: RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })),
125
+ emitRawSDKMessages: [...RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })), ...RAW_TYPES.map((type) => ({ type }))],
114
126
  },
115
127
  }),
116
128
  unknownSession: (error) => answered(error).code === -32002,
117
- renames: false,
118
129
  allowHouse: nothing,
130
+ questionFields: claudeQuestionFields,
119
131
  signedIn: { command: ['auth', 'status'] },
120
132
  login: { args: ['auth', 'login', '--claudeai'], code: 'collect', rejected: 'Invalid code' },
121
133
  air: ['asyncTasks', 'sessionFailure'],
@@ -124,51 +136,36 @@ export const CLIS = {
124
136
  bin: 'grok',
125
137
  minimum: '1.0.46',
126
138
  install: 'curl -fsSL https://x.ai/cli/install.sh | bash',
139
+ update: 'grok update',
127
140
  adapter: null,
128
141
  args: ['--sandbox', 'off', 'agent', '--always-approve', '--no-leader', 'stdio'],
129
142
  fullAccess: null,
130
143
  sessionMeta: () => ({}),
131
144
  unknownSession: (error) => answered(error).data?.code === 'FS_NOT_FOUND',
132
- renames: false,
133
145
  allowHouse: nothing,
146
+ questionFields: () => [],
134
147
  signedIn: { initializeMeta: 'defaultAuthMethodId' },
135
148
  login: { args: ['login', '--device-auth'], code: 'show' },
136
149
  air: ['asyncTasks'],
137
150
  },
138
151
  };
139
152
  const KIT_PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
140
- export const KIT_VERSION = KIT_PACKAGE.version;
141
- const PROXY = /^https?_proxy$/i;
153
+ export const KIT_RELEASE = KIT_PACKAGE.version;
142
154
  const VERSION = /\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?/;
143
- // An install still running after fifteen minutes is ended and reported as failed, so a hung download cannot hold its CLI's report.
155
+ // 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.
144
156
  const INSTALL_MS = 15 * 60_000;
145
157
  // A login shell or a version read is ended after half a minute, so a profile that waits for input cannot stall the report.
146
158
  const READ_MS = 30_000;
147
159
  const CAUSE_CHARACTERS = 4000;
148
- function prefix(kind) {
149
- return join(kitHome(), 'agents', kind);
150
- }
151
160
  export function adapterCommand(kind) {
152
- return join(prefix(kind), 'node_modules', '.bin', CLIS[kind].adapter.bin);
153
- }
154
- async function installedAdapter(kind) {
155
- try {
156
- const manifest = join(prefix(kind), 'node_modules', CLIS[kind].adapter.package, 'package.json');
157
- return JSON.parse(await readFile(manifest, 'utf8')).version;
158
- }
159
- catch {
160
- return null;
161
- }
162
- }
163
- export function withoutProxy() {
164
- return Object.fromEntries(Object.entries(process.env).filter(([name]) => !PROXY.test(name)));
161
+ return join(releaseDirectory(KIT_RELEASE), 'adapters', kind, 'node_modules', '.bin', CLIS[kind].adapter.bin);
165
162
  }
166
163
  export function run(command, args, timeoutMs, detached = false, signal) {
167
164
  return new Promise((resolve) => {
168
165
  const child = spawn(command, args, {
169
166
  stdio: ['ignore', 'pipe', 'pipe'],
170
167
  timeout: timeoutMs,
171
- env: withoutProxy(),
168
+ env: childEnvironment(),
172
169
  detached,
173
170
  signal: detached ? undefined : signal,
174
171
  });
@@ -202,19 +199,18 @@ export function run(command, args, timeoutMs, detached = false, signal) {
202
199
  export function failureOf(ran, program) {
203
200
  return ran.output.trim().slice(-CAUSE_CHARACTERS) || `${program} exited with ${ran.status ?? 'a signal'}`;
204
201
  }
205
- export async function installAdapter(kind, signal) {
206
- const adapter = CLIS[kind].adapter;
207
- if (adapter === null)
208
- return null;
209
- const release = KIT_PACKAGE.peerDependencies[adapter.package];
210
- if ((await installedAdapter(kind)) === release)
211
- return null;
212
- const ran = await run('npm', ['install', '--prefix', prefix(kind), '--cache', join(kitHome(), 'npm-cache'), '--no-save', '--no-audit', '--no-fund', '--omit=optional', `${adapter.package}@${release}`], INSTALL_MS, true, signal);
213
- return ran.status === 0 ? null : failureOf(ran, 'npm');
202
+ export function adapterArchive(kind) {
203
+ return `${kind}-${KIT_PACKAGE.peerDependencies[CLIS[kind].adapter.package]}.tar.gz`;
214
204
  }
215
- export async function installCli(kind, signal) {
216
- const ran = await run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true, signal);
217
- return ran.status === 0 ? null : failureOf(ran, 'the install');
205
+ async function bounded(program, work, signal) {
206
+ const deadline = AbortSignal.timeout(INSTALL_MS);
207
+ const ran = await work(signal === undefined ? deadline : AbortSignal.any([signal, deadline]));
208
+ if (deadline.aborted && signal?.aborted !== true)
209
+ return `${program} did not end within ${INSTALL_MS / 1000} seconds`;
210
+ return ran.status === 0 ? null : failureOf(ran, program);
211
+ }
212
+ export function installCli(kind, signal) {
213
+ return bounded('the install', (within) => run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true, within), signal);
218
214
  }
219
215
  function loginShell() {
220
216
  return process.env.SHELL || userInfo().shell;
@@ -222,13 +218,19 @@ function loginShell() {
222
218
  const FOUND = 'house-kit-cli ';
223
219
  const LOOKUP = `found=$(command -v "$1") || exit 0; case $found in /*) ;; *) found=$(pwd -P)/$found ;; esac; printf "${FOUND}%s\\n" "$found"`;
224
220
  const USER_BIN = 'case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) PATH="$PATH:$HOME/.local/bin" ;; esac; export PATH';
225
- function inLoginShell(script, argument = '', signal) {
226
- return run(loginShell(), ['-l', '-i', '-c', `exec /bin/sh -c '${USER_BIN}; ${script}' sh ${argument}`], READ_MS, true, signal);
221
+ function inLoginShell(script, argument = '', signal, timeoutMs = READ_MS) {
222
+ return run(loginShell(), ['-l', '-i', '-c', `exec /bin/sh -c '${USER_BIN}; ${script}' sh ${argument}`], timeoutMs, true, signal);
227
223
  }
228
- export async function locate(kind, signal) {
229
- const ran = await inLoginShell(LOOKUP, CLIS[kind].bin, signal);
224
+ export async function onLoginPath(program, signal) {
225
+ const ran = await inLoginShell(LOOKUP, program, signal);
230
226
  return ran.stdout.split('\n').findLast((line) => line.startsWith(FOUND))?.slice(FOUND.length) ?? null;
231
227
  }
228
+ export function locate(kind, signal) {
229
+ return onLoginPath(CLIS[kind].bin, signal);
230
+ }
231
+ export function updateCli(kind) {
232
+ return bounded('the update', (within) => inLoginShell(CLIS[kind].update, '', within, INSTALL_MS));
233
+ }
232
234
  export async function loginPath() {
233
235
  const marker = 'house-kit-path ';
234
236
  const ran = await inLoginShell(`printf "${marker}%s\\n" "$PATH"`);
@@ -1,43 +1,19 @@
1
1
  import { subscribe } from 'node:diagnostics_channel';
2
+ import { setTimeout as delay } from 'node:timers/promises';
2
3
  import { HouseRefusal, retryDelay } from './api.js';
3
- import { end, REPLACED, signInAgain, updateRequired } from './end.js';
4
+ import { end, REPLACED, signInAgain } from './end.js';
4
5
  import { readEnrolment } from './home.js';
5
6
  import { relayed } from './relay.js';
6
- import { KIT_WIRE, tooOld } from './wire.js';
7
+ import { Silence } from './silence.js';
8
+ import { endUnserved, KIT_WIRE, unserved } from './wire.js';
7
9
  const PATH = '/kit/stream';
8
10
  const SUBPROTOCOL = `house.kit.stream.${KIT_WIRE}`;
9
11
  const REFUSAL_HEADER = 'x-house-refusal';
10
- // House beats each stream every thirty seconds, so two silent beats mean this Kit cannot hear House.
11
- export const STREAM_SILENCE_MS = 60_000;
12
- const SYSTEM_STREAM_CLOCK = {
13
- later: (delay, callback) => setTimeout(callback, delay),
14
- clear: (timer) => clearTimeout(timer),
15
- };
16
- export class StreamSilence {
17
- timer = null;
18
- silent;
19
- clock;
20
- interval;
21
- constructor(silent, clock = SYSTEM_STREAM_CLOCK, interval = STREAM_SILENCE_MS) {
22
- this.silent = silent;
23
- this.clock = clock;
24
- this.interval = interval;
25
- }
26
- heard() {
27
- this.stop();
28
- this.timer = this.clock.later(this.interval, () => {
29
- this.timer = null;
30
- this.silent();
31
- });
32
- }
33
- stop() {
34
- if (this.timer === null)
35
- return;
36
- this.clock.clear(this.timer);
37
- this.timer = null;
38
- }
39
- }
40
- function streamUrl(house) {
12
+ // House beats each Kit connection every thirty seconds, so two silent beats mean this Kit process cannot hear House.
13
+ export const CONNECTION_SILENCE_MS = 60_000;
14
+ // A stopping Kit waits up to two seconds for House to answer its close, so what it sent last reaches House and a House that does not answer holds no stop.
15
+ const CLOSE_ANSWER_MS = 2_000;
16
+ function connectionUrl(house) {
41
17
  const url = new URL(PATH, house);
42
18
  url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
43
19
  return url;
@@ -56,16 +32,21 @@ subscribe('undici:request:headers', (message) => {
56
32
  return;
57
33
  refused = new HouseRefusal(PATH, response.statusCode, header(response.headers, REFUSAL_HEADER) || response.statusText);
58
34
  });
59
- export function holdStream(handlers) {
35
+ export function holdConnection(handlers) {
36
+ let connection = null;
60
37
  let socket = null;
61
38
  let failures = 0;
39
+ let stopping = false;
62
40
  const connect = async () => {
63
41
  const { house, credential } = (await readEnrolment());
42
+ if (socket !== null || unserved() || stopping)
43
+ return;
64
44
  refused = null;
65
- const opening = new WebSocket(relayed(streamUrl(house)), {
45
+ const opening = new WebSocket(relayed(connectionUrl(house)), {
66
46
  protocols: [SUBPROTOCOL],
67
47
  headers: { authorization: `Bearer ${credential}` },
68
48
  });
49
+ socket = opening;
69
50
  let opened = false;
70
51
  let silence = null;
71
52
  const closed = (event) => {
@@ -73,28 +54,33 @@ export function holdStream(handlers) {
73
54
  silence = null;
74
55
  if (socket === opening)
75
56
  socket = null;
76
- process.stderr.write(`kit: control stream closed ${event.code} ${event.reason}\n`);
57
+ if (connection === opening)
58
+ connection = null;
59
+ handlers.closed();
60
+ process.stderr.write(`kit: connection closed ${event.code} ${event.reason}\n`);
61
+ if (stopping)
62
+ return;
77
63
  if (event.reason === 'replaced')
78
64
  end(REPLACED);
79
65
  if (event.reason === 'credential_rejected' || refused?.status === 401) {
80
66
  void signInAgain(credential);
81
67
  return;
82
68
  }
83
- if (refused !== null && tooOld(refused.text))
84
- updateRequired();
69
+ if (refused !== null)
70
+ endUnserved(refused.text);
85
71
  if (!opened && refused !== null)
86
72
  process.stderr.write(`kit: ${refused.message}\n`);
87
- // A closed socket reopens in one to three seconds, spread so Kits 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.
73
+ // 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.
88
74
  setTimeout(() => void connect(), opened ? 1000 + Math.random() * 2000 : retryDelay(failures++));
89
75
  };
90
76
  opening.onopen = () => {
91
77
  opened = true;
92
78
  failures = 0;
93
- socket = opening;
94
- silence = new StreamSilence(() => {
95
- if (socket !== opening)
79
+ connection = opening;
80
+ silence = new Silence(CONNECTION_SILENCE_MS, () => {
81
+ if (connection !== opening)
96
82
  return;
97
- socket = null;
83
+ connection = null;
98
84
  opening.onclose = null;
99
85
  opening.close();
100
86
  closed(new CloseEvent('close', { code: 1006, reason: 'heartbeat_missed' }));
@@ -104,20 +90,31 @@ export function holdStream(handlers) {
104
90
  };
105
91
  opening.onmessage = (event) => {
106
92
  silence?.heard();
107
- const frame = JSON.parse(String(event.data));
108
- if (frame.type !== 'beat')
109
- handlers.frame(frame);
93
+ const arrived = JSON.parse(String(event.data));
94
+ if (arrived.type === 'input')
95
+ handlers.call(arrived);
96
+ else if (arrived.type !== 'beat')
97
+ handlers.oneWayCall(arrived);
110
98
  };
111
99
  opening.onerror = () => undefined;
112
100
  opening.onclose = closed;
113
101
  };
114
102
  void connect();
115
103
  return {
116
- send(frame) {
117
- if (socket === null || socket.readyState !== WebSocket.OPEN)
104
+ send(oneWayCall) {
105
+ if (connection === null || connection.readyState !== WebSocket.OPEN)
118
106
  return false;
119
- socket.send(JSON.stringify(frame));
107
+ connection.send(JSON.stringify(oneWayCall));
120
108
  return true;
121
109
  },
110
+ close() {
111
+ stopping = true;
112
+ const open = socket;
113
+ if (open === null)
114
+ return Promise.resolve();
115
+ const answered = new Promise((resolve) => open.addEventListener('close', () => resolve(), { once: true }));
116
+ open.close();
117
+ return Promise.race([answered, delay(CLOSE_ANSWER_MS)]);
118
+ },
122
119
  };
123
120
  }
@@ -0,0 +1,63 @@
1
+ import { applied } from '@agentshouse/session-content';
2
+ function whole(part, parent) {
3
+ return { ...part, parent };
4
+ }
5
+ export class Content {
6
+ parts = [];
7
+ emit;
8
+ keys = new Map();
9
+ writing = new Map();
10
+ planned = null;
11
+ constructor(emit) {
12
+ this.emit = emit;
13
+ }
14
+ index(key) {
15
+ return this.keys.get(key);
16
+ }
17
+ write(type, id, parent, text) {
18
+ if (text === '')
19
+ return;
20
+ const writing = this.writing.get(parent);
21
+ if (writing?.type === type && writing.id === id) {
22
+ this.apply({ op: 'append', index: writing.index, text });
23
+ return;
24
+ }
25
+ const index = this.add(parent, { type, text });
26
+ this.writing.set(parent, { type, id, index });
27
+ }
28
+ put(key, parent, part) {
29
+ const index = this.keys.get(key);
30
+ if (index === undefined) {
31
+ const added = this.add(parent, part);
32
+ this.keys.set(key, added);
33
+ return added;
34
+ }
35
+ const changed = whole(part, this.parts[index].parent);
36
+ if (JSON.stringify(changed) !== JSON.stringify(this.parts[index]))
37
+ this.apply({ op: 'set', index, part: changed });
38
+ return index;
39
+ }
40
+ plan(entries) {
41
+ if (this.planned === null) {
42
+ this.planned = this.add(null, { type: 'plan', entries });
43
+ return;
44
+ }
45
+ this.apply({ op: 'set', index: this.planned, part: { type: 'plan', parent: null, entries } });
46
+ }
47
+ add(parent, part) {
48
+ this.writing.delete(parent);
49
+ return this.arrived(parent, part);
50
+ }
51
+ arrived(parent, part) {
52
+ const index = this.parts.length;
53
+ this.apply({ op: 'start', index, part: whole(part, parent) });
54
+ return index;
55
+ }
56
+ operations() {
57
+ return this.parts.map((part, index) => ({ op: 'start', index, part }));
58
+ }
59
+ apply(operation) {
60
+ this.parts = applied(this.parts, operation);
61
+ this.emit(operation);
62
+ }
63
+ }