@agentshouse/kit 0.2.1-cd9cbd8b6428c → 0.2.1-cdc3937dea52e

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 (145) 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 +271 -73
  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 +179 -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 +451 -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-main.js +24 -29
  23. package/dist/git.js +57 -21
  24. package/dist/grok.js +39 -0
  25. package/dist/home.js +134 -9
  26. package/dist/house-cli.js +362 -0
  27. package/dist/house-main.js +7 -159
  28. package/dist/instructions.js +7 -11
  29. package/dist/keys.js +238 -0
  30. package/dist/kit-cli.js +78 -0
  31. package/dist/kit-main.js +8 -19
  32. package/dist/login.js +133 -104
  33. package/dist/logout.js +15 -14
  34. package/dist/mcp.js +6 -2
  35. package/dist/owner.js +46 -0
  36. package/dist/placement.js +25 -0
  37. package/dist/refusals.js +12 -0
  38. package/dist/relay.js +33 -2
  39. package/dist/resident.js +161 -61
  40. package/dist/scope.js +214 -0
  41. package/dist/scripts.js +303 -0
  42. package/dist/secret-input.js +5 -2
  43. package/dist/settings.js +188 -0
  44. package/dist/shell.js +3 -0
  45. package/dist/sign-in.js +85 -32
  46. package/dist/silence.js +28 -0
  47. package/dist/skills.js +49 -35
  48. package/dist/supervisor.js +163 -0
  49. package/dist/transcription.js +131 -40
  50. package/dist/translate.js +19 -16
  51. package/dist/update.js +119 -100
  52. package/dist/wire.js +32 -0
  53. package/dist/work.js +353 -0
  54. package/dist/workspace.js +103 -0
  55. package/package.json +26 -21
  56. package/dist/authority-main.js +0 -22
  57. package/dist/blocks.js +0 -51
  58. package/dist/bootstrap.json +0 -24
  59. package/dist/clis-main.js +0 -23
  60. package/dist/configure-main.js +0 -6
  61. package/dist/enrol-main.js +0 -4
  62. package/dist/stream.js +0 -47
  63. package/how-we-work.md +0 -23
  64. package/skills/ask-matt/LICENSE +0 -21
  65. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  66. package/skills/ask-matt/SKILL.md +0 -91
  67. package/skills/ask-matt/agents/openai.yaml +0 -4
  68. package/skills/code-review/LICENSE +0 -21
  69. package/skills/code-review/SKILL.md +0 -89
  70. package/skills/code-review/agents/openai.yaml +0 -3
  71. package/skills/codebase-design/DEEPENING.md +0 -37
  72. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  73. package/skills/codebase-design/LICENSE +0 -21
  74. package/skills/codebase-design/SKILL.md +0 -116
  75. package/skills/codebase-design/agents/openai.yaml +0 -3
  76. package/skills/diagnosing-bugs/LICENSE +0 -21
  77. package/skills/diagnosing-bugs/SKILL.md +0 -140
  78. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  79. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  80. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  81. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  82. package/skills/domain-modeling/LICENSE +0 -21
  83. package/skills/domain-modeling/SKILL.md +0 -76
  84. package/skills/domain-modeling/agents/openai.yaml +0 -3
  85. package/skills/grill-me/LICENSE +0 -21
  86. package/skills/grill-me/SKILL.md +0 -8
  87. package/skills/grill-me/agents/openai.yaml +0 -4
  88. package/skills/grill-with-docs/LICENSE +0 -21
  89. package/skills/grill-with-docs/SKILL.md +0 -8
  90. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  91. package/skills/grilling/LICENSE +0 -21
  92. package/skills/grilling/SKILL.md +0 -30
  93. package/skills/grilling/agents/openai.yaml +0 -3
  94. package/skills/handoff/LICENSE +0 -21
  95. package/skills/handoff/SKILL.md +0 -17
  96. package/skills/handoff/agents/openai.yaml +0 -4
  97. package/skills/implement/LICENSE +0 -21
  98. package/skills/implement/SKILL.md +0 -16
  99. package/skills/implement/agents/openai.yaml +0 -4
  100. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  101. package/skills/improve-codebase-architecture/LICENSE +0 -21
  102. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  103. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  104. package/skills/prototype/LICENSE +0 -21
  105. package/skills/prototype/LOGIC.md +0 -67
  106. package/skills/prototype/SKILL.md +0 -28
  107. package/skills/prototype/UI.md +0 -112
  108. package/skills/prototype/agents/openai.yaml +0 -3
  109. package/skills/research/LICENSE +0 -21
  110. package/skills/research/SKILL.md +0 -14
  111. package/skills/research/agents/openai.yaml +0 -3
  112. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  113. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  114. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  115. package/skills/tdd/LICENSE +0 -21
  116. package/skills/tdd/SKILL.md +0 -40
  117. package/skills/tdd/agents/openai.yaml +0 -3
  118. package/skills/tdd/mocking.md +0 -59
  119. package/skills/tdd/tests.md +0 -77
  120. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  121. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  122. package/skills/teach/LICENSE +0 -21
  123. package/skills/teach/MISSION-FORMAT.md +0 -31
  124. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  125. package/skills/teach/SKILL.md +0 -141
  126. package/skills/teach/agents/openai.yaml +0 -4
  127. package/skills/to-questionnaire/LICENSE +0 -21
  128. package/skills/to-questionnaire/SKILL.md +0 -55
  129. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  130. package/skills/to-spec/LICENSE +0 -21
  131. package/skills/to-spec/SKILL.md +0 -76
  132. package/skills/to-spec/agents/openai.yaml +0 -4
  133. package/skills/to-tickets/LICENSE +0 -21
  134. package/skills/to-tickets/SKILL.md +0 -106
  135. package/skills/to-tickets/agents/openai.yaml +0 -4
  136. package/skills/wait-what/LICENSE +0 -21
  137. package/skills/wait-what/SKILL.md +0 -8
  138. package/skills/wait-what/agents/openai.yaml +0 -4
  139. package/skills/wayfinder/LICENSE +0 -21
  140. package/skills/wayfinder/SKILL.md +0 -129
  141. package/skills/wayfinder/agents/openai.yaml +0 -4
  142. package/skills/writing-for-agents/LICENSE +0 -21
  143. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  144. package/skills/writing-for-agents/SKILL.md +0 -83
  145. 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, 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;
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,165 @@ 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 };
92
+ }
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
+ function keyedOf({ api_key, provider }) {
101
+ return { ...(api_key === undefined ? {} : { api_key }), ...(provider === undefined ? {} : { provider }) };
43
102
  }
44
- async function offer(kind, cli, known) {
45
- const probe = CLIS[kind].signedIn;
46
- if ('command' in probe && (await run(cli, probe.command, 30_000)).status !== 0)
47
- return SIGNED_OUT;
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
+ }
48
110
  let adapter;
49
111
  try {
50
- 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();
51
114
  if ('initializeMeta' in probe) {
52
115
  const method = adapter.initialized._meta?.[probe.initializeMeta];
53
116
  if (typeof method !== 'string' || method.length === 0)
54
- return SIGNED_OUT;
117
+ return { ...SIGNED_OUT, ...keyed };
118
+ if (method === probe.apiKey)
119
+ keyed.api_key = true;
55
120
  }
56
- return { signed_in: true, models: await models(kind, adapter, known.models) };
121
+ return { signed_in: true, ...keyed, ...(await models(kind, adapter, known.models)) };
57
122
  }
58
123
  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 };
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;
129
+ return {
130
+ signed_in: unread ? known.signed_in : true,
131
+ ...keyedOf({ api_key: unread ? known.api_key : keyed.api_key, provider: keyed.provider }),
132
+ models: known.models,
133
+ default_model: known.default_model,
134
+ default_effort: known.default_effort,
135
+ modes: known.modes,
136
+ };
61
137
  }
62
138
  finally {
63
- if (adapter !== undefined)
64
- killTree(adapter.child);
139
+ adapter?.retire();
65
140
  }
66
141
  }
67
142
  function reported(kind, reading) {
143
+ const { minimum, update } = CLIS[kind];
68
144
  return {
69
145
  kind,
70
146
  release: reading.release,
71
- ...(reading.minimum === undefined ? {} : { minimum: reading.minimum }),
147
+ ...(reading.release !== null && below(reading.release, minimum) ? { minimum, update } : {}),
72
148
  failure: reading.failure,
149
+ ...(reading.installing === undefined ? {} : { installing: reading.installing }),
73
150
  signed_in: reading.signed_in,
151
+ ...keyedOf(reading),
74
152
  models: reading.models,
153
+ modes: reading.modes,
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 }),
75
157
  };
76
158
  }
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
- }
159
+ const NOT_READY = "the Agent's CLI is not ready on this computer";
81
160
  async function sshHostKey() {
161
+ // Listing a local host key takes a moment, so ten seconds only bounds a stuck ssh-keygen.
82
162
  const listed = await run('ssh-keygen', ['-l', '-E', 'sha256', '-f', '/etc/ssh/ssh_host_ed25519_key.pub'], 10_000);
83
163
  return listed.status === 0 ? (/^\d+ (SHA256:\S+)/.exec(listed.output)?.[1] ?? null) : null;
84
164
  }
85
165
  async function operatingSystem() {
166
+ // sw_vers answers at once, so ten seconds only bounds a stuck call.
86
167
  if (process.platform === 'darwin')
87
168
  return `macOS ${(await run('sw_vers', ['-productVersion'], 10_000)).output.trim()}`;
88
169
  const release = await readFile('/etc/os-release', 'utf8');
89
170
  return /^PRETTY_NAME="?([^"\n]*)"?$/m.exec(release)?.[1] ?? release;
90
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
+ }
91
188
  export class Agents {
92
- desired = { agents: [], routes: [] };
189
+ desired = { agents: [], routes: [], transcribe: false };
93
190
  house;
94
191
  reading = Promise.resolve();
95
192
  queues = new Map();
96
193
  installing = Promise.resolve();
194
+ installs = new Map();
97
195
  readings = new Map();
98
196
  reads = new Map();
197
+ starts = 0;
99
198
  sending = Promise.resolve();
100
199
  sent = null;
101
- constructor(house) {
200
+ refreshing = 0;
201
+ loaded = Promise.resolve();
202
+ updating = null;
203
+ changed;
204
+ constructor(house, changed = () => undefined) {
102
205
  this.house = house;
206
+ this.changed = changed;
207
+ }
208
+ idle() {
209
+ return this.refreshing === 0 && this.updating === null;
103
210
  }
104
211
  read() {
105
212
  return this.reading.then(() => undefined, () => undefined);
@@ -108,51 +215,90 @@ export class Agents {
108
215
  return this.desired.routes.find((route) => route.agent_id === agentId);
109
216
  }
110
217
  refresh() {
218
+ this.refreshing++;
219
+ this.changed();
111
220
  const reading = this.read().then(async () => {
112
- this.desired = await this.house.deliver('/kit/agents/desired', {});
221
+ this.desired = await this.house.deliver('agents/desired/list', {});
113
222
  return this.desired;
114
223
  });
115
224
  this.reading = reading;
116
- return reading.then(({ agents }) => {
117
- Promise.all(agents.map((kind) => this.queue(kind, () => this.load(kind))))
225
+ this.loaded = reading
226
+ .then(({ agents, transcribe }) => Promise.all([
227
+ holdTranscription(transcribe)
228
+ .then((changed) => (changed ? this.report() : undefined))
229
+ .catch(logged),
230
+ Promise.all(agents.map((kind) => this.load(kind)))
118
231
  .then(() => this.report())
119
- .catch(logged);
232
+ .catch(logged),
233
+ ]))
234
+ .catch(() => undefined)
235
+ .finally(() => {
236
+ this.refreshing--;
237
+ this.changed();
120
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);
121
247
  }
122
248
  cli(kind) {
249
+ this.starts += 1;
123
250
  return this.queue(kind, async () => {
124
251
  const resolved = await this.resolve(kind);
125
252
  if (!('cli' in resolved)) {
126
253
  this.update(kind, resolved);
127
- throw new Error(resolved.failure ?? tooOld(kind, resolved.release));
254
+ throw new Error(NOT_READY);
128
255
  }
129
256
  const { cli, release } = resolved;
130
257
  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 });
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
+ });
134
270
  }
135
271
  const read = this.nextRead(kind);
136
- offer(kind, cli, kept)
272
+ this.quietOffer(kind, cli, kept)
137
273
  .then((offered) => {
138
274
  const current = this.readings.get(kind);
139
275
  if (this.reads.get(kind) === read && current?.release === release)
140
- this.update(kind, { ...current, ...offered });
276
+ this.update(kind, { release, failure: current.failure, ...offered });
141
277
  })
142
278
  .catch(logged);
143
279
  return cli;
144
280
  });
145
281
  }
146
- located(kind) {
147
- 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);
148
285
  }
149
286
  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
- });
287
+ await this.examine(kind, this.readings.get(kind) ?? SIGNED_OUT, offer);
154
288
  await this.report();
155
289
  }
290
+ async recheck(kind, signal) {
291
+ const known = this.readings.get(kind) ?? SIGNED_OUT;
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();
301
+ }
156
302
  report() {
157
303
  const sending = this.sending.catch(() => undefined).then(() => this.send());
158
304
  this.sending = sending;
@@ -163,80 +309,132 @@ export class Agents {
163
309
  this.reads.set(kind, read);
164
310
  return read;
165
311
  }
166
- update(kind, reading) {
312
+ hold(kind, reading) {
167
313
  this.readings.set(kind, reading);
314
+ this.installs.delete(kind);
315
+ }
316
+ update(kind, reading) {
317
+ this.hold(kind, reading);
168
318
  this.report().catch(logged);
169
319
  }
170
- queue(kind, work) {
171
- 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
+ });
172
331
  this.queues.set(kind, queued.catch(() => undefined));
173
- return queued;
332
+ return signal === undefined ? queued : Promise.race([queued, ended(signal)]);
174
333
  }
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);
334
+ async ensure(kind, signal, owner = {}) {
335
+ const found = await locate(kind, signal);
180
336
  if (found !== null)
181
337
  return found;
182
- 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));
183
341
  this.installing = installing;
184
342
  const failure = await installing;
185
343
  if (failure !== null)
186
344
  throw new Error(failure);
187
- const installed = await locate(kind);
345
+ const installed = await locate(kind, signal);
188
346
  if (installed === null)
189
347
  throw new Error(`the login shell does not find ${CLIS[kind].bin} after its install`);
190
348
  return installed;
191
349
  }
192
- async resolve(kind) {
350
+ async resolve(kind, signal, owner) {
193
351
  let cli;
194
352
  try {
195
- cli = await realpath(await this.ensure(kind));
353
+ cli = await this.ensure(kind, signal, owner);
196
354
  }
197
355
  catch (error) {
198
356
  const failure = causeOf(error);
199
357
  process.stderr.write(`kit: ${kind} did not install: ${failure}\n`);
200
358
  return { release: null, failure, ...SIGNED_OUT };
201
359
  }
202
- const release = await versionOf(cli);
360
+ const release = await versionOf(kind, cli, signal);
203
361
  if (release === null)
204
362
  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
363
  return { cli, release };
209
364
  }
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)) };
365
+ async examine(kind, known, read, signal, owner) {
366
+ const current = this.nextRead(kind);
367
+ const resolved = await this.queue(kind, () => this.resolve(kind, signal, owner), signal);
368
+ const reading = 'cli' in resolved ? { release: resolved.release, failure: null, ...(await read(kind, resolved.cli, known)) } : resolved;
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);
215
407
  }
216
408
  async load(kind) {
217
409
  const known = this.readings.get(kind);
218
410
  if (known !== undefined && known.failure === null)
219
411
  return;
220
- this.nextRead(kind);
221
- this.readings.set(kind, await this.examine(kind, SIGNED_OUT));
412
+ await this.examine(kind, SIGNED_OUT, (kind, cli, known) => this.quietOffer(kind, cli, known));
413
+ await this.report();
222
414
  }
223
415
  async send() {
224
416
  const agents = this.desired.agents.flatMap((kind) => {
225
- const reading = this.readings.get(kind);
417
+ const reading = this.installs.has(kind) ? INSTALLING : this.readings.get(kind);
226
418
  return reading === undefined ? [] : [reported(kind, reading)];
227
419
  });
228
420
  const hostKey = await sshHostKey();
421
+ const form = await hostForm();
229
422
  const body = {
230
423
  os: await operatingSystem(),
231
- kit_version: KIT_VERSION,
424
+ ...(form === undefined ? {} : { form }),
425
+ kit_release: KIT_RELEASE,
426
+ wire: KIT_WIRE,
232
427
  agent_base: agentBase(),
428
+ ...(reinstall() === undefined ? {} : { reinstall: reinstall() }),
429
+ settings: await heldSettings(),
233
430
  agents,
431
+ transcription: transcriptionReport(),
234
432
  ...(hostKey === null ? {} : { ssh_host_key: hostKey }),
235
433
  };
236
434
  const state = JSON.stringify(body);
237
435
  if (state === this.sent)
238
436
  return;
239
- await this.house.deliver('/kit/agents/report', body);
437
+ await this.house.deliver('agents/report', body);
240
438
  this.sent = state;
241
439
  }
242
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
+ }