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