service.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. import { spawn } from 'node:child_process';
  2. import * as fs from 'node:fs/promises';
  3. import * as path from 'node:path';
  4. import type { PluginInput } from '@opencode-ai/plugin';
  5. import type { InterviewConfig } from '../config';
  6. import {
  7. createInternalAgentTextPart,
  8. hasInternalInitiatorMarker,
  9. log,
  10. } from '../utils';
  11. import { parseModelReference } from '../utils/session';
  12. import {
  13. appendInterviewAnswers,
  14. createInterviewDirectoryPath,
  15. createInterviewFilePath,
  16. DEFAULT_OUTPUT_FOLDER,
  17. ensureInterviewFile,
  18. extractSummarySection,
  19. extractTitle,
  20. normalizeOutputFolder,
  21. readInterviewDocument,
  22. relativeInterviewPath,
  23. resolveExistingInterviewPath,
  24. rewriteInterviewDocument,
  25. slugify,
  26. } from './document';
  27. import { buildFallbackState, findLatestAssistantState } from './parser';
  28. import {
  29. buildAnswerPrompt,
  30. buildKickoffPrompt,
  31. buildResumePrompt,
  32. } from './prompts';
  33. import type {
  34. InterviewAnswer,
  35. InterviewFileItem,
  36. InterviewListItem,
  37. InterviewMessage,
  38. InterviewRecord,
  39. InterviewState,
  40. } from './types';
  41. const COMMAND_NAME = 'interview';
  42. const DEFAULT_MAX_QUESTIONS = 2;
  43. function isTruthyEnvFlag(value: string | undefined): boolean {
  44. if (!value) {
  45. return false;
  46. }
  47. return value !== '0' && value.toLowerCase() !== 'false';
  48. }
  49. function isAutomatedRuntime(env: NodeJS.ProcessEnv): boolean {
  50. return (
  51. env.NODE_ENV === 'test' ||
  52. isTruthyEnvFlag(env.CI) ||
  53. isTruthyEnvFlag(env.BUN_TEST) ||
  54. isTruthyEnvFlag(env.VITEST) ||
  55. env.JEST_WORKER_ID !== undefined
  56. );
  57. }
  58. function shouldAutoOpenBrowser(
  59. config: InterviewConfig | undefined,
  60. env: NodeJS.ProcessEnv,
  61. ): boolean {
  62. const requested = config?.autoOpenBrowser ?? true;
  63. return requested && !isAutomatedRuntime(env);
  64. }
  65. /**
  66. * Open a URL in the default browser.
  67. * Supports macOS, Linux, and Windows. Failures are logged but not thrown.
  68. */
  69. function openBrowser(url: string): void {
  70. const platform = process.platform;
  71. let command: string;
  72. let args: string[];
  73. if (platform === 'darwin') {
  74. command = 'open';
  75. args = [url];
  76. } else if (platform === 'win32') {
  77. command = 'cmd';
  78. args = ['/c', 'start', '', url];
  79. } else {
  80. // Linux and other Unix-like systems
  81. command = 'xdg-open';
  82. args = [url];
  83. }
  84. try {
  85. const child = spawn(command, args, { detached: true, stdio: 'ignore' });
  86. child.on('error', (error) => {
  87. log('[interview] failed to open browser:', { error: error.message, url });
  88. });
  89. child.unref();
  90. } catch (error) {
  91. log('[interview] failed to spawn browser opener:', {
  92. error: error instanceof Error ? error.message : String(error),
  93. url,
  94. });
  95. }
  96. }
  97. function nowIso(): string {
  98. return new Date().toISOString();
  99. }
  100. export function createInterviewService(
  101. ctx: PluginInput,
  102. config?: InterviewConfig,
  103. deps?: {
  104. openBrowser?: (url: string) => void;
  105. env?: NodeJS.ProcessEnv;
  106. },
  107. ): {
  108. setBaseUrlResolver: (resolver: () => Promise<string>) => void;
  109. setStatePushCallback: (
  110. callback: (interviewId: string, state: InterviewState) => void,
  111. ) => void;
  112. setOnInterviewCreated: (
  113. callback: (interview: InterviewRecord) => void,
  114. ) => void;
  115. getActiveInterviewId: (sessionID: string) => string | null;
  116. registerCommand: (config: Record<string, unknown>) => void;
  117. handleCommandExecuteBefore: (
  118. input: { command: string; sessionID: string; arguments: string },
  119. output: { parts: Array<{ type: string; text?: string }> },
  120. ) => Promise<void>;
  121. handleEvent: (input: {
  122. event: { type: string; properties?: Record<string, unknown> };
  123. }) => Promise<void>;
  124. getInterviewState: (interviewId: string) => Promise<InterviewState>;
  125. listInterviewFiles: () => Promise<InterviewFileItem[]>;
  126. listInterviews: () => InterviewListItem[];
  127. submitAnswers: (
  128. interviewId: string,
  129. answers: InterviewAnswer[],
  130. ) => Promise<void>;
  131. handleNudgeAction: (
  132. interviewId: string,
  133. action: 'more-questions' | 'confirm-complete',
  134. ) => Promise<void>;
  135. } {
  136. const maxQuestions = config?.maxQuestions ?? DEFAULT_MAX_QUESTIONS;
  137. const outputFolder = normalizeOutputFolder(
  138. config?.outputFolder ?? DEFAULT_OUTPUT_FOLDER,
  139. );
  140. const autoOpenBrowser = shouldAutoOpenBrowser(
  141. config,
  142. deps?.env ?? process.env,
  143. );
  144. const browserOpener = deps?.openBrowser ?? openBrowser;
  145. const activeInterviewIds = new Map<string, string>();
  146. const interviewsById = new Map<string, InterviewRecord>();
  147. const sessionBusy = new Map<string, boolean>();
  148. const sessionModel = new Map<string, string>();
  149. const browserOpened = new Set<string>(); // Track interviews that have opened browser
  150. let resolveBaseUrl: (() => Promise<string>) | null = null;
  151. let onStateChange:
  152. | ((interviewId: string, state: InterviewState) => void)
  153. | null = null;
  154. let onInterviewCreated: ((interview: InterviewRecord) => void) | null = null;
  155. let idCounter = 0;
  156. function setBaseUrlResolver(resolver: () => Promise<string>): void {
  157. resolveBaseUrl = resolver;
  158. }
  159. function setStatePushCallback(
  160. callback: (interviewId: string, state: InterviewState) => void,
  161. ): void {
  162. onStateChange = callback;
  163. }
  164. function setOnInterviewCreated(
  165. callback: (interview: InterviewRecord) => void,
  166. ): void {
  167. onInterviewCreated = callback;
  168. }
  169. function getActiveInterviewId(sessionID: string): string | null {
  170. return activeInterviewIds.get(sessionID) ?? null;
  171. }
  172. async function ensureServer(): Promise<string> {
  173. if (!resolveBaseUrl) {
  174. throw new Error('Interview server is not attached');
  175. }
  176. return resolveBaseUrl();
  177. }
  178. function maybeOpenBrowser(interviewId: string, url: string): void {
  179. if (!autoOpenBrowser) {
  180. return;
  181. }
  182. if (browserOpened.has(interviewId)) {
  183. return;
  184. }
  185. browserOpened.add(interviewId);
  186. browserOpener(url);
  187. }
  188. async function maybeRenameWithTitle(
  189. interview: InterviewRecord,
  190. assistantTitle: string | undefined,
  191. ): Promise<void> {
  192. if (!assistantTitle) {
  193. return;
  194. }
  195. const newSlug = slugify(assistantTitle);
  196. if (!newSlug) {
  197. return;
  198. }
  199. const currentFileName = path.basename(interview.markdownPath, '.md');
  200. // If already matches (or user-provided idea matches), skip
  201. if (currentFileName === newSlug) {
  202. return;
  203. }
  204. const dir = path.dirname(interview.markdownPath);
  205. const newPath = path.join(dir, `${newSlug}.md`);
  206. // Don't overwrite existing files
  207. try {
  208. await fs.access(newPath);
  209. // File exists, don't rename
  210. return;
  211. } catch {
  212. // File doesn't exist, safe to rename
  213. }
  214. try {
  215. await fs.rename(interview.markdownPath, newPath);
  216. interview.markdownPath = newPath;
  217. log('[interview] renamed file with assistant title:', {
  218. from: currentFileName,
  219. to: newSlug,
  220. });
  221. } catch (error) {
  222. log('[interview] failed to rename file:', {
  223. error: error instanceof Error ? error.message : String(error),
  224. });
  225. }
  226. }
  227. async function loadMessages(sessionID: string): Promise<InterviewMessage[]> {
  228. const result = await ctx.client.session.messages({
  229. path: { id: sessionID },
  230. });
  231. return result.data as InterviewMessage[];
  232. }
  233. function isUserVisibleMessage(message: InterviewMessage): boolean {
  234. return !(message.parts ?? []).some((part) =>
  235. hasInternalInitiatorMarker(part),
  236. );
  237. }
  238. function getInterviewById(interviewId: string): InterviewRecord | null {
  239. return interviewsById.get(interviewId) ?? null;
  240. }
  241. async function createInterview(
  242. sessionID: string,
  243. idea: string,
  244. ): Promise<InterviewRecord> {
  245. const normalizedIdea = idea.trim();
  246. const activeId = activeInterviewIds.get(sessionID);
  247. if (activeId) {
  248. const active = interviewsById.get(activeId);
  249. if (active && active.status === 'active') {
  250. if (active.idea === normalizedIdea) {
  251. return active;
  252. }
  253. active.status = 'abandoned';
  254. }
  255. }
  256. const messages = await loadMessages(sessionID);
  257. const record: InterviewRecord = {
  258. id: `${Date.now()}-${++idCounter}-${slugify(idea) || 'interview'}`,
  259. sessionID,
  260. idea: normalizedIdea,
  261. markdownPath: createInterviewFilePath(ctx.directory, outputFolder, idea),
  262. createdAt: nowIso(),
  263. status: 'active',
  264. baseMessageCount: messages.length,
  265. };
  266. await ensureInterviewFile(record);
  267. activeInterviewIds.set(sessionID, record.id);
  268. interviewsById.set(record.id, record);
  269. fileCache = null;
  270. if (onInterviewCreated) {
  271. onInterviewCreated(record);
  272. }
  273. return record;
  274. }
  275. async function resumeInterview(
  276. sessionID: string,
  277. markdownPath: string,
  278. ): Promise<InterviewRecord> {
  279. const activeId = activeInterviewIds.get(sessionID);
  280. if (activeId) {
  281. const active = interviewsById.get(activeId);
  282. if (active && active.status === 'active') {
  283. if (active.markdownPath === markdownPath) {
  284. return active;
  285. }
  286. active.status = 'abandoned';
  287. }
  288. }
  289. const document = await fs.readFile(markdownPath, 'utf8');
  290. const messages = await loadMessages(sessionID);
  291. const title = extractTitle(document);
  292. const record: InterviewRecord = {
  293. id: `${Date.now()}-${++idCounter}-${slugify(path.basename(markdownPath, '.md')) || 'interview'}`,
  294. sessionID,
  295. idea: title || path.basename(markdownPath, '.md'),
  296. markdownPath,
  297. createdAt: nowIso(),
  298. status: 'active',
  299. baseMessageCount: messages.length,
  300. };
  301. activeInterviewIds.set(sessionID, record.id);
  302. interviewsById.set(record.id, record);
  303. fileCache = null;
  304. if (onInterviewCreated) {
  305. onInterviewCreated(record);
  306. }
  307. return record;
  308. }
  309. async function syncInterview(
  310. interview: InterviewRecord,
  311. ): Promise<InterviewState> {
  312. const allMessages = await loadMessages(interview.sessionID);
  313. const interviewMessages = allMessages
  314. .slice(interview.baseMessageCount)
  315. .filter(isUserVisibleMessage);
  316. const parsed = findLatestAssistantState(interviewMessages, maxQuestions);
  317. const existingDocument = await readInterviewDocument(interview);
  318. const fallbackState = buildFallbackState(interviewMessages);
  319. const state = parsed.state ?? {
  320. ...fallbackState,
  321. summary: extractSummarySection(existingDocument) || fallbackState.summary,
  322. };
  323. // Rename file if assistant provided a title (and file hasn't been renamed yet)
  324. await maybeRenameWithTitle(interview, state.title);
  325. const document = await rewriteInterviewDocument(interview, state.summary);
  326. const interviewState: InterviewState = {
  327. interview,
  328. url: `${await ensureServer()}/interview/${interview.id}`,
  329. markdownPath: relativeInterviewPath(
  330. ctx.directory,
  331. interview.markdownPath,
  332. ),
  333. mode:
  334. interview.status === 'abandoned'
  335. ? 'abandoned'
  336. : parsed.state && state.questions.length === 0
  337. ? 'completed'
  338. : sessionBusy.get(interview.sessionID) === true
  339. ? 'awaiting-agent'
  340. : state.questions.length > 0
  341. ? 'awaiting-user'
  342. : parsed.latestAssistantError
  343. ? 'error'
  344. : 'awaiting-agent',
  345. lastParseError: parsed.latestAssistantError,
  346. isBusy: sessionBusy.get(interview.sessionID) === true,
  347. summary: state.summary,
  348. questions: state.questions,
  349. document,
  350. };
  351. // Push state to dashboard if callback is set (dashboard mode)
  352. if (onStateChange) {
  353. onStateChange(interview.id, interviewState);
  354. }
  355. return interviewState;
  356. }
  357. async function notifyInterviewUrl(
  358. sessionID: string,
  359. interview: InterviewRecord,
  360. ): Promise<void> {
  361. const baseUrl = await ensureServer();
  362. const url = `${baseUrl}/interview/${interview.id}`;
  363. // Auto-open browser on initial creation (not on every poll/refresh)
  364. maybeOpenBrowser(interview.id, url);
  365. await ctx.client.session.prompt({
  366. path: { id: sessionID },
  367. body: {
  368. noReply: true,
  369. parts: [
  370. {
  371. type: 'text',
  372. text: [
  373. '⎔ Interview UI ready',
  374. '',
  375. `Open: ${url}`,
  376. `Document: ${relativeInterviewPath(ctx.directory, interview.markdownPath)}`,
  377. '',
  378. '[system status: continue without acknowledging this notification]',
  379. ].join('\n'),
  380. },
  381. ],
  382. },
  383. });
  384. }
  385. function registerCommand(opencodeConfig: Record<string, unknown>): void {
  386. const configCommand = opencodeConfig.command as
  387. | Record<string, unknown>
  388. | undefined;
  389. if (!configCommand?.[COMMAND_NAME]) {
  390. if (!opencodeConfig.command) {
  391. opencodeConfig.command = {};
  392. }
  393. (opencodeConfig.command as Record<string, unknown>)[COMMAND_NAME] = {
  394. template: 'Start an interview and write a live markdown spec',
  395. description:
  396. 'Open a localhost interview UI linked to the current OpenCode session',
  397. };
  398. }
  399. }
  400. async function getInterviewState(
  401. interviewId: string,
  402. ): Promise<InterviewState> {
  403. const interview = getInterviewById(interviewId);
  404. if (!interview) {
  405. throw new Error('Interview not found');
  406. }
  407. return syncInterview(interview);
  408. }
  409. function listInterviews(): InterviewListItem[] {
  410. const result: InterviewListItem[] = [];
  411. for (const interview of interviewsById.values()) {
  412. if (interview.status !== 'active') continue;
  413. result.push({
  414. id: interview.id,
  415. idea: interview.idea,
  416. status: interview.status,
  417. createdAt: interview.createdAt,
  418. });
  419. }
  420. return result.sort(
  421. (a, b) =>
  422. new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
  423. );
  424. }
  425. async function submitAnswers(
  426. interviewId: string,
  427. answers: InterviewAnswer[],
  428. ): Promise<void> {
  429. const interview = getInterviewById(interviewId);
  430. if (!interview) {
  431. throw new Error('Interview not found');
  432. }
  433. if (interview.status === 'abandoned') {
  434. throw new Error('Interview session is no longer active.');
  435. }
  436. if (sessionBusy.get(interview.sessionID) === true) {
  437. throw new Error(
  438. 'Interview session is busy. Wait for the current response.',
  439. );
  440. }
  441. // Acquire busy lock immediately before any async operations to prevent race
  442. sessionBusy.set(interview.sessionID, true);
  443. let promptSent = false;
  444. try {
  445. const state = await getInterviewState(interviewId);
  446. if (state.mode === 'error') {
  447. throw new Error('Interview is waiting for a valid agent update.');
  448. }
  449. const activeQuestionIds = new Set(
  450. state.questions.map((question) => question.id),
  451. );
  452. if (activeQuestionIds.size === 0) {
  453. throw new Error('There are no active interview questions to answer.');
  454. }
  455. if (answers.length !== activeQuestionIds.size) {
  456. throw new Error(
  457. 'Answer every active interview question before submitting.',
  458. );
  459. }
  460. const invalidAnswer = answers.find(
  461. (answer) =>
  462. !activeQuestionIds.has(answer.questionId) || !answer.answer.trim(),
  463. );
  464. if (invalidAnswer) {
  465. throw new Error(
  466. 'Answers do not match the current interview questions.',
  467. );
  468. }
  469. await appendInterviewAnswers(interview, state.questions, answers);
  470. const prompt = buildAnswerPrompt(answers, state.questions, maxQuestions);
  471. // Use promptAsync for non-blocking — returns immediately, LLM
  472. // processes in background. State push updates dashboard when done.
  473. const model = sessionModel.get(interview.sessionID);
  474. await ctx.client.session.promptAsync({
  475. path: { id: interview.sessionID },
  476. body: {
  477. parts: [createInternalAgentTextPart(prompt)],
  478. ...(model
  479. ? { model: parseModelReference(model) ?? undefined }
  480. : {}),
  481. },
  482. });
  483. promptSent = true;
  484. } finally {
  485. if (!promptSent) {
  486. sessionBusy.set(interview.sessionID, false);
  487. }
  488. }
  489. }
  490. async function handleCommandExecuteBefore(
  491. input: { command: string; sessionID: string; arguments: string },
  492. output: { parts: Array<{ type: string; text?: string }> },
  493. ): Promise<void> {
  494. if (input.command !== COMMAND_NAME) {
  495. return;
  496. }
  497. const idea = input.arguments.trim();
  498. output.parts.length = 0;
  499. if (!idea) {
  500. const activeId = activeInterviewIds.get(input.sessionID);
  501. const interview = activeId ? interviewsById.get(activeId) : null;
  502. if (!interview || interview.status !== 'active') {
  503. output.parts.push(
  504. createInternalAgentTextPart(
  505. 'The user ran /interview without an idea. Ask them for the product idea in one sentence.',
  506. ),
  507. );
  508. return;
  509. }
  510. await notifyInterviewUrl(input.sessionID, interview);
  511. output.parts.push(
  512. createInternalAgentTextPart(
  513. `The interview UI was reopened for the current session. If your latest interview turn already contains unanswered questions, do not repeat them. Otherwise continue the interview with up to ${maxQuestions} clarifying questions and include the structured <interview_state> block.`,
  514. ),
  515. );
  516. return;
  517. }
  518. const resumePath = resolveExistingInterviewPath(
  519. ctx.directory,
  520. outputFolder,
  521. idea,
  522. );
  523. if (resumePath) {
  524. const interview = await resumeInterview(input.sessionID, resumePath);
  525. const document = await fs.readFile(interview.markdownPath, 'utf8');
  526. await notifyInterviewUrl(input.sessionID, interview);
  527. output.parts.push(
  528. createInternalAgentTextPart(buildResumePrompt(document, maxQuestions)),
  529. );
  530. return;
  531. }
  532. const interview = await createInterview(input.sessionID, idea);
  533. await notifyInterviewUrl(input.sessionID, interview);
  534. output.parts.push(
  535. createInternalAgentTextPart(buildKickoffPrompt(idea, maxQuestions)),
  536. );
  537. }
  538. async function handleEvent(input: {
  539. event: { type: string; properties?: Record<string, unknown> };
  540. }): Promise<void> {
  541. const { event } = input;
  542. const properties = event.properties ?? {};
  543. if (event.type === 'session.status') {
  544. const sessionID = properties.sessionID as string | undefined;
  545. const status = properties.status as { type?: string } | undefined;
  546. if (sessionID) {
  547. sessionBusy.set(sessionID, status?.type === 'busy');
  548. }
  549. return;
  550. }
  551. if (event.type === 'message.updated') {
  552. const info = properties as
  553. | {
  554. info?: {
  555. sessionID?: string;
  556. providerID?: string;
  557. modelID?: string;
  558. };
  559. }
  560. | undefined;
  561. const sessionID = info?.info?.sessionID;
  562. const providerID = info?.info?.providerID;
  563. const modelID = info?.info?.modelID;
  564. if (sessionID && providerID && modelID) {
  565. sessionModel.set(sessionID, `${providerID}/${modelID}`);
  566. }
  567. return;
  568. }
  569. if (event.type === 'session.deleted') {
  570. const deletedSessionId =
  571. ((properties.info as { id?: string } | undefined)?.id ??
  572. (properties.sessionID as string | undefined)) ||
  573. null;
  574. if (!deletedSessionId) {
  575. return;
  576. }
  577. sessionBusy.delete(deletedSessionId);
  578. sessionModel.delete(deletedSessionId);
  579. const interviewId = activeInterviewIds.get(deletedSessionId);
  580. if (!interviewId) {
  581. return;
  582. }
  583. const interview = interviewsById.get(interviewId);
  584. if (!interview) {
  585. return;
  586. }
  587. interview.status = 'abandoned';
  588. fileCache = null;
  589. activeInterviewIds.delete(deletedSessionId);
  590. log('[interview] session deleted, interview marked abandoned', {
  591. sessionID: deletedSessionId,
  592. interviewId,
  593. });
  594. }
  595. }
  596. let fileCache: { items: InterviewFileItem[]; at: number } | null = null;
  597. const FILE_CACHE_TTL = 10_000;
  598. async function listInterviewFiles(): Promise<InterviewFileItem[]> {
  599. if (fileCache && Date.now() - fileCache.at < FILE_CACHE_TTL) {
  600. return fileCache.items;
  601. }
  602. const outputDir = createInterviewDirectoryPath(ctx.directory, outputFolder);
  603. const activePaths = new Set(
  604. [...interviewsById.values()]
  605. .filter((i) => i.status === 'active')
  606. .map((i) => path.resolve(i.markdownPath)),
  607. );
  608. let entries: string[];
  609. try {
  610. entries = await fs.readdir(outputDir);
  611. } catch {
  612. return [];
  613. }
  614. const items: InterviewFileItem[] = [];
  615. for (const entry of entries) {
  616. if (!entry.endsWith('.md')) continue;
  617. const fullPath = path.join(outputDir, entry);
  618. if (activePaths.has(path.resolve(fullPath))) continue;
  619. let content: string;
  620. try {
  621. content = await fs.readFile(fullPath, 'utf8');
  622. } catch {
  623. continue;
  624. }
  625. const title = extractTitle(content) || entry.replace(/\.md$/, '');
  626. const summary = extractSummarySection(content) || '';
  627. const baseName = entry.replace(/\.md$/, '');
  628. items.push({
  629. fileName: entry,
  630. resumeCommand: `/interview ${baseName}`,
  631. title,
  632. summary:
  633. summary.length > 120 ? `${summary.slice(0, 120)}\u2026` : summary,
  634. });
  635. }
  636. const sorted = items.sort((a, b) => a.title.localeCompare(b.title));
  637. fileCache = { items: sorted, at: Date.now() };
  638. return sorted;
  639. }
  640. async function handleNudgeAction(
  641. interviewId: string,
  642. action: 'more-questions' | 'confirm-complete',
  643. ): Promise<void> {
  644. const interview = getInterviewById(interviewId);
  645. if (!interview) {
  646. throw new Error('Interview not found');
  647. }
  648. if (interview.status === 'abandoned') {
  649. throw new Error('Interview session is no longer active.');
  650. }
  651. if (sessionBusy.get(interview.sessionID) === true) {
  652. throw new Error(
  653. 'Interview session is busy. Wait for the current response.',
  654. );
  655. }
  656. sessionBusy.set(interview.sessionID, true);
  657. let promptSent = false;
  658. try {
  659. const state = await getInterviewState(interviewId);
  660. let prompt: string;
  661. if (action === 'more-questions') {
  662. prompt = [
  663. `The user reviewed the completed interview spec and wants you to continue.`,
  664. ``,
  665. `Current spec summary: ${state.summary}`,
  666. ``,
  667. `Ask up to ${maxQuestions} new clarifying questions about aspects that are still unclear or underspecified.`,
  668. `Include the structured <interview_state> block with new questions.`,
  669. ].join('\n');
  670. } else {
  671. prompt = [
  672. `The user confirmed the interview spec is complete.`,
  673. ``,
  674. `Current spec summary: ${state.summary}`,
  675. ``,
  676. `Produce a final, polished version of the full spec document.`,
  677. `Do NOT include any <interview_state> block — just output the final spec as clean markdown.`,
  678. `The spec should be comprehensive, well-structured, and ready for implementation.`,
  679. ].join('\n');
  680. }
  681. const model = sessionModel.get(interview.sessionID);
  682. await ctx.client.session.promptAsync({
  683. path: { id: interview.sessionID },
  684. body: {
  685. parts: [createInternalAgentTextPart(prompt)],
  686. ...(model
  687. ? { model: parseModelReference(model) ?? undefined }
  688. : {}),
  689. },
  690. });
  691. promptSent = true;
  692. } finally {
  693. if (!promptSent) {
  694. sessionBusy.set(interview.sessionID, false);
  695. }
  696. }
  697. }
  698. return {
  699. setBaseUrlResolver,
  700. setStatePushCallback,
  701. setOnInterviewCreated,
  702. getActiveInterviewId,
  703. registerCommand,
  704. handleCommandExecuteBefore,
  705. handleEvent,
  706. getInterviewState,
  707. listInterviewFiles,
  708. listInterviews,
  709. submitAnswers,
  710. handleNudgeAction,
  711. };
  712. }