@agentshouse/kit 0.2.1-ce3d2bb67177c → 0.2.1-ce46b2b55463f

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 (161) hide show
  1. package/README.md +31 -35
  2. package/dist/acp.js +56 -6
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +120 -51
  5. package/dist/api.js +11 -6
  6. package/dist/binaries.js +79 -0
  7. package/dist/bridge.js +30 -26
  8. package/dist/building.js +50 -0
  9. package/dist/calls.js +29 -4
  10. package/dist/chunks.js +49 -0
  11. package/dist/clis.js +61 -49
  12. package/dist/connect.js +108 -0
  13. package/dist/connection.js +33 -38
  14. package/dist/content.js +106 -0
  15. package/dist/conversations.js +325 -141
  16. package/dist/copies.js +720 -247
  17. package/dist/earlier.js +263 -0
  18. package/dist/end.js +4 -5
  19. package/dist/events.js +549 -281
  20. package/dist/files.js +110 -28
  21. package/dist/git-main.js +24 -29
  22. package/dist/git.js +89 -14
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +65 -29
  25. package/dist/house-cli.js +114 -159
  26. package/dist/house-main.js +3 -3
  27. package/dist/instructions.js +29 -11
  28. package/dist/keys.js +238 -0
  29. package/dist/kit-cli.js +16 -6
  30. package/dist/kit-main.js +3 -3
  31. package/dist/login.js +36 -20
  32. package/dist/logout.js +2 -2
  33. package/dist/mcp.js +38 -1
  34. package/dist/owner.js +46 -0
  35. package/dist/placement.js +9 -23
  36. package/dist/refusals.js +37 -21
  37. package/dist/relay.js +21 -0
  38. package/dist/resident.js +109 -65
  39. package/dist/scope.js +12 -4
  40. package/dist/scripts.js +303 -0
  41. package/dist/secret-input.js +1 -1
  42. package/dist/settings.js +188 -0
  43. package/dist/sign-in.js +49 -3
  44. package/dist/silence.js +28 -0
  45. package/dist/skills.js +41 -96
  46. package/dist/supervisor.js +163 -0
  47. package/dist/transcription.js +37 -25
  48. package/dist/translate.js +18 -9
  49. package/dist/update.js +115 -117
  50. package/dist/wire.js +19 -9
  51. package/dist/work.js +9 -2
  52. package/dist/workspace.js +103 -0
  53. package/package.json +25 -21
  54. package/dist/authority-main.js +0 -22
  55. package/dist/bootstrap.json +0 -24
  56. package/dist/chatgpt.js +0 -32
  57. package/dist/clis-main.js +0 -23
  58. package/dist/configure-main.js +0 -6
  59. package/dist/enrol-main.js +0 -10
  60. package/dist/parts.js +0 -82
  61. package/dist/service-main.js +0 -9
  62. package/dist/service.js +0 -55
  63. package/how-we-work.md +0 -33
  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 -97
  67. package/skills/ask-matt/agents/openai.yaml +0 -5
  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 -114
  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 -138
  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/GLOSSARY-FORMAT.md +0 -60
  82. package/skills/domain-modeling/LICENSE +0 -21
  83. package/skills/domain-modeling/SKILL.md +0 -74
  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 -7
  87. package/skills/grill-me/agents/openai.yaml +0 -5
  88. package/skills/grill-with-docs/LICENSE +0 -21
  89. package/skills/grill-with-docs/SKILL.md +0 -7
  90. package/skills/grill-with-docs/agents/openai.yaml +0 -5
  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 -16
  96. package/skills/handoff/agents/openai.yaml +0 -5
  97. package/skills/implement/LICENSE +0 -21
  98. package/skills/implement/SKILL.md +0 -17
  99. package/skills/implement/agents/openai.yaml +0 -5
  100. package/skills/implement-spec/LICENSE +0 -21
  101. package/skills/implement-spec/SKILL.md +0 -40
  102. package/skills/implement-spec/agents/openai.yaml +0 -5
  103. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  104. package/skills/improve-codebase-architecture/LICENSE +0 -21
  105. package/skills/improve-codebase-architecture/SKILL.md +0 -71
  106. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
  107. package/skills/pr/CREDITS.md +0 -3
  108. package/skills/pr/LICENSE +0 -21
  109. package/skills/pr/SKILL.md +0 -170
  110. package/skills/pr/agents/openai.yaml +0 -3
  111. package/skills/prototype/LICENSE +0 -21
  112. package/skills/prototype/LOGIC.md +0 -67
  113. package/skills/prototype/SKILL.md +0 -26
  114. package/skills/prototype/UI.md +0 -112
  115. package/skills/prototype/agents/openai.yaml +0 -3
  116. package/skills/research/LICENSE +0 -21
  117. package/skills/research/SKILL.md +0 -12
  118. package/skills/research/agents/openai.yaml +0 -3
  119. package/skills/retro/LICENSE +0 -21
  120. package/skills/retro/SKILL.md +0 -44
  121. package/skills/retro/agents/openai.yaml +0 -5
  122. package/skills/tdd/LICENSE +0 -21
  123. package/skills/tdd/SKILL.md +0 -38
  124. package/skills/tdd/agents/openai.yaml +0 -3
  125. package/skills/tdd/mocking.md +0 -59
  126. package/skills/tdd/tests.md +0 -77
  127. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  128. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  129. package/skills/teach/LICENSE +0 -21
  130. package/skills/teach/MISSION-FORMAT.md +0 -31
  131. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  132. package/skills/teach/SKILL.md +0 -140
  133. package/skills/teach/agents/openai.yaml +0 -5
  134. package/skills/to-questionnaire/LICENSE +0 -21
  135. package/skills/to-questionnaire/SKILL.md +0 -54
  136. package/skills/to-questionnaire/agents/openai.yaml +0 -5
  137. package/skills/to-spec/LICENSE +0 -21
  138. package/skills/to-spec/SKILL.md +0 -75
  139. package/skills/to-spec/agents/openai.yaml +0 -5
  140. package/skills/to-tickets/LICENSE +0 -21
  141. package/skills/to-tickets/SKILL.md +0 -105
  142. package/skills/to-tickets/agents/openai.yaml +0 -5
  143. package/skills/triage/AGENT-BRIEF.md +0 -207
  144. package/skills/triage/LICENSE +0 -21
  145. package/skills/triage/OUT-OF-SCOPE.md +0 -105
  146. package/skills/triage/SKILL.md +0 -112
  147. package/skills/triage/agents/openai.yaml +0 -5
  148. package/skills/wait-what/LICENSE +0 -21
  149. package/skills/wait-what/SKILL.md +0 -7
  150. package/skills/wait-what/agents/openai.yaml +0 -5
  151. package/skills/wayfinder/LICENSE +0 -21
  152. package/skills/wayfinder/SKILL.md +0 -128
  153. package/skills/wayfinder/agents/openai.yaml +0 -5
  154. package/skills/wizard/LICENSE +0 -21
  155. package/skills/wizard/SKILL.md +0 -44
  156. package/skills/wizard/agents/openai.yaml +0 -3
  157. package/skills/wizard/template.sh +0 -223
  158. package/skills/writing-for-agents/LICENSE +0 -21
  159. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  160. package/skills/writing-for-agents/SKILL.md +0 -81
  161. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/relay.js CHANGED
@@ -1,6 +1,11 @@
1
+ import { setGlobalProxyFromEnv } from 'node:http';
2
+ const PROXY = /^https?_proxy$/i;
3
+ const LOOPBACK = ['127.0.0.1', 'localhost', '::1'];
1
4
  let selected;
5
+ let restoreProxy;
2
6
  export function selectRelay(relay) {
3
7
  selected = relay === undefined || relay === '' ? null : relay;
8
+ proxyUnlessRelayed();
4
9
  }
5
10
  export function relayOrigin() {
6
11
  if (selected !== undefined)
@@ -8,6 +13,22 @@ export function relayOrigin() {
8
13
  const ambient = process.env.HOUSE_KIT_RELAY;
9
14
  return ambient === undefined || ambient === '' ? undefined : ambient;
10
15
  }
16
+ function unlessRelayed() {
17
+ if (relayOrigin() === undefined)
18
+ return { ...process.env };
19
+ return Object.fromEntries(Object.entries(process.env).filter(([name]) => !PROXY.test(name)));
20
+ }
21
+ export function proxyUnlessRelayed() {
22
+ restoreProxy?.();
23
+ restoreProxy = setGlobalProxyFromEnv(unlessRelayed());
24
+ }
25
+ export function childEnvironment() {
26
+ const environment = unlessRelayed();
27
+ if (!Object.keys(environment).some((name) => PROXY.test(name)))
28
+ return environment;
29
+ const bypassed = [environment.NO_PROXY ?? environment.no_proxy, ...LOOPBACK].filter((entry) => entry !== undefined && entry !== '').join(',');
30
+ return { ...environment, NO_PROXY: bypassed, no_proxy: bypassed };
31
+ }
11
32
  export function relayed(target) {
12
33
  const url = new URL(target);
13
34
  const relay = relayOrigin();
package/dist/resident.js CHANGED
@@ -1,24 +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
12
  import { restart } from './end.js';
14
- import { agentBase, enrolled, forgetRestart, kitHome, ownerLock, ownerSocket, restartAsked } from './home.js';
13
+ import { agentBase, enrolled, kitHome, ownerSocket, readEnrolment } 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';
19
+ import { removeInputs, Scripts } from './scripts.js';
20
+ import { applySettings, enrolledRoutes, resumeWorkspaceMove } from './settings.js';
17
21
  import { quoted } from './shell.js';
18
22
  import { SignIns } from './sign-in.js';
19
23
  import { placeSkillSet } from './skills.js';
20
24
  import { holdConnection } from './connection.js';
21
25
  import { KitUpdate } from './update.js';
26
+ import { takeUnservedRelease } from './wire.js';
22
27
  import { codexLauncher } from './work.js';
23
28
  function report(error) {
24
29
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
@@ -31,39 +36,27 @@ async function installShim(path, module) {
31
36
  await mkdir(dirname(path), { recursive: true });
32
37
  await writeFile(path, `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, { mode: 0o755 });
33
38
  }
34
- function claimed(lock) {
35
- try {
36
- lock.exec('BEGIN EXCLUSIVE');
37
- return true;
38
- }
39
- catch (error) {
40
- if (error.errcode === 5)
41
- return false;
42
- throw error;
43
- }
44
- }
45
- async function serveOwner(copies) {
46
- const lock = new DatabaseSync(ownerLock());
47
- if (!claimed(lock)) {
48
- lock.close();
49
- const running = await runningResident();
50
- 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`);
51
- }
39
+ async function serveOwner(lock, copies, settling) {
52
40
  const server = createServer(async (request, response) => {
53
41
  try {
54
42
  const text = await received(request);
55
43
  let answered;
56
44
  if (request.url === '/resident') {
57
- 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 }));
58
46
  return;
59
47
  }
60
48
  if (request.url === '/git/fetch') {
61
- answered = await copies.fetch();
49
+ answered = await copies.fetch(copies.owner);
62
50
  }
63
51
  else if (request.url === '/git/push') {
64
52
  const { cwd, commit } = JSON.parse(text);
65
53
  answered = await copies.push(cwd, commit, copies.owner);
66
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
+ }
67
60
  else {
68
61
  response.writeHead(404).end();
69
62
  return;
@@ -79,18 +72,6 @@ async function serveOwner(copies) {
79
72
  server.listen(ownerSocket());
80
73
  await once(server, 'listening');
81
74
  }
82
- function runningResident() {
83
- return new Promise((resolve, reject) => {
84
- get({ socketPath: ownerSocket(), path: '/resident' }, (answer) => {
85
- received(answer).then((text) => resolve(JSON.parse(text).pid), reject);
86
- }).on('error', (error) => {
87
- if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED')
88
- resolve(null);
89
- else
90
- reject(error);
91
- });
92
- });
93
- }
94
75
  function connected() {
95
76
  return new Promise((resolve) => {
96
77
  const watcher = watch(kitHome(), () => {
@@ -109,23 +90,54 @@ function connected() {
109
90
  }
110
91
  async function started() {
111
92
  await connected();
112
- await forgetRestart();
113
- watch(kitHome(), () => {
114
- if (enrolled())
115
- return;
116
- killDescendants();
117
- process.exit(1);
118
- });
119
- await placeSkillSet();
93
+ await placeSkillSet((await readEnrolment()).house);
120
94
  await mkdir(agentBase(), { recursive: true });
121
95
  await installShim(join(kitHome(), 'shim', 'git'), 'git-main');
122
96
  await installShim(codexLauncher(), 'codex-main');
123
97
  }
124
98
  export async function resident() {
99
+ await moveEarlier();
125
100
  await mkdir(kitHome(), { recursive: true, mode: 0o700 });
101
+ const lock = await holdOwner();
102
+ await resumeWorkspaceMove();
126
103
  const copies = new LocalCopies(house);
127
104
  await copies.load();
128
- await serveOwner(copies);
105
+ let running = null;
106
+ let settings = Promise.resolve();
107
+ const settle = (change) => {
108
+ const applied = settings.then(() => applySettings(change, {
109
+ working: () => running !== null && (running.conversations.turnOpen() || running.calls.busy()),
110
+ end: () => {
111
+ running?.conversations.stopped();
112
+ killDescendants();
113
+ },
114
+ routes: async () => {
115
+ if (running === null)
116
+ return enrolledRoutes();
117
+ await running.agents.read();
118
+ return running.agents.desired.routes;
119
+ },
120
+ }));
121
+ settings = applied.catch(() => undefined);
122
+ return applied.then((answer) => {
123
+ if ('settings' in answer && !answer.moved)
124
+ running?.agents.report().catch(report);
125
+ return answer;
126
+ });
127
+ };
128
+ const answered = (applied) => {
129
+ if ('settings' in applied ? !applied.moved : !applied.ended)
130
+ return;
131
+ const ended = 'settings' in applied
132
+ ? `the workspace moved to ${applied.settings.workspace}; its supervisor starts Kit there`
133
+ : 'the workspace stays where it was; its supervisor starts Kit again';
134
+ if (running === null)
135
+ restart(ended);
136
+ else
137
+ void running.stop(() => restart(ended));
138
+ };
139
+ await copies.swept();
140
+ await serveOwner(lock, copies, { settle, answered });
129
141
  await started().catch((error) => {
130
142
  report(error);
131
143
  process.exit(1);
@@ -134,17 +146,28 @@ export async function resident() {
134
146
  const agents = new Agents(house, () => changed());
135
147
  let connection = null;
136
148
  let reported = false;
149
+ let stopping = false;
150
+ const stop = async (then) => {
151
+ if (stopping)
152
+ return;
153
+ stopping = true;
154
+ conversations.stopped();
155
+ killDescendants();
156
+ await connection?.close();
157
+ then();
158
+ };
137
159
  const idle = () => calls.idle() && conversations.idle() && agents.idle();
138
160
  const changed = () => {
139
161
  if (!idle()) {
140
162
  reported = false;
141
163
  }
142
- else if (restartAsked() && conversations.quiet()) {
143
- restart('restarting for an updated CLI');
164
+ else if (update.placedRelease() !== null && conversations.quiet() && process.env.HOUSE_KIT_SANDBOX !== '1') {
165
+ const placed = update.placedRelease();
166
+ void stop(() => restart(`Kit ${placed} is placed; its supervisor starts it`));
144
167
  }
145
168
  else if (!reported) {
146
169
  reported = true;
147
- logged(house.deliver('/kit/idle', {}, idle));
170
+ logged(house.deliver('kits/report-idle', {}, idle));
148
171
  }
149
172
  };
150
173
  const calls = new Calls(house, changed);
@@ -153,45 +176,66 @@ export async function resident() {
153
176
  agents,
154
177
  copies,
155
178
  calls,
156
- send: (notification) => connection?.send(notification) ?? false,
179
+ send: (oneWayCall) => connection?.send(oneWayCall) ?? false,
157
180
  changed,
158
181
  });
159
182
  const signIns = new SignIns(house, agents, calls);
160
183
  const update = new KitUpdate(calls);
184
+ takeUnservedRelease((release) => logged(update.takeRefused(release)));
185
+ removeInputs();
186
+ const scripts = new Scripts(calls, (oneWayCall) => connection?.send(oneWayCall) ?? false);
187
+ running = { conversations, agents, calls, stop };
161
188
  for (const signal of ['SIGTERM', 'SIGINT']) {
162
189
  process.once(signal, () => {
163
- killDescendants();
164
- process.kill(process.pid, signal);
190
+ void stop(() => {
191
+ removeInputs();
192
+ process.kill(process.pid, signal);
193
+ });
165
194
  });
166
195
  }
167
- await house.deliver('/kit/restarted', {}).catch(report);
168
- await update.resumed().catch(report);
196
+ const unenrolled = () => {
197
+ if (!enrolled())
198
+ void stop(() => process.exit(1));
199
+ };
200
+ watch(kitHome(), unenrolled);
201
+ unenrolled();
202
+ await house.deliver('kits/report-restart', {}).catch(report);
169
203
  logged(agents.refresh());
204
+ agents.keepCurrent(() => process.env.HOUSE_KIT_SANDBOX === '1' && reported);
170
205
  connection = holdConnection({
171
206
  opened: () => {
172
207
  conversations.opened();
208
+ scripts.connected();
173
209
  changed();
174
210
  logged(copies.connected());
175
211
  },
212
+ closed: () => scripts.disconnected(),
176
213
  call: (call) => {
177
214
  if (call.kind === 'sign_in')
178
215
  signIns.start(call);
179
216
  else if (call.kind === 'update')
180
- update.start(call);
181
- else if (CONVERSATION_METHODS.has(call.kind))
182
- conversations.call(call);
183
- else {
184
- const refused = { refused: `This Kit does not know ${call.kind}; update the Kit` };
185
- void calls.carry(call.input_id, async () => ({ result: refused }));
217
+ update.take(call);
218
+ else if (call.kind === 'settings') {
219
+ void calls.carrySettings(call.input_id, async () => {
220
+ const applied = await settle(call);
221
+ const result = 'refused' in applied ? { refused: applied.refused } : { settings: applied.settings };
222
+ if ('settings' in applied ? !applied.moved : !applied.ended)
223
+ return { result };
224
+ calls.keepResult(call.input_id, result);
225
+ return new Promise(() => answered(applied));
226
+ });
186
227
  }
228
+ else if (call.kind === 'run_wizard' || call.kind === 'run_function')
229
+ scripts.start(call);
230
+ else
231
+ conversations.call(call);
187
232
  },
188
- notification: (notification) => {
189
- if (notification.type === 'watching')
190
- conversations.watching(notification.watching === true);
191
- if (notification.type === 'authority_changed')
192
- logged(copies.changed(notification.rooms));
193
- if (notification.type === 'work_available' && notification.subject === 'agents')
233
+ oneWayCall: (oneWayCall) => {
234
+ if (oneWayCall.type === 'watching')
235
+ conversations.watching(oneWayCall.watching);
236
+ if (oneWayCall.type === 'work_available' && oneWayCall.subject === 'agents')
194
237
  logged(agents.refresh());
238
+ scripts.notified(oneWayCall);
195
239
  },
196
240
  });
197
241
  }
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;
@@ -0,0 +1,303 @@
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
+ 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;
23
+ function causeOf(error) {
24
+ return error instanceof Error ? error.message : String(error);
25
+ }
26
+ function failed(plan, cause) {
27
+ process.stderr.write(`kit: ${plan.named} could not start: ${cause}\n`);
28
+ return { refused: `the script could not start: ${cause}` };
29
+ }
30
+ function planned(call) {
31
+ if (call.kind === 'run_wizard')
32
+ return { named: 'a Web Wizard', script: call.script, terminal: 'page', function: null };
33
+ return {
34
+ named: 'an Environment function',
35
+ script: call.script,
36
+ terminal: call.terminal ? 'at once' : null,
37
+ function: { input: call.input, timeCap: call.time_cap, outputCap: call.output_cap },
38
+ };
39
+ }
40
+ function inputs() {
41
+ return join(kitHome(), 'inputs');
42
+ }
43
+ async function inputFile(value) {
44
+ await mkdir(inputs(), { recursive: true, mode: 0o700 });
45
+ const path = join(inputs(), `${randomUUID()}.json`);
46
+ await writeFile(path, JSON.stringify(value), { mode: 0o600, flag: 'wx' });
47
+ return path;
48
+ }
49
+ export function removeInputs() {
50
+ rmSync(inputs(), { recursive: true, force: true });
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
+ }
58
+ function struck(line, typed) {
59
+ return typed.some((typedLine) => line.includes(typedLine));
60
+ }
61
+ class KeptOutput {
62
+ cap;
63
+ typedText = '';
64
+ text = '';
65
+ bytes = 0;
66
+ line = '';
67
+ lineBytes = 0;
68
+ dropping = false;
69
+ cut = false;
70
+ constructor(cap) {
71
+ this.cap = cap;
72
+ }
73
+ typed(data) {
74
+ this.typedText += data;
75
+ }
76
+ add(data) {
77
+ const pieces = data.split('\n');
78
+ const rest = pieces.pop();
79
+ for (const piece of pieces)
80
+ this.ended(piece);
81
+ this.extend(rest);
82
+ }
83
+ kept() {
84
+ const typed = this.typedLines(true);
85
+ this.text = [...this.text.split(/(?<=\n)/), this.line].filter((line) => line !== '' && !struck(line, typed)).join('');
86
+ this.bytes = Buffer.byteLength(this.text);
87
+ this.trim();
88
+ return { output: this.text, cut: this.cut };
89
+ }
90
+ typedLines(all) {
91
+ const lines = this.typedText.split(/\r\n|\r|\n/);
92
+ if (!all)
93
+ lines.pop();
94
+ return lines.filter((line) => line !== '');
95
+ }
96
+ ended(piece) {
97
+ const line = `${this.line}${piece}\n`;
98
+ const dropped = this.dropping;
99
+ this.line = '';
100
+ this.lineBytes = 0;
101
+ this.dropping = false;
102
+ if (dropped || struck(line, this.typedLines(false)))
103
+ return;
104
+ this.text += line;
105
+ this.bytes += Buffer.byteLength(line);
106
+ if (this.bytes > 2 * this.cap)
107
+ this.trim();
108
+ }
109
+ extend(piece) {
110
+ if (this.dropping)
111
+ return;
112
+ this.line += piece;
113
+ this.lineBytes += Buffer.byteLength(piece);
114
+ if (this.lineBytes <= this.cap)
115
+ return;
116
+ this.text = '';
117
+ this.bytes = 0;
118
+ this.line = '';
119
+ this.lineBytes = 0;
120
+ this.dropping = true;
121
+ this.cut = true;
122
+ }
123
+ trim() {
124
+ if (this.bytes <= this.cap)
125
+ return;
126
+ const bytes = Buffer.from(this.text);
127
+ const start = bytes.indexOf(NEWLINE, bytes.length - this.cap - 1) + 1;
128
+ this.text = bytes.subarray(start).toString('utf8');
129
+ this.bytes = bytes.length - start;
130
+ this.cut = true;
131
+ }
132
+ }
133
+ export class Scripts {
134
+ calls;
135
+ send;
136
+ runs = new Map();
137
+ constructor(calls, send) {
138
+ this.calls = calls;
139
+ this.send = send;
140
+ }
141
+ start(call) {
142
+ void this.calls.carry(call.input_id, () => this.run(call.input_id, planned(call)));
143
+ }
144
+ notified(oneWayCall) {
145
+ if (!('wizard' in oneWayCall))
146
+ return;
147
+ const run = this.runs.get(oneWayCall.wizard);
148
+ if (run === undefined)
149
+ return;
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')
156
+ this.end(run, {});
157
+ }
158
+ disconnected() {
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
+ }
174
+ }
175
+ async run(id, plan) {
176
+ const size = plan.terminal === 'page' ? null : FIRST_SIZE;
177
+ const output = plan.function === null ? null : new KeptOutput(plan.function.outputCap);
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
+ };
192
+ if (size !== null)
193
+ run.sized.resolve();
194
+ this.runs.set(id, run);
195
+ try {
196
+ return { result: await this.ran(id, run), release: plan.function !== null };
197
+ }
198
+ finally {
199
+ this.runs.delete(id);
200
+ if (run.input !== null)
201
+ await rm(run.input, { force: true });
202
+ }
203
+ }
204
+ async ran(id, run) {
205
+ const { plan, output } = run;
206
+ let exited;
207
+ try {
208
+ const { spawn } = await import('@lydell/node-pty');
209
+ const shell = await onLoginPath('bash');
210
+ if (shell === null)
211
+ return failed(plan, NO_BASH);
212
+ const path = await loginPath();
213
+ await run.sized.promise;
214
+ if (plan.function !== null)
215
+ run.input = await inputFile(plan.function.input);
216
+ if (run.ended !== null)
217
+ return run.ended;
218
+ const environment = { ...childEnvironment(), PATH: path, ...(run.input === null ? {} : { HOUSE_INPUT: run.input }) };
219
+ if (plan.terminal === null) {
220
+ ({ exited } = await this.piped(plan.script, shell, environment, run));
221
+ }
222
+ else {
223
+ const terminal = spawn(shell, ['-c', plan.script], { name: TERMINAL, ...run.size, cwd: process.cwd(), env: environment });
224
+ run.process = terminal;
225
+ run.terminal = terminal;
226
+ terminal.onData((data) => {
227
+ if (!this.send({ type: 'wizard_output', wizard: id, data }))
228
+ run.unsent = latest(`${run.unsent}${data}`);
229
+ output?.add(data);
230
+ });
231
+ for (const data of run.typed.splice(0))
232
+ terminal.write(data);
233
+ exited = new Promise((resolve) => terminal.onExit(({ exitCode, signal }) => resolve(signal ? SIGNALLED + signal : exitCode)));
234
+ }
235
+ }
236
+ catch (error) {
237
+ return failed(plan, causeOf(error));
238
+ }
239
+ let timedOut = false;
240
+ // 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.
241
+ const capped = plan.function === null ? undefined : setTimeout(() => {
242
+ timedOut = true;
243
+ this.stop(run);
244
+ }, plan.function.timeCap * 1000);
245
+ const code = await exited;
246
+ clearTimeout(capped);
247
+ if (run.ended !== null)
248
+ return run.ended;
249
+ if (output === null)
250
+ return { exit_code: code };
251
+ const kept = output.kept();
252
+ return timedOut ? { timed_out: true, ...kept } : { exit_code: code, ...kept };
253
+ }
254
+ async piped(script, shell, environment, run) {
255
+ const child = spawnPiped(shell, ['-c', script], { cwd: process.cwd(), env: environment, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
256
+ const exited = new Promise((resolve) => child.once('close', (code, signal) => resolve(signal === null ? code : SIGNALLED + constants.signals[signal])));
257
+ await once(child, 'spawn');
258
+ run.process = { pid: child.pid };
259
+ run.pipes = [child.stdout, child.stderr];
260
+ for (const pipe of run.pipes) {
261
+ pipe.setEncoding('utf8');
262
+ pipe.on('data', (data) => run.output.add(data));
263
+ }
264
+ if (run.ended !== null)
265
+ this.stop(run);
266
+ return { exited };
267
+ }
268
+ typed(run, data) {
269
+ run.output?.typed(data);
270
+ if (run.terminal === null)
271
+ run.typed.push(data);
272
+ else
273
+ run.terminal.write(data);
274
+ }
275
+ resized(run, size) {
276
+ run.size = size;
277
+ run.sized.resolve();
278
+ try {
279
+ run.terminal?.resize(size.cols, size.rows);
280
+ }
281
+ catch { }
282
+ }
283
+ end(run, result) {
284
+ if (run.ended !== null)
285
+ return;
286
+ this.waited(run, null);
287
+ run.ended = result;
288
+ run.sized.resolve();
289
+ this.stop(run);
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
+ }
297
+ stop(run) {
298
+ if (run.process !== null)
299
+ killTree(run.process);
300
+ for (const pipe of run.pipes)
301
+ pipe.destroy();
302
+ }
303
+ }
@@ -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')