@agentshouse/kit 0.2.1-ccb257fa8a318 → 0.2.1-ccffb3f637815

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 (57) hide show
  1. package/README.md +27 -31
  2. package/dist/acp.js +17 -10
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +121 -52
  5. package/dist/api.js +11 -6
  6. package/dist/binaries.js +89 -0
  7. package/dist/bridge.js +28 -27
  8. package/dist/building.js +7 -3
  9. package/dist/calls.js +18 -1
  10. package/dist/chunks.js +49 -0
  11. package/dist/clis.js +52 -63
  12. package/dist/connect.js +108 -0
  13. package/dist/connection.js +24 -20
  14. package/dist/content.js +106 -0
  15. package/dist/conversations.js +255 -134
  16. package/dist/copies.js +748 -248
  17. package/dist/earlier.js +263 -0
  18. package/dist/end.js +9 -6
  19. package/dist/events.js +549 -281
  20. package/dist/files.js +77 -11
  21. package/dist/git-main.js +24 -29
  22. package/dist/git.js +87 -12
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +80 -29
  25. package/dist/house-cli.js +106 -123
  26. package/dist/instructions.js +2 -4
  27. package/dist/keys.js +238 -0
  28. package/dist/kit-cli.js +14 -4
  29. package/dist/login.js +34 -20
  30. package/dist/logout.js +2 -2
  31. package/dist/mcp.js +38 -3
  32. package/dist/old-references.js +27 -0
  33. package/dist/owner.js +46 -0
  34. package/dist/placement.js +9 -23
  35. package/dist/refusals.js +37 -21
  36. package/dist/resident.js +107 -72
  37. package/dist/scope.js +12 -4
  38. package/dist/scripts.js +59 -11
  39. package/dist/secret-input.js +1 -1
  40. package/dist/settings.js +188 -0
  41. package/dist/sign-in.js +49 -4
  42. package/dist/supervisor.js +163 -0
  43. package/dist/transcription.js +5 -2
  44. package/dist/translate.js +18 -11
  45. package/dist/update.js +115 -160
  46. package/dist/wire.js +19 -9
  47. package/dist/work.js +27 -2
  48. package/dist/workspace.js +103 -0
  49. package/package.json +13 -8
  50. package/dist/authority-main.js +0 -22
  51. package/dist/chatgpt.js +0 -32
  52. package/dist/clis-main.js +0 -23
  53. package/dist/configure-main.js +0 -6
  54. package/dist/enrol-main.js +0 -10
  55. package/dist/parts.js +0 -82
  56. package/dist/service-main.js +0 -9
  57. package/dist/service.js +0 -55
package/dist/resident.js CHANGED
@@ -1,25 +1,29 @@
1
1
  import { once } from 'node:events';
2
2
  import { watch } from 'node:fs';
3
3
  import { mkdir, rm, writeFile } from 'node:fs/promises';
4
- import { createServer, get } from 'node:http';
4
+ import { createServer } from 'node:http';
5
5
  import { dirname, extname, join } from 'node:path';
6
- import { DatabaseSync } from 'node:sqlite';
7
6
  import { fileURLToPath } from 'node:url';
8
7
  import { Agents } from './agents.js';
9
8
  import { house } from './api.js';
10
9
  import { received } from './bridge.js';
11
- import { CONVERSATION_METHODS, Conversations } from './conversations.js';
10
+ import { Conversations } from './conversations.js';
12
11
  import { LocalCopies } from './copies.js';
13
- import { restart } from './end.js';
14
- import { agentBase, enrolled, forgetRestart, kitHome, ownerLock, ownerSocket, readEnrolment, restartAsked } from './home.js';
12
+ import { restart, restartPlaced } from './end.js';
13
+ import { agentBase, enrolled, kitHome, ownerSocket, readEnrolment, recordPlannedRestart, takePlannedRestart } from './home.js';
15
14
  import { Calls } from './calls.js';
15
+ import { KIT_RELEASE } from './clis.js';
16
+ import { moveEarlier } from './earlier.js';
17
+ import { holdOwner } from './owner.js';
16
18
  import { killDescendants } from './scope.js';
17
19
  import { removeInputs, Scripts } from './scripts.js';
20
+ import { applySettings, enrolledRoutes, resumeWorkspaceMove } from './settings.js';
18
21
  import { quoted } from './shell.js';
19
22
  import { SignIns } from './sign-in.js';
20
23
  import { placeSkillSet } from './skills.js';
21
24
  import { holdConnection } from './connection.js';
22
25
  import { KitUpdate } from './update.js';
26
+ import { takeUnservedRelease } from './wire.js';
23
27
  import { codexLauncher } from './work.js';
24
28
  function report(error) {
25
29
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
@@ -32,39 +36,27 @@ async function installShim(path, module) {
32
36
  await mkdir(dirname(path), { recursive: true });
33
37
  await writeFile(path, `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, { mode: 0o755 });
34
38
  }
35
- function claimed(lock) {
36
- try {
37
- lock.exec('BEGIN EXCLUSIVE');
38
- return true;
39
- }
40
- catch (error) {
41
- if (error.errcode === 5)
42
- return false;
43
- throw error;
44
- }
45
- }
46
- async function serveOwner(copies) {
47
- const lock = new DatabaseSync(ownerLock());
48
- if (!claimed(lock)) {
49
- lock.close();
50
- const running = await runningResident();
51
- throw new Error(`${running === null ? 'another Kit process' : `Kit process ${running}`} already runs this Environment from Kit home ${kitHome()}; stop it first to run another Kit process here`);
52
- }
39
+ async function serveOwner(lock, copies, settling) {
53
40
  const server = createServer(async (request, response) => {
54
41
  try {
55
42
  const text = await received(request);
56
43
  let answered;
57
44
  if (request.url === '/resident') {
58
- response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ pid: process.pid }));
45
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ pid: process.pid, release: KIT_RELEASE }));
59
46
  return;
60
47
  }
61
48
  if (request.url === '/git/fetch') {
62
- answered = await copies.fetch();
49
+ answered = await copies.fetch(copies.owner);
63
50
  }
64
51
  else if (request.url === '/git/push') {
65
52
  const { cwd, commit } = JSON.parse(text);
66
53
  answered = await copies.push(cwd, commit, copies.owner);
67
54
  }
55
+ else if (request.url === '/settings') {
56
+ const applied = await settling.settle(JSON.parse(text));
57
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(applied), () => settling.answered(applied));
58
+ return;
59
+ }
68
60
  else {
69
61
  response.writeHead(404).end();
70
62
  return;
@@ -80,18 +72,6 @@ async function serveOwner(copies) {
80
72
  server.listen(ownerSocket());
81
73
  await once(server, 'listening');
82
74
  }
83
- function runningResident() {
84
- return new Promise((resolve, reject) => {
85
- get({ socketPath: ownerSocket(), path: '/resident' }, (answer) => {
86
- received(answer).then((text) => resolve(JSON.parse(text).pid), reject);
87
- }).on('error', (error) => {
88
- if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED')
89
- resolve(null);
90
- else
91
- reject(error);
92
- });
93
- });
94
- }
95
75
  function connected() {
96
76
  return new Promise((resolve) => {
97
77
  const watcher = watch(kitHome(), () => {
@@ -110,23 +90,55 @@ function connected() {
110
90
  }
111
91
  async function started() {
112
92
  await connected();
113
- await forgetRestart();
114
- watch(kitHome(), () => {
115
- if (enrolled())
116
- return;
117
- killDescendants();
118
- process.exit(1);
119
- });
120
93
  await placeSkillSet((await readEnrolment()).house);
121
94
  await mkdir(agentBase(), { recursive: true });
122
95
  await installShim(join(kitHome(), 'shim', 'git'), 'git-main');
123
96
  await installShim(codexLauncher(), 'codex-main');
124
97
  }
125
98
  export async function resident() {
99
+ await moveEarlier();
126
100
  await mkdir(kitHome(), { recursive: true, mode: 0o700 });
101
+ const lock = await holdOwner();
102
+ const planned = takePlannedRestart();
103
+ await resumeWorkspaceMove();
127
104
  const copies = new LocalCopies(house);
128
105
  await copies.load();
129
- await serveOwner(copies);
106
+ let running = null;
107
+ let settings = Promise.resolve();
108
+ const settle = (change) => {
109
+ const applied = settings.then(() => applySettings(change, {
110
+ working: () => running !== null && (running.conversations.turnOpen() || running.calls.busy()),
111
+ end: () => {
112
+ running?.conversations.stopped();
113
+ killDescendants();
114
+ },
115
+ routes: async () => {
116
+ if (running === null)
117
+ return enrolledRoutes();
118
+ await running.agents.read();
119
+ return running.agents.desired.routes;
120
+ },
121
+ }));
122
+ settings = applied.catch(() => undefined);
123
+ return applied.then((answer) => {
124
+ if ('settings' in answer && !answer.moved)
125
+ running?.agents.report().catch(report);
126
+ return answer;
127
+ });
128
+ };
129
+ const answered = (applied) => {
130
+ if ('settings' in applied ? !applied.moved : !applied.ended)
131
+ return;
132
+ const ended = 'settings' in applied
133
+ ? `the workspace moved to ${applied.settings.workspace}; its supervisor starts Kit there`
134
+ : 'the workspace stays where it was; its supervisor starts Kit again';
135
+ if (running === null)
136
+ restart(ended);
137
+ else
138
+ void running.stop(() => restart(ended));
139
+ };
140
+ await copies.swept();
141
+ await serveOwner(lock, copies, { settle, answered });
130
142
  await started().catch((error) => {
131
143
  report(error);
132
144
  process.exit(1);
@@ -135,20 +147,28 @@ export async function resident() {
135
147
  const agents = new Agents(house, () => changed());
136
148
  let connection = null;
137
149
  let reported = false;
150
+ let stopping = false;
151
+ const stop = async (then) => {
152
+ if (stopping)
153
+ return;
154
+ stopping = true;
155
+ conversations.stopped();
156
+ killDescendants();
157
+ await connection?.close();
158
+ then();
159
+ };
138
160
  const idle = () => calls.idle() && conversations.idle() && agents.idle();
139
161
  const changed = () => {
140
162
  if (!idle()) {
141
163
  reported = false;
142
164
  }
143
- else if (restartAsked() && conversations.quiet()) {
144
- restart('restarting for an updated CLI');
145
- }
146
- else if (update.held() && conversations.quiet()) {
147
- update.apply(connection.pause());
165
+ else if (update.placedRelease() !== null && conversations.quiet() && process.env.HOUSE_KIT_SANDBOX !== '1') {
166
+ const placed = update.placedRelease();
167
+ void stop(() => restartPlaced(placed));
148
168
  }
149
169
  else if (!reported) {
150
170
  reported = true;
151
- logged(house.deliver('/kit/idle', {}, idle));
171
+ logged(house.deliver('kits/report-idle', {}, idle));
152
172
  }
153
173
  };
154
174
  const calls = new Calls(house, changed);
@@ -157,26 +177,37 @@ export async function resident() {
157
177
  agents,
158
178
  copies,
159
179
  calls,
160
- send: (notification) => connection?.send(notification) ?? false,
180
+ send: (oneWayCall) => connection?.send(oneWayCall) ?? false,
161
181
  changed,
162
182
  });
163
183
  const signIns = new SignIns(house, agents, calls);
164
- const update = new KitUpdate(calls, changed);
184
+ const update = new KitUpdate(calls);
185
+ takeUnservedRelease((release) => logged(update.takeRefused(release)));
165
186
  removeInputs();
166
- const scripts = new Scripts(calls, (notification) => connection?.send(notification) ?? false);
187
+ const scripts = new Scripts(calls, (oneWayCall) => connection?.send(oneWayCall) ?? false);
188
+ running = { conversations, agents, calls, stop };
167
189
  for (const signal of ['SIGTERM', 'SIGINT']) {
168
190
  process.once(signal, () => {
169
- killDescendants();
170
- removeInputs();
171
- process.kill(process.pid, signal);
191
+ recordPlannedRestart();
192
+ void stop(() => {
193
+ removeInputs();
194
+ process.kill(process.pid, signal);
195
+ });
172
196
  });
173
197
  }
174
- await house.deliver('/kit/restarted', {}).catch(report);
175
- await update.resumed().catch(report);
198
+ const unenrolled = () => {
199
+ if (!enrolled())
200
+ void stop(() => process.exit(1));
201
+ };
202
+ watch(kitHome(), unenrolled);
203
+ unenrolled();
204
+ await house.deliver('kits/report-restart', planned ? { planned } : {}).catch(report);
176
205
  logged(agents.refresh());
206
+ agents.keepCurrent(() => process.env.HOUSE_KIT_SANDBOX === '1' && reported);
177
207
  connection = holdConnection({
178
208
  opened: () => {
179
209
  conversations.opened();
210
+ scripts.connected();
180
211
  changed();
181
212
  logged(copies.connected());
182
213
  },
@@ -185,24 +216,28 @@ export async function resident() {
185
216
  if (call.kind === 'sign_in')
186
217
  signIns.start(call);
187
218
  else if (call.kind === 'update')
188
- update.hold(call);
219
+ update.take(call);
220
+ else if (call.kind === 'settings') {
221
+ void calls.carrySettings(call.input_id, async () => {
222
+ const applied = await settle(call);
223
+ const result = 'refused' in applied ? { refused: applied.refused } : { settings: applied.settings };
224
+ if ('settings' in applied ? !applied.moved : !applied.ended)
225
+ return { result };
226
+ calls.keepResult(call.input_id, result);
227
+ return new Promise(() => answered(applied));
228
+ });
229
+ }
189
230
  else if (call.kind === 'run_wizard' || call.kind === 'run_function')
190
231
  scripts.start(call);
191
- else if (CONVERSATION_METHODS.has(call.kind))
232
+ else
192
233
  conversations.call(call);
193
- else {
194
- const refused = { refused: `This Kit does not know ${call.kind}; update the Kit` };
195
- void calls.carry(call.input_id, async () => ({ result: refused }));
196
- }
197
234
  },
198
- notification: (notification) => {
199
- if (notification.type === 'watching')
200
- conversations.watching(notification.watching === true);
201
- if (notification.type === 'authority_changed')
202
- logged(copies.changed(notification.rooms));
203
- if (notification.type === 'work_available' && notification.subject === 'agents')
235
+ oneWayCall: (oneWayCall) => {
236
+ if (oneWayCall.type === 'watching')
237
+ conversations.watching(oneWayCall.watching);
238
+ if (oneWayCall.type === 'work_available' && oneWayCall.subject === 'agents')
204
239
  logged(agents.refresh());
205
- scripts.notified(notification);
240
+ scripts.notified(oneWayCall);
206
241
  },
207
242
  });
208
243
  }
package/dist/scope.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { mkdirSync, readdirSync, readFileSync, rmdirSync, statSync, writeFileSync } from 'node:fs';
2
+ import { mkdirSync, readdirSync, readFileSync, realpathSync, rmdirSync, statSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  const LISTING_BYTES = 1 << 28;
5
5
  const CGROUPS = '/sys/fs/cgroup';
@@ -122,15 +122,23 @@ function members(group) {
122
122
  }
123
123
  return pids;
124
124
  }
125
+ function besideCli(cli) {
126
+ try {
127
+ return `${realpathSync(cli)}-`;
128
+ }
129
+ catch {
130
+ return null;
131
+ }
132
+ }
125
133
  export class Scope {
126
134
  marker;
127
- cli;
135
+ helpers;
128
136
  group;
129
137
  session = null;
130
138
  recorded = null;
131
139
  constructor(marker, name, cli) {
132
140
  this.marker = marker;
133
- this.cli = cli;
141
+ this.helpers = besideCli(cli);
134
142
  const own = ownGroup();
135
143
  this.group = own === null ? null : join(own, name);
136
144
  try {
@@ -168,7 +176,7 @@ export class Scope {
168
176
  return true;
169
177
  if (this.recorded === null)
170
178
  return found.size > 0;
171
- return [...found].some(([pid, { session, command }]) => session !== this.session || !(this.recorded.has(pid) || command.startsWith(`${this.cli}-`)));
179
+ return [...found].some(([pid, { session, command }]) => session !== this.session || !(this.recorded.has(pid) || (this.helpers !== null && command.startsWith(this.helpers))));
172
180
  }
173
181
  empty() {
174
182
  return this.found()?.size === 0;
package/dist/scripts.js CHANGED
@@ -15,6 +15,11 @@ const SIGNALLED = 128;
15
15
  const NEWLINE = 0x0a;
16
16
  const NO_BASH = "bash is not on the login shell's PATH";
17
17
  const LOST = { refused: 'the Kit lost its connection to House' };
18
+ const UNSENT_CHARS = 64_000;
19
+ // House holds a Web Wizard's run two minutes for its Kit to connect again, so the script waits as long for a dropped connection to come back.
20
+ const RETURN_MS = 120_000;
21
+ // House takes a run on again with its page's terminal size in the frames right after the Kit connects, so a script it sent nothing for in ten seconds is one House no longer carries.
22
+ const TAKEN_ON_MS = 10_000;
18
23
  function causeOf(error) {
19
24
  return error instanceof Error ? error.message : String(error);
20
25
  }
@@ -44,6 +49,12 @@ async function inputFile(value) {
44
49
  export function removeInputs() {
45
50
  rmSync(inputs(), { recursive: true, force: true });
46
51
  }
52
+ function latest(screen) {
53
+ if (screen.length <= UNSENT_CHARS)
54
+ return screen;
55
+ const line = screen.indexOf('\n', screen.length - UNSENT_CHARS);
56
+ return screen.slice(line < 0 ? screen.length - UNSENT_CHARS : line + 1);
57
+ }
47
58
  function struck(line, typed) {
48
59
  return typed.some((typedLine) => line.includes(typedLine));
49
60
  }
@@ -130,25 +141,54 @@ export class Scripts {
130
141
  start(call) {
131
142
  void this.calls.carry(call.input_id, () => this.run(call.input_id, planned(call)));
132
143
  }
133
- notified(notification) {
134
- const run = this.runs.get(String(notification.wizard));
144
+ notified(oneWayCall) {
145
+ if (!('wizard' in oneWayCall))
146
+ return;
147
+ const run = this.runs.get(oneWayCall.wizard);
135
148
  if (run === undefined)
136
149
  return;
137
- if (notification.type === 'wizard_input')
138
- this.typed(run, String(notification.data));
139
- if (notification.type === 'wizard_size')
140
- this.resized(run, { cols: Number(notification.cols), rows: Number(notification.rows) });
141
- if (notification.type === 'wizard_end' && run.plan.terminal === 'page')
150
+ this.waited(run, null);
151
+ if (oneWayCall.type === 'wizard_input')
152
+ this.typed(run, oneWayCall.data);
153
+ if (oneWayCall.type === 'wizard_size')
154
+ this.resized(run, { cols: oneWayCall.cols, rows: oneWayCall.rows });
155
+ if (oneWayCall.type === 'wizard_end' && run.plan.terminal === 'page')
142
156
  this.end(run, {});
143
157
  }
144
158
  disconnected() {
145
- for (const run of this.runs.values())
146
- this.end(run, LOST);
159
+ for (const run of this.runs.values()) {
160
+ if (run.plan.terminal === 'page')
161
+ this.waited(run, RETURN_MS);
162
+ else
163
+ this.end(run, LOST);
164
+ }
165
+ }
166
+ connected() {
167
+ for (const [id, run] of this.runs) {
168
+ if (run.waiting === null)
169
+ continue;
170
+ this.waited(run, TAKEN_ON_MS);
171
+ if (run.unsent !== '' && this.send({ type: 'wizard_output', wizard: id, data: run.unsent }))
172
+ run.unsent = '';
173
+ }
147
174
  }
148
175
  async run(id, plan) {
149
176
  const size = plan.terminal === 'page' ? null : FIRST_SIZE;
150
177
  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() };
178
+ const run = {
179
+ plan,
180
+ input: null,
181
+ output,
182
+ process: null,
183
+ pipes: [],
184
+ terminal: null,
185
+ size,
186
+ typed: [],
187
+ unsent: '',
188
+ waiting: null,
189
+ ended: null,
190
+ sized: Promise.withResolvers(),
191
+ };
152
192
  if (size !== null)
153
193
  run.sized.resolve();
154
194
  this.runs.set(id, run);
@@ -184,7 +224,8 @@ export class Scripts {
184
224
  run.process = terminal;
185
225
  run.terminal = terminal;
186
226
  terminal.onData((data) => {
187
- this.send({ type: 'wizard_output', wizard: id, data });
227
+ if (!this.send({ type: 'wizard_output', wizard: id, data }))
228
+ run.unsent = latest(`${run.unsent}${data}`);
188
229
  output?.add(data);
189
230
  });
190
231
  for (const data of run.typed.splice(0))
@@ -242,10 +283,17 @@ export class Scripts {
242
283
  end(run, result) {
243
284
  if (run.ended !== null)
244
285
  return;
286
+ this.waited(run, null);
245
287
  run.ended = result;
246
288
  run.sized.resolve();
247
289
  this.stop(run);
248
290
  }
291
+ waited(run, ms) {
292
+ if (run.waiting !== null)
293
+ clearTimeout(run.waiting);
294
+ run.waiting = ms === null ? null : setTimeout(() => this.end(run, LOST), ms);
295
+ run.waiting?.unref();
296
+ }
249
297
  stop(run) {
250
298
  if (run.process !== null)
251
299
  killTree(run.process);
@@ -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.act('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,188 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, mkdir, readdir, rm, stat } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import { house } from './api.js';
5
+ import { earlierPrefix, enrolled, kitHome, readDisconnected, oneFolder, readConfiguration, readEnrolment, readHome, storedConfiguration, workspaceRoot, writeConfiguration, writeHome, } from './home.js';
6
+ import { askOwner, holdOwner } from './owner.js';
7
+ import { placeSkillSet } from './skills.js';
8
+ import { followRoot, merged, present, within } from './workspace.js';
9
+ const FOLDERS = ['agents', 'local-copies'];
10
+ const RECORDS = join('local-copies', 'rooms');
11
+ const MOVE = 'workspace-move.json';
12
+ const WORKING = 'an Agent is working; change the workspace once its turn ends';
13
+ const LOGGED_OUT = "Kit is logged out, so it cannot tell which Agents' folders their owners chose; run kit login, then change its workspace";
14
+ export const SETTINGS_USAGE = 'usage: kit settings [skills on|off | workspace <absolute path>]';
15
+ export async function enrolledRoutes() {
16
+ if (enrolled())
17
+ return (await house.act('agents/desired/list', {})).routes;
18
+ return (await readDisconnected()) === null ? [] : null;
19
+ }
20
+ const IDLE = { working: () => false, end: () => undefined, routes: enrolledRoutes };
21
+ export async function heldSettings() {
22
+ return { skills: (await readConfiguration()).skills, workspace: workspaceRoot() };
23
+ }
24
+ function records() {
25
+ return join(kitHome(), RECORDS);
26
+ }
27
+ function placing(kept) {
28
+ return (source, entry) => {
29
+ if ((dirname(source) === records() && entry.isFile()) || kept.includes(source))
30
+ return 'stays';
31
+ return [records(), ...kept].some((folder) => within(folder, source)) ? 'opens' : 'moves';
32
+ };
33
+ }
34
+ function causeOf(error) {
35
+ return error instanceof Error ? error.message : String(error);
36
+ }
37
+ async function recordsOnly(folder) {
38
+ const entries = await readdir(folder);
39
+ if (entries.some((name) => name !== 'rooms'))
40
+ return false;
41
+ if (entries.length === 0)
42
+ return true;
43
+ return (await readdir(join(folder, 'rooms'), { withFileTypes: true })).every((entry) => entry.isFile());
44
+ }
45
+ async function writable(root) {
46
+ for (let at = root;; at = dirname(at)) {
47
+ const found = await stat(at).catch((error) => {
48
+ if (error.code === 'ENOENT')
49
+ return null;
50
+ throw error;
51
+ });
52
+ if (found !== null) {
53
+ return found.isDirectory() && access(at, constants.W_OK | constants.X_OK).then(() => true, () => false);
54
+ }
55
+ if (dirname(at) === at)
56
+ return false;
57
+ }
58
+ }
59
+ async function refusedRoot(from, to) {
60
+ for (const name of FOLDERS) {
61
+ const moving = join(from, name);
62
+ if (within(to, moving))
63
+ return `${to} is inside ${moving}, which the change moves`;
64
+ }
65
+ if (!(await writable(to)))
66
+ return `this account cannot write ${to}`;
67
+ for (const name of FOLDERS) {
68
+ const held = join(to, name);
69
+ if ((await present(held)) === null)
70
+ continue;
71
+ if (name === 'local-copies' && to === kitHome() && (await recordsOnly(held)))
72
+ continue;
73
+ return `${to} already holds ${held}`;
74
+ }
75
+ return null;
76
+ }
77
+ async function forward({ from, to, kept = [] }) {
78
+ await mkdir(to, { recursive: true, mode: 0o700 });
79
+ for (const name of FOLDERS)
80
+ await merged(join(from, name), join(to, name), placing(kept));
81
+ await followRoot(records(), from, to, kept);
82
+ await writeConfiguration({ ...(await storedConfiguration()), workspace: to });
83
+ await rm(join(kitHome(), MOVE), { force: true });
84
+ }
85
+ async function backward({ from, to, kept = [] }) {
86
+ for (const name of FOLDERS)
87
+ await merged(join(to, name), join(from, name), placing([]));
88
+ await followRoot(records(), to, from, kept);
89
+ await rm(join(kitHome(), MOVE), { force: true });
90
+ }
91
+ async function finished(move) {
92
+ try {
93
+ await forward(move);
94
+ return null;
95
+ }
96
+ catch (error) {
97
+ const cause = causeOf(error);
98
+ try {
99
+ await backward(move);
100
+ return cause;
101
+ }
102
+ catch (again) {
103
+ return `${cause}; its folders could not all go back to ${move.from} (${causeOf(again)}), so Kit moves them again when it next starts`;
104
+ }
105
+ }
106
+ }
107
+ export async function resumeWorkspaceMove() {
108
+ const move = await readHome(MOVE);
109
+ if (move === null)
110
+ return;
111
+ process.stderr.write(`kit: moving the workspace ${move.from} to ${move.to}, as a change that did not finish asked\n`);
112
+ const failure = await finished(move);
113
+ if (failure !== null)
114
+ process.stderr.write(`kit: the workspace could not be moved to ${move.to}: ${failure}\n`);
115
+ }
116
+ async function changeSkills(on) {
117
+ const stored = await storedConfiguration();
118
+ await writeConfiguration({ ...stored, skills: on });
119
+ const enrolment = await readEnrolment();
120
+ if (enrolment !== null)
121
+ await placeSkillSet(enrolment.house);
122
+ }
123
+ export async function applySettings(change, kit) {
124
+ const from = workspaceRoot();
125
+ let move = null;
126
+ if (change.workspace !== undefined) {
127
+ if (earlierPrefix() !== null) {
128
+ return { refused: `Kit runs where an earlier install placed it; its workspace changes once Kit moves into ${oneFolder()}`, ended: false };
129
+ }
130
+ if (!isAbsolute(change.workspace))
131
+ return { refused: `${change.workspace} is not an absolute path`, ended: false };
132
+ const to = resolve(change.workspace);
133
+ if (to !== from) {
134
+ const refused = await refusedRoot(from, to);
135
+ if (refused !== null)
136
+ return { refused, ended: false };
137
+ const routes = await kit.routes();
138
+ if (routes === null)
139
+ return { refused: LOGGED_OUT, ended: false };
140
+ const agents = join(from, 'agents');
141
+ const copies = join(from, 'local-copies');
142
+ const kept = routes
143
+ .filter(({ agent_id, working_directory }) => resolve(working_directory) !== join(agents, agent_id))
144
+ .map(({ working_directory }) => resolve(working_directory))
145
+ .filter((folder) => folder.startsWith(`${agents}/`) || folder.startsWith(`${copies}/`));
146
+ move = { from, to, kept };
147
+ }
148
+ }
149
+ if (move !== null) {
150
+ if (kit.working())
151
+ return { refused: WORKING, ended: false };
152
+ kit.end();
153
+ await writeHome(MOVE, move);
154
+ const failure = await finished(move);
155
+ if (failure !== null)
156
+ return { refused: `the workspace could not be moved to ${move.to}: ${failure}`, ended: true };
157
+ }
158
+ if (change.skills !== undefined)
159
+ await changeSkills(change.skills);
160
+ return { settings: await heldSettings(), moved: move !== null };
161
+ }
162
+ function changeOf(operands) {
163
+ const [name, value, ...rest] = operands;
164
+ if (name === undefined)
165
+ return null;
166
+ if (rest.length === 0 && name === 'skills' && (value === 'on' || value === 'off'))
167
+ return { skills: value === 'on' };
168
+ if (rest.length === 0 && name === 'workspace' && value !== undefined)
169
+ return { workspace: value };
170
+ throw new Error(SETTINGS_USAGE);
171
+ }
172
+ async function appliedHere(change) {
173
+ const lock = await holdOwner();
174
+ try {
175
+ await resumeWorkspaceMove();
176
+ return await applySettings(change, IDLE);
177
+ }
178
+ finally {
179
+ lock.close();
180
+ }
181
+ }
182
+ export async function kitSettings(operands) {
183
+ const change = changeOf(operands);
184
+ const answer = change === null ? { settings: await heldSettings(), moved: false } : ((await askOwner('/settings', change)) ?? (await appliedHere(change)));
185
+ if ('refused' in answer)
186
+ throw new Error(answer.refused);
187
+ process.stdout.write(`skills ${answer.settings.skills ? 'on' : 'off'}\nworkspace ${answer.settings.workspace}\n`);
188
+ }