@anyswarm/core 0.5.1 → 0.5.2

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 (171) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +13 -6
  3. package/dist/examples/README.md +16 -5
  4. package/dist/examples/authoring/README.md +4 -4
  5. package/dist/examples/autoresearch/README.md +15 -8
  6. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +3 -10
  7. package/dist/examples/autoresearch/demo.js +1 -1
  8. package/dist/examples/autoresearch/eject.json +2 -0
  9. package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -0
  10. package/dist/examples/autoresearch/frontiercs2-config.js +3 -0
  11. package/dist/examples/autoresearch/prepare-demo.d.ts +1 -0
  12. package/dist/examples/autoresearch/prepare-demo.js +15 -0
  13. package/dist/examples/autoresearch/prepare.js +3 -3
  14. package/dist/examples/autoresearch/project.d.ts +0 -94
  15. package/dist/examples/autoresearch/project.js +2 -20
  16. package/dist/examples/code/README.md +25 -17
  17. package/dist/examples/code/REQUIREMENTS.zh.md +3 -3
  18. package/dist/examples/harness-session/README.md +3 -3
  19. package/dist/examples/messages/README.md +1 -1
  20. package/dist/examples/notes/README.md +3 -3
  21. package/dist/examples/services/mathlib-search/README.md +1 -1
  22. package/dist/examples/services/persistent-board/README.md +5 -2
  23. package/dist/examples/subagents/README.md +2 -2
  24. package/dist/examples/subagents/config.js +3 -3
  25. package/dist/examples/substrate/README.md +2 -2
  26. package/dist/examples/super/README.md +34 -22
  27. package/dist/examples/super/actions.d.ts +1 -1
  28. package/dist/examples/super/actions.js +11 -11
  29. package/dist/examples/super/config.js +3 -3
  30. package/dist/examples/super/eject.json +1 -1
  31. package/dist/examples/super/location.js +1 -1
  32. package/dist/examples/super/operator.d.ts +1 -0
  33. package/dist/examples/super/operator.js +31 -0
  34. package/dist/examples/super/project.d.ts +0 -107
  35. package/dist/examples/super/project.js +1 -3
  36. package/dist/scripts/anyswarm-arguments.d.ts +7 -25
  37. package/dist/scripts/anyswarm-arguments.js +69 -97
  38. package/dist/scripts/anyswarm-eject.js +1 -1
  39. package/dist/scripts/anyswarm-harnesses.d.ts +0 -1
  40. package/dist/scripts/anyswarm-harnesses.js +1 -22
  41. package/dist/scripts/anyswarm-installation.d.ts +7 -40
  42. package/dist/scripts/anyswarm-installation.js +17 -291
  43. package/dist/scripts/anyswarm-launch.d.ts +6 -36
  44. package/dist/scripts/anyswarm-launch.js +32 -81
  45. package/dist/scripts/anyswarm-progress.d.ts +6 -0
  46. package/dist/scripts/anyswarm-progress.js +102 -0
  47. package/dist/scripts/anyswarm-project.d.ts +1 -9
  48. package/dist/scripts/anyswarm-project.js +40 -127
  49. package/dist/scripts/anyswarm-source-runner.js +9 -41
  50. package/dist/scripts/anyswarm.js +6 -26
  51. package/dist/scripts/build-provenance.json +1 -1
  52. package/dist/scripts/local-environment.d.ts +10 -4
  53. package/dist/scripts/local-environment.js +67 -20
  54. package/dist/scripts/local-setup.d.ts +3 -0
  55. package/dist/scripts/local-setup.js +135 -107
  56. package/dist/scripts/pack-release.js +4 -1
  57. package/dist/src/core/worker-image.js +1 -1
  58. package/dist/src/harness/project-harness.d.ts +1 -0
  59. package/dist/src/harness/project-harness.js +2 -2
  60. package/dist/src/harness/project-runtime.js +3 -1
  61. package/docs/INDEX.md +2 -1
  62. package/docs/architecture/04-services.md +1 -1
  63. package/docs/architecture/07-run-configuration.md +28 -14
  64. package/docs/architecture/12-code-coverage.md +56 -57
  65. package/docs/architecture/17-harness-reporting.md +1 -1
  66. package/docs/architecture/22-website.md +4 -7
  67. package/docs/architecture/23-project-harness.md +48 -23
  68. package/docs/architecture/26-code.md +20 -5
  69. package/docs/architecture/27-personal.md +23 -8
  70. package/docs/architecture/28-autoresearch.md +18 -6
  71. package/docs/architecture/INDEX.md +1 -2
  72. package/docs/architecture/prompts/source-manifest.json +5 -5
  73. package/docs/architecture/source-map.json +51 -71
  74. package/docs/designs/core-harness/01-core.md +2 -2
  75. package/docs/designs/core-harness/06-project-harness.md +3 -3
  76. package/docs/designs/core-harness/README.md +2 -2
  77. package/docs/en/agents.md +1 -1
  78. package/docs/en/build-your-harness.md +1 -1
  79. package/docs/en/changelog.md +7 -0
  80. package/docs/en/first-harness.md +6 -6
  81. package/docs/en/harnesses/lead-worker.md +1 -1
  82. package/docs/en/harnesses/peermesh.md +2 -2
  83. package/docs/en/harnesses/subagents.md +2 -2
  84. package/docs/en/harnesses/substrate.md +4 -4
  85. package/docs/en/harnesses/taskpool.md +2 -2
  86. package/docs/en/latest.md +9 -5
  87. package/docs/en/quickstart.md +20 -41
  88. package/docs/en/reference/api.md +1 -1
  89. package/docs/en/reference/cli.md +47 -85
  90. package/docs/en/sandbox.md +3 -3
  91. package/docs/operations/trace-viewer.md +1 -1
  92. package/docs/third-party-notices.md +0 -1
  93. package/docs/workflows/development.md +14 -12
  94. package/docs/workflows/release-and-docs-versioning.md +13 -12
  95. package/docs/workflows/release-cli-acceptance.md +85 -0
  96. package/docs/zh/agents.md +1 -1
  97. package/docs/zh/build-your-harness.md +1 -1
  98. package/docs/zh/changelog.md +8 -1
  99. package/docs/zh/first-harness.md +7 -7
  100. package/docs/zh/harnesses/lead-worker.md +1 -1
  101. package/docs/zh/harnesses/peermesh.md +2 -2
  102. package/docs/zh/harnesses/subagents.md +2 -2
  103. package/docs/zh/harnesses/substrate.md +4 -4
  104. package/docs/zh/harnesses/taskpool.md +2 -2
  105. package/docs/zh/latest.md +9 -5
  106. package/docs/zh/quickstart.md +20 -41
  107. package/docs/zh/reference/api.md +1 -1
  108. package/docs/zh/reference/cli.md +19 -79
  109. package/docs/zh/sandbox.md +3 -3
  110. package/examples/README.md +16 -5
  111. package/examples/authoring/README.md +4 -4
  112. package/examples/autoresearch/README.md +15 -8
  113. package/examples/autoresearch/REQUIREMENTS.zh.md +3 -10
  114. package/examples/autoresearch/demo.ts +1 -1
  115. package/examples/autoresearch/eject.json +2 -0
  116. package/examples/autoresearch/frontiercs2-config.ts +4 -0
  117. package/examples/autoresearch/prepare-demo.ts +15 -0
  118. package/examples/autoresearch/prepare.ts +3 -3
  119. package/examples/autoresearch/project.ts +2 -19
  120. package/examples/code/README.md +25 -17
  121. package/examples/code/REQUIREMENTS.zh.md +3 -3
  122. package/examples/harness-session/README.md +3 -3
  123. package/examples/messages/README.md +1 -1
  124. package/examples/notes/README.md +3 -3
  125. package/examples/services/mathlib-search/README.md +1 -1
  126. package/examples/services/persistent-board/README.md +5 -2
  127. package/examples/subagents/README.md +2 -2
  128. package/examples/subagents/config.ts +4 -3
  129. package/examples/substrate/README.md +2 -2
  130. package/examples/super/README.md +34 -22
  131. package/examples/super/actions.ts +11 -11
  132. package/examples/super/config.ts +3 -3
  133. package/examples/super/eject.json +1 -1
  134. package/examples/super/location.ts +1 -1
  135. package/examples/super/operator.ts +28 -0
  136. package/examples/super/project.ts +1 -3
  137. package/npm-shrinkwrap.development.json +42 -1541
  138. package/npm-shrinkwrap.json +3 -43
  139. package/package.development.json +2 -6
  140. package/package.json +2 -5
  141. package/scripts/anyswarm-arguments.ts +67 -96
  142. package/scripts/anyswarm-eject.ts +1 -1
  143. package/scripts/anyswarm-harnesses.ts +1 -18
  144. package/scripts/anyswarm-installation.ts +18 -294
  145. package/scripts/anyswarm-launch.ts +30 -102
  146. package/scripts/anyswarm-progress.ts +95 -0
  147. package/scripts/anyswarm-project.ts +31 -123
  148. package/scripts/anyswarm-source-runner.ts +9 -36
  149. package/scripts/anyswarm.ts +4 -24
  150. package/scripts/local-environment.ts +71 -20
  151. package/scripts/local-setup.ts +134 -94
  152. package/scripts/pack-release.ts +4 -1
  153. package/src/core/worker-image.ts +1 -1
  154. package/src/harness/project-harness.ts +2 -2
  155. package/src/harness/project-runtime.ts +2 -1
  156. package/dist/scripts/anyswarm-applications.d.ts +0 -19
  157. package/dist/scripts/anyswarm-applications.js +0 -19
  158. package/dist/scripts/anyswarm-tui-config.d.ts +0 -36
  159. package/dist/scripts/anyswarm-tui-config.js +0 -189
  160. package/dist/scripts/anyswarm-tui-session.d.ts +0 -66
  161. package/dist/scripts/anyswarm-tui-session.js +0 -304
  162. package/dist/scripts/anyswarm-tui-terminal.d.ts +0 -41
  163. package/dist/scripts/anyswarm-tui-terminal.js +0 -154
  164. package/dist/scripts/anyswarm-tui.d.ts +0 -2
  165. package/dist/scripts/anyswarm-tui.js +0 -1012
  166. package/docs/architecture/25-foreground-tui.md +0 -51
  167. package/scripts/anyswarm-applications.ts +0 -39
  168. package/scripts/anyswarm-tui-config.ts +0 -174
  169. package/scripts/anyswarm-tui-session.ts +0 -295
  170. package/scripts/anyswarm-tui-terminal.ts +0 -147
  171. package/scripts/anyswarm-tui.ts +0 -912
@@ -1,1012 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { mkdir, realpath } from 'node:fs/promises';
3
- import { homedir } from 'node:os';
4
- import { basename, dirname, join, resolve } from 'node:path';
5
- import { Editor, CURSOR_MARKER, CombinedAutocompleteProvider, ScrollView, TuiAltScreen, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
6
- import { createRedactor } from '../src/core/run-records.js';
7
- import { createHarnessSession, getHarnessExitCode } from '../src/harness/project-harness.js';
8
- import { resolveHarnessInput } from '../src/harness/project-input.js';
9
- import { isLocalHarness } from './anyswarm-arguments.js';
10
- import { applicationAliases as aliases, preferredTerminalLifetime } from './anyswarm-applications.js';
11
- import { builtins } from './anyswarm-harnesses.js';
12
- import { actionReport, actionRun, configuredStopTimeout, harnessLifetime, interactiveTerminal, loadHarness, requestedTraceRoot, splitInput } from './anyswarm-launch.js';
13
- import { LauncherConfiguration, terminalObject } from './anyswarm-tui-config.js';
14
- import { formatSessionError, TerminalSession } from './anyswarm-tui-session.js';
15
- import { AnySwarmTerminal, terminalText } from './anyswarm-tui-terminal.js';
16
- const commands = {
17
- use: 'Select a Harness', status: 'Show Run, Agents and artifacts', trace: 'Open the local Trace Viewer',
18
- agents: 'List Agents and select a target', to: 'Send text to an Agent', target: 'Select a default Agent or main',
19
- stop: 'Stop an Agent or the Run', interrupt: 'Interrupt an Agent turn', approve: 'Answer yes', y: 'Answer yes',
20
- reject: 'Answer no', n: 'Answer no', reply: 'Answer a pending question', quit: 'Exit',
21
- config: 'Select a trusted configuration', doctor: 'Check the local setup', 'setup-host': 'Run platform setup with pi or codex',
22
- attach: 'Reconnect a background observer', retry: 'Retry an unknown receipt', help: 'Show commands',
23
- };
24
- const pass = (value) => value;
25
- const bold = (value) => '\x1b[1m' + value + '\x1b[0m';
26
- const dim = (value) => '\x1b[2m' + value + '\x1b[0m';
27
- const inputByteLimit = 262_144;
28
- function agentName(id) {
29
- const name = id.split('/').filter(Boolean).at(-1) ?? id;
30
- return /^[a-f0-9]{8}(?:-[a-f0-9]+){4}$/i.test(name) ? name.slice(0, 8) : name;
31
- }
32
- function reportLines(result) {
33
- const artifacts = result.artifacts.flatMap(item => {
34
- if (typeof item === 'string')
35
- return [item];
36
- const { path, destination, name } = terminalObject(item);
37
- return typeof path === 'string' ? [path] : typeof destination === 'string' ? [destination] :
38
- typeof name === 'string' ? [name] : [];
39
- });
40
- return [
41
- 'Run ' + result.outcome + ' · ' + result.reason + ' · Cleanup ' + result.cleanup.status,
42
- ...(result.failure ? [result.failure.code + ' ' + result.failure.message] : []),
43
- ...(result.reportSaveFailure ? [result.reportSaveFailure.code + ' ' + result.reportSaveFailure.message] : []),
44
- ...artifacts.slice(0, 8).map(path => 'Artifact ' + path),
45
- ...(result.reportPath ? ['Report ' + result.reportPath] : []),
46
- ];
47
- }
48
- class ForegroundScreen extends TuiAltScreen {
49
- renderFailed;
50
- constructor(terminal, renderFailed) {
51
- super(terminal, true, undefined, { mouse: false, copyOnSelect: false });
52
- this.renderFailed = renderFailed;
53
- }
54
- doRender() {
55
- try {
56
- super.doRender();
57
- }
58
- catch {
59
- this.renderFailed();
60
- }
61
- }
62
- }
63
- class Composer extends Editor {
64
- label = '';
65
- renderTopBorder(width, hiddenLineCount) {
66
- const label = '[' + truncateToWidth(this.label, width - 4, '…') + '] >';
67
- const remaining = width - visibleWidth(label);
68
- return bold(label) + (remaining > 0 ? ' ' + super.renderTopBorder(remaining - 1, hiddenLineCount) : '');
69
- }
70
- }
71
- class Foreground {
72
- command;
73
- launchDirectory;
74
- done = Promise.withResolvers();
75
- shutdown = new AbortController();
76
- redactor = createRedactor(Object.entries(process.env)
77
- .filter(([key]) => /(?:TOKEN|PASSWORD|SECRET|API_KEY)$/i.test(key)).map(([, value]) => value));
78
- terminal = new AnySwarmTerminal(() => this.notice('Paste exceeds 256 KiB and was discarded.'));
79
- tui = new ForegroundScreen(this.terminal, () => this.requestExit(1));
80
- editor = new Composer(this.tui, {
81
- borderColor: dim, selectList: { selectedPrefix: pass, selectedText: pass, description: pass, scrollInfo: pass, noMatch: pass },
82
- }, { paddingX: 1 });
83
- stream = new ScrollView({ invalidate() { }, render: () => [] }, { follow: 'end' });
84
- entries = [];
85
- terminalStarted = false;
86
- closing = false;
87
- work;
88
- setupRunning = false;
89
- launcher;
90
- loaded;
91
- specifier = '';
92
- run;
93
- target;
94
- selection;
95
- switchRequest;
96
- trace;
97
- traceStarting = false;
98
- exitCode = 0;
99
- cleanupLine;
100
- constructor(command, launchDirectory) {
101
- this.command = command;
102
- this.launchDirectory = launchDirectory;
103
- this.editor.onSubmit = text => {
104
- this.editor.setText('');
105
- this.invoke(() => this.submit(text.trim()));
106
- };
107
- }
108
- async open() {
109
- const originalOut = process.stdout.write;
110
- const originalErr = process.stderr.write;
111
- const signal = (name) => this.requestExit(name === 'SIGINT' ? 130 : name === 'SIGTERM' ? 143 : 1);
112
- const ended = () => this.requestExit(1);
113
- process.on('SIGINT', signal).on('SIGTERM', signal).on('SIGHUP', signal);
114
- process.stdin.on('end', ended).on('error', ended).on('close', ended);
115
- process.stdout.on('error', ended).on('close', ended);
116
- process.stderr.on('error', ended);
117
- let restorationError = false;
118
- try {
119
- this.tui.setFocus(this.editor);
120
- this.tui.setLayoutRoot({ invalidate() { }, render: width => this.render(width) });
121
- this.tui.addInputListener(data => {
122
- this.invoke(() => this.handle(data));
123
- return { consume: true };
124
- });
125
- this.terminal.enableRawMode();
126
- this.terminalStarted = true;
127
- this.tui.start();
128
- const divert = (_chunk, encoding, callback) => {
129
- const completed = typeof encoding === 'function' ? encoding : callback;
130
- if (completed)
131
- queueMicrotask(completed);
132
- return true;
133
- };
134
- process.stdout.write = divert;
135
- process.stderr.write = divert;
136
- this.completeCommands();
137
- if (this.command.harness)
138
- this.invoke(() => this.exclusive(() => this.select(this.command.harness, this.command.prompt ?? '')));
139
- else
140
- this.notice('Choose a Harness with /use <name or path>. Try /help for commands.');
141
- return await this.done.promise;
142
- }
143
- catch {
144
- originalErr.call(process.stderr, 'The TUI could not enable terminal mode. Use --headless or --rpc.\n');
145
- return 2;
146
- }
147
- finally {
148
- this.shutdown.abort();
149
- try {
150
- this.run?.model.close();
151
- this.run?.closeTraceRequests();
152
- }
153
- catch (error) {
154
- this.cleanupLine ??= formatSessionError(error);
155
- }
156
- try {
157
- if (this.terminalStarted)
158
- this.tui.stop({ preserveScreen: true });
159
- }
160
- catch {
161
- restorationError = true;
162
- }
163
- try {
164
- this.terminal.stop();
165
- }
166
- catch {
167
- restorationError = true;
168
- }
169
- if (this.terminalStarted) {
170
- try {
171
- if (restorationError)
172
- this.terminal.restoreDisplay();
173
- await this.bounded(this.terminal.drained(), 1000, 'Terminal restoration timed out.');
174
- }
175
- catch {
176
- restorationError = true;
177
- }
178
- }
179
- process.stdout.write = originalOut;
180
- process.stderr.write = originalErr;
181
- if (restorationError && !process.stderr.destroyed) {
182
- originalErr.call(process.stderr, 'anyswarm: terminal restoration could not be confirmed.\n');
183
- }
184
- const cleanupLine = this.cleanupLine;
185
- if (cleanupLine && !process.stdout.destroyed) {
186
- await this.bounded(new Promise((done, reject) => originalOut.call(process.stdout, this.clean(cleanupLine) + '\n', undefined, error => error ? reject(error) : done())), 1000, 'Terminal output timed out.').catch(() => { });
187
- }
188
- try {
189
- await this.bounded(Promise.resolve().then(() => this.trace?.close()), 1000, 'Trace Viewer close timed out.');
190
- if (this.trace && !process.stderr.destroyed) {
191
- originalErr.call(process.stderr, 'Replay with anys trace --root ' + JSON.stringify(this.trace.root) + '\n');
192
- }
193
- }
194
- catch (error) {
195
- if (!process.stderr.destroyed)
196
- originalErr.call(process.stderr, this.clean(formatSessionError(error)) + '\n');
197
- }
198
- process.off('SIGINT', signal).off('SIGTERM', signal).off('SIGHUP', signal);
199
- process.stdin.off('end', ended).off('error', ended).off('close', ended);
200
- process.stdout.off('error', ended).off('close', ended);
201
- process.stderr.off('error', ended);
202
- }
203
- }
204
- async bounded(work, ms, message) {
205
- let timer;
206
- try {
207
- return await Promise.race([work, new Promise((_, reject) => {
208
- timer = setTimeout(() => reject(new Error(message)), ms);
209
- })]);
210
- }
211
- finally {
212
- clearTimeout(timer);
213
- }
214
- }
215
- invoke(action) {
216
- try {
217
- void Promise.resolve(action()).catch(error => this.notice(formatSessionError(error)));
218
- }
219
- catch (error) {
220
- this.notice(formatSessionError(error));
221
- }
222
- }
223
- exclusive(action) {
224
- if (this.work)
225
- throw new Error('Wait for the current Harness operation.');
226
- this.work = Promise.resolve().then(action).finally(() => {
227
- this.work = undefined;
228
- this.completeCommands();
229
- this.redraw();
230
- });
231
- return this.work;
232
- }
233
- redraw() { if (this.terminalStarted && !this.closing)
234
- this.tui.requestRender(); }
235
- clean(text) { return terminalText(this.redactor.text(text)); }
236
- notice(text) {
237
- this.entries.push({ order: (this.run?.model.revision ?? 0) + 0.5, text: this.clean(text).slice(0, 8192) });
238
- if (this.entries.length > 100)
239
- this.entries.shift();
240
- this.redraw();
241
- }
242
- addSecrets(configuration) {
243
- const config = terminalObject(configuration);
244
- const sandbox = terminalObject(config.sandbox);
245
- const connection = terminalObject(config.connection);
246
- this.redactor.add([sandbox.apiKey, sandbox.execdToken, connection.apiKey, connection.token,
247
- ...Object.values(terminalObject(config.models)).flatMap(value => Object.values(terminalObject(terminalObject(terminalObject(value).upstream).headers)))]);
248
- }
249
- completeCommands() {
250
- const names = new Set([...Object.keys(commands), ...aliases, ...(this.loaded?.actions.keys() ?? [])]);
251
- for (const name of this.inputCommands())
252
- names.add(name);
253
- this.editor.setAutocompleteProvider(new CombinedAutocompleteProvider([...names].map(name => ({
254
- name, description: Object.hasOwn(commands, name) ? commands[name] : undefined,
255
- ...(name === 'use' ? { getArgumentCompletions: (prefix) => Object.keys(builtins)
256
- .filter(id => id.startsWith(prefix)).map(id => ({ value: id, label: id })) } : {}),
257
- })), this.launcher?.workspace ?? this.launchDirectory));
258
- }
259
- launchContext(launcher) {
260
- return { cwd: launcher.workspace, configuration: launcher.configuration, signal: this.shutdown.signal,
261
- outputRoot: this.command.outputRoot && resolve(this.launchDirectory, this.command.outputRoot) };
262
- }
263
- async select(specifier, prompt) {
264
- const previous = this.run;
265
- if (previous) {
266
- if (previous.observer)
267
- await this.disconnectRun(previous);
268
- else if (this.running(previous)) {
269
- const result = await this.stop(previous, 'switch-harness');
270
- if (result?.cleanup.status !== 'complete')
271
- throw new Error('Cleanup is unconfirmed. See /status and /trace before switching.');
272
- }
273
- if (!previous.observer && previous.model.result?.cleanup.status === 'pending') {
274
- throw new Error('Cleanup is unconfirmed. See /status and /trace before switching.');
275
- }
276
- this.releaseRun(previous);
277
- }
278
- this.loaded = undefined;
279
- this.specifier = specifier;
280
- this.exitCode = 2;
281
- const launcher = new LauncherConfiguration(specifier, specifier, this.launchDirectory, this.launcher?.workspace ?? this.command.cwd, this.command.configPath, this.launcher?.selectedChoice());
282
- this.launcher = launcher;
283
- const loaded = await loadHarness(this.launchDirectory, specifier);
284
- this.shutdown.signal.throwIfAborted();
285
- this.loaded = loaded;
286
- await launcher.refresh();
287
- this.addSecrets(launcher.configuration);
288
- this.shutdown.signal.throwIfAborted();
289
- harnessLifetime(loaded.definition, this.command.lifetime, preferredTerminalLifetime(this.specifier));
290
- this.exitCode = 0;
291
- this.notice(launcher.error ?? this.modeLabel() + ' ready. Enter a prompt or use /help.');
292
- if (loaded.observe) {
293
- if (launcher.error && launcher.path)
294
- throw new Error(launcher.error);
295
- if (await this.attach(loaded, launcher)) {
296
- if (prompt)
297
- await this.sendInput(prompt);
298
- }
299
- else {
300
- this.notice('No background Session is available. Use /help to see the Harness commands.');
301
- if (prompt)
302
- this.editor.setText(prompt);
303
- }
304
- }
305
- else if (prompt && launcher.error)
306
- this.editor.setText(prompt);
307
- else if (prompt)
308
- await this.start(prompt);
309
- }
310
- modeLabel() {
311
- return '/' + (isLocalHarness(this.specifier) ? this.loaded?.definition.id ?? basename(this.specifier) : this.specifier);
312
- }
313
- bind(session, observer) {
314
- let run;
315
- let inputCommands;
316
- const model = new TerminalSession(session, () => {
317
- if (!run || run !== this.run)
318
- return;
319
- const current = run.model.state?.capabilities.input.commands;
320
- if (JSON.stringify(current) !== JSON.stringify(inputCommands)) {
321
- inputCommands = current;
322
- this.completeCommands();
323
- }
324
- this.showResult(run);
325
- this.redraw();
326
- });
327
- const closeTraceRequests = observer ? () => { } : session.onEvent(event => {
328
- if (event.type !== 'event' || !run || run !== this.run || this.closing)
329
- return;
330
- const root = requestedTraceRoot(event.event, event.runId);
331
- if (root)
332
- this.invoke(() => this.openTrace(root, true));
333
- }, { initialSnapshot: false });
334
- run = { model, observer, stopId: randomUUID(), closeTraceRequests };
335
- this.run = run;
336
- this.showResult(run);
337
- return run;
338
- }
339
- showResult(run) {
340
- const result = run.model.result;
341
- if (!result || run.resultShown)
342
- return;
343
- run.resultShown = true;
344
- run.exitCode = getHarnessExitCode(run.model.session) ?? (result.outcome === 'completed' && result.cleanup.status === 'complete' ? 0 : 1);
345
- const lines = reportLines(result);
346
- for (const text of lines)
347
- this.notice(text);
348
- if (!run.observer)
349
- this.cleanupLine = lines.join('\n');
350
- }
351
- watch(run) {
352
- void run.model.session.completion?.then(result => {
353
- run.model.result = result;
354
- if (run === this.run)
355
- this.showResult(run);
356
- }, error => { if (run === this.run)
357
- this.notice(formatSessionError(error)); });
358
- }
359
- async attach(loaded, launcher) {
360
- if (!loaded.observe)
361
- return false;
362
- const observer = await loaded.observe(this.launchContext(launcher));
363
- if (!observer)
364
- return false;
365
- try {
366
- this.shutdown.signal.throwIfAborted();
367
- this.watch(this.bind(observer.session, observer));
368
- }
369
- catch (error) {
370
- await this.disconnect(observer);
371
- throw error;
372
- }
373
- this.notice('Attached to background Session.');
374
- return true;
375
- }
376
- async start(prompt, launch) {
377
- const { launcher, loaded } = this;
378
- if (!launcher || !loaded)
379
- throw new Error('Select a working Harness with /use.');
380
- if (launcher.error)
381
- throw new Error(launcher.error);
382
- if (this.running())
383
- throw new Error('Stop the active Run before starting another one.');
384
- if (this.run?.model.result?.cleanup.status === 'pending')
385
- throw new Error('Cleanup is unconfirmed. See /status and /trace before starting another Run.');
386
- if (loaded.observe)
387
- throw new Error('Attach the background Session with /attach or use its startup commands.');
388
- this.shutdown.signal.throwIfAborted();
389
- const configuration = launch?.configuration ?? launcher.configuration;
390
- const cwd = launch?.cwd ?? (this.command.cwd ? launcher.workspace
391
- : loaded.workspace?.({ cwd: launcher.workspace, configuration }) ?? launcher.workspace);
392
- const input = resolveHarnessInput({ cwd, prompt }, this.launchDirectory);
393
- if (this.run)
394
- this.releaseRun(this.run);
395
- this.addSecrets(configuration);
396
- const session = createHarnessSession(loaded.definition, {
397
- launchDirectory: this.launchDirectory, configuration, outputRoot: this.command.outputRoot,
398
- lifetime: harnessLifetime(loaded.definition, this.command.lifetime, preferredTerminalLifetime(this.specifier)),
399
- clientCapabilities: { questions: this.command.interaction !== 'none' },
400
- stopTimeoutMs: configuredStopTimeout(configuration) ?? 35_000,
401
- });
402
- const run = this.bind(session);
403
- this.notice('[you] ' + prompt);
404
- try {
405
- await session.start(input, { requestId: randomUUID() });
406
- this.watch(run);
407
- }
408
- catch (error) {
409
- this.releaseRun(run);
410
- this.exitCode = 2;
411
- throw error;
412
- }
413
- }
414
- releaseRun(run) {
415
- const lines = this.streamLines().slice(-30);
416
- run.model.close();
417
- run.closeTraceRequests();
418
- this.run = undefined;
419
- this.cleanupLine = undefined;
420
- this.switchRequest = undefined;
421
- this.target = undefined;
422
- this.selection = undefined;
423
- this.entries.splice(0, this.entries.length, ...lines.map(text => ({ order: 0, text })));
424
- }
425
- running(run = this.run) {
426
- return !!run && !run.model.result && run.model.state?.phase !== 'finished';
427
- }
428
- disconnect(observer) {
429
- return this.bounded(Promise.resolve().then(() => observer.close()), 1000, 'Observer disconnect could not be confirmed.');
430
- }
431
- disconnectRun(run) {
432
- run.disconnecting ??= this.disconnect(run.observer).catch(error => {
433
- run.disconnecting = undefined;
434
- throw error;
435
- });
436
- return run.disconnecting;
437
- }
438
- stop(run, reason) {
439
- if (run.stopping)
440
- return run.stopping;
441
- this.notice('Stopping Run. Waiting for Harness cleanup.');
442
- const session = run.model.session;
443
- run.stopping = (async () => {
444
- run.stopReason ??= reason;
445
- const receipt = await session.stop({ requestId: run.stopId, reason: run.stopReason });
446
- if (receipt.status !== 'accepted')
447
- throw new Error('Run stop was not accepted.');
448
- if (run.observer) {
449
- this.notice('Run stop accepted by the background Session.');
450
- return;
451
- }
452
- if (!session.completion)
453
- throw new Error('Run completion is unavailable.');
454
- return session.completion;
455
- })().finally(() => { run.stopping = undefined; });
456
- return run.stopping;
457
- }
458
- requestExit(code, useTaskExitCode = false) {
459
- if (this.closing)
460
- return;
461
- this.closing = true;
462
- this.shutdown.abort();
463
- void (async () => {
464
- const run = this.run;
465
- const business = terminalObject(run?.model.state?.business);
466
- const taskSucceeded = useTaskExitCode && (business.exitCode ?? terminalObject(business.detail).exitCode) === 0;
467
- try {
468
- if (run?.observer)
469
- await this.disconnectRun(run);
470
- else if (run && this.running(run)) {
471
- const result = await this.stop(run, 'terminal-exit');
472
- const finalExitCode = terminalObject(terminalObject(result?.result).business).exitCode;
473
- if (taskSucceeded && result?.stopReason === 'terminal-exit' &&
474
- (finalExitCode === undefined || finalExitCode === 0) &&
475
- (result.outcome === 'completed' || (result.outcome === 'cancelled' && result.reason === 'cancelled')) &&
476
- result.cleanup.status === 'complete' && !result.failure && !result.reportSaveFailure &&
477
- (!result.export || result.export.status === 'complete')) {
478
- run.exitCode = 0;
479
- this.cleanupLine = ['Run ended · Cleanup complete', ...reportLines(result).slice(1)].join('\n');
480
- }
481
- }
482
- }
483
- catch (error) {
484
- this.cleanupLine = formatSessionError(error);
485
- code ??= 1;
486
- }
487
- if (this.work)
488
- await this.bounded(this.work.catch(() => { }), this.setupRunning ? 45_000 : 1000, 'Harness preparation is still stopping.').catch(() => { });
489
- this.done.resolve(code ?? (run?.observer ? 0 : run?.exitCode ?? this.exitCode));
490
- })();
491
- }
492
- async openTrace(path, live = false) {
493
- if (this.traceStarting)
494
- return;
495
- this.traceStarting = true;
496
- try {
497
- const run = this.run;
498
- const report = run?.model.result?.reportPath;
499
- // Owned reports live under <output-root>/<run-id>/project-run.json.
500
- const reportRoot = report && (run?.observer ? dirname(report) : dirname(dirname(report)));
501
- const directory = resolve(this.launchDirectory, path || this.command.outputRoot || run?.observer?.traceRoot || reportRoot ||
502
- resolve(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'anyswarm', 'runs'));
503
- if (!path)
504
- await mkdir(directory, { recursive: true, mode: 0o700 });
505
- const root = await realpath(directory);
506
- if (this.trace?.root === root) {
507
- this.notice('Trace Viewer ' + this.trace.url);
508
- return;
509
- }
510
- const modulePath = '../src/trace-viewer/server.mjs';
511
- const { startTraceServer } = await import(modulePath);
512
- const viewer = await startTraceServer({ root, port: 0 });
513
- if (this.closing) {
514
- await viewer.close();
515
- return;
516
- }
517
- const previous = this.trace;
518
- this.trace = { ...viewer, root };
519
- this.notice((live ? 'Live Trace URL ' : 'Trace Viewer ') + viewer.url);
520
- if (previous)
521
- await this.bounded(previous.close(), 1000, 'Previous Trace Viewer close timed out.');
522
- }
523
- finally {
524
- this.traceStarting = false;
525
- }
526
- }
527
- agents() {
528
- const state = this.run?.model.state;
529
- const agents = new Map();
530
- for (const id of Object.keys(state?.capabilities.agents ?? {}))
531
- agents.set(id, { profile: '', status: 'unknown' });
532
- for (const raw of Array.isArray(state?.agents) ? state.agents : []) {
533
- const item = terminalObject(raw);
534
- const id = item.id ?? item.agentId;
535
- if (typeof id === 'string')
536
- agents.set(id, { profile: typeof item.profile === 'string' ? item.profile : '',
537
- status: typeof item.status === 'string' ? item.status : 'unknown' });
538
- }
539
- return agents;
540
- }
541
- agentId(name) {
542
- const agents = this.agents();
543
- if (agents.has(name))
544
- return name;
545
- const matches = [...agents].filter(([id, agent]) => agentName(id) === name || id.startsWith(name) || agent.profile === name);
546
- if (matches.length === 1)
547
- return matches[0][0];
548
- throw new Error(matches.length ? 'Ambiguous Agent name. Use its full ID from /agents.' : 'Unknown Agent. Use /agents.');
549
- }
550
- agentLine(id, roster = this.agents()) {
551
- const agent = roster.get(id);
552
- const capabilities = this.run?.model.state?.capabilities.agents[id];
553
- const available = ['send', 'interrupt', 'stop'].filter(name => capabilities?.[name]?.available);
554
- const short = agentName(id);
555
- return [short === id ? id : short + ' (' + id + ')', agent?.profile, agent?.status,
556
- available.length ? available.join('/') : 'no controls'].filter(Boolean).join(' · ');
557
- }
558
- agentControl(id, operation, text = '', followUp = false) {
559
- const model = this.requireModel();
560
- const capability = model.state?.capabilities.agents[id]?.[operation];
561
- if (!capability?.supported || !capability.available)
562
- throw new Error(capability?.reason ?? 'Agent operation unavailable.');
563
- const key = 'agent:' + id + ':' + operation;
564
- const agents = model.session.agents;
565
- if (operation === 'send') {
566
- if (!text)
567
- throw new Error('Enter a message for the Agent.');
568
- const mode = followUp || (capability.modes?.includes('followUp') && !capability.modes.includes('steer')) ? 'followUp' : 'steer';
569
- if (capability.text === false || (capability.modes && !capability.modes.includes(mode)))
570
- throw new Error('Agent does not support ' + mode + ' text.');
571
- this.notice('[you → @' + agentName(id) + '] ' + text);
572
- return this.mutate(model, key, { text, mode }, request => agents.send(id, text, { ...request, mode }));
573
- }
574
- return this.mutate(model, key, null, request => agents[operation](id, request));
575
- }
576
- requireModel() {
577
- const model = this.run?.model;
578
- if (!model || this.run?.stopping || this.run?.disconnecting)
579
- throw new Error('No active Session.');
580
- if (model.subscribing)
581
- throw new Error('Wait for the Session snapshot.');
582
- return model;
583
- }
584
- async mutate(model, key, payload, send) {
585
- const result = await model.mutate(key, payload, send);
586
- if (model !== this.run?.model)
587
- return;
588
- const receipt = terminalObject(result);
589
- const core = terminalObject(receipt.core ?? receipt.result);
590
- const details = [receipt.status ?? core.status, core.disposition ?? receipt.disposition, receipt.reason ?? core.reason,
591
- core.cleanup === 'pending' ? 'cleanup pending' : undefined].filter(value => typeof value === 'string').join(' · ');
592
- this.notice(key + ' · ' + (details || (result === undefined ? 'already pending' : 'received')));
593
- if (model.operations.get(key)?.status === 'unknown')
594
- this.notice('Receipt unknown. Use /retry to reconcile.');
595
- }
596
- async sendInput(text, slash = false) {
597
- const model = this.run?.model;
598
- if (!model || this.run?.stopping || this.run?.disconnecting || model.result)
599
- throw new Error('No active Session.');
600
- const capability = model.state?.capabilities.input ?? (await model.session.describe()).input;
601
- if (model !== this.run?.model || this.run?.stopping || this.run?.disconnecting || this.closing)
602
- throw new Error('Session changed before input was submitted.');
603
- if (!capability.available)
604
- throw new Error(capability.reason ?? 'Harness input is unavailable.');
605
- let payload = text;
606
- const schema = terminalObject(capability.schema);
607
- if (!slash && (schema.type === 'object' || schema.type === 'array' || schema.type === 'number' ||
608
- schema.type === 'integer' || schema.type === 'boolean' || schema.type === 'null')) {
609
- try {
610
- payload = JSON.parse(text);
611
- }
612
- catch {
613
- throw new Error((capability.description ?? 'Harness input') + ' · Enter a JSON ' + schema.type + '.');
614
- }
615
- }
616
- this.notice('[you] ' + text);
617
- await this.mutate(model, 'input', payload, request => model.session.input(payload, request));
618
- }
619
- questions() {
620
- return [...(this.run?.model.questions.values() ?? [])].filter(question => question.status === 'pending' && Date.parse(question.deadline) > Date.now());
621
- }
622
- registeredInputs() {
623
- const names = this.run?.model.state?.capabilities.input.commands ?? this.loaded?.definition.inputDescriptor?.commands;
624
- return Array.isArray(names) ? names.filter((name) => typeof name === 'string' && /^[\/@]?[a-z][\w-]*$/.test(name)) : [];
625
- }
626
- inputCommands() {
627
- return this.registeredInputs().filter(name => !name.startsWith('@')).map(name => name.replace(/^\//, ''));
628
- }
629
- answer(command, args) {
630
- const pending = this.questions();
631
- const [first, rest] = splitInput(args);
632
- const confirm = command !== 'reply';
633
- const id = first.replace(/^#/, '');
634
- const requested = (confirm || rest) ? pending.find(question => question.questionId === id) : undefined;
635
- const namedApproval = command === 'approve' || command === 'reject';
636
- if (!requested && namedApproval && (!pending.length || first) &&
637
- (this.loaded?.actions.has(command) || this.inputCommands().includes(command)))
638
- return;
639
- const singleRejectionReason = command === 'reject' && pending.length === 1 && !first.startsWith('#');
640
- if (!requested && confirm && first && !singleRejectionReason)
641
- throw new Error('No pending confirmation with that ID.');
642
- const question = requested ?? (pending.length === 1 ? pending[0] : undefined);
643
- if (!question) {
644
- if (pending.length > 1)
645
- throw new Error('Choose a question by ID from the decision cards.');
646
- throw new Error('No pending question.');
647
- }
648
- const reply = requested ? rest : args;
649
- if (confirm && question.kind !== 'confirm')
650
- throw new Error('Use /reply with an option ID or text.');
651
- if (!confirm && question.kind === 'confirm')
652
- throw new Error('Use /y or /n for confirmation.');
653
- if (!confirm && (!reply || (question.kind === 'choice' && !question.options?.some(option => option.id === reply)))) {
654
- throw new Error('Enter an answer or use an option ID from the decision card.');
655
- }
656
- const answer = confirm ? command === 'y' || command === 'approve' : reply;
657
- if (typeof answer === 'string' && question.maxAnswerBytes !== undefined &&
658
- Buffer.byteLength(JSON.stringify(answer)) > question.maxAnswerBytes)
659
- throw new Error('Answer exceeds the question JSON byte limit.');
660
- const model = this.requireModel();
661
- if (confirm && reply)
662
- this.notice('[you · ' + question.questionId + '] ' + reply);
663
- return this.mutate(model, 'question:' + question.questionId, answer, request => model.session.respond(question.questionId, answer, request));
664
- }
665
- async submit(text) {
666
- if (!text || this.closing)
667
- return;
668
- if (Buffer.byteLength(text) > inputByteLimit)
669
- throw new Error('Input exceeds 256 KiB.');
670
- this.stream.scrollToEnd();
671
- this.selection = undefined;
672
- const [token, args] = splitInput(text);
673
- if (this.switchRequest && ['/y', '/n'].includes(text)) {
674
- const request = this.switchRequest;
675
- this.switchRequest = undefined;
676
- if (token === '/y' && request.run === this.run)
677
- await this.exclusive(() => this.select(request.specifier, request.prompt));
678
- else
679
- this.notice('Harness switch cancelled.');
680
- return;
681
- }
682
- if (token.startsWith('@')) {
683
- if (this.registeredInputs().includes(token))
684
- return this.sendInput(text, true);
685
- return this.agentControl(this.agentId(token.slice(1)), 'send', args);
686
- }
687
- if (!token.startsWith('/')) {
688
- if (text === 'q' && this.run?.observer)
689
- this.requestExit();
690
- else if (this.target)
691
- await this.agentControl(this.target, 'send', text);
692
- else if (this.running())
693
- await this.sendInput(text);
694
- else if (this.run?.observer || this.run?.model.result?.cleanup.status === 'pending') {
695
- throw new Error('The previous Session needs attention. Use /status or /use.');
696
- }
697
- else
698
- await this.exclusive(() => this.start(text));
699
- return;
700
- }
701
- const name = token.slice(1);
702
- if (name === 'use' || aliases.some(alias => alias === name)) {
703
- const [specifier, prompt] = name === 'use' ? splitInput(args) : [name, args];
704
- if (!specifier)
705
- throw new Error('Usage: /use <Harness> [initial prompt]');
706
- if (this.work)
707
- throw new Error('Wait for the current Harness operation.');
708
- const run = this.run;
709
- if (run && !run.observer && this.running(run)) {
710
- this.switchRequest = { run, specifier, prompt };
711
- this.notice('Stop the foreground Run and switch to /' + specifier + '? /y to stop or /n to stay.');
712
- }
713
- else
714
- await this.exclusive(() => this.select(specifier, prompt));
715
- return;
716
- }
717
- switch (name) {
718
- case 'quit':
719
- this.requestExit(undefined, true);
720
- return;
721
- case 'help': {
722
- const extra = [...new Set([...(this.loaded?.actions.keys() ?? []), ...this.inputCommands()])];
723
- this.notice(Object.keys(commands).map(command => '/' + command).join(' · ') +
724
- '\nModes ' + aliases.map(alias => '/' + alias).join(' · ') + ' · @agent <message>' +
725
- (extra.length ? '\nHarness commands ' + extra.map(name => '/' + name).join(' · ') : ''));
726
- return;
727
- }
728
- case 'status': {
729
- const model = this.run?.model;
730
- const roster = this.agents();
731
- this.notice('Run ' + (model?.state?.runId ?? 'none') + ' · ' + (model?.state?.phase ?? 'ready') +
732
- '\n' + [...roster.keys()].map(id => this.agentLine(id, roster)).join('\n') +
733
- this.questions().map(question => '\nDecision #' + question.questionId + ' · ' + question.text +
734
- (question.options?.length ? '\n' + question.options.map(option => option.id + ' · ' + option.label).join(' / ') : '')).join('') +
735
- (model?.result ? '\n' + reportLines(model.result).join('\n') : ''));
736
- return;
737
- }
738
- case 'trace': return this.openTrace(args);
739
- case 'agents': {
740
- const ids = [...this.agents().keys()];
741
- if (!ids.length) {
742
- this.notice('No Agents in the Session.');
743
- return;
744
- }
745
- this.selection = { ids, index: Math.max(0, ids.indexOf(this.target ?? '')) };
746
- this.redraw();
747
- return;
748
- }
749
- case 'target':
750
- this.target = args === 'main' ? undefined : this.agentId(args);
751
- this.notice('Target ' + (this.target ? '@' + agentName(this.target) : 'main'));
752
- return;
753
- case 'to': {
754
- const [target, message] = splitInput(args);
755
- const followUp = message.startsWith('--follow-up ');
756
- return this.agentControl(this.agentId(target.replace(/^@/, '')), 'send', followUp ? message.slice(12).trimStart() : message, followUp);
757
- }
758
- case 'stop':
759
- if (args)
760
- return this.agentControl(this.agentId(args.replace(/^@/, '')), 'stop');
761
- if (!this.run || !this.running())
762
- throw new Error('No active Run.');
763
- await this.stop(this.run, 'user-stop');
764
- return;
765
- case 'interrupt':
766
- if (!args)
767
- return this.interrupt();
768
- return this.agentControl(this.agentId(args.replace(/^@/, '')), 'interrupt');
769
- case 'config':
770
- return this.exclusive(async () => {
771
- if (!this.launcher || this.running())
772
- throw new Error('Select a Harness or stop the current Run before configuring.');
773
- if (args === '--remember')
774
- await this.launcher.remember();
775
- else if (args === '--forget')
776
- await this.launcher.forget();
777
- else if (args)
778
- await this.launcher.select(args === '--default' ? '' : args);
779
- this.addSecrets(this.launcher.configuration);
780
- this.notice(this.launcher.error ?? 'Configuration ' + this.launcher.source +
781
- (this.launcher.path ? ' · ' + this.launcher.path : '') + '\n/config <path> · /config --default · /config --remember · /config --forget');
782
- });
783
- case 'doctor':
784
- case 'setup-host':
785
- return this.exclusive(async () => {
786
- this.setupRunning = name === 'setup-host';
787
- try {
788
- await this.diagnose(name, args);
789
- }
790
- finally {
791
- this.setupRunning = false;
792
- }
793
- });
794
- case 'attach':
795
- return this.exclusive(async () => {
796
- if (this.run || !this.loaded || !this.launcher || !await this.attach(this.loaded, this.launcher)) {
797
- throw new Error('No new background Session can be attached.');
798
- }
799
- });
800
- case 'retry': {
801
- const model = this.requireModel();
802
- const unknown = [...model.operations].filter(([, operation]) => operation.status === 'unknown');
803
- const key = args || (unknown.length === 1 ? unknown[0][0] : undefined);
804
- if (!key || !unknown.some(([id]) => id === key)) {
805
- throw new Error(unknown.length ? 'Usage: /retry <operation>\n' + unknown.map(([id]) => id).join('\n') : 'No unknown receipts.');
806
- }
807
- await model.retry(key);
808
- this.notice(key + ' · ' + model.operations.get(key)?.status);
809
- return;
810
- }
811
- case 'y':
812
- case 'n':
813
- case 'approve':
814
- case 'reject':
815
- case 'reply': {
816
- const receipt = this.answer(name, args);
817
- if (receipt)
818
- return receipt;
819
- break;
820
- }
821
- }
822
- const action = this.loaded?.actions.get(name);
823
- if (action && this.launcher) {
824
- return this.exclusive(async () => {
825
- const launcher = this.launcher;
826
- if (launcher.error && launcher.path)
827
- throw new Error(launcher.error);
828
- const result = await action({ ...this.launchContext(launcher), args, progress: message => this.notice(message) });
829
- const launch = actionRun(result);
830
- if (launch) {
831
- await this.start(launch.prompt, launch);
832
- return;
833
- }
834
- const report = actionReport(result);
835
- const output = report ? report.result : result;
836
- if (output !== undefined)
837
- this.notice('[' + name + '] ' +
838
- (typeof output === 'string' ? output : JSON.stringify(this.redactor.value(output))));
839
- if (this.run?.observer && this.run.model.result) {
840
- await this.disconnectRun(this.run);
841
- this.releaseRun(this.run);
842
- }
843
- if (!this.run && this.loaded?.observe && !this.closing) {
844
- await launcher.refresh();
845
- this.addSecrets(launcher.configuration);
846
- await this.attach(this.loaded, launcher);
847
- }
848
- });
849
- }
850
- if (!this.running())
851
- throw new Error('Unknown command ' + token + '. Try /help.');
852
- return this.sendInput(text, true);
853
- }
854
- async diagnose(command, backend) {
855
- const preparing = command === 'setup-host';
856
- if (preparing && backend !== 'pi' && backend !== 'codex')
857
- throw new Error('Usage: /setup-host <pi|codex>');
858
- if (preparing && this.running())
859
- throw new Error('Stop the current Run before running setup.');
860
- const launcher = this.launcher ?? new LauncherConfiguration('', '', this.launchDirectory, this.command.cwd, this.command.configPath);
861
- if (!this.launcher)
862
- await launcher.refresh();
863
- await launcher.diagnose(preparing, this.shutdown.signal, text => this.notice(text), backend === 'pi' || backend === 'codex' ? backend : undefined);
864
- const report = launcher.diagnostics;
865
- for (const check of report?.checks ?? []) {
866
- this.notice((check.ok ? 'PASS ' : 'FAIL ') + check.id + ' · ' + check.detail + (check.remedy ? ' · ' + check.remedy : ''));
867
- }
868
- if (preparing)
869
- this.addSecrets(launcher.configuration);
870
- }
871
- interrupt() {
872
- if (!this.running()) {
873
- this.requestExit();
874
- return;
875
- }
876
- const state = this.run?.model.state;
877
- const roster = this.agents();
878
- const candidates = Object.entries(state?.capabilities.agents ?? {})
879
- .filter(([, actions]) => actions.interrupt?.available).map(([id]) => id);
880
- const roots = candidates.filter(id => agentName(id) === 'root' || roster.get(id)?.profile === 'root');
881
- const id = this.target ?? (roots.length === 1 ? roots[0] : undefined) ??
882
- (candidates.length === 1 ? candidates[0] : undefined);
883
- if (!id)
884
- throw new Error('Select an Agent to interrupt with /agents, or stop the Run with /stop.');
885
- return this.agentControl(id, 'interrupt');
886
- }
887
- handle(data) {
888
- if (this.closing)
889
- return;
890
- if (matchesKey(data, 'ctrl+c') || matchesKey(data, 'escape')) {
891
- if (this.switchRequest || this.selection) {
892
- this.switchRequest = undefined;
893
- this.selection = undefined;
894
- this.redraw();
895
- return;
896
- }
897
- if (matchesKey(data, 'ctrl+c'))
898
- return this.interrupt();
899
- }
900
- const selection = this.selection;
901
- if (selection) {
902
- if (matchesKey(data, 'up') || matchesKey(data, 'down')) {
903
- selection.index = (selection.index + (matchesKey(data, 'up') ? -1 : 1) + selection.ids.length) % selection.ids.length;
904
- this.redraw();
905
- return;
906
- }
907
- if (matchesKey(data, 'enter')) {
908
- this.selection = undefined;
909
- this.target = this.agentId(selection.ids[selection.index]);
910
- this.notice('Target @' + agentName(this.target));
911
- return;
912
- }
913
- this.selection = undefined;
914
- }
915
- if (matchesKey(data, 'pageUp') || matchesKey(data, 'pageDown')) {
916
- this.stream.scrollBy(this.stream.viewportHeight * (matchesKey(data, 'pageUp') ? -1 : 1));
917
- return;
918
- }
919
- if (matchesKey(data, 'ctrl+end')) {
920
- this.stream.scrollToEnd();
921
- return;
922
- }
923
- this.editor.handleInput(data);
924
- this.redraw();
925
- }
926
- streamLines() {
927
- const model = this.run?.model;
928
- const entries = [...this.entries];
929
- for (const message of model?.messages.values() ?? []) {
930
- if (message.hidden || ['toolResult', 'tool', 'system', 'developer'].includes(message.role))
931
- continue;
932
- const text = [...message.blocks.entries()].sort(([a], [b]) => a - b).map(([, value]) => value).join('');
933
- if (text)
934
- entries.push({ order: message.order, text: '[' + (agentName(message.agentId) || message.role) + '] ' +
935
- text.slice(-8192) + (message.truncated ? ' […]' : '') });
936
- }
937
- for (const activity of model?.activity.values() ?? []) {
938
- entries.push({ order: activity.order, text: '[' + (agentName(activity.agentId) || 'harness') + '] ' + activity.event +
939
- (activity.summary ? ' · ' + activity.summary : '') });
940
- }
941
- return entries.sort((a, b) => a.order - b.order).map(entry => entry.text);
942
- }
943
- render(width) {
944
- const rows = this.terminal.rows;
945
- if (width < 8 || rows < 5)
946
- return [truncateToWidth('anys', width, '')];
947
- const model = this.run?.model;
948
- const state = model?.state;
949
- const pending = this.questions();
950
- const roster = this.agents();
951
- const agents = [...roster.values()].filter(agent => !['closed', 'closing', 'exited', 'stopped'].includes(agent.status));
952
- const counts = new Map();
953
- for (const agent of agents)
954
- counts.set(agent.status, (counts.get(agent.status) ?? 0) + 1);
955
- const phase = model?.result ? 'finished' : pending.length ? 'waiting' : state?.phase ??
956
- (this.run ? 'starting' : 'ready');
957
- const mode = this.specifier ? this.modeLabel() : 'select a Harness';
958
- const summary = terminalObject(state?.business).summary;
959
- const workspace = this.launcher?.workspace ?? resolve(this.launchDirectory, this.command.cwd ?? '.');
960
- const routes = Object.keys(terminalObject(this.launcher?.configuration?.models));
961
- const fit = (line) => truncateToWidth(this.clean(line).replace(/\s*\n\s*/g, ' '), width, '');
962
- const header = [
963
- bold(fit('anys · ' + phase + ' · ' + mode + (this.run?.observer ? ' [attached]' : this.loaded?.observe ? ' [detached]' : '') +
964
- ' · Agents ' + agents.length + [...counts].map(([status, count]) => ' · ' + count + ' ' + status).join(''))),
965
- ];
966
- if (rows >= 7)
967
- header.push(dim(fit((this.trace ? 'Trace ' + this.trace.url : '/trace') + ' · ' +
968
- (typeof summary === 'string' && summary ? summary : workspace + (routes.length ? ' · model ' + routes.join('/') : '')))));
969
- if (rows >= 9)
970
- header.push(dim('─'.repeat(width)));
971
- this.editor.label = this.clean((this.specifier ? mode : 'anys') + (this.target ? ' @' + agentName(this.target) : ''))
972
- .replace(/\s*\n\s*/g, ' ');
973
- const maxEditorRows = Math.min(Math.ceil(rows / 3), rows - header.length - 2);
974
- const [promptRule, ...input] = this.editor.render(width);
975
- const cursorLine = input.findIndex(line => line.includes(CURSOR_MARKER));
976
- const editorStart = Math.max(0, Math.min(input.length - maxEditorRows, cursorLine < 0 ? 0 : cursorLine - maxEditorRows + 1));
977
- const editor = input.slice(editorStart, editorStart + maxEditorRows);
978
- const room = rows - header.length - 1 - editor.length;
979
- const cards = pending.flatMap(question => {
980
- const choices = question.options?.map(option => option.id + ' · ' + option.label).join(' / ');
981
- const help = question.kind === 'confirm' ? '/y or /n' : '/reply ' + question.questionId + ' <' +
982
- (question.kind === 'choice' ? 'option' : 'answer') + '>';
983
- return wrapTextWithAnsi(this.clean('◆ Decision #' + question.questionId + ' · ' +
984
- (question.agentId ?? question.sourceId) + '\n' + question.text + (choices ? '\n' + choices : '') +
985
- '\n' + help).slice(0, 4096), width);
986
- });
987
- const selection = this.selection;
988
- const selected = selection ? ['Agents · ↑/↓ select · Enter targets · Esc closes',
989
- ...selection.ids.slice(Math.max(0, selection.index - 2), selection.index + 3).map(id => (id === selection.ids[selection.index] ? '› ' : ' ') + this.agentLine(id, roster))] : [];
990
- const switchHint = this.switchRequest ? ['Confirm switch with /y or /n'] : [];
991
- const overlay = [...switchHint, ...(selected.length ? selected : cards)].slice(0, Math.max(0, room - 1)).map(line => {
992
- const visible = fit(line);
993
- return visible.startsWith('◆') ? '\x1b[1;33m' + visible + '\x1b[0m' : visible;
994
- });
995
- const warnings = model?.subscribing ? ['Session snapshot pending'] :
996
- model?.observationLost || model?.runtimeObservationLost || model?.workerHistoryLost || model?.truncated
997
- ? ['Stream history may be incomplete · /trace'] : [];
998
- const text = this.clean([...this.streamLines(), ...warnings].join('\n').slice(-100_000));
999
- const lines = text ? wrapTextWithAnsi(text, width) : [];
1000
- const height = Math.max(0, room - overlay.length);
1001
- this.stream.updateLayout(lines.length, height, () => this.redraw());
1002
- const body = lines.slice(this.stream.scrollTop, this.stream.scrollTop + height);
1003
- return [...header, ...body, ...Array(height - body.length).fill(''), ...overlay, promptRule, ...editor];
1004
- }
1005
- }
1006
- export async function runAnySwarmTui(command, launchDirectory) {
1007
- if (!interactiveTerminal()) {
1008
- console.error('The TUI needs an interactive terminal on stdin and stdout. Use anys -u H --headless or --rpc.');
1009
- return 2;
1010
- }
1011
- return new Foreground(command, launchDirectory).open();
1012
- }