@agentshouse/kit 0.2.1-ccf188e02985d → 0.2.1-cd423aab3dbcc

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 (164) hide show
  1. package/README.md +35 -42
  2. package/dist/acp.js +66 -12
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +122 -53
  5. package/dist/api.js +15 -10
  6. package/dist/binaries.js +60 -0
  7. package/dist/bridge.js +100 -45
  8. package/dist/building.js +50 -0
  9. package/dist/calls.js +88 -0
  10. package/dist/chunks.js +54 -0
  11. package/dist/clis.js +62 -50
  12. package/dist/connect.js +121 -0
  13. package/dist/connection.js +120 -0
  14. package/dist/content.js +106 -0
  15. package/dist/conversations.js +617 -240
  16. package/dist/copies.js +1277 -623
  17. package/dist/earlier.js +273 -0
  18. package/dist/end.js +12 -5
  19. package/dist/events.js +549 -281
  20. package/dist/files.js +206 -38
  21. package/dist/git.js +2 -72
  22. package/dist/grok.js +39 -0
  23. package/dist/home.js +86 -29
  24. package/dist/house-cli.js +180 -189
  25. package/dist/house-main.js +3 -3
  26. package/dist/instructions.js +29 -11
  27. package/dist/keys.js +238 -0
  28. package/dist/kit-cli.js +18 -8
  29. package/dist/kit-main.js +3 -3
  30. package/dist/login.js +36 -22
  31. package/dist/logout.js +2 -2
  32. package/dist/manifest.js +75 -0
  33. package/dist/mcp.js +47 -7
  34. package/dist/owner.js +46 -0
  35. package/dist/placement.js +15 -20
  36. package/dist/refusals.js +50 -23
  37. package/dist/relay.js +21 -0
  38. package/dist/resident.js +141 -90
  39. package/dist/scope.js +15 -4
  40. package/dist/scripts.js +319 -0
  41. package/dist/secret-input.js +1 -1
  42. package/dist/settings.js +247 -0
  43. package/dist/sign-in.js +67 -21
  44. package/dist/silence.js +28 -0
  45. package/dist/skills.js +42 -97
  46. package/dist/supervisor.js +163 -0
  47. package/dist/transcription.js +88 -45
  48. package/dist/update.js +118 -120
  49. package/dist/wire.js +30 -4
  50. package/dist/work.js +27 -2
  51. package/dist/workspace.js +113 -0
  52. package/package.json +25 -22
  53. package/dist/authority-main.js +0 -22
  54. package/dist/bootstrap.json +0 -24
  55. package/dist/chatgpt.js +0 -32
  56. package/dist/clis-main.js +0 -23
  57. package/dist/configure-main.js +0 -6
  58. package/dist/enrol-main.js +0 -10
  59. package/dist/git-main.js +0 -153
  60. package/dist/inputs.js +0 -37
  61. package/dist/parts.js +0 -82
  62. package/dist/service-main.js +0 -9
  63. package/dist/service.js +0 -55
  64. package/dist/stream.js +0 -123
  65. package/dist/translate.js +0 -51
  66. package/how-we-work.md +0 -33
  67. package/skills/ask-matt/LICENSE +0 -21
  68. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  69. package/skills/ask-matt/SKILL.md +0 -97
  70. package/skills/ask-matt/agents/openai.yaml +0 -5
  71. package/skills/code-review/LICENSE +0 -21
  72. package/skills/code-review/SKILL.md +0 -89
  73. package/skills/code-review/agents/openai.yaml +0 -3
  74. package/skills/codebase-design/DEEPENING.md +0 -37
  75. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  76. package/skills/codebase-design/LICENSE +0 -21
  77. package/skills/codebase-design/SKILL.md +0 -114
  78. package/skills/codebase-design/agents/openai.yaml +0 -3
  79. package/skills/diagnosing-bugs/LICENSE +0 -21
  80. package/skills/diagnosing-bugs/SKILL.md +0 -138
  81. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  82. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  83. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  84. package/skills/domain-modeling/GLOSSARY-FORMAT.md +0 -60
  85. package/skills/domain-modeling/LICENSE +0 -21
  86. package/skills/domain-modeling/SKILL.md +0 -74
  87. package/skills/domain-modeling/agents/openai.yaml +0 -3
  88. package/skills/grill-me/LICENSE +0 -21
  89. package/skills/grill-me/SKILL.md +0 -7
  90. package/skills/grill-me/agents/openai.yaml +0 -5
  91. package/skills/grill-with-docs/LICENSE +0 -21
  92. package/skills/grill-with-docs/SKILL.md +0 -7
  93. package/skills/grill-with-docs/agents/openai.yaml +0 -5
  94. package/skills/grilling/LICENSE +0 -21
  95. package/skills/grilling/SKILL.md +0 -30
  96. package/skills/grilling/agents/openai.yaml +0 -3
  97. package/skills/handoff/LICENSE +0 -21
  98. package/skills/handoff/SKILL.md +0 -16
  99. package/skills/handoff/agents/openai.yaml +0 -5
  100. package/skills/implement/LICENSE +0 -21
  101. package/skills/implement/SKILL.md +0 -17
  102. package/skills/implement/agents/openai.yaml +0 -5
  103. package/skills/implement-spec/LICENSE +0 -21
  104. package/skills/implement-spec/SKILL.md +0 -40
  105. package/skills/implement-spec/agents/openai.yaml +0 -5
  106. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  107. package/skills/improve-codebase-architecture/LICENSE +0 -21
  108. package/skills/improve-codebase-architecture/SKILL.md +0 -71
  109. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
  110. package/skills/pr/CREDITS.md +0 -3
  111. package/skills/pr/LICENSE +0 -21
  112. package/skills/pr/SKILL.md +0 -170
  113. package/skills/pr/agents/openai.yaml +0 -3
  114. package/skills/prototype/LICENSE +0 -21
  115. package/skills/prototype/LOGIC.md +0 -67
  116. package/skills/prototype/SKILL.md +0 -26
  117. package/skills/prototype/UI.md +0 -112
  118. package/skills/prototype/agents/openai.yaml +0 -3
  119. package/skills/research/LICENSE +0 -21
  120. package/skills/research/SKILL.md +0 -12
  121. package/skills/research/agents/openai.yaml +0 -3
  122. package/skills/retro/LICENSE +0 -21
  123. package/skills/retro/SKILL.md +0 -44
  124. package/skills/retro/agents/openai.yaml +0 -5
  125. package/skills/tdd/LICENSE +0 -21
  126. package/skills/tdd/SKILL.md +0 -38
  127. package/skills/tdd/agents/openai.yaml +0 -3
  128. package/skills/tdd/mocking.md +0 -59
  129. package/skills/tdd/tests.md +0 -77
  130. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  131. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  132. package/skills/teach/LICENSE +0 -21
  133. package/skills/teach/MISSION-FORMAT.md +0 -31
  134. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  135. package/skills/teach/SKILL.md +0 -140
  136. package/skills/teach/agents/openai.yaml +0 -5
  137. package/skills/to-questionnaire/LICENSE +0 -21
  138. package/skills/to-questionnaire/SKILL.md +0 -54
  139. package/skills/to-questionnaire/agents/openai.yaml +0 -5
  140. package/skills/to-spec/LICENSE +0 -21
  141. package/skills/to-spec/SKILL.md +0 -75
  142. package/skills/to-spec/agents/openai.yaml +0 -5
  143. package/skills/to-tickets/LICENSE +0 -21
  144. package/skills/to-tickets/SKILL.md +0 -105
  145. package/skills/to-tickets/agents/openai.yaml +0 -5
  146. package/skills/triage/AGENT-BRIEF.md +0 -207
  147. package/skills/triage/LICENSE +0 -21
  148. package/skills/triage/OUT-OF-SCOPE.md +0 -105
  149. package/skills/triage/SKILL.md +0 -112
  150. package/skills/triage/agents/openai.yaml +0 -5
  151. package/skills/wait-what/LICENSE +0 -21
  152. package/skills/wait-what/SKILL.md +0 -7
  153. package/skills/wait-what/agents/openai.yaml +0 -5
  154. package/skills/wayfinder/LICENSE +0 -21
  155. package/skills/wayfinder/SKILL.md +0 -128
  156. package/skills/wayfinder/agents/openai.yaml +0 -5
  157. package/skills/wizard/LICENSE +0 -21
  158. package/skills/wizard/SKILL.md +0 -44
  159. package/skills/wizard/agents/openai.yaml +0 -3
  160. package/skills/wizard/template.sh +0 -223
  161. package/skills/writing-for-agents/LICENSE +0 -21
  162. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  163. package/skills/writing-for-agents/SKILL.md +0 -81
  164. package/skills/writing-for-agents/agents/openai.yaml +0 -3
@@ -0,0 +1,319 @@
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 { openRunBridge } from './bridge.js';
9
+ import { loginPath, onLoginPath } from './clis.js';
10
+ import { kitHome } from './home.js';
11
+ import { childEnvironment } from './relay.js';
12
+ import { killTree } from './scope.js';
13
+ const TERMINAL = 'xterm-256color';
14
+ const FIRST_SIZE = { cols: 80, rows: 24 };
15
+ const SIGNALLED = 128;
16
+ const NEWLINE = 0x0a;
17
+ const NO_BASH = "bash is not on the login shell's PATH";
18
+ const LOST = { refused: 'the Kit lost its connection to House' };
19
+ const UNSENT_CHARS = 64_000;
20
+ // 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.
21
+ const RETURN_MS = 120_000;
22
+ // 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.
23
+ const TAKEN_ON_MS = 10_000;
24
+ function causeOf(error) {
25
+ return error instanceof Error ? error.message : String(error);
26
+ }
27
+ function failed(plan, cause) {
28
+ process.stderr.write(`kit: ${plan.named} could not start: ${cause}\n`);
29
+ return { refused: `the script could not start: ${cause}` };
30
+ }
31
+ function planned(call) {
32
+ if (call.kind === 'run_wizard')
33
+ return { named: 'a Web Wizard', script: call.script, terminal: 'page', function: null };
34
+ return {
35
+ named: 'an Environment function',
36
+ script: call.script,
37
+ terminal: call.terminal ? 'at once' : null,
38
+ function: { input: call.input, timeCap: call.time_cap, outputCap: call.output_cap },
39
+ };
40
+ }
41
+ function inputs() {
42
+ return join(kitHome(), 'inputs');
43
+ }
44
+ async function inputFile(value) {
45
+ await mkdir(inputs(), { recursive: true, mode: 0o700 });
46
+ const path = join(inputs(), `${randomUUID()}.json`);
47
+ await writeFile(path, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
48
+ return path;
49
+ }
50
+ export function removeInputs() {
51
+ rmSync(inputs(), { recursive: true, force: true });
52
+ }
53
+ function latest(screen) {
54
+ if (screen.length <= UNSENT_CHARS)
55
+ return screen;
56
+ const line = screen.indexOf('\n', screen.length - UNSENT_CHARS);
57
+ return screen.slice(line < 0 ? screen.length - UNSENT_CHARS : line + 1);
58
+ }
59
+ function struck(line, typed) {
60
+ return typed.some((typedLine) => line.includes(typedLine));
61
+ }
62
+ class KeptOutput {
63
+ cap;
64
+ typedText = '';
65
+ text = '';
66
+ bytes = 0;
67
+ line = '';
68
+ lineBytes = 0;
69
+ dropping = false;
70
+ cut = false;
71
+ constructor(cap) {
72
+ this.cap = cap;
73
+ }
74
+ typed(data) {
75
+ this.typedText += data;
76
+ }
77
+ add(data) {
78
+ const pieces = data.split('\n');
79
+ const rest = pieces.pop();
80
+ for (const piece of pieces)
81
+ this.ended(piece);
82
+ this.extend(rest);
83
+ }
84
+ kept() {
85
+ const typed = this.typedLines(true);
86
+ this.text = [...this.text.split(/(?<=\n)/), this.line].filter((line) => line !== '' && !struck(line, typed)).join('');
87
+ this.bytes = Buffer.byteLength(this.text);
88
+ this.trim();
89
+ return { output: this.text, cut: this.cut };
90
+ }
91
+ typedLines(all) {
92
+ const lines = this.typedText.split(/\r\n|\r|\n/);
93
+ if (!all)
94
+ lines.pop();
95
+ return lines.filter((line) => line !== '');
96
+ }
97
+ ended(piece) {
98
+ const line = `${this.line}${piece}\n`;
99
+ const dropped = this.dropping;
100
+ this.line = '';
101
+ this.lineBytes = 0;
102
+ this.dropping = false;
103
+ if (dropped || struck(line, this.typedLines(false)))
104
+ return;
105
+ this.text += line;
106
+ this.bytes += Buffer.byteLength(line);
107
+ if (this.bytes > 2 * this.cap)
108
+ this.trim();
109
+ }
110
+ extend(piece) {
111
+ if (this.dropping)
112
+ return;
113
+ this.line += piece;
114
+ this.lineBytes += Buffer.byteLength(piece);
115
+ if (this.lineBytes <= this.cap)
116
+ return;
117
+ this.text = '';
118
+ this.bytes = 0;
119
+ this.line = '';
120
+ this.lineBytes = 0;
121
+ this.dropping = true;
122
+ this.cut = true;
123
+ }
124
+ trim() {
125
+ if (this.bytes <= this.cap)
126
+ return;
127
+ const bytes = Buffer.from(this.text);
128
+ const start = bytes.indexOf(NEWLINE, bytes.length - this.cap - 1) + 1;
129
+ this.text = bytes.subarray(start).toString('utf8');
130
+ this.bytes = bytes.length - start;
131
+ this.cut = true;
132
+ }
133
+ }
134
+ export class Scripts {
135
+ calls;
136
+ send;
137
+ house;
138
+ copies;
139
+ runs = new Map();
140
+ constructor(calls, send, house, copies) {
141
+ this.calls = calls;
142
+ this.send = send;
143
+ this.house = house;
144
+ this.copies = copies;
145
+ }
146
+ start(call) {
147
+ void this.calls.carry(call.input_id, () => this.run(call.input_id, planned(call)));
148
+ }
149
+ notified(oneWayCall) {
150
+ if (!('wizard' in oneWayCall))
151
+ return;
152
+ const run = this.runs.get(oneWayCall.wizard);
153
+ if (run === undefined)
154
+ return;
155
+ this.waited(run, null);
156
+ if (oneWayCall.type === 'wizard_input')
157
+ this.typed(run, oneWayCall.data);
158
+ if (oneWayCall.type === 'wizard_size')
159
+ this.resized(run, { cols: oneWayCall.cols, rows: oneWayCall.rows });
160
+ if (oneWayCall.type === 'wizard_end' && run.plan.terminal === 'page')
161
+ this.end(run, {});
162
+ }
163
+ disconnected() {
164
+ for (const run of this.runs.values()) {
165
+ if (run.plan.terminal === 'page')
166
+ this.waited(run, RETURN_MS);
167
+ else
168
+ this.end(run, LOST);
169
+ }
170
+ }
171
+ connected() {
172
+ for (const [id, run] of this.runs) {
173
+ if (run.waiting === null)
174
+ continue;
175
+ this.waited(run, TAKEN_ON_MS);
176
+ if (run.unsent !== '' && this.send({ type: 'wizard_output', wizard: id, data: run.unsent }))
177
+ run.unsent = '';
178
+ }
179
+ }
180
+ async run(id, plan) {
181
+ const size = plan.terminal === 'page' ? null : FIRST_SIZE;
182
+ const output = plan.function === null ? null : new KeptOutput(plan.function.outputCap);
183
+ const run = {
184
+ plan,
185
+ input: null,
186
+ bridge: null,
187
+ closed: new AbortController(),
188
+ output,
189
+ process: null,
190
+ pipes: [],
191
+ terminal: null,
192
+ size,
193
+ typed: [],
194
+ unsent: '',
195
+ waiting: null,
196
+ ended: null,
197
+ sized: Promise.withResolvers(),
198
+ };
199
+ if (size !== null)
200
+ run.sized.resolve();
201
+ this.runs.set(id, run);
202
+ try {
203
+ return { result: await this.ran(id, run), release: plan.function !== null };
204
+ }
205
+ finally {
206
+ this.runs.delete(id);
207
+ run.bridge?.close();
208
+ if (run.input !== null)
209
+ await rm(run.input, { force: true });
210
+ }
211
+ }
212
+ async ran(id, run) {
213
+ const { plan, output } = run;
214
+ let exited;
215
+ try {
216
+ const { spawn } = await import('@lydell/node-pty');
217
+ const shell = await onLoginPath('bash');
218
+ if (shell === null)
219
+ return failed(plan, NO_BASH);
220
+ const path = await loginPath();
221
+ await run.sized.promise;
222
+ if (plan.function !== null) {
223
+ run.input = await inputFile(plan.function.input);
224
+ run.bridge = await openRunBridge(this.house, this.copies, id, run.closed.signal);
225
+ }
226
+ if (run.ended !== null)
227
+ return run.ended;
228
+ const environment = {
229
+ ...childEnvironment(),
230
+ ...run.bridge?.env,
231
+ PATH: path,
232
+ ...(run.input === null ? {} : { HOUSE_INPUT: run.input }),
233
+ };
234
+ if (plan.terminal === null) {
235
+ ({ exited } = await this.piped(plan.script, shell, environment, run));
236
+ }
237
+ else {
238
+ const terminal = spawn(shell, ['-c', plan.script], { name: TERMINAL, ...run.size, cwd: process.cwd(), env: environment });
239
+ run.process = terminal;
240
+ run.terminal = terminal;
241
+ terminal.onData((data) => {
242
+ if (!this.send({ type: 'wizard_output', wizard: id, data }))
243
+ run.unsent = latest(`${run.unsent}${data}`);
244
+ output?.add(data);
245
+ });
246
+ for (const data of run.typed.splice(0))
247
+ terminal.write(data);
248
+ exited = new Promise((resolve) => terminal.onExit(({ exitCode, signal }) => resolve(signal ? SIGNALLED + signal : exitCode)));
249
+ }
250
+ }
251
+ catch (error) {
252
+ return run.ended ?? failed(plan, causeOf(error));
253
+ }
254
+ let timedOut = false;
255
+ // 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.
256
+ const capped = plan.function === null ? undefined : setTimeout(() => {
257
+ timedOut = true;
258
+ this.stop(run);
259
+ }, plan.function.timeCap * 1000);
260
+ const code = await exited;
261
+ clearTimeout(capped);
262
+ if (run.ended !== null)
263
+ return run.ended;
264
+ if (output === null)
265
+ return { exit_code: code };
266
+ const kept = output.kept();
267
+ return timedOut ? { timed_out: true, ...kept } : { exit_code: code, ...kept };
268
+ }
269
+ async piped(script, shell, environment, run) {
270
+ const child = spawnPiped(shell, ['-c', script], { cwd: process.cwd(), env: environment, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
271
+ const exited = new Promise((resolve) => child.once('close', (code, signal) => resolve(signal === null ? code : SIGNALLED + constants.signals[signal])));
272
+ await once(child, 'spawn');
273
+ run.process = { pid: child.pid };
274
+ run.pipes = [child.stdout, child.stderr];
275
+ for (const pipe of run.pipes) {
276
+ pipe.setEncoding('utf8');
277
+ pipe.on('data', (data) => run.output.add(data));
278
+ }
279
+ if (run.ended !== null)
280
+ this.stop(run);
281
+ return { exited };
282
+ }
283
+ typed(run, data) {
284
+ run.output?.typed(data);
285
+ if (run.terminal === null)
286
+ run.typed.push(data);
287
+ else
288
+ run.terminal.write(data);
289
+ }
290
+ resized(run, size) {
291
+ run.size = size;
292
+ run.sized.resolve();
293
+ try {
294
+ run.terminal?.resize(size.cols, size.rows);
295
+ }
296
+ catch { }
297
+ }
298
+ end(run, result) {
299
+ if (run.ended !== null)
300
+ return;
301
+ this.waited(run, null);
302
+ run.ended = result;
303
+ run.closed.abort();
304
+ run.sized.resolve();
305
+ this.stop(run);
306
+ }
307
+ waited(run, ms) {
308
+ if (run.waiting !== null)
309
+ clearTimeout(run.waiting);
310
+ run.waiting = ms === null ? null : setTimeout(() => this.end(run, LOST), ms);
311
+ run.waiting?.unref();
312
+ }
313
+ stop(run) {
314
+ if (run.process !== null)
315
+ killTree(run.process);
316
+ for (const pipe of run.pipes)
317
+ pipe.destroy();
318
+ }
319
+ }
@@ -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,247 @@
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 { KIT_RELEASE } from './clis.js';
6
+ import { LocalCopies } from './copies.js';
7
+ import { earlierPrefix, enrolled, houseFolder, kitHome, readDisconnected, oneFolder, readConfiguration, readEnrolment, readHome, storedConfiguration, workspaceRoot, writeConfiguration, writeHome, } from './home.js';
8
+ import { askOwner, holdOwner } from './owner.js';
9
+ import { placeSkillSet } from './skills.js';
10
+ import { followRoot, merged, present, within } from './workspace.js';
11
+ const FOLDERS = ['agents', 'rooms'];
12
+ const RECORDS = join('local-copies', 'rooms');
13
+ const MOVE = 'workspace-move.json';
14
+ const WORKING = 'an Agent is working; change the workspace once its turn ends';
15
+ const UNCHOSEN = "Kit is logged out, so it cannot tell which Agents' folders their owners chose";
16
+ const LOGGED_OUT = `${UNCHOSEN}; run kit login, then change its workspace`;
17
+ export const SETTINGS_USAGE = 'usage: kit settings [skills on|off | workspace <absolute path>]';
18
+ export async function enrolledRoutes() {
19
+ if (enrolled())
20
+ return (await house.act('agents/desired/list', {})).routes;
21
+ return (await readDisconnected()) === null ? [] : null;
22
+ }
23
+ export async function launchDirectories() {
24
+ return ((await enrolledRoutes()) ?? []).map(({ working_directory }) => resolve(working_directory));
25
+ }
26
+ const IDLE = { working: () => false, end: () => undefined, routes: enrolledRoutes };
27
+ export async function heldSettings() {
28
+ return { skills: (await readConfiguration()).skills, workspace: workspaceRoot() };
29
+ }
30
+ function records() {
31
+ return join(kitHome(), RECORDS);
32
+ }
33
+ function placing(kept) {
34
+ return (source) => {
35
+ if (kept.includes(source))
36
+ return 'stays';
37
+ return kept.some((folder) => within(folder, source)) ? 'opens' : 'moves';
38
+ };
39
+ }
40
+ function causeOf(error) {
41
+ return error instanceof Error ? error.message : String(error);
42
+ }
43
+ async function writable(root) {
44
+ for (let at = root;; at = dirname(at)) {
45
+ const found = await stat(at).catch((error) => {
46
+ if (error.code === 'ENOENT')
47
+ return null;
48
+ throw error;
49
+ });
50
+ if (found !== null) {
51
+ return found.isDirectory() && access(at, constants.W_OK | constants.X_OK).then(() => true, () => false);
52
+ }
53
+ if (dirname(at) === at)
54
+ return false;
55
+ }
56
+ }
57
+ async function refusedRoot(from, to) {
58
+ for (const name of FOLDERS) {
59
+ const moving = join(from, name);
60
+ if (within(to, moving))
61
+ return `${to} is inside ${moving}, which the change moves`;
62
+ }
63
+ if (!(await writable(to)))
64
+ return `this account cannot write ${to}`;
65
+ for (const name of FOLDERS) {
66
+ const held = join(to, name);
67
+ if ((await present(held)) === null)
68
+ continue;
69
+ return `${to} already holds ${held}`;
70
+ }
71
+ return null;
72
+ }
73
+ async function forward({ from, to, kept = [] }) {
74
+ await mkdir(to, { recursive: true, mode: 0o700 });
75
+ for (const name of FOLDERS)
76
+ await merged(join(from, name), join(to, name), placing(kept));
77
+ await followRoot(records(), from, to, kept);
78
+ await writeConfiguration({ ...(await storedConfiguration()), workspace: to });
79
+ await rm(join(kitHome(), MOVE), { force: true });
80
+ }
81
+ async function backward({ from, to, kept = [] }) {
82
+ for (const name of FOLDERS)
83
+ await merged(join(to, name), join(from, name), placing([]));
84
+ await followRoot(records(), to, from, kept);
85
+ await rm(join(kitHome(), MOVE), { force: true });
86
+ }
87
+ async function finished(move) {
88
+ try {
89
+ await forward(move);
90
+ return null;
91
+ }
92
+ catch (error) {
93
+ const cause = causeOf(error);
94
+ try {
95
+ await backward(move);
96
+ return cause;
97
+ }
98
+ catch (again) {
99
+ return `${cause}; its folders could not all go back to ${move.from} (${causeOf(again)}), so Kit moves them again when it next starts`;
100
+ }
101
+ }
102
+ }
103
+ export async function resumeWorkspaceMove() {
104
+ const move = await readHome(MOVE);
105
+ if (move === null)
106
+ return;
107
+ process.stderr.write(`kit: moving the workspace ${move.from} to ${move.to}, as a change that did not finish asked\n`);
108
+ const failure = await finished(move);
109
+ if (failure !== null)
110
+ process.stderr.write(`kit: the workspace could not be moved to ${move.to}: ${failure}\n`);
111
+ }
112
+ export const HOUSE_NOT_KITS = `${houseFolder()} holds what is not Kit's; move it elsewhere, then run this command again`;
113
+ async function free(folder, from) {
114
+ if ((await present(folder)) !== null) {
115
+ const held = await stat(folder).catch(() => null);
116
+ if (held === null || !held.isDirectory() || (await readdir(folder)).length > 0)
117
+ return false;
118
+ }
119
+ return (await refusedRoot(from, folder)) === null;
120
+ }
121
+ async function earlierLayout(root) {
122
+ const copies = await readdir(join(root, RECORDS), { withFileTypes: true }).catch(() => []);
123
+ if (copies.some((entry) => entry.isDirectory() && !entry.name.startsWith('.')))
124
+ return true;
125
+ return root === kitHome() && (await present(join(root, 'agents'))) !== null && (await present(join(root, 'rooms'))) === null;
126
+ }
127
+ export async function houseRoot() {
128
+ if (await earlierLayout(kitHome()))
129
+ return kitHome();
130
+ return (await free(houseFolder(), kitHome())) ? houseFolder() : null;
131
+ }
132
+ function chosenFolders(routes, from) {
133
+ const agents = join(from, 'agents');
134
+ const roots = [agents, join(from, 'rooms'), join(from, RECORDS)];
135
+ return routes
136
+ .filter(({ agent_id, working_directory }) => resolve(working_directory) !== join(agents, agent_id))
137
+ .map(({ working_directory }) => resolve(working_directory))
138
+ .filter((folder) => roots.some((root) => folder.startsWith(`${root}/`)));
139
+ }
140
+ export async function moveIntoHouse(copies) {
141
+ if (earlierPrefix() !== null)
142
+ return null;
143
+ const stored = await storedConfiguration();
144
+ const from = stored.workspace ?? kitHome();
145
+ if (!(await earlierLayout(from))) {
146
+ if (stored.workspace !== undefined)
147
+ return null;
148
+ const root = await houseRoot();
149
+ if (root === null)
150
+ throw new Error(HOUSE_NOT_KITS);
151
+ await writeConfiguration({ ...stored, workspace: root });
152
+ return null;
153
+ }
154
+ if (stored.workspace === undefined)
155
+ await writeConfiguration({ ...stored, workspace: from });
156
+ const routes = await enrolledRoutes().catch((error) => {
157
+ process.stderr.write(`kit: the workspace stays at ${from} and moves at the next start: ${causeOf(error)}\n`);
158
+ return undefined;
159
+ });
160
+ if (routes === undefined)
161
+ return null;
162
+ if (routes === null) {
163
+ process.stderr.write(`kit: the workspace stays at ${from} and moves at the next start: ${UNCHOSEN}; run kit login\n`);
164
+ return null;
165
+ }
166
+ const chosen = chosenFolders(routes, from);
167
+ const to = from === kitHome() && (await free(houseFolder(), from)) ? houseFolder() : from;
168
+ const laid = await copies.laidOut(join(from, RECORDS), join(from, 'rooms'), chosen);
169
+ if (to === from)
170
+ return laid.moved ? `Kit ${KIT_RELEASE} laid out its workspace ${from}; its supervisor starts it again` : null;
171
+ const move = { from, to, kept: [...chosen, ...laid.kept] };
172
+ await writeHome(MOVE, move);
173
+ const failure = await finished(move);
174
+ if (failure === null)
175
+ return `Kit ${KIT_RELEASE} moved its workspace to ${to}; its supervisor starts it there`;
176
+ return `the workspace could not be moved to ${to}: ${failure}; it stays at ${from} and its supervisor starts Kit again`;
177
+ }
178
+ async function changeSkills(on) {
179
+ const stored = await storedConfiguration();
180
+ await writeConfiguration({ ...stored, skills: on });
181
+ const enrolment = await readEnrolment();
182
+ if (enrolment !== null)
183
+ await placeSkillSet(enrolment.house);
184
+ }
185
+ export async function applySettings(change, kit) {
186
+ const from = workspaceRoot();
187
+ let move = null;
188
+ if (change.workspace !== undefined) {
189
+ if (earlierPrefix() !== null) {
190
+ return { refused: `Kit runs where an earlier install placed it; its workspace changes once Kit moves into ${oneFolder()}`, ended: false };
191
+ }
192
+ if (!isAbsolute(change.workspace))
193
+ return { refused: `${change.workspace} is not an absolute path`, ended: false };
194
+ const to = resolve(change.workspace);
195
+ if (to !== from) {
196
+ const refused = await refusedRoot(from, to);
197
+ if (refused !== null)
198
+ return { refused, ended: false };
199
+ const routes = await kit.routes();
200
+ if (routes === null)
201
+ return { refused: LOGGED_OUT, ended: false };
202
+ move = { from, to, kept: chosenFolders(routes, from) };
203
+ }
204
+ }
205
+ if (move !== null) {
206
+ if (kit.working())
207
+ return { refused: WORKING, ended: false };
208
+ kit.end();
209
+ await writeHome(MOVE, move);
210
+ const failure = await finished(move);
211
+ if (failure !== null)
212
+ return { refused: `the workspace could not be moved to ${move.to}: ${failure}`, ended: true };
213
+ }
214
+ if (change.skills !== undefined)
215
+ await changeSkills(change.skills);
216
+ return { settings: await heldSettings(), moved: move !== null };
217
+ }
218
+ function changeOf(operands) {
219
+ const [name, value, ...rest] = operands;
220
+ if (name === undefined)
221
+ return null;
222
+ if (rest.length === 0 && name === 'skills' && (value === 'on' || value === 'off'))
223
+ return { skills: value === 'on' };
224
+ if (rest.length === 0 && name === 'workspace' && value !== undefined)
225
+ return { workspace: value };
226
+ throw new Error(SETTINGS_USAGE);
227
+ }
228
+ async function appliedHere(change) {
229
+ const lock = await holdOwner();
230
+ try {
231
+ await resumeWorkspaceMove();
232
+ const copies = new LocalCopies(house, launchDirectories);
233
+ await copies.load();
234
+ await moveIntoHouse(copies);
235
+ return await applySettings(change, IDLE);
236
+ }
237
+ finally {
238
+ lock.close();
239
+ }
240
+ }
241
+ export async function kitSettings(operands) {
242
+ const change = changeOf(operands);
243
+ const answer = change === null ? { settings: await heldSettings(), moved: false } : ((await askOwner('/settings', change)) ?? (await appliedHere(change)));
244
+ if ('refused' in answer)
245
+ throw new Error(answer.refused);
246
+ process.stdout.write(`skills ${answer.settings.skills ? 'on' : 'off'}\nworkspace ${answer.settings.workspace}\n`);
247
+ }