import type { AIImagePart, AIMessage, AITool, AIToolCall, AIToolChatOptions, AIToolChatResult } from '../types.js'; /** * AI 가 응답을 만드는 동안 호출한 도구의 시간순 trace. * * UX 목적 — 사용자가 "왜 이렇게 답했지" 의문 가질 때 fold-able 박스에서 확인. * 디버그용 + 신뢰도 향상. */ export interface ToolUsage { /** 도구 이름 (예: 'getSelection', 'modifyBoard', 'addComponent') */ name: string; /** 호출 인자 JSON */ arguments: any; /** 도구 결과 — read tool 은 실제 값 (truncated 가능), write tool 은 queued 마커 */ result: any; /** read tool / write tool 분류 */ kind: 'read' | 'write' | 'unknown'; /** * 몇 번째 LLM 턴에서 불렀는가(0부터). 판단 과정을 단계로 읽을 수 있게 한다 — * "조회 → 거절 → 정정 → 제안" 이 한 턴 안의 일인지 여러 턴에 걸친 일인지가 진단의 절반이다. */ iter?: number; /** * 이 호출이 **어떻게 끝났는가** — 화면이 배지로 보여줄 판정. * ok 조회·실행이 정상 완료 * rejected 도구가 거절(인자 누락·대상 없음 등). 무엇이 빠졌는지는 result 에 있다. * queued 보드 편집처럼 클라이언트에서 적용될 예정 * proposed 조치 제안이 만들어졌다(실행 아님 — 사용자가 버튼을 누른다) * folded 같은 효과의 제안이 이미 있어 접혔다. **조용히 버리지 않는다** — 접힌 사실이 보여야 * "왜 카드가 하나뿐인가" 를 추적할 수 있다. * error 알 수 없는 도구·검증 실패 */ outcome?: 'ok' | 'rejected' | 'queued' | 'proposed' | 'folded' | 'error'; } /** * Loop 가 호출하는 dispatch 함수들. 모두 의존성 주입. * * assistant.ts 가 자기 자신의 함수 (isReadTool, executeReadTool 등) 를 그대로 * 넘겨주는 구조. 본 모듈은 이 함수들의 *시그니처* 만 알면 됨. */ export interface ToolDispatchHelpers { isReadTool: (name: string) => boolean; isWriteTool: (name: string) => boolean; isActionTool: (name: string) => boolean; /** read/external 도구 실행. **Promise 를 반환할 수 있다** — 호출부는 반드시 await 한다. */ executeReadTool: (tc: AIToolCall, context: TCtx) => any | Promise; /** * 쓰기 도구 호출이 유효한가. * * **문맥을 통째로 받는다** — 전에는 루프가 `currentBoard?.components` 를 꺼내 넘겼고, 그 한 줄이 * 문서의 모양을 이 파일에 심고 있었다. 꺼내는 일은 검증기 자신이 한다. */ validateWriteToolCall: (tc: AIToolCall, context: TCtx) => { valid: boolean; errors?: any[]; suggestion?: string; }; /** 도구 호출을 쌓아 둘 op 로. 모양은 부르는 쪽의 것이다 — 루프는 나르기만 한다. */ toolCallToOp: (tc: AIToolCall) => TOp | null; summarizeToolResult: (value: any) => any; } export interface AgenticLoopOptions { systemPrompt: string; model?: string; temperature?: number; maxTokens?: number; /** 최대 iteration. 기본 8. */ maxIterations?: number; /** * 사용자 abort 신호. iteration 시작 직전 / chat() 호출 후 체크. * 이미 abort 된 신호로 들어오면 첫 iteration 도 안 돔. */ signal?: AbortSignal; /** * 같은 tool 의 validation 실패가 N회 연속이면 조기 종료. 기본 3. * LLM 이 같은 잘못을 무한 반복하는 경우 방어. */ repeatedFailureLimit?: number; /** * **첫 턴에 도구 호출을 강제**한다(toolChoice: 'required'). 두 번째 턴부터는 자유(auto). * * 왜: 접지 가드는 답이 지어낸 **식별자**를 잡지만, 식별자 없이 지어낸 **상황 서술**은 잡지 못한다 * ("지게차들이 바쁘게 움직이고 있다" — 실제로 이 답이 나왔다). 그건 도구를 아예 부르지 않고 답한 * 경우이고, 사후 검사로는 막을 수 없다. 첫 턴에 무엇이든 조회하게 만들면 근거 없이 상태를 단언할 * 길이 없어진다 — 개념·사용법 질문도 문서 조회 도구로 답하므로 막히지 않는다. * * 대화면이 정한다(라이브 상태를 다루는 면에서만 켠다) — 여기서 질문 내용을 눈치로 분류하지 않는다. */ requireToolOnFirstTurn?: boolean; /** * **한도에 닿아도 알아낸 것을 버리지 않는다.** 기본 꺼짐. * * ── 왜 (twin-ai 에서 옮겨 옴, 2026-08-30 → 2026-09-05) ────────────────────── * 예전에는 한도에 닿으면 「질문을 좁혀 달라」 한 줄만 냈다. 그때까지 여러 번 조회해서 얻은 * 사실이 있는데도 전부 버렸다 — 사용자는 기다린 시간만 쓰고 아무것도 못 받는다. * * 켜면 마지막으로 한 번 더 부른다. **이번에는 도구를 안 준다**(`toolChoice: 'none'`) — 그래야 * 모델이 더 조회하지 않고 지금까지 받은 것으로 답한다. 못 채운 것이 있으면 그것을 말하게 한다. * * 그 호출마저 실패하면 원래대로 `max_iterations` 로 끝난다 — 마지막 바닥은 그대로다. * * ── 왜 루프가 하나 ───────────────────────────────────────────────────────── * 이 문제는 도메인과 무관하다. 어느 대화면이든 한도는 있고, 한도에 닿으면 같은 손실이 난다. * 두 곳에 두면 한 곳만 갖게 되고 — 실제로 그랬다(twin-ai 만 갖고 board-ai 는 없었다). */ salvageOnMaxIterations?: boolean; /** * 마무리 호출에 덧붙일 지시. 없으면 아래 기본 문장을 쓴다. * * 기본 문장은 도메인 중립이다 — 대화면이 자기 어휘로 바꾸고 싶으면 여기에 준다. */ salvagePrompt?: string; } export interface AgenticLoopInput { initialConversation: AIMessage[]; /** * The tools the model is offered. A function is asked before every call, so a conversation that opens tools in a * turn (ADR-0061 decision 9, `openTools`) offers them from its next call on. */ tools: AITool[] | (() => AITool[]); options: AgenticLoopOptions; /** LLM provider 의 chatWithTools 위임. provider-specific 구현. */ chat: (messages: AIMessage[], tools: AITool[], options: AIToolChatOptions) => Promise; dispatch: ToolDispatchHelpers; /** 도구가 알아야 하는 것 한 뭉치 — 루프는 들여다보지 않고 나른다. */ context: TCtx; } export interface AgenticLoopResult { lastText: string | undefined; accumulatedWriteCalls: AIToolCall[]; accumulatedActions: TOp[]; toolUsages: ToolUsage[]; /** * LLM 에게 실제로 회신된 도구 결과 문자열(시간순) — **접지 판정의 근거집합**. * * `toolUsages[].result` 를 쓰면 안 된다: 그건 UI 표시용으로 압축된(잘린) 값이라 근거로 삼으면 * 잘려 나간 식별자를 "근거 없음" 으로 오판한다. 여기 담기는 것은 tool_result 로 보낸 원문 그대로다. */ groundedTexts: string[]; /** * **제안** — 도구가 "실행하지 않고 제안만 했다" 고 알린 결과들(시간순). * * 규약: read/external 도구의 결과에 `proposed === true` 가 있으면 그것은 조치 제안이다. 그 도구가 * 어느 도메인인지 이 루프는 모른다 — 결과를 그대로 실어 올리고, 해석·실행 확인은 대화면이 한다. * 되돌릴 수 없는 조치를 AI 가 직접 실행하지 않게 하는 경계가 이 채널이다(사람이 버튼을 누른다). */ proposals: any[]; /** LLM 마지막 응답의 stopReason. provider-specific 문자열. */ stopReason: string; /** * The words handed back (lastText) are the model's last answer, and it stopped at the output limit before it ended * (stopReason `max_tokens`, no call in it) -- the turn's own answer, or the wrap-up's. Not a stop of the loop -- the * words are what the model said -- but a reader must not take them for the whole answer. */ cutShort?: boolean; /** * 비정상 종료 사유 — 정상 종료 시 undefined. * 호출자 (assistant.ts) 가 사용자 메시지에 반영 (예: '시도 중 오류가 발생했어요'). */ abortReason?: { type: 'provider_error'; message: string; iter: number; } | { type: 'aborted'; iter: number; } | { type: 'max_iterations'; iter: number; salvaged?: boolean; } | { type: 'repeated_validation_failure'; toolName: string; consecutive: number; iter: number; }; } /** * multi-turn agentic loop. * * LLM 이 read tool 을 호출 → 서버에서 즉시 실행 → 결과 회신 → LLM 추론 반복. * write tool 은 누적해 client 에 patch 로 전달. 무한 루프 방지를 위해 iteration cap. * * 본 함수는 *순수* — input 만 보고 결정. 외부 mutable state 없음. */ export declare function runAgenticLoop(input: AgenticLoopInput): Promise>; /** * 제안의 **효과 키** — 도구·명령·대상·인자만 본다(설명 문구는 제외). * * 인자는 **키 순서를 정렬**해 문자열로 만든다: 같은 인자를 다른 순서로 받았을 뿐인데 다른 제안으로 * 보이면 카드가 둘이 되고, 사용자가 같은 명령을 두 번 실행할 수 있다. */ export declare function proposalEffectKey(p: any): string; /** * 같은 tool 의 validation 실패 연속 감지 — pure helper. * * 같은 tool 이 반복 fail 하면 LLM 이 self-correct 못 하는 상태. * 다른 tool 이 fail 하면 시퀀스 새로 시작 (전혀 다른 패턴이라). * tool 이 succeed 하면 카운터 reset. */ /** What a read tool that threw answers, in place of its result. */ export declare const TOOL_FAILED = "TOOL_FAILED"; /** * A proposal's reserved `forScreen` field, taken out of what the model reads and kept for the card. * * A read tool that has queried many rows puts them on the card (the AI 작업 패널 table) but tells the model only the * count, the totals and a few rows - the model does not copy a table it never received, so the card's numbers are * the query's own (operato-application/design/ai/read-targets.md §4). Only a proposal (`proposed: true`) carries it. */ export declare function takeForScreen(result: any): { value: any; forScreen: Record; }; /** * The pictures a read tool returned in its reserved `images` field, taken out of the result. * * A tool result reaches the model as JSON text; a picture cannot. So a read tool that must show one - a picture * sent in an earlier turn of the conversation - returns `images: [{ data, mediaType }]`, and the loop sends each as an * image part of the same turn. The bytes never stay in the JSON, the grounding texts or the usage record. A picture * of a type the providers do not all take is left out and said in the result. */ export declare function takeToolImages(result: any): { value: any; images: AIImagePart[]; };