tui-scripted-llm.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import type { Context } from 'cordis'
  2. import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
  3. import { CallId, LlmAdapter } from '@deepseek-ai/dsh-llm'
  4. const CONTROL_PROBE = '\u001b]2;MODEL_CONTROLLED\u0007\u001b[999CMODEL_CURSOR\u009b31mMODEL_C1'
  5. const INITIAL_TEXT = `I need one decision before I continue. ${CONTROL_PROBE}`
  6. const FINAL_TEXT = 'Decision received. Scripted TUI run complete.'
  7. function textChunks(text: string): StreamChunk[] {
  8. return [
  9. { type: 'block-start', index: 0, blockType: 'text' },
  10. ...Array.from(text, (char): StreamChunk => ({ type: 'text-delta', index: 0, text: char })),
  11. { type: 'block-end', index: 0, block: { type: 'text', text } },
  12. { type: 'usage', usage: { inputTokens: 20, outputTokens: text.length } },
  13. { type: 'finish', reason: { kind: 'stop' } },
  14. ]
  15. }
  16. /** Keyless two-step adapter for the real-PTY TUI conversation test. */
  17. class ScriptedTuiAdapter extends LlmAdapter {
  18. async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  19. const hasToolResult = options.messages.at(-1)?.content.some(block => block.type === 'tool-result') ?? false
  20. if (hasToolResult) {
  21. for (const chunk of textChunks(FINAL_TEXT)) yield chunk
  22. return
  23. }
  24. const args = JSON.stringify({
  25. questions: [{
  26. id: 'mode',
  27. header: 'Execution mode',
  28. question: 'How should the scripted run proceed?',
  29. options: [
  30. { label: 'Safe', description: 'Use the guarded path.' },
  31. { label: 'Fast', description: 'Use the shorter path.' },
  32. ],
  33. }],
  34. })
  35. const callId = CallId('call-ask-mode')
  36. yield { type: 'block-start', index: 0, blockType: 'text' }
  37. for (const char of INITIAL_TEXT) yield { type: 'text-delta', index: 0, text: char }
  38. yield { type: 'block-end', index: 0, block: { type: 'text', text: INITIAL_TEXT } }
  39. yield { type: 'block-start', index: 1, blockType: 'tool-call' }
  40. yield { type: 'tool-call-delta', index: 1, id: callId, name: 'ask_user_question', argumentsDelta: args }
  41. yield {
  42. type: 'block-end',
  43. index: 1,
  44. block: { type: 'tool-call', id: callId, name: 'ask_user_question', arguments: args },
  45. }
  46. yield { type: 'usage', usage: { inputTokens: 20, outputTokens: 10 } }
  47. yield { type: 'finish', reason: { kind: 'tool-calls' } }
  48. }
  49. }
  50. export const name = 'tui-scripted-llm'
  51. export const inject = ['llm']
  52. /** Register the network-free adapter used by the PTY fixture. */
  53. export function apply(ctx: Context): void {
  54. ctx.llm.registerAdapter(['tui-scripted'], new ScriptedTuiAdapter())
  55. }