bash-output-writer.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import type { LocalTaskRunnerHostWithSessionLookup } from '../api/local-task-host.js';
  2. import type { TaskOutputReadResult, TaskOutputRef } from './domain.js';
  3. import type { LocalBackgroundBashExecutorResult } from './bash-executor.js';
  4. const OUTPUT_READ_CHUNK_BYTES = 64 * 1024;
  5. const ERROR_OUTPUT_PREFIX_CHARS = 64 * 1024;
  6. const INITIAL_RECOVERY_RETRY_MS = 100;
  7. const MAX_RECOVERY_RETRY_MS = 5_000;
  8. const MAX_RECOVERY_CHARS = 1024 * 1024;
  9. const TERMINAL_REPAIR_ATTEMPTS = 3;
  10. const TERMINAL_REPAIR_DELAY_MS = 25;
  11. export class BackgroundBashOutputWriter {
  12. outputBytes = 0;
  13. streamedOutput = false;
  14. streamedTextForError = '';
  15. private lastOutputRef: TaskOutputRef | undefined;
  16. private pendingContent = '';
  17. private drainPromise: Promise<void> | undefined;
  18. private rawOutputAccounting = false;
  19. private persistenceIncomplete = false;
  20. private recoveryOffset = 0;
  21. private recoveryContent = '';
  22. private droppedRecoveryBytes = 0;
  23. private retryTimer: NodeJS.Timeout | undefined;
  24. private retryDelayMs = INITIAL_RECOVERY_RETRY_MS;
  25. private settling = false;
  26. constructor(
  27. private readonly host: LocalTaskRunnerHostWithSessionLookup,
  28. private readonly ownerSessionId: string,
  29. private readonly taskId: string,
  30. ) {}
  31. readonly push = (content: string, byteLength?: number): void => {
  32. if (byteLength !== undefined) this.rawOutputAccounting = true;
  33. this.outputBytes += byteLength ?? Buffer.byteLength(content, 'utf8');
  34. if (!content) return;
  35. this.streamedOutput = true;
  36. if (this.streamedTextForError.length < ERROR_OUTPUT_PREFIX_CHARS) {
  37. this.streamedTextForError += content.slice(
  38. 0,
  39. ERROR_OUTPUT_PREFIX_CHARS - this.streamedTextForError.length,
  40. );
  41. }
  42. if (this.persistenceIncomplete) this.queueRecovery(content);
  43. else this.pendingContent += content;
  44. this.startDrain();
  45. };
  46. async settleSuccess(
  47. result: LocalBackgroundBashExecutorResult,
  48. ): Promise<TaskOutputRef | undefined> {
  49. this.beginSettlement();
  50. await this.flush();
  51. if (!this.streamedOutput && !this.rawOutputAccounting) {
  52. this.outputBytes = Buffer.byteLength(result.text, 'utf8');
  53. }
  54. if (!this.persistenceIncomplete) {
  55. return this.lastOutputRef ?? (await this.tryAppend(result.text, 'final_result'));
  56. }
  57. try {
  58. return await this.repairPendingOutput();
  59. } catch (error) {
  60. this.warn('repair', error);
  61. return this.lastOutputRef;
  62. }
  63. }
  64. async settleFailure(content: string): Promise<TaskOutputRef | undefined> {
  65. this.beginSettlement();
  66. await this.flush();
  67. if (this.persistenceIncomplete) {
  68. try {
  69. const repaired = await this.repairPendingOutput();
  70. return (await this.appendTerminalOutput(content)) ?? repaired;
  71. } catch (error) {
  72. this.warn('repair', error);
  73. return this.lastOutputRef;
  74. }
  75. }
  76. return this.appendTerminalOutput(content);
  77. }
  78. private startDrain(): void {
  79. // Once the bounded window overflows, defer its omission marker until the
  80. // executor settles. This freezes the byte count while it is persisted and
  81. // keeps ambiguous "append succeeded, response failed" retries prefix-safe.
  82. if (this.drainPromise || this.retryTimer || (!this.settling && this.droppedRecoveryBytes > 0))
  83. return;
  84. this.drainPromise = this.drain().finally(() => {
  85. this.drainPromise = undefined;
  86. });
  87. }
  88. private async drain(): Promise<void> {
  89. for (;;) {
  90. if (this.persistenceIncomplete) {
  91. if (!this.settling && this.droppedRecoveryBytes > 0) return;
  92. try {
  93. const outputRef = await this.repairPendingOutput();
  94. if (outputRef) this.lastOutputRef = outputRef;
  95. } catch (error) {
  96. this.warn('repair', error);
  97. this.scheduleRetry();
  98. return;
  99. }
  100. continue;
  101. }
  102. if (!this.pendingContent) return;
  103. const content = this.pendingContent;
  104. this.pendingContent = '';
  105. const outputRef = await this.tryAppend(content, 'stdout');
  106. if (outputRef) this.lastOutputRef = outputRef;
  107. else {
  108. this.persistenceIncomplete = true;
  109. this.recoveryOffset = this.lastOutputRef?.offset ?? 0;
  110. this.queueRecovery(content);
  111. this.queueRecovery(this.pendingContent);
  112. this.pendingContent = '';
  113. }
  114. }
  115. }
  116. private async flush(): Promise<void> {
  117. this.startDrain();
  118. await this.drainPromise;
  119. }
  120. private beginSettlement(): void {
  121. this.settling = true;
  122. if (this.retryTimer) clearTimeout(this.retryTimer);
  123. this.retryTimer = undefined;
  124. }
  125. private scheduleRetry(): void {
  126. if (this.settling || this.retryTimer || this.droppedRecoveryBytes > 0) return;
  127. this.retryTimer = setTimeout(() => {
  128. this.retryTimer = undefined;
  129. this.startDrain();
  130. }, this.retryDelayMs);
  131. this.retryTimer.unref?.();
  132. this.retryDelayMs = Math.min(this.retryDelayMs * 2, MAX_RECOVERY_RETRY_MS);
  133. }
  134. private queueRecovery(content: string): void {
  135. if (!content) return;
  136. const availableChars =
  137. this.droppedRecoveryBytes > 0
  138. ? 0
  139. : Math.max(0, MAX_RECOVERY_CHARS - this.recoveryContent.length);
  140. let retained = content.slice(0, availableChars);
  141. if (retained && isHighSurrogate(retained.charCodeAt(retained.length - 1))) {
  142. retained = retained.slice(0, -1);
  143. }
  144. this.recoveryContent += retained;
  145. this.droppedRecoveryBytes += Math.max(
  146. 0,
  147. Buffer.byteLength(content, 'utf8') - Buffer.byteLength(retained, 'utf8'),
  148. );
  149. }
  150. warn(operation: string, error: unknown): void {
  151. try {
  152. this.host.matrixLogger?.warn(
  153. { sessionId: this.ownerSessionId, turnId: this.taskId },
  154. `Failed to ${operation} background bash output: ${formatError(error)}`,
  155. );
  156. } catch {
  157. // Diagnostics must not turn a recoverable persistence failure into a
  158. // runner failure after the command has already settled.
  159. }
  160. }
  161. private async repairPendingOutput(): Promise<TaskOutputRef | undefined> {
  162. const recoveryContent = this.recoveryContent;
  163. const droppedRecoveryBytes = this.droppedRecoveryBytes;
  164. const expectedContent = recoveryContent + formatDroppedOutputMarker(droppedRecoveryBytes);
  165. const persisted = await readAllTaskOutput(this.host, this.taskId, this.recoveryOffset);
  166. let repaired = persisted.outputRef ?? this.lastOutputRef;
  167. if (!expectedContent.startsWith(persisted.content)) {
  168. throw new Error('persisted output is not a prefix of the pending bash output');
  169. }
  170. if (persisted.content !== expectedContent) {
  171. repaired = await this.tryAppend(
  172. expectedContent.slice(persisted.content.length),
  173. 'final_result',
  174. );
  175. if (!repaired) {
  176. const afterRetry = await readAllTaskOutput(this.host, this.taskId, this.recoveryOffset);
  177. if (afterRetry.content !== expectedContent) {
  178. throw new Error('pending bash output suffix could not be persisted');
  179. }
  180. repaired = afterRetry.outputRef ?? this.lastOutputRef;
  181. }
  182. }
  183. this.recoveryContent = this.recoveryContent.slice(recoveryContent.length);
  184. this.droppedRecoveryBytes = Math.max(0, this.droppedRecoveryBytes - droppedRecoveryBytes);
  185. this.lastOutputRef = repaired ?? this.lastOutputRef;
  186. this.recoveryOffset =
  187. repaired?.offset ?? this.recoveryOffset + Buffer.byteLength(expectedContent, 'utf8');
  188. this.persistenceIncomplete = this.recoveryContent.length > 0 || this.droppedRecoveryBytes > 0;
  189. this.retryDelayMs = INITIAL_RECOVERY_RETRY_MS;
  190. return this.lastOutputRef;
  191. }
  192. private async appendTerminalOutput(content: string): Promise<TaskOutputRef | undefined> {
  193. const appended = await this.tryAppend(content, 'final_result');
  194. if (appended) {
  195. this.lastOutputRef = appended;
  196. return appended;
  197. }
  198. this.persistenceIncomplete = true;
  199. this.recoveryOffset = this.lastOutputRef?.offset ?? this.recoveryOffset;
  200. this.recoveryContent = content;
  201. this.droppedRecoveryBytes = 0;
  202. for (let attempt = 0; attempt < TERMINAL_REPAIR_ATTEMPTS; attempt += 1) {
  203. try {
  204. return await this.repairPendingOutput();
  205. } catch (error) {
  206. this.warn('repair terminal', error);
  207. if (attempt + 1 < TERMINAL_REPAIR_ATTEMPTS) {
  208. await delay(TERMINAL_REPAIR_DELAY_MS * 2 ** attempt);
  209. }
  210. }
  211. }
  212. return this.lastOutputRef;
  213. }
  214. private async tryAppend(
  215. content: string,
  216. stream: 'stdout' | 'final_result',
  217. ): Promise<TaskOutputRef | undefined> {
  218. try {
  219. return await this.host.backgroundTaskService.appendOutput({
  220. taskId: this.taskId,
  221. stream,
  222. content,
  223. timestamp: this.host.nowMs(),
  224. });
  225. } catch (error) {
  226. this.warn('persist', error);
  227. return undefined;
  228. }
  229. }
  230. }
  231. async function readAllTaskOutput(
  232. host: LocalTaskRunnerHostWithSessionLookup,
  233. taskId: string,
  234. initialOffset = 0,
  235. ): Promise<Pick<TaskOutputReadResult, 'content' | 'outputRef'>> {
  236. const chunks: string[] = [];
  237. let offset = initialOffset;
  238. let outputRef: TaskOutputRef | undefined;
  239. for (;;) {
  240. const read = await host.backgroundTaskService.readOutput(taskId, {
  241. offset,
  242. limitBytes: OUTPUT_READ_CHUNK_BYTES,
  243. });
  244. chunks.push(read.content);
  245. outputRef = read.outputRef ?? outputRef;
  246. const nextOffset = read.nextOffset ?? offset + Buffer.byteLength(read.content, 'utf8');
  247. if (!read.truncated || nextOffset <= offset) return { content: chunks.join(''), outputRef };
  248. offset = nextOffset;
  249. }
  250. }
  251. function formatError(error: unknown): string {
  252. return error instanceof Error ? error.message : String(error);
  253. }
  254. function formatDroppedOutputMarker(droppedBytes: number): string {
  255. return droppedBytes > 0
  256. ? `\n<bash_status>Output persistence was unavailable; omitted ${droppedBytes} bytes.</bash_status>\n`
  257. : '';
  258. }
  259. function isHighSurrogate(codeUnit: number): boolean {
  260. return codeUnit >= 0xd800 && codeUnit <= 0xdbff;
  261. }
  262. async function delay(ms: number): Promise<void> {
  263. await new Promise<void>((resolve) => setTimeout(resolve, ms));
  264. }