@agentshouse/kit 0.2.1-cd9cbd8b6428c → 0.2.1-cdc381ebf021f

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