@agentshouse/kit 0.2.1-ce145e9aadbf6 → 0.2.1-ce46b2b55463f

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 (146) hide show
  1. package/README.md +46 -49
  2. package/dist/acp.js +101 -108
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +252 -73
  5. package/dist/api.js +43 -6
  6. package/dist/app-git.js +48 -0
  7. package/dist/binaries.js +79 -0
  8. package/dist/bridge.js +62 -79
  9. package/dist/building.js +50 -0
  10. package/dist/calls.js +88 -0
  11. package/dist/chunks.js +49 -0
  12. package/dist/clis.js +171 -102
  13. package/dist/codex-main.js +58 -0
  14. package/dist/connect.js +108 -0
  15. package/dist/connection.js +120 -0
  16. package/dist/content.js +106 -0
  17. package/dist/conversations.js +816 -335
  18. package/dist/copies.js +842 -309
  19. package/dist/earlier.js +263 -0
  20. package/dist/end.js +26 -0
  21. package/dist/events.js +793 -0
  22. package/dist/files.js +206 -18
  23. package/dist/git-main.js +24 -29
  24. package/dist/git.js +95 -18
  25. package/dist/grok.js +39 -0
  26. package/dist/home.js +134 -9
  27. package/dist/house-cli.js +282 -0
  28. package/dist/house-main.js +7 -159
  29. package/dist/instructions.js +7 -11
  30. package/dist/keys.js +238 -0
  31. package/dist/kit-cli.js +78 -0
  32. package/dist/kit-main.js +8 -19
  33. package/dist/login.js +133 -104
  34. package/dist/logout.js +15 -14
  35. package/dist/mcp.js +42 -3
  36. package/dist/owner.js +46 -0
  37. package/dist/placement.js +25 -0
  38. package/dist/refusals.js +43 -15
  39. package/dist/relay.js +33 -2
  40. package/dist/resident.js +161 -61
  41. package/dist/scope.js +214 -0
  42. package/dist/scripts.js +303 -0
  43. package/dist/secret-input.js +4 -3
  44. package/dist/settings.js +188 -0
  45. package/dist/shell.js +3 -0
  46. package/dist/sign-in.js +85 -33
  47. package/dist/silence.js +28 -0
  48. package/dist/skills.js +49 -35
  49. package/dist/supervisor.js +163 -0
  50. package/dist/transcription.js +131 -40
  51. package/dist/translate.js +19 -16
  52. package/dist/update.js +119 -100
  53. package/dist/wire.js +32 -0
  54. package/dist/work.js +353 -0
  55. package/dist/workspace.js +103 -0
  56. package/package.json +26 -21
  57. package/dist/authority-main.js +0 -22
  58. package/dist/blocks.js +0 -51
  59. package/dist/bootstrap.json +0 -24
  60. package/dist/clis-main.js +0 -23
  61. package/dist/configure-main.js +0 -6
  62. package/dist/enrol-main.js +0 -4
  63. package/dist/stream.js +0 -47
  64. package/how-we-work.md +0 -23
  65. package/skills/ask-matt/LICENSE +0 -21
  66. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  67. package/skills/ask-matt/SKILL.md +0 -91
  68. package/skills/ask-matt/agents/openai.yaml +0 -4
  69. package/skills/code-review/LICENSE +0 -21
  70. package/skills/code-review/SKILL.md +0 -89
  71. package/skills/code-review/agents/openai.yaml +0 -3
  72. package/skills/codebase-design/DEEPENING.md +0 -37
  73. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  74. package/skills/codebase-design/LICENSE +0 -21
  75. package/skills/codebase-design/SKILL.md +0 -116
  76. package/skills/codebase-design/agents/openai.yaml +0 -3
  77. package/skills/diagnosing-bugs/LICENSE +0 -21
  78. package/skills/diagnosing-bugs/SKILL.md +0 -140
  79. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  80. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  81. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  82. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  83. package/skills/domain-modeling/LICENSE +0 -21
  84. package/skills/domain-modeling/SKILL.md +0 -76
  85. package/skills/domain-modeling/agents/openai.yaml +0 -3
  86. package/skills/grill-me/LICENSE +0 -21
  87. package/skills/grill-me/SKILL.md +0 -8
  88. package/skills/grill-me/agents/openai.yaml +0 -4
  89. package/skills/grill-with-docs/LICENSE +0 -21
  90. package/skills/grill-with-docs/SKILL.md +0 -8
  91. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  92. package/skills/grilling/LICENSE +0 -21
  93. package/skills/grilling/SKILL.md +0 -30
  94. package/skills/grilling/agents/openai.yaml +0 -3
  95. package/skills/handoff/LICENSE +0 -21
  96. package/skills/handoff/SKILL.md +0 -17
  97. package/skills/handoff/agents/openai.yaml +0 -4
  98. package/skills/implement/LICENSE +0 -21
  99. package/skills/implement/SKILL.md +0 -16
  100. package/skills/implement/agents/openai.yaml +0 -4
  101. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  102. package/skills/improve-codebase-architecture/LICENSE +0 -21
  103. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  104. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  105. package/skills/prototype/LICENSE +0 -21
  106. package/skills/prototype/LOGIC.md +0 -67
  107. package/skills/prototype/SKILL.md +0 -28
  108. package/skills/prototype/UI.md +0 -112
  109. package/skills/prototype/agents/openai.yaml +0 -3
  110. package/skills/research/LICENSE +0 -21
  111. package/skills/research/SKILL.md +0 -14
  112. package/skills/research/agents/openai.yaml +0 -3
  113. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  114. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  115. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  116. package/skills/tdd/LICENSE +0 -21
  117. package/skills/tdd/SKILL.md +0 -40
  118. package/skills/tdd/agents/openai.yaml +0 -3
  119. package/skills/tdd/mocking.md +0 -59
  120. package/skills/tdd/tests.md +0 -77
  121. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  122. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  123. package/skills/teach/LICENSE +0 -21
  124. package/skills/teach/MISSION-FORMAT.md +0 -31
  125. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  126. package/skills/teach/SKILL.md +0 -141
  127. package/skills/teach/agents/openai.yaml +0 -4
  128. package/skills/to-questionnaire/LICENSE +0 -21
  129. package/skills/to-questionnaire/SKILL.md +0 -55
  130. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  131. package/skills/to-spec/LICENSE +0 -21
  132. package/skills/to-spec/SKILL.md +0 -76
  133. package/skills/to-spec/agents/openai.yaml +0 -4
  134. package/skills/to-tickets/LICENSE +0 -21
  135. package/skills/to-tickets/SKILL.md +0 -106
  136. package/skills/to-tickets/agents/openai.yaml +0 -4
  137. package/skills/wait-what/LICENSE +0 -21
  138. package/skills/wait-what/SKILL.md +0 -8
  139. package/skills/wait-what/agents/openai.yaml +0 -4
  140. package/skills/wayfinder/LICENSE +0 -21
  141. package/skills/wayfinder/SKILL.md +0 -129
  142. package/skills/wayfinder/agents/openai.yaml +0 -4
  143. package/skills/writing-for-agents/LICENSE +0 -21
  144. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  145. package/skills/writing-for-agents/SKILL.md +0 -83
  146. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/agents.js CHANGED
@@ -1,9 +1,21 @@
1
1
  import { client } from '@agentclientprotocol/sdk';
2
- import { readFile, realpath } from 'node:fs/promises';
3
- import { killTree, startAdapter } from './acp.js';
4
- import { CLIS, KIT_VERSION, below, installAdapter, installCli, locate, run, versionOf } from './clis.js';
5
- import { agentBase, kitHome } from './home.js';
6
- const SIGNED_OUT = { signed_in: false, models: [], modes: [] };
2
+ import { KIT_WIRE } from '@agentshouse/kit-wire';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+ import { signedOut, startAdapter } from './acp.js';
6
+ import { CLIS, KIT_RELEASE, below, cliEnvironment, installCli, locate, run, updateCli, versionOf } from './clis.js';
7
+ import { agentBase, kitHome, reinstall } from './home.js';
8
+ import { heldSettings } from './settings.js';
9
+ import { holdTranscription, transcriptionReport } from './transcription.js';
10
+ // Two quiet seconds let a fresh conversation start before background model discovery competes for its CPU.
11
+ const MODEL_PROBE_QUIET_MS = 2_000;
12
+ // A CLI's maker can publish several releases a day, so running each chosen CLI's update command hourly brings a new one to the next conversation within the hour for one small check.
13
+ export const CLI_UPDATE_MS = 60 * 60_000;
14
+ // A sign-in's model read that has not answered in ten seconds leaves its sign-in to the status check, so a hung CLI never holds the sign-in's result.
15
+ const SIGNED_IN_READ_MS = 10_000;
16
+ const UNNAMED = { default_model: null, default_effort: null };
17
+ const SIGNED_OUT = { signed_in: false, models: [], ...UNNAMED, modes: [] };
18
+ const INSTALLING = { release: null, failure: null, installing: true, ...SIGNED_OUT };
7
19
  function select(options, category) {
8
20
  const option = options.find((candidate) => candidate.category === category);
9
21
  return option?.type === 'select' ? option : undefined;
@@ -14,12 +26,44 @@ function choices(options) {
14
26
  function values(options) {
15
27
  return choices(options).map((entry) => entry.value);
16
28
  }
29
+ const CLI_DEFAULT = 'default';
30
+ function effortsOf(option) {
31
+ return option === undefined ? [] : values(option.options).filter((value) => value !== CLI_DEFAULT);
32
+ }
33
+ function named(options) {
34
+ const listed = choices(options).filter((entry) => entry.value !== CLI_DEFAULT);
35
+ return listed.filter((entry, at) => listed.findIndex((first) => first.name === entry.name) === at);
36
+ }
37
+ function starting(model, effort) {
38
+ const current = choices(model.options).find((entry) => entry.value === model.currentValue);
39
+ const name = current?.value === CLI_DEFAULT ? current.description : current?.name;
40
+ return {
41
+ default_model: named(model.options).find((entry) => entry.name === name)?.value ?? null,
42
+ default_effort: effort === undefined || effort.currentValue === CLI_DEFAULT ? null : effort.currentValue,
43
+ };
44
+ }
17
45
  function causeOf(error) {
18
46
  return error instanceof Error ? error.message : String(error);
19
47
  }
20
48
  function logged(error) {
21
49
  process.stderr.write(`kit: ${causeOf(error)}\n`);
22
50
  }
51
+ const LAPTOP_CHASSIS = new Set(['8', '9', '10', '14', '30', '31', '32']);
52
+ const DESKTOP_CHASSIS = new Set(['3', '4', '5', '6', '7', '15', '16']);
53
+ const SERVER_CHASSIS = new Set(['17', '18', '19', '20', '21', '22', '23', '24']);
54
+ export function chassisForm(value) {
55
+ const chassis = value.trim();
56
+ if (LAPTOP_CHASSIS.has(chassis))
57
+ return 'laptop';
58
+ if (DESKTOP_CHASSIS.has(chassis))
59
+ return 'desktop';
60
+ if (SERVER_CHASSIS.has(chassis))
61
+ return 'server';
62
+ return undefined;
63
+ }
64
+ export function hostVm(version) {
65
+ return /docker desktop|microsoft|wsl|linuxkit/i.test(version);
66
+ }
23
67
  async function models(kind, adapter, known) {
24
68
  const agent = adapter.connection.agent;
25
69
  const opened = await agent.request('session/new', { cwd: kitHome(), mcpServers: [] });
@@ -28,95 +72,141 @@ async function models(kind, adapter, known) {
28
72
  const modes = mode === undefined ? [] : choices(mode.options).map(({ value, name }) => ({ mode: value, name }));
29
73
  const model = select(options, 'model');
30
74
  if (model === undefined)
31
- return { models: [], modes };
75
+ return { models: [], ...UNNAMED, modes };
76
+ const started = starting(model, select(options, 'thought_level'));
32
77
  const offered = [];
33
- for (const value of values(model.options)) {
78
+ for (const { value, name } of named(model.options)) {
34
79
  if (select(options, 'model')?.currentValue !== value) {
35
80
  try {
36
81
  options = (await agent.request('session/set_config_option', { sessionId: opened.sessionId, configId: model.id, value })).configOptions;
37
82
  }
38
83
  catch (error) {
39
84
  process.stderr.write(`kit: ${kind} refused its model ${value}: ${causeOf(error)}\n`);
40
- offered.push({ model: value, efforts: known.find((entry) => entry.model === value)?.efforts ?? [] });
85
+ offered.push({ model: value, name, efforts: known.find((entry) => entry.model === value)?.efforts ?? [] });
41
86
  continue;
42
87
  }
43
88
  }
44
- const effort = select(options, 'thought_level');
45
- offered.push({ model: value, efforts: effort === undefined ? [] : values(effort.options) });
89
+ offered.push({ model: value, name, efforts: effortsOf(select(options, 'thought_level')) });
46
90
  }
47
- return { models: offered, modes };
91
+ return { models: offered, ...started, modes };
48
92
  }
49
- async function signedIn(kind, cli, known) {
50
- const probe = CLIS[kind].signedIn;
51
- if ('command' in probe)
52
- return (await run(cli, probe.command, 30_000)).status === 0;
53
- return (await offer(kind, cli, known)).signed_in;
93
+ function ended(signal) {
94
+ return new Promise((_, reject) => {
95
+ if (signal.aborted)
96
+ reject(signal.reason);
97
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });
98
+ });
54
99
  }
55
- async function offer(kind, cli, known) {
56
- const probe = CLIS[kind].signedIn;
57
- if ('command' in probe && (await run(cli, probe.command, 30_000)).status !== 0)
58
- return SIGNED_OUT;
100
+ function keyedOf({ api_key, provider }) {
101
+ return { ...(api_key === undefined ? {} : { api_key }), ...(provider === undefined ? {} : { provider }) };
102
+ }
103
+ async function offer(kind, cli, known, signal) {
104
+ const { signedIn: probe, key } = CLIS[kind];
105
+ const keyed = await key.read();
106
+ // A sign-in check that has not answered in half a minute counts as signed out rather than stalling the report.
107
+ if ('command' in probe && !keyed.api_key && (await run(cli, probe.command, 30_000, false, signal, await cliEnvironment(kind))).status !== 0) {
108
+ return { ...SIGNED_OUT, ...keyed };
109
+ }
59
110
  let adapter;
60
111
  try {
61
- adapter = await startAdapter(kind, cli, kitHome(), client({ name: '@agentshouse/kit' }));
112
+ adapter = await startAdapter(kind, cli, kitHome(), client({ name: '@agentshouse/kit' }), () => undefined, {}, signal);
113
+ signal?.throwIfAborted();
62
114
  if ('initializeMeta' in probe) {
63
115
  const method = adapter.initialized._meta?.[probe.initializeMeta];
64
116
  if (typeof method !== 'string' || method.length === 0)
65
- return SIGNED_OUT;
117
+ return { ...SIGNED_OUT, ...keyed };
118
+ if (method === probe.apiKey)
119
+ keyed.api_key = true;
66
120
  }
67
- return { signed_in: true, ...(await models(kind, adapter, known.models)) };
121
+ return { signed_in: true, ...keyed, ...(await models(kind, adapter, known.models)) };
68
122
  }
69
123
  catch (error) {
70
- process.stderr.write(`kit: ${kind} did not offer its models: ${causeOf(error)}\n`);
124
+ if (!signal?.aborted)
125
+ process.stderr.write(`kit: ${kind} did not offer its models: ${causeOf(error)}\n`);
126
+ if (signedOut(error))
127
+ return { ...SIGNED_OUT, ...keyed };
128
+ const unread = adapter === undefined && 'initializeMeta' in probe;
71
129
  return {
72
- signed_in: adapter === undefined && 'initializeMeta' in probe ? known.signed_in : true,
130
+ signed_in: unread ? known.signed_in : true,
131
+ ...keyedOf({ api_key: unread ? known.api_key : keyed.api_key, provider: keyed.provider }),
73
132
  models: known.models,
133
+ default_model: known.default_model,
134
+ default_effort: known.default_effort,
74
135
  modes: known.modes,
75
136
  };
76
137
  }
77
138
  finally {
78
- if (adapter !== undefined)
79
- killTree(adapter.child);
139
+ adapter?.retire();
80
140
  }
81
141
  }
82
142
  function reported(kind, reading) {
143
+ const { minimum, update } = CLIS[kind];
83
144
  return {
84
145
  kind,
85
146
  release: reading.release,
86
- ...(reading.minimum === undefined ? {} : { minimum: reading.minimum }),
147
+ ...(reading.release !== null && below(reading.release, minimum) ? { minimum, update } : {}),
87
148
  failure: reading.failure,
149
+ ...(reading.installing === undefined ? {} : { installing: reading.installing }),
88
150
  signed_in: reading.signed_in,
151
+ ...keyedOf(reading),
89
152
  models: reading.models,
90
153
  modes: reading.modes,
91
154
  full_access: CLIS[kind].fullAccess,
155
+ ...(reading.default_model === null ? {} : { default_model: reading.default_model }),
156
+ ...(reading.default_effort === null ? {} : { default_effort: reading.default_effort }),
92
157
  };
93
158
  }
94
- function tooOld(kind, release) {
95
- const cli = CLIS[kind];
96
- return `${cli.bin} ${release} is older than ${cli.minimum}, the oldest this Kit runs`;
97
- }
159
+ const NOT_READY = "the Agent's CLI is not ready on this computer";
98
160
  async function sshHostKey() {
161
+ // Listing a local host key takes a moment, so ten seconds only bounds a stuck ssh-keygen.
99
162
  const listed = await run('ssh-keygen', ['-l', '-E', 'sha256', '-f', '/etc/ssh/ssh_host_ed25519_key.pub'], 10_000);
100
163
  return listed.status === 0 ? (/^\d+ (SHA256:\S+)/.exec(listed.output)?.[1] ?? null) : null;
101
164
  }
102
165
  async function operatingSystem() {
166
+ // sw_vers answers at once, so ten seconds only bounds a stuck call.
103
167
  if (process.platform === 'darwin')
104
168
  return `macOS ${(await run('sw_vers', ['-productVersion'], 10_000)).output.trim()}`;
105
169
  const release = await readFile('/etc/os-release', 'utf8');
106
170
  return /^PRETTY_NAME="?([^"\n]*)"?$/m.exec(release)?.[1] ?? release;
107
171
  }
172
+ async function hostForm() {
173
+ if (process.platform === 'darwin') {
174
+ const battery = await run('pmset', ['-g', 'batt'], 10_000);
175
+ return battery.status === 0 && battery.output.includes('InternalBattery') ? 'laptop' : 'desktop';
176
+ }
177
+ if (process.platform !== 'linux')
178
+ return undefined;
179
+ const [container, version, chassis] = await Promise.all([
180
+ readFile('/.dockerenv', 'utf8').then(() => true).catch(() => false),
181
+ readFile('/proc/version', 'utf8').catch(() => ''),
182
+ readFile('/sys/class/dmi/id/chassis_type', 'utf8').catch(() => ''),
183
+ ]);
184
+ if (container && hostVm(version))
185
+ return undefined;
186
+ return chassisForm(chassis);
187
+ }
108
188
  export class Agents {
109
- desired = { agents: [], routes: [] };
189
+ desired = { agents: [], routes: [], transcribe: false };
110
190
  house;
111
191
  reading = Promise.resolve();
112
192
  queues = new Map();
113
193
  installing = Promise.resolve();
194
+ installs = new Map();
114
195
  readings = new Map();
115
196
  reads = new Map();
197
+ starts = 0;
116
198
  sending = Promise.resolve();
117
199
  sent = null;
118
- constructor(house) {
200
+ refreshing = 0;
201
+ loaded = Promise.resolve();
202
+ updating = null;
203
+ changed;
204
+ constructor(house, changed = () => undefined) {
119
205
  this.house = house;
206
+ this.changed = changed;
207
+ }
208
+ idle() {
209
+ return this.refreshing === 0 && this.updating === null;
120
210
  }
121
211
  read() {
122
212
  return this.reading.then(() => undefined, () => undefined);
@@ -125,52 +215,89 @@ export class Agents {
125
215
  return this.desired.routes.find((route) => route.agent_id === agentId);
126
216
  }
127
217
  refresh() {
218
+ this.refreshing++;
219
+ this.changed();
128
220
  const reading = this.read().then(async () => {
129
- this.desired = await this.house.deliver('/kit/agents/desired', {});
221
+ this.desired = await this.house.deliver('agents/desired/list', {});
130
222
  return this.desired;
131
223
  });
132
224
  this.reading = reading;
133
- return reading.then(({ agents }) => {
225
+ this.loaded = reading
226
+ .then(({ agents, transcribe }) => Promise.all([
227
+ holdTranscription(transcribe)
228
+ .then((changed) => (changed ? this.report() : undefined))
229
+ .catch(logged),
134
230
  Promise.all(agents.map((kind) => this.load(kind)))
135
231
  .then(() => this.report())
136
- .catch(logged);
232
+ .catch(logged),
233
+ ]))
234
+ .catch(() => undefined)
235
+ .finally(() => {
236
+ this.refreshing--;
237
+ this.changed();
137
238
  });
239
+ return reading.then(() => undefined);
240
+ }
241
+ keepCurrent(stopping) {
242
+ this.updateAll(this.loaded);
243
+ setInterval(() => {
244
+ if (!stopping())
245
+ this.updateAll(Promise.resolve());
246
+ }, CLI_UPDATE_MS);
138
247
  }
139
248
  cli(kind) {
249
+ this.starts += 1;
140
250
  return this.queue(kind, async () => {
141
251
  const resolved = await this.resolve(kind);
142
252
  if (!('cli' in resolved)) {
143
253
  this.update(kind, resolved);
144
- throw new Error(resolved.failure ?? tooOld(kind, resolved.release));
254
+ throw new Error(NOT_READY);
145
255
  }
146
256
  const { cli, release } = resolved;
147
257
  const known = this.readings.get(kind);
148
- const kept = known?.release === null || known?.minimum !== undefined ? SIGNED_OUT : (known ?? SIGNED_OUT);
149
- if (known?.release !== release || known.minimum !== undefined) {
150
- this.update(kind, { release, failure: null, signed_in: kept.signed_in, models: kept.models, modes: kept.modes });
258
+ const kept = known?.release === null ? SIGNED_OUT : (known ?? SIGNED_OUT);
259
+ if (known?.release !== release || this.installs.has(kind)) {
260
+ this.update(kind, {
261
+ release,
262
+ failure: null,
263
+ signed_in: kept.signed_in,
264
+ ...keyedOf(kept),
265
+ models: kept.models,
266
+ default_model: kept.default_model,
267
+ default_effort: kept.default_effort,
268
+ modes: kept.modes,
269
+ });
151
270
  }
152
271
  const read = this.nextRead(kind);
153
- offer(kind, cli, kept)
272
+ this.quietOffer(kind, cli, kept)
154
273
  .then((offered) => {
155
274
  const current = this.readings.get(kind);
156
275
  if (this.reads.get(kind) === read && current?.release === release)
157
- this.update(kind, { ...current, ...offered });
276
+ this.update(kind, { release, failure: current.failure, ...offered });
158
277
  })
159
278
  .catch(logged);
160
279
  return cli;
161
280
  });
162
281
  }
163
- located(kind) {
164
- return this.queue(kind, () => this.ensure(kind));
282
+ located(kind, signal) {
283
+ const owner = {};
284
+ return this.queue(kind, () => this.ensure(kind, signal, owner).finally(() => this.settle(kind, owner)), signal);
165
285
  }
166
286
  async reread(kind) {
167
287
  await this.examine(kind, this.readings.get(kind) ?? SIGNED_OUT, offer);
168
288
  await this.report();
169
289
  }
170
- async recheck(kind) {
290
+ async recheck(kind, signal) {
171
291
  const known = this.readings.get(kind) ?? SIGNED_OUT;
172
- await this.examine(kind, known, async (kind, cli) => (await signedIn(kind, cli, known)) ? { ...known, signed_in: true } : SIGNED_OUT);
173
- await this.report();
292
+ const owner = {};
293
+ try {
294
+ await this.examine(kind, known, (kind, cli) => offer(kind, cli, known, AbortSignal.any([signal, AbortSignal.timeout(SIGNED_IN_READ_MS)])), signal, owner);
295
+ }
296
+ finally {
297
+ this.settle(kind, owner);
298
+ }
299
+ if (!signal.aborted)
300
+ await this.report();
174
301
  }
175
302
  report() {
176
303
  const sending = this.sending.catch(() => undefined).then(() => this.send());
@@ -182,80 +309,132 @@ export class Agents {
182
309
  this.reads.set(kind, read);
183
310
  return read;
184
311
  }
185
- update(kind, reading) {
312
+ hold(kind, reading) {
186
313
  this.readings.set(kind, reading);
314
+ this.installs.delete(kind);
315
+ }
316
+ update(kind, reading) {
317
+ this.hold(kind, reading);
187
318
  this.report().catch(logged);
188
319
  }
189
- queue(kind, work) {
190
- const queued = (this.queues.get(kind) ?? Promise.resolve()).then(work);
320
+ settle(kind, owner) {
321
+ if (this.installs.get(kind) !== owner)
322
+ return;
323
+ this.installs.delete(kind);
324
+ this.report().catch(logged);
325
+ }
326
+ queue(kind, work, signal) {
327
+ const queued = (this.queues.get(kind) ?? Promise.resolve()).then(() => {
328
+ signal?.throwIfAborted();
329
+ return work();
330
+ });
191
331
  this.queues.set(kind, queued.catch(() => undefined));
192
- return queued;
332
+ return signal === undefined ? queued : Promise.race([queued, ended(signal)]);
193
333
  }
194
- async ensure(kind) {
195
- const failed = await installAdapter(kind);
196
- if (failed !== null)
197
- throw new Error(failed);
198
- const found = await locate(kind);
334
+ async ensure(kind, signal, owner = {}) {
335
+ const found = await locate(kind, signal);
199
336
  if (found !== null)
200
337
  return found;
201
- const installing = this.installing.catch(() => undefined).then(() => installCli(kind));
338
+ this.installs.set(kind, owner);
339
+ this.report().catch(logged);
340
+ const installing = this.installing.catch(() => undefined).then(() => installCli(kind, signal));
202
341
  this.installing = installing;
203
342
  const failure = await installing;
204
343
  if (failure !== null)
205
344
  throw new Error(failure);
206
- const installed = await locate(kind);
345
+ const installed = await locate(kind, signal);
207
346
  if (installed === null)
208
347
  throw new Error(`the login shell does not find ${CLIS[kind].bin} after its install`);
209
348
  return installed;
210
349
  }
211
- async resolve(kind) {
350
+ async resolve(kind, signal, owner) {
212
351
  let cli;
213
352
  try {
214
- cli = await realpath(await this.ensure(kind));
353
+ cli = await this.ensure(kind, signal, owner);
215
354
  }
216
355
  catch (error) {
217
356
  const failure = causeOf(error);
218
357
  process.stderr.write(`kit: ${kind} did not install: ${failure}\n`);
219
358
  return { release: null, failure, ...SIGNED_OUT };
220
359
  }
221
- const release = await versionOf(cli);
360
+ const release = await versionOf(kind, cli, signal);
222
361
  if (release === null)
223
362
  return { release: null, failure: `${cli} --version names no version`, ...SIGNED_OUT };
224
- const minimum = CLIS[kind].minimum;
225
- if (below(release, minimum))
226
- return { release, minimum, failure: null, ...SIGNED_OUT };
227
363
  return { cli, release };
228
364
  }
229
- async examine(kind, known, read) {
365
+ async examine(kind, known, read, signal, owner) {
230
366
  const current = this.nextRead(kind);
231
- const resolved = await this.queue(kind, () => this.resolve(kind));
367
+ const resolved = await this.queue(kind, () => this.resolve(kind, signal, owner), signal);
232
368
  const reading = 'cli' in resolved ? { release: resolved.release, failure: null, ...(await read(kind, resolved.cli, known)) } : resolved;
233
- if (this.reads.get(kind) === current)
234
- this.readings.set(kind, reading);
369
+ if (this.reads.get(kind) === current && !signal?.aborted)
370
+ this.hold(kind, reading);
371
+ }
372
+ updateAll(after) {
373
+ if (this.updating !== null)
374
+ return;
375
+ this.updating = after
376
+ .then(async () => {
377
+ for (const kind of this.desired.agents) {
378
+ if (this.installs.has(kind) || !this.readings.get(kind)?.release)
379
+ continue;
380
+ const failure = await updateCli(kind);
381
+ if (failure !== null)
382
+ process.stderr.write(`kit: ${kind} did not update: ${failure}\n`);
383
+ await this.readVersion(kind);
384
+ }
385
+ })
386
+ .catch(logged)
387
+ .finally(() => {
388
+ this.updating = null;
389
+ this.changed();
390
+ });
391
+ this.changed();
392
+ }
393
+ async readVersion(kind) {
394
+ const cli = await locate(kind);
395
+ const release = cli === null ? null : await versionOf(kind, cli);
396
+ const current = this.readings.get(kind);
397
+ if (release === null || !current?.release || current.release === release)
398
+ return;
399
+ this.update(kind, { ...current, release });
400
+ }
401
+ async quietOffer(kind, cli, known) {
402
+ for (let seen = -1; seen !== this.starts;) {
403
+ seen = this.starts;
404
+ await delay(MODEL_PROBE_QUIET_MS);
405
+ }
406
+ return offer(kind, cli, known);
235
407
  }
236
408
  async load(kind) {
237
409
  const known = this.readings.get(kind);
238
410
  if (known !== undefined && known.failure === null)
239
411
  return;
240
- await this.examine(kind, SIGNED_OUT, offer);
412
+ await this.examine(kind, SIGNED_OUT, (kind, cli, known) => this.quietOffer(kind, cli, known));
413
+ await this.report();
241
414
  }
242
415
  async send() {
243
416
  const agents = this.desired.agents.flatMap((kind) => {
244
- const reading = this.readings.get(kind);
417
+ const reading = this.installs.has(kind) ? INSTALLING : this.readings.get(kind);
245
418
  return reading === undefined ? [] : [reported(kind, reading)];
246
419
  });
247
420
  const hostKey = await sshHostKey();
421
+ const form = await hostForm();
248
422
  const body = {
249
423
  os: await operatingSystem(),
250
- kit_version: KIT_VERSION,
424
+ ...(form === undefined ? {} : { form }),
425
+ kit_release: KIT_RELEASE,
426
+ wire: KIT_WIRE,
251
427
  agent_base: agentBase(),
428
+ ...(reinstall() === undefined ? {} : { reinstall: reinstall() }),
429
+ settings: await heldSettings(),
252
430
  agents,
431
+ transcription: transcriptionReport(),
253
432
  ...(hostKey === null ? {} : { ssh_host_key: hostKey }),
254
433
  };
255
434
  const state = JSON.stringify(body);
256
435
  if (state === this.sent)
257
436
  return;
258
- await this.house.deliver('/kit/agents/report', body);
437
+ await this.house.deliver('agents/report', body);
259
438
  this.sent = state;
260
439
  }
261
440
  }
package/dist/api.js CHANGED
@@ -1,5 +1,10 @@
1
+ import { KIT_WIRE, KIT_WIRE_HEADER, } from '@agentshouse/kit-wire';
2
+ import { setTimeout as delay } from 'node:timers/promises';
3
+ import { signInAgain } from './end.js';
1
4
  import { readEnrolment } from './home.js';
5
+ import { retryable } from './refusals.js';
2
6
  import { relayed } from './relay.js';
7
+ import { endUnserved } from './wire.js';
3
8
  export class HouseRefusal extends Error {
4
9
  status;
5
10
  text;
@@ -9,39 +14,71 @@ export class HouseRefusal extends Error {
9
14
  this.text = text;
10
15
  }
11
16
  }
17
+ export function finalRefusal(error) {
18
+ return error instanceof HouseRefusal && retryable(error.text) === false;
19
+ }
12
20
  export function retryDelay(attempt) {
21
+ // Full jitter, doubling from one second to a 30-second cap, spreads the Kit processes one outage dropped and retries within half a minute of House's return.
13
22
  return Math.random() * Math.min(30_000, 1000 * 2 ** attempt);
14
23
  }
24
+ export async function retrying(sent, signal, pause = retryDelay) {
25
+ for (let attempt = 0;; attempt++) {
26
+ try {
27
+ return await sent();
28
+ }
29
+ catch (error) {
30
+ if (!(error instanceof HouseRefusal) || retryable(error.text) !== true)
31
+ throw error;
32
+ }
33
+ // A request House refused as retryable is sent again after the caller's pause, the jittered curve unless it names its own.
34
+ await delay(pause(attempt), undefined, { signal });
35
+ }
36
+ }
15
37
  export async function post(house, path, body, credential, signal) {
16
38
  const answer = await fetch(relayed(new URL(path, house)), {
17
39
  method: 'POST',
18
40
  headers: {
19
41
  'content-type': 'application/json',
42
+ [KIT_WIRE_HEADER]: KIT_WIRE,
20
43
  ...(credential === undefined ? {} : { authorization: `Bearer ${credential}` }),
21
44
  },
22
45
  body: JSON.stringify(body),
23
46
  signal,
24
47
  });
25
48
  const text = await answer.text();
49
+ if (!answer.ok)
50
+ endUnserved(text);
26
51
  if (!answer.ok)
27
52
  throw new HouseRefusal(path, answer.status, text);
28
53
  return JSON.parse(text);
29
54
  }
55
+ export function kitAct(house, act, request, credential, signal) {
56
+ return post(house, `/kit/${act}`, request, credential, signal);
57
+ }
30
58
  async function enrolledPost(path, body, signal) {
31
59
  const { house, credential } = (await readEnrolment());
32
- return post(house, path, body, credential, signal);
60
+ try {
61
+ return await post(house, path, body, credential, signal);
62
+ }
63
+ catch (error) {
64
+ if (error instanceof HouseRefusal && error.status === 401)
65
+ await signInAgain(credential);
66
+ throw error;
67
+ }
33
68
  }
34
69
  export const house = {
35
- post: enrolledPost,
36
- deliver: async (path, body, current = () => true) => {
70
+ act: (act, request, signal) => enrolledPost(`/kit/${act}`, request, signal),
71
+ door: (act, body, signal) => enrolledPost(`/kit/door/${act}`, body, signal),
72
+ deliver: async (act, request, current = () => true) => {
37
73
  for (let attempt = 0;; attempt++) {
38
74
  try {
39
- return await enrolledPost(path, body);
75
+ return await enrolledPost(`/kit/${act}`, request);
40
76
  }
41
77
  catch (error) {
42
- if (error instanceof HouseRefusal && error.status < 500)
78
+ if (finalRefusal(error))
43
79
  throw error;
44
- process.stderr.write(`kit: ${path} did not reach House: ${error.message}\n`);
80
+ process.stderr.write(`kit: /kit/${act} did not reach House: ${error.message}\n`);
81
+ // A delivery House did not take is sent again on the jittered curve for as long as it is still current.
45
82
  await new Promise((resolve) => setTimeout(resolve, retryDelay(attempt)));
46
83
  if (!current())
47
84
  throw error;
@@ -0,0 +1,48 @@
1
+ import { run } from './git.js';
2
+ import { kitHome, readOwnAgent } from './home.js';
3
+ const HELPER = '!kit git-credential';
4
+ function section(house) {
5
+ return `credential.${new URL('/app/', house).href}`;
6
+ }
7
+ async function configured(args) {
8
+ try {
9
+ return await run(kitHome(), ['config', '--global', ...args]);
10
+ }
11
+ catch (error) {
12
+ if (error.code === 'ENOENT')
13
+ return null;
14
+ throw error;
15
+ }
16
+ }
17
+ export async function placeAppGit(ownAgent) {
18
+ if (ownAgent === null)
19
+ return;
20
+ await configured(['--remove-section', section(ownAgent.house)]);
21
+ for (const value of ['', HELPER]) {
22
+ const ran = await configured(['--add', `${section(ownAgent.house)}.helper`, value]);
23
+ if (ran === null)
24
+ return;
25
+ if (ran.status !== 0)
26
+ throw new Error(`git config failed: ${ran.stderr.trim()}`);
27
+ }
28
+ }
29
+ export async function answerGitCredential(operation) {
30
+ let asked = '';
31
+ for await (const chunk of process.stdin)
32
+ asked += String(chunk);
33
+ if (operation !== 'get')
34
+ return;
35
+ const attributes = new Map(asked
36
+ .split('\n')
37
+ .filter((line) => line.includes('='))
38
+ .map((line) => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]));
39
+ const ownAgent = await readOwnAgent();
40
+ if (ownAgent === null) {
41
+ process.stderr.write(`kit: Kit home ${kitHome()} is not signed in; run kit login\n`);
42
+ return;
43
+ }
44
+ const house = new URL(ownAgent.house);
45
+ if (attributes.get('protocol') !== house.protocol.slice(0, -1) || attributes.get('host') !== house.host)
46
+ return;
47
+ process.stdout.write(`username=house\npassword=${ownAgent.credential}\n`);
48
+ }