tui-scripted-llm.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. import type { Context } from 'cordis'
  2. import type {
  3. GenerateOptions,
  4. LlmModelInfo,
  5. LlmResolvedModelInfo,
  6. StreamChunk,
  7. } from '@deepseek-ai/dsh-llm'
  8. import { CallId, LlmAdapter, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
  9. const CONTROL_PROBE = '\u001b]2;MODEL_CONTROLLED\u0007\u001b[999CMODEL_CURSOR\u009b31mMODEL_C1'
  10. const INITIAL_TEXT = `I need one decision before I continue. ${CONTROL_PROBE}`
  11. const FINAL_TEXT = 'Decision received. Scripted TUI run complete.'
  12. const DEFAULT_MODE_PROBE = 'Confirm the scripted run left plan mode.'
  13. const DEFAULT_MODE_TEXT = 'Default mode confirmed.'
  14. // The `skill` scenario types `/skill:scripted-skill`; the manual-invocation front
  15. // door delivers the loaded skill as a user turn wrapped in `<skill name="…">`. The
  16. // body marker below lives in the fixture skill, so echoing it back proves the whole
  17. // block (name attribute plus body) reached the model, not just the command text.
  18. const SKILL_BLOCK_OPEN = '<skill name="scripted-skill">'
  19. const SKILL_BODY_MARKER = 'SCRIPTED SKILL BODY MARKER'
  20. const SKILL_RECEIVED_TEXT = 'Scripted skill body received.'
  21. const TITLE_TEXT = 'scripted session title'
  22. function textChunks(text: string): StreamChunk[] {
  23. return [
  24. { type: 'block-start', index: 0, blockType: 'text' },
  25. ...Array.from(text, (char): StreamChunk => ({ type: 'text-delta', index: 0, text: char })),
  26. { type: 'block-end', index: 0, block: { type: 'text', text } },
  27. { type: 'usage', usage: { inputTokens: 20, outputTokens: text.length } },
  28. { type: 'finish', reason: { kind: 'stop' } },
  29. ]
  30. }
  31. /** Keyless adapter for the real-PTY TUI tests: the two-step conversation and the `/skill:` round-trip. */
  32. class ScriptedTuiAdapter extends LlmAdapter {
  33. override listModels(provider: string): Promise<readonly LlmModelInfo[]> {
  34. return Promise.resolve([
  35. { provider, id: 'tui-scripted-model', name: 'Scripted Base' },
  36. { provider, id: 'tui-scripted-model-pro', name: 'Scripted Pro' },
  37. ])
  38. }
  39. override resolveModel(
  40. provider: string,
  41. model: string,
  42. ): Promise<LlmResolvedModelInfo> {
  43. return Promise.resolve({
  44. provider,
  45. id: model,
  46. name: model === 'tui-scripted-model-pro' ? 'Scripted Pro' : 'Scripted Base',
  47. context: { contextWindow: 128_000 },
  48. ...model !== 'tui-scripted-model-pro'
  49. ? {}
  50. : {
  51. reasoning: {
  52. efforts: [
  53. { id: ReasoningEffortId('off'), name: 'Off' },
  54. { id: ReasoningEffortId('high'), name: 'High' },
  55. { id: ReasoningEffortId('max'), name: 'Max' },
  56. ],
  57. defaultEffort: ReasoningEffortId('high'),
  58. },
  59. },
  60. })
  61. }
  62. override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  63. // The session-title provider's auxiliary request carries no tool schemas,
  64. // unlike every agent turn; answer it with a fixed title so the PTY test can
  65. // assert the logged title reaches the terminal window title.
  66. if ((options.tools?.length ?? 0) === 0) {
  67. for (const chunk of textChunks(TITLE_TEXT)) yield chunk
  68. return
  69. }
  70. if (
  71. options.model !== 'tui-scripted-model-pro'
  72. || !options.system?.includes('tui-scripted-model-pro')
  73. || options.reasoningEffort !== ReasoningEffortId('max')
  74. ) {
  75. throw new Error('the scripted TUI request did not apply the selected model and reasoning effort')
  76. }
  77. const lastMessage = options.messages.at(-1)
  78. // The loop appends plugin-sourced context (the plan-mode notice, the
  79. // tool-skill catalog) AFTER the admitted prompt, so the scripted trigger
  80. // may sit one or more user messages back: scan the whole trailing run of
  81. // user-role messages since the last assistant message.
  82. const trailingUserTexts: string[] = []
  83. for (let index = options.messages.length - 1; index >= 0; index--) {
  84. const message = options.messages[index]
  85. if (message?.role !== 'user') break
  86. for (const block of message.content) {
  87. if (block.type === 'text') trailingUserTexts.push(block.text)
  88. }
  89. }
  90. const lastText = trailingUserTexts.join('\n')
  91. if (lastText.includes(DEFAULT_MODE_PROBE)) {
  92. if (options.system?.includes('Stay in plan mode for this scripted TUI test.')) {
  93. throw new Error('the scripted TUI request retained plan guidance after /plan off')
  94. }
  95. for (const chunk of textChunks(DEFAULT_MODE_TEXT)) yield chunk
  96. return
  97. }
  98. if (lastText.includes(SKILL_BLOCK_OPEN)) {
  99. const ack = lastText.includes(SKILL_BODY_MARKER)
  100. ? SKILL_RECEIVED_TEXT
  101. : 'Scripted skill block arrived without its body.'
  102. for (const chunk of textChunks(ack)) yield chunk
  103. return
  104. }
  105. const hasToolResult = lastMessage?.content.some(block => block.type === 'tool-result') ?? false
  106. if (hasToolResult) {
  107. for (const chunk of textChunks(FINAL_TEXT)) yield chunk
  108. return
  109. }
  110. const args = JSON.stringify({
  111. questions: [{
  112. id: 'mode',
  113. header: 'Execution mode',
  114. question: 'How should the scripted run proceed?',
  115. options: [
  116. { label: 'Safe', description: 'Use the guarded path.' },
  117. { label: 'Fast', description: 'Use the shorter path.' },
  118. ],
  119. }],
  120. })
  121. const callId = CallId('call-ask-mode')
  122. yield { type: 'block-start', index: 0, blockType: 'text' }
  123. for (const char of INITIAL_TEXT) yield { type: 'text-delta', index: 0, text: char }
  124. yield { type: 'block-end', index: 0, block: { type: 'text', text: INITIAL_TEXT } }
  125. yield { type: 'block-start', index: 1, blockType: 'tool-call' }
  126. yield { type: 'tool-call-delta', index: 1, id: callId, name: 'ask_user_question', argumentsDelta: args }
  127. yield {
  128. type: 'block-end',
  129. index: 1,
  130. block: { type: 'tool-call', id: callId, name: 'ask_user_question', arguments: args },
  131. }
  132. yield { type: 'usage', usage: { inputTokens: 20, outputTokens: 10 } }
  133. yield { type: 'finish', reason: { kind: 'tool-calls' } }
  134. }
  135. }
  136. export const name = 'tui-scripted-llm'
  137. export const inject = ['llm']
  138. /** Register the network-free adapter used by the PTY fixture. */
  139. export function apply(ctx: Context): void {
  140. ctx.llm.registerAdapter(['tui-scripted'], new ScriptedTuiAdapter())
  141. }