@agentshouse/kit 0.2.1-cb997daca91ed → 0.2.1-cba216f2c559c

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.
@@ -0,0 +1,255 @@
1
+ import { spawn as spawnPiped } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { once } from 'node:events';
4
+ import { rmSync } from 'node:fs';
5
+ import { mkdir, rm, writeFile } from 'node:fs/promises';
6
+ import { constants } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { loginPath, onLoginPath } from './clis.js';
9
+ import { kitHome } from './home.js';
10
+ import { childEnvironment } from './relay.js';
11
+ import { killTree } from './scope.js';
12
+ const TERMINAL = 'xterm-256color';
13
+ const FIRST_SIZE = { cols: 80, rows: 24 };
14
+ const SIGNALLED = 128;
15
+ const NEWLINE = 0x0a;
16
+ const NO_BASH = "bash is not on the login shell's PATH";
17
+ const LOST = { refused: 'the Kit lost its connection to House' };
18
+ function causeOf(error) {
19
+ return error instanceof Error ? error.message : String(error);
20
+ }
21
+ function failed(plan, cause) {
22
+ process.stderr.write(`kit: ${plan.named} could not start: ${cause}\n`);
23
+ return { refused: `the script could not start: ${cause}` };
24
+ }
25
+ function planned(call) {
26
+ if (call.kind === 'run_wizard')
27
+ return { named: 'a Web Wizard', script: call.script, terminal: 'page', function: null };
28
+ return {
29
+ named: 'an Environment function',
30
+ script: call.script,
31
+ terminal: call.terminal ? 'at once' : null,
32
+ function: { input: call.input, timeCap: call.time_cap, outputCap: call.output_cap },
33
+ };
34
+ }
35
+ function inputs() {
36
+ return join(kitHome(), 'inputs');
37
+ }
38
+ async function inputFile(value) {
39
+ await mkdir(inputs(), { recursive: true, mode: 0o700 });
40
+ const path = join(inputs(), `${randomUUID()}.json`);
41
+ await writeFile(path, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
42
+ return path;
43
+ }
44
+ export function removeInputs() {
45
+ rmSync(inputs(), { recursive: true, force: true });
46
+ }
47
+ function struck(line, typed) {
48
+ return typed.some((typedLine) => line.includes(typedLine));
49
+ }
50
+ class KeptOutput {
51
+ cap;
52
+ typedText = '';
53
+ text = '';
54
+ bytes = 0;
55
+ line = '';
56
+ lineBytes = 0;
57
+ dropping = false;
58
+ cut = false;
59
+ constructor(cap) {
60
+ this.cap = cap;
61
+ }
62
+ typed(data) {
63
+ this.typedText += data;
64
+ }
65
+ add(data) {
66
+ const pieces = data.split('\n');
67
+ const rest = pieces.pop();
68
+ for (const piece of pieces)
69
+ this.ended(piece);
70
+ this.extend(rest);
71
+ }
72
+ kept() {
73
+ const typed = this.typedLines(true);
74
+ this.text = [...this.text.split(/(?<=\n)/), this.line].filter((line) => line !== '' && !struck(line, typed)).join('');
75
+ this.bytes = Buffer.byteLength(this.text);
76
+ this.trim();
77
+ return { output: this.text, cut: this.cut };
78
+ }
79
+ typedLines(all) {
80
+ const lines = this.typedText.split(/\r\n|\r|\n/);
81
+ if (!all)
82
+ lines.pop();
83
+ return lines.filter((line) => line !== '');
84
+ }
85
+ ended(piece) {
86
+ const line = `${this.line}${piece}\n`;
87
+ const dropped = this.dropping;
88
+ this.line = '';
89
+ this.lineBytes = 0;
90
+ this.dropping = false;
91
+ if (dropped || struck(line, this.typedLines(false)))
92
+ return;
93
+ this.text += line;
94
+ this.bytes += Buffer.byteLength(line);
95
+ if (this.bytes > 2 * this.cap)
96
+ this.trim();
97
+ }
98
+ extend(piece) {
99
+ if (this.dropping)
100
+ return;
101
+ this.line += piece;
102
+ this.lineBytes += Buffer.byteLength(piece);
103
+ if (this.lineBytes <= this.cap)
104
+ return;
105
+ this.text = '';
106
+ this.bytes = 0;
107
+ this.line = '';
108
+ this.lineBytes = 0;
109
+ this.dropping = true;
110
+ this.cut = true;
111
+ }
112
+ trim() {
113
+ if (this.bytes <= this.cap)
114
+ return;
115
+ const bytes = Buffer.from(this.text);
116
+ const start = bytes.indexOf(NEWLINE, bytes.length - this.cap - 1) + 1;
117
+ this.text = bytes.subarray(start).toString('utf8');
118
+ this.bytes = bytes.length - start;
119
+ this.cut = true;
120
+ }
121
+ }
122
+ export class Scripts {
123
+ calls;
124
+ send;
125
+ runs = new Map();
126
+ constructor(calls, send) {
127
+ this.calls = calls;
128
+ this.send = send;
129
+ }
130
+ start(call) {
131
+ void this.calls.carry(call.input_id, () => this.run(call.input_id, planned(call)));
132
+ }
133
+ notified(oneWayCall) {
134
+ const run = this.runs.get(String(oneWayCall.wizard));
135
+ if (run === undefined)
136
+ return;
137
+ if (oneWayCall.type === 'wizard_input')
138
+ this.typed(run, String(oneWayCall.data));
139
+ if (oneWayCall.type === 'wizard_size')
140
+ this.resized(run, { cols: Number(oneWayCall.cols), rows: Number(oneWayCall.rows) });
141
+ if (oneWayCall.type === 'wizard_end' && run.plan.terminal === 'page')
142
+ this.end(run, {});
143
+ }
144
+ disconnected() {
145
+ for (const run of this.runs.values())
146
+ this.end(run, LOST);
147
+ }
148
+ async run(id, plan) {
149
+ const size = plan.terminal === 'page' ? null : FIRST_SIZE;
150
+ const output = plan.function === null ? null : new KeptOutput(plan.function.outputCap);
151
+ const run = { plan, input: null, output, process: null, pipes: [], terminal: null, size, typed: [], ended: null, sized: Promise.withResolvers() };
152
+ if (size !== null)
153
+ run.sized.resolve();
154
+ this.runs.set(id, run);
155
+ try {
156
+ return { result: await this.ran(id, run), release: plan.function !== null };
157
+ }
158
+ finally {
159
+ this.runs.delete(id);
160
+ if (run.input !== null)
161
+ await rm(run.input, { force: true });
162
+ }
163
+ }
164
+ async ran(id, run) {
165
+ const { plan, output } = run;
166
+ let exited;
167
+ try {
168
+ const { spawn } = await import('@lydell/node-pty');
169
+ const shell = await onLoginPath('bash');
170
+ if (shell === null)
171
+ return failed(plan, NO_BASH);
172
+ const path = await loginPath();
173
+ await run.sized.promise;
174
+ if (plan.function !== null)
175
+ run.input = await inputFile(plan.function.input);
176
+ if (run.ended !== null)
177
+ return run.ended;
178
+ const environment = { ...childEnvironment(), PATH: path, ...(run.input === null ? {} : { HOUSE_INPUT: run.input }) };
179
+ if (plan.terminal === null) {
180
+ ({ exited } = await this.piped(plan.script, shell, environment, run));
181
+ }
182
+ else {
183
+ const terminal = spawn(shell, ['-c', plan.script], { name: TERMINAL, ...run.size, cwd: process.cwd(), env: environment });
184
+ run.process = terminal;
185
+ run.terminal = terminal;
186
+ terminal.onData((data) => {
187
+ this.send({ type: 'wizard_output', wizard: id, data });
188
+ output?.add(data);
189
+ });
190
+ for (const data of run.typed.splice(0))
191
+ terminal.write(data);
192
+ exited = new Promise((resolve) => terminal.onExit(({ exitCode, signal }) => resolve(signal ? SIGNALLED + signal : exitCode)));
193
+ }
194
+ }
195
+ catch (error) {
196
+ return failed(plan, causeOf(error));
197
+ }
198
+ let timedOut = false;
199
+ // House sends a function run's time cap in seconds, and a run still going at its cap ends with its process group and the output pipes it holds.
200
+ const capped = plan.function === null ? undefined : setTimeout(() => {
201
+ timedOut = true;
202
+ this.stop(run);
203
+ }, plan.function.timeCap * 1000);
204
+ const code = await exited;
205
+ clearTimeout(capped);
206
+ if (run.ended !== null)
207
+ return run.ended;
208
+ if (output === null)
209
+ return { exit_code: code };
210
+ const kept = output.kept();
211
+ return timedOut ? { timed_out: true, ...kept } : { exit_code: code, ...kept };
212
+ }
213
+ async piped(script, shell, environment, run) {
214
+ const child = spawnPiped(shell, ['-c', script], { cwd: process.cwd(), env: environment, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
215
+ const exited = new Promise((resolve) => child.once('close', (code, signal) => resolve(signal === null ? code : SIGNALLED + constants.signals[signal])));
216
+ await once(child, 'spawn');
217
+ run.process = { pid: child.pid };
218
+ run.pipes = [child.stdout, child.stderr];
219
+ for (const pipe of run.pipes) {
220
+ pipe.setEncoding('utf8');
221
+ pipe.on('data', (data) => run.output.add(data));
222
+ }
223
+ if (run.ended !== null)
224
+ this.stop(run);
225
+ return { exited };
226
+ }
227
+ typed(run, data) {
228
+ run.output?.typed(data);
229
+ if (run.terminal === null)
230
+ run.typed.push(data);
231
+ else
232
+ run.terminal.write(data);
233
+ }
234
+ resized(run, size) {
235
+ run.size = size;
236
+ run.sized.resolve();
237
+ try {
238
+ run.terminal?.resize(size.cols, size.rows);
239
+ }
240
+ catch { }
241
+ }
242
+ end(run, result) {
243
+ if (run.ended !== null)
244
+ return;
245
+ run.ended = result;
246
+ run.sized.resolve();
247
+ this.stop(run);
248
+ }
249
+ stop(run) {
250
+ if (run.process !== null)
251
+ killTree(run.process);
252
+ for (const pipe of run.pipes)
253
+ pipe.destroy();
254
+ }
255
+ }
@@ -2,7 +2,7 @@ import { finalRefusal, retryDelay } from './api.js';
2
2
  export async function holdSecretInput(house, subject, steps, waiting) {
3
3
  for (let failures = 0; waiting();) {
4
4
  try {
5
- const held = await house.post(`/kit/secret-input/${subject}`, { steps });
5
+ const held = await house.post('/kit/secret-inputs/await', { subject, steps });
6
6
  if (held.outcome === 'collected')
7
7
  return held.content;
8
8
  if (held.release !== 'held')
@@ -0,0 +1,28 @@
1
+ const SYSTEM_CLOCK = {
2
+ later: (delay, callback) => setTimeout(callback, delay),
3
+ clear: (timer) => clearTimeout(timer),
4
+ };
5
+ export class Silence {
6
+ timer = null;
7
+ interval;
8
+ silent;
9
+ clock;
10
+ constructor(interval, silent, clock = SYSTEM_CLOCK) {
11
+ this.interval = interval;
12
+ this.silent = silent;
13
+ this.clock = clock;
14
+ }
15
+ heard() {
16
+ this.stop();
17
+ this.timer = this.clock.later(this.interval, () => {
18
+ this.timer = null;
19
+ this.silent();
20
+ });
21
+ }
22
+ stop() {
23
+ if (this.timer === null)
24
+ return;
25
+ this.clock.clear(this.timer);
26
+ this.timer = null;
27
+ }
28
+ }
package/dist/update.js CHANGED
@@ -1,176 +1,127 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
3
- import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
4
- import { homedir } from 'node:os';
2
+ import { mkdir } from 'node:fs/promises';
5
3
  import { join } from 'node:path';
6
- import { run } from './clis.js';
7
- import { kitHome, workspaceRoot } from './home.js';
8
- import { service, throughSudo } from './placement.js';
9
- import { relayed } from './relay.js';
10
- const BOOTSTRAP_BYTES = 1_000_000;
11
- // A bootstrap is at most a million bytes, so two minutes carry it over ten kilobytes a second and no stalled host holds the update queue.
12
- const BOOTSTRAP_MS = 120_000;
13
- function directory() {
14
- return join(kitHome(), 'update');
15
- }
16
- function pending() {
17
- return join(directory(), 'pending.json');
18
- }
19
- function outcome() {
20
- return join(directory(), 'outcome');
21
- }
22
- function unit(callId) {
23
- return `house-kit-update-${callId}`;
24
- }
25
- function manager() {
26
- return service() === 'user' ? ['--user'] : [];
27
- }
28
- function elevated() {
29
- return throughSudo() ? ['sudo', '-n'] : [];
30
- }
31
- function account() {
32
- return throughSudo() ? [`--uid=${process.getuid()}`, `--gid=${process.getgid()}`] : [];
33
- }
34
- function placement() {
35
- return service() === 'user' ? ['--workspace', workspaceRoot()] : ['--linux'];
36
- }
37
- function record() {
38
- return `outcome=$1; shift; bash "$0" "$@"; printf %s "$?" > "$outcome"; ${[...elevated(), 'systemctl', ...manager(), 'start', 'house-kit.service'].join(' ')}`;
39
- }
40
- async function pendingCall() {
41
- try {
42
- return JSON.parse(await readFile(pending(), 'utf8')).input_id;
43
- }
44
- catch {
45
- return null;
46
- }
47
- }
48
- async function recorded() {
49
- const status = await readFile(outcome(), 'utf8').catch(() => null);
50
- if (status === null)
51
- return null;
52
- return status.trim() === '0' ? {} : { refused: `the Kit bootstrap exited with ${status.trim()}` };
53
- }
54
- async function forget(callId) {
55
- if ((await pendingCall()) !== callId)
56
- return;
57
- await rm(pending(), { force: true });
58
- await rm(outcome(), { force: true });
59
- }
60
- async function finished(callId) {
61
- for (;;) {
62
- const result = await recorded();
63
- if (result !== null)
64
- return result;
65
- // systemctl answers at once, so ten seconds only bounds a stuck service manager.
66
- if ((await run('systemctl', [...manager(), 'is-active', '--quiet', unit(callId)], 10_000)).status !== 0) {
67
- return (await recorded()) ?? { refused: 'the Kit bootstrap did not finish' };
68
- }
69
- // The bootstrap runs for minutes, so checking each second sees its outcome within a second at little cost.
70
- await new Promise((resolve) => setTimeout(resolve, 1000));
71
- }
72
- }
73
- async function bounded(body, most) {
74
- const chunks = [];
75
- let bytes = 0;
76
- for await (const chunk of body ?? []) {
77
- bytes += chunk.length;
78
- if (bytes > most)
79
- return null;
80
- chunks.push(chunk);
81
- }
82
- return Buffer.concat(chunks, bytes);
83
- }
84
- function rerun(script, callId, flags) {
4
+ import { downloadServed, servedRelease } from './building.js';
5
+ import { KIT_RELEASE } from './clis.js';
6
+ import { restart, updateLine } from './end.js';
7
+ import { kitHome, readEnrolment } from './home.js';
8
+ import { placedPrefix } from './placement.js';
9
+ import { childEnvironment, relayOrigin } from './relay.js';
10
+ const INSTALLER_BYTES = 1_000_000;
11
+ // A release's Node.js, Kit package and adapters are about a hundred megabytes, so an hour carries them at thirty kilobytes a second, and a placement still running then has hung.
12
+ const PLACEMENT_MS = 60 * 60_000;
13
+ // A refused Kit is offline until its placement succeeds, so it tries again within five minutes of its Building or this computer recovering, while a placement that fails only after its hundred-megabyte download runs at most twelve times an hour.
14
+ export const PLACEMENT_RETRY_MS = 5 * 60_000;
15
+ const REFUSED = 'kit_bootstrap_refused: ';
16
+ const OUTPUT_CHARACTERS = 4000;
17
+ function causeOf(error) {
18
+ if (error instanceof TypeError && error.cause instanceof Error)
19
+ return `the Building did not answer: ${error.cause.message}`;
20
+ return error instanceof Error ? error.message : String(error);
21
+ }
22
+ function placing(installer, house, prefix, signal) {
85
23
  return new Promise((resolve) => {
86
- const [command, ...args] = [
87
- ...elevated(),
88
- 'systemd-run',
89
- ...manager(),
90
- ...account(),
91
- '--wait',
92
- '--collect',
93
- '--quiet',
94
- `--unit=${unit(callId)}`,
95
- `--setenv=HOME=${homedir()}`,
96
- `--setenv=HOUSE_KIT_HOME=${kitHome()}`,
97
- '/bin/sh',
98
- '-c',
99
- record(),
100
- script,
101
- outcome(),
102
- ...placement(),
103
- ...flags,
104
- ];
105
- const child = spawn(command, args, { stdio: ['ignore', 'ignore', 'inherit'] });
106
- child.on('error', () => resolve({ refused: 'no service manager runs this Kit process' }));
107
- child.on('close', () => resolve(null));
24
+ const relay = relayOrigin();
25
+ const child = spawn('bash', [installer, '--house', house, '--place', prefix], {
26
+ stdio: ['ignore', 'pipe', 'pipe'],
27
+ env: { ...childEnvironment(), ...(relay === undefined ? {} : { HOUSE_KIT_RELAY: relay }) },
28
+ detached: true,
29
+ });
30
+ const stop = () => {
31
+ try {
32
+ process.kill(-child.pid, 'SIGKILL');
33
+ }
34
+ catch { }
35
+ };
36
+ signal.addEventListener('abort', stop, { once: true });
37
+ if (signal.aborted)
38
+ stop();
39
+ let output = '';
40
+ for (const stream of [child.stdout, child.stderr]) {
41
+ stream.setEncoding('utf8').on('data', (chunk) => {
42
+ output = (output + chunk).slice(-OUTPUT_CHARACTERS);
43
+ });
44
+ }
45
+ const ended = (failure) => {
46
+ signal.removeEventListener('abort', stop);
47
+ resolve(failure);
48
+ };
49
+ child.on('error', (error) => ended(error.message));
50
+ child.on('close', (status) => {
51
+ if (status === 0)
52
+ return ended(null);
53
+ if (signal.aborted)
54
+ return ended(`the placement did not end within ${PLACEMENT_MS / 1000} seconds`);
55
+ const lines = output.split('\n').filter((line) => line.trim() !== '');
56
+ const refused = lines.findLast((line) => line.startsWith(REFUSED));
57
+ ended(refused?.slice(REFUSED.length) ?? lines.at(-1) ?? `the placement ended with status ${status ?? 'a signal'}`);
58
+ });
108
59
  });
109
60
  }
110
61
  export class KitUpdate {
111
62
  calls;
112
- changed;
113
- waiting = new Map();
114
63
  queue = Promise.resolve();
115
- constructor(calls, changed) {
64
+ placed = null;
65
+ constructor(calls) {
116
66
  this.calls = calls;
117
- this.changed = changed;
118
67
  }
119
- async resumed() {
120
- const callId = await pendingCall();
121
- if (callId === null)
122
- return;
123
- await this.enqueue(callId, () => finished(callId));
68
+ take(call) {
69
+ void this.calls.carry(call.input_id, async () => ({ result: await this.queued(() => this.update(call.release)) }));
124
70
  }
125
- hold(call) {
126
- this.waiting.set(call.input_id, call);
127
- this.changed();
71
+ async takeRefused(release) {
72
+ for (;;) {
73
+ const failure = await this.queued(async () => (this.placed === null ? this.place(release, 'served') : null));
74
+ if (failure === null)
75
+ restart(`Kit ${this.placed} is placed; its supervisor starts it`);
76
+ process.stderr.write(`kit: ${updateLine(`Kit ${KIT_RELEASE} stays offline and tries again in ${PLACEMENT_RETRY_MS / 60_000} minutes`)}\n`);
77
+ await new Promise((resolve) => setTimeout(resolve, PLACEMENT_RETRY_MS));
78
+ }
128
79
  }
129
- held() {
130
- return this.waiting.size > 0;
80
+ placedRelease() {
81
+ return this.placed;
131
82
  }
132
- apply(resume) {
133
- const held = [...this.waiting.values()];
134
- this.waiting.clear();
135
- void Promise.all(held.map((call) => this.enqueue(call.input_id, () => this.carry(call)))).then(resume);
83
+ queued(work) {
84
+ const taken = this.queue.then(work);
85
+ this.queue = taken.catch(() => undefined);
86
+ return taken;
136
87
  }
137
- enqueue(callId, work) {
138
- const before = this.queue;
139
- const carried = this.calls.carry(callId, async () => {
140
- await before;
141
- return { result: await work(), returned: () => forget(callId) };
142
- });
143
- this.queue = before.then(() => carried);
144
- return carried;
88
+ async update(release) {
89
+ if (release === (this.placed ?? KIT_RELEASE))
90
+ return {};
91
+ if (this.placed !== null)
92
+ return { refused: `Kit ${this.placed} is placed and starts first, once no turn is open` };
93
+ const failure = await this.place(release, 'named');
94
+ if (failure !== null)
95
+ return { refused: failure };
96
+ process.stderr.write(`kit: Kit ${release} is placed; it starts once no turn is open\n`);
97
+ return {};
145
98
  }
146
- async carry(call) {
147
- if ((await pendingCall()) === call.input_id)
148
- return finished(call.input_id);
149
- const deadline = AbortSignal.timeout(BOOTSTRAP_MS);
150
- let script;
99
+ async place(release, which) {
100
+ const signal = AbortSignal.timeout(PLACEMENT_MS);
101
+ let version = release;
102
+ let failure;
151
103
  try {
152
- const answer = await fetch(relayed(call.bootstrap), { signal: deadline });
153
- if (!answer.ok)
154
- return { refused: `the Kit bootstrap could not be downloaded: ${answer.status}` };
155
- script = await bounded(answer.body, BOOTSTRAP_BYTES);
104
+ const prefix = placedPrefix();
105
+ const served = await servedRelease(signal);
106
+ if (which === 'named' && served.version !== release)
107
+ throw new Error(`the Building serves Kit ${served.version}, not Kit ${release}`);
108
+ version = served.version;
109
+ if (version === KIT_RELEASE)
110
+ throw new Error(`the Building serves Kit ${KIT_RELEASE}, which this Kit runs`);
111
+ await mkdir(join(kitHome(), 'update'), { recursive: true, mode: 0o700 });
112
+ const installer = join(kitHome(), 'update', served.installer);
113
+ await downloadServed(served.installer, served.sha256, installer, signal, INSTALLER_BYTES);
114
+ failure = await placing(installer, (await readEnrolment()).house, prefix, signal);
156
115
  }
157
116
  catch (error) {
158
- if (!deadline.aborted)
159
- throw error;
160
- return { refused: `the Kit bootstrap did not arrive within ${BOOTSTRAP_MS / 1000} seconds` };
117
+ failure = signal.aborted ? `the placement did not end within ${PLACEMENT_MS / 1000} seconds` : causeOf(error);
161
118
  }
162
- if (script === null)
163
- return { refused: `the Kit bootstrap is larger than ${BOOTSTRAP_BYTES} bytes` };
164
- if (createHash('sha256').update(script).digest('hex') !== call.sha256) {
165
- return { refused: 'the Kit bootstrap does not match its sha256' };
119
+ if (failure !== null) {
120
+ const refused = `Kit ${version} could not be placed: ${failure}`;
121
+ process.stderr.write(`kit: ${refused}\n`);
122
+ return refused;
166
123
  }
167
- await mkdir(directory(), { recursive: true, mode: 0o700 });
168
- const path = join(directory(), 'connect-linux.sh');
169
- await writeFile(path, script, { mode: 0o700 });
170
- await rm(outcome(), { force: true });
171
- await writeFile(pending(), `${JSON.stringify({ input_id: call.input_id })}\n`, { mode: 0o600 });
172
- return (await rerun(path, call.input_id, call.update_clis ? ['--update-clis'] : [])) ?? (await recorded()) ?? {
173
- refused: 'the Kit bootstrap did not finish',
174
- };
124
+ this.placed = version;
125
+ return null;
175
126
  }
176
127
  }
package/dist/wire.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { newerThanHouse, updateRequired } from './end.js';
2
2
  import { machine } from './placement.js';
3
3
  import { refusalOf } from './refusals.js';
4
- export const KIT_WIRE = 3;
4
+ export const KIT_WIRE = 5;
5
5
  export const KIT_WIRE_HEADER = 'x-house-kit-wire';
6
- function newer(text) {
6
+ let take = null;
7
+ let taken = false;
8
+ function unservedBy(text) {
7
9
  let body;
8
10
  try {
9
11
  body = JSON.parse(text);
@@ -11,12 +13,28 @@ function newer(text) {
11
13
  catch {
12
14
  return null;
13
15
  }
14
- return body?.error?.code === 'kit_newer_than_house' ? body.error : null;
16
+ const error = body?.error;
17
+ if (error?.code !== 'kit_update_required' && error?.code !== 'kit_newer_than_house')
18
+ return null;
19
+ return typeof error.release === 'string' ? error : null;
20
+ }
21
+ export function takeUnservedRelease(taking) {
22
+ take = taking;
23
+ }
24
+ export function unserved() {
25
+ return taken;
15
26
  }
16
27
  export function endUnserved(text) {
28
+ const refused = unservedBy(text);
29
+ if (refused !== null && take !== null) {
30
+ if (!taken) {
31
+ taken = true;
32
+ take(refused.release);
33
+ }
34
+ return;
35
+ }
17
36
  if (refusalOf(text)?.code === 'kit_update_required')
18
37
  updateRequired();
19
- const refused = newer(text);
20
- if (refused !== null)
38
+ if (refused?.code === 'kit_newer_than_house')
21
39
  newerThanHouse(refused.release, refused.commands[machine()]);
22
40
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentshouse/kit",
3
- "version": "0.2.1-cb997daca91ed",
3
+ "version": "0.2.1-cba216f2c559c",
4
4
  "description": "Kit connects an Environment to agents.house.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -26,7 +26,7 @@
26
26
  "dependencies": {
27
27
  "@agentclientprotocol/sdk": "2.0.1",
28
28
  "@agentshouse/mdmodel": "0.1.0-c4f4d37bc9d6a",
29
- "@agentshouse/skills": "0.1.0-c08575ab21b57",
29
+ "@agentshouse/skills": "0.1.0-c3402d5699e50",
30
30
  "@lydell/node-pty": "1.2.0-beta.15",
31
31
  "yaml": "2.9.1"
32
32
  },
package/dist/clis-main.js DELETED
@@ -1,23 +0,0 @@
1
- import { post } from './api.js';
2
- import { CLIS, below, locate, versionOf } from './clis.js';
3
- import { readEnrolment } from './home.js';
4
- import { proxyUnlessRelayed } from './relay.js';
5
- proxyUnlessRelayed();
6
- try {
7
- const { house, credential } = (await readEnrolment());
8
- const { agents } = await post(house, '/kit/agents/desired', {}, credential);
9
- for (const kind of agents) {
10
- const cli = await locate(kind);
11
- if (cli === null)
12
- continue;
13
- const release = await versionOf(cli);
14
- if (release === null)
15
- continue;
16
- const { bin, minimum } = CLIS[kind];
17
- process.stdout.write(`${[bin, cli, release, minimum, below(release, minimum) ? 'old' : 'current'].join('\t')}\n`);
18
- }
19
- }
20
- catch (error) {
21
- process.stderr.write(`kit: ${error.message}\n`);
22
- process.exitCode = 1;
23
- }