fix: local/cloud model detection, capability cache TTL, chat cursor offset
- isSmallLocalModel(baseURL, model) replaces isLocalBackendURL() for system-prompt
branching and context-window fallback defaults: Ollama's cloud-routed models
(glm-5.2:cloud, qwen3.5:397b-cloud, etc.) share a localhost endpoint with
genuinely local models, so the base URL alone can't tell them apart. Recomputed
on /model and /backend switches too, not just at session creation.
- Fixed a latent isLocalBackendURL bug found while testing it: URL.hostname keeps
the brackets on a literal IPv6 host ("[::1]"), so the old "::1" comparison never
matched.
- capabilityCache entries now carry a cachedAt timestamp with a 30-day TTL
(LOCODE_CAPABILITY_CACHE_TTL_DAYS), so a stale "fallback" verdict from a
transient probe failure doesn't permanently disable native tool calls.
- ChatInput's cursor row offset (+2 -> +1): the extra row was empirical padding
for a bottomSectionRef wrapper Box and virtual-scroll viewport that no longer
exist since the Static-based rendering change.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LxiAaGhSD4DRVYYQZ5GJjm
This commit is contained in:
1 parent
09cd992aa6
commit
5bf60c7921
12 files changed
+251
-207
No files matched your search
+49
-150
@@ -1,161 +1,61 @@
|
||||
# locode 업그레이드 작업 메모
|
||||
# locode 설계 메모
|
||||
|
||||
## 프로젝트 개요
|
||||
**locode** — Claude Code의 설계 철학을 가져와 로컬 모델(Ollama/LM Studio)용으로 재구현한 에이전트 코딩 CLI. TypeScript + Ink(React-for-CLI) 기반. 백엔드는 OpenAI 호환 `/v1/chat/completions` 엔드포인트 사용.
|
||||
**locode** — Claude Code의 설계 철학을 가져와 구현한 에이전트 코딩 CLI. TypeScript + Ink(React-for-CLI) 기반. 백엔드는 OpenAI 호환 `/v1/chat/completions` 엔드포인트 사용 (Ollama, LM Studio, 클라우드 API 모두 지원).
|
||||
|
||||
- 핵심 철학: "신뢰할 수 없고 느리고 비전/툴콜 지원이 불확실한 로컬 모델"이라는 현실에 맞춰 모든 가정을 비관적으로 재단
|
||||
- 핵심 철학: "신뢰할 수 없고 느리고 비전/툴콜 지원이 불확실한 모델"이라는 현실에 맞춰 모든 가정을 비관적으로 재단. 로컬/클라우드 자동 감지로 프롬프트 분기.
|
||||
- Claude Code 플러그인 포맷을 직접 소비하는 하위호환 브리지 (`.claude-plugin/plugin.json`, commands/agents/skills/hooks/MCP)
|
||||
|
||||
## 빌드/테스트 상태 (최신: c539995)
|
||||
- `npx tsc --noEmit` — 깨끗
|
||||
- `npm run build` (tsup) — 290.75 KB
|
||||
- `npm test` (vitest) — **43 파일 347개 전부 통과**
|
||||
- Node 타겟: **node22** (tsup.config.ts에서 변경)
|
||||
- 파일 인코딩: CRLF/LF 섹션 혼재 (edit_file의 EOL 정규화 로직으로 처리)
|
||||
---
|
||||
|
||||
## 아키텍처 결정 이유
|
||||
|
||||
### Normal Screen + `<Static>` (alternate screen 폐지)
|
||||
이전에는 alternate screen buffer + 인앱 가상 스크롤 + 마우스 트래킹을 직접 구현했으나 완전히 폐지. 이유:
|
||||
- **코드 복잡도**: 마우스 SGR-1006 파싱, 선택 영역, 스크롤 상태 관리가 App.tsx의 절반을 차지
|
||||
- **터미널 호환성**: alternate screen은 SSH, tmux, Windows Terminal 등에서 파편화 심함
|
||||
- **버그 발생률**: 마우스 크래시, 선택 텍스트 깨짐 등 이슈가 끝없이 발생
|
||||
- **현재 방식**: Ink `<Static>`으로 완료된 히스토리를 한 번만 렌더링 → 터미널 스크롤백의 영구 부분. 재렌더링 없음. 마우스는 터미널 네이티브에 의존.
|
||||
|
||||
### 로컬/클라우드 모델 감지: `isSmallLocalModel()`
|
||||
- **이전**: `isLocalBackendURL(baseURL)` — URL이 localhost면 무조건 "로컬 모델"
|
||||
- **문제**: Ollama가 클라우드 라우팅 모델(`glm-5.2:cloud`, `qwen3.5:397b-cloud`)도 같은 localhost에서 서비스함. 이 모델들은 컨텍스트 128K~1M이고 툴콜도 안정적인데 로컬용 보수적 프롬프트가 적용됨.
|
||||
- **해결**: `isSmallLocalModel(baseURL, model)` = `isLocalBackendURL(baseURL) && !isCloudRoutedModelName(model)` — 모델명의 `:cloud`/`:-cloud` 태그로 구분.
|
||||
- **기본값**: `isLocal`의 기본값을 `true`에서 `false`(클라우드)로 변경. 명시적 지정이 없으면 보수적이 아닌 기본 프롬프트 사용.
|
||||
|
||||
### 컨텍스트 윈도우 기본값 분리
|
||||
- **이전**: `DEFAULT_CONTEXT_WINDOW = 8192` (단일, 로컬 모델 기준)
|
||||
- **현재**: `DEFAULT_CONTEXT_WINDOW_LOCAL = 8192`, `DEFAULT_CONTEXT_WINDOW_CLOUD = 131072` — 클라우드/Ollama 클라우드 라우팅 모델은 128K~1M 컨텍스트를 가지므로 8192는 과도하게 보수적.
|
||||
|
||||
### 번인레이트(🔥) 계산
|
||||
- **이전**: `outputTokens / 세션 경과 시간` — 사용자가 방치하면 번인레이트가 0에 수렴해서 의미 없음
|
||||
- **현재**: `outputTokens / modelTimeMs` — 실제 모델 응답 시간으로 계산. "이 모델이 얼마나 빠르게 토큰을 뿜는가"를 정확히 반영.
|
||||
|
||||
### 파일 인코딩: CRLF/LF 혼재
|
||||
- Windows 환경에서는 CRLF, Unix에서는 LF가 섞여 있음. `edit_file`/`multi_edit`은 매칭 전 LF로 정규화하고, 쓰기 전 원래 EOL을 복원. 이것 없이는 Windows에서 거의 모든 edit_file이 실패함.
|
||||
|
||||
---
|
||||
|
||||
## 아키텍처 개요 (현재)
|
||||
|
||||
### 렌더링 모델: Normal Screen + `<Static>`
|
||||
**대폭 변경**: 이전 alternate screen buffer + 인앱 가상 스크롤 + 마우스 트래킹 아키텍처를 완전히 폐기.
|
||||
|
||||
- **Normal screen buffer**: `index.tsx`가 alternate screen에 진입하지 않음. 앱이 터미널의 일반 스크롤백에 직접 출력.
|
||||
- **Ink `<Static>`**: 완료된 턴/이벤트를 `<Static>` 컴포넌트로 한 번만 렌더링 → 터미널 스크롤백의 영구 부분이 됨. 재렌더링 없음.
|
||||
- **마우스 트래킹 완전 제거**: `mouseInput.ts` 파일 삭제. SGR-1006, `logicalButton()`, `copyToClipboard()`, `mouseToContentRow` 모두 제거. 터미널 자체 네이티브 스크롤/선택/복사에 의존.
|
||||
- **이점**: 코드 대폭 감소, 터미널 호환성 향상, SSH/tmux에서도 기본 스크롤 작동, 인앱 마우스 버그 불가.
|
||||
|
||||
### 핵심 파일 맵
|
||||
## 핵심 파일 맵
|
||||
- `src/ui/ink/index.tsx` — 진입점. alternate screen 없이 Ink render. cleanup 시 flush + 종료.
|
||||
- `src/ui/ink/App.tsx` (1107행) — 메인 UI 컴포넌트. `<Static>` + 라이브 영역. 상태: starting→connecting→loading-models→model-select/session-select→input.
|
||||
- `src/ui/ink/App.tsx` — 메인 UI 컴포넌트. `<Static>` + 라이브 영역. 상태: starting→connecting→loading-models→model-select/session-select→input.
|
||||
- `src/ui/ink/ChatInput.tsx` — 커스텀 multiline 입력. Shift+Enter 줄바꿈, bracket paste, @멘션 fuzzy picker, IME 커서.
|
||||
- `src/ui/ink/HistoryItemView.tsx` — memo() 래핑. thinking/streaming_text/assistant/tool_call 등 다양한 아이템 렌더.
|
||||
- `src/ui/ink/FilePanel.tsx` — Ctrl+F 토글 사이드 패널 (Files/Activity 탭).
|
||||
- `src/agent/loop.ts` (1284행) — 메인 에이전트 루프. 턴/스트리밍/툴콜/컴팩션/서브에이전트/병렬 툴 배치/반복 루프 감지.
|
||||
- `src/agent/loop.ts` — 메인 에이전트 루프. 턴/스트리밍/툴콜/컴팩션/서브에이전트/병렬 툴 배치/반복 루프 감지.
|
||||
- `src/agent/session.ts` — Session 객체, 통계, 상태, mutation gate.
|
||||
- `src/agent/systemPrompt.ts` — 시스템 프롬프트 빌더 (로컬/클라우드 분기).
|
||||
- `src/agent/events.ts` — AgentEvent 타입 (thinking_delta/thinking_done 추가).
|
||||
- `src/tools/` — 14+ 내장 툴 (read_file, list_files, grep, definition, references, diagnostics, web_search, web_fetch, git_status, write_file, edit_file, multi_edit, notebook_edit, bash, bash_output, bash_kill, git_commit, todo_write, task_create/list/get/update, agent).
|
||||
- `src/agent/systemPrompt.ts` — 시스템 프롬프트 빌더 (`isSmallLocalModel` 기반 로컬/클라우드 분기).
|
||||
- `src/config/defaults.ts` — 모든 기본값. `isSmallLocalModel()`, `isCloudRoutedModelName()`, `DEFAULT_CONTEXT_WINDOW_LOCAL/CLOUD` 등.
|
||||
- `src/toolcalling/` — native 어댑터, fallback 파서/프롬프트, partialJson 복구, resolve (Ollama 빈키 복구 포함).
|
||||
- `src/mcp/` — MCP 클라이언트/매니저/어댑터/config (모든 MCP 툴 mutating 강제).
|
||||
- `src/codeintel/lspManager.ts` (452행) — 언어별 LSP 서버 lazy spawn (tsserver/pyright/gopls/rust-analyzer/clangd + 사용자 설정 가능).
|
||||
- `src/config/defaults.ts` — 모든 기본값. `DEFAULT_MAX_ITERATIONS = 300`, `DEFAULT_MAX_OUTPUT_TOKENS = 131072` 등.
|
||||
- `src/config/store.ts` — StoredConfig 타입. 메모리 캐시 + 영속 설정.
|
||||
- `src/persistence/sessionStore.ts` — 세션 CRUD, 인덱스 자가 복구, 원자 쓰기, 큐잉.
|
||||
- `src/utils/` — tokens(스크립트 인식 휴리스틱), truncate(head+tail), diff, shell, processTree, image, html, mentions, projectInstructions, writeFileAtomic.
|
||||
|
||||
---
|
||||
|
||||
## 완료된 업그레이드 전체 목록
|
||||
|
||||
### 초기 12개 (v0.6.0, 6fe9888)
|
||||
| # | 항목 | 상태 |
|
||||
|---|---|:---:|
|
||||
| 1 | 병렬 툴 실행 (read-only Promise.all) | ✅ |
|
||||
| 2 | 재시도 정책 설정화 (maxRetries) | ✅ |
|
||||
| 3 | 정확한 토큰 추정 (CJK/기호 스크립트 인식) | ✅ |
|
||||
| 4 | 스마트 출력 캡 (head+tail 보존) | ✅ |
|
||||
| 5 | 부분 히스토리 보존 컴팩션 | ✅ |
|
||||
| 6 | 동적 max_tokens (resolveMaxTokens) | ✅ |
|
||||
| 7 | 툴 설명 풍부화 | ✅ |
|
||||
| 8 | MCP 연결 재시도·재연결 | ✅ |
|
||||
| 9 | 컨텍스트 윈도우 캐시 TTL | ✅ |
|
||||
| 10 | edit_file 유사 매치 제안 (Levenshtein) | ✅ |
|
||||
| 11 | git 출력 head+tail | ✅ |
|
||||
| 12 | auto-accept 모드 세분화 | ✅ |
|
||||
|
||||
### 08-20 세션 (6fe9888..dfaf8d1)
|
||||
- LSP 코드 인텔리전스 + 병렬 서브에이전트 mutation gate
|
||||
- 로컬 모델 툴콜 안정성 3종 (부분 JSON 복구, fallback 파서, 빈 응답 재시도)
|
||||
- multi_edit, DiffView, notebook_edit, task 시스템, 트랜스크립트 내보내기
|
||||
- /mouse 토글, 출력 중 입력창 작동
|
||||
|
||||
### 08-21 세션 (dfaf8d1..5c3fcfd)
|
||||
- 마우스 기본 ON + SGR-1006 전체 파싱 + 드래그 선택/OSC 52 클립보드
|
||||
- 병렬 툴 실행 검증 (runToolBatch 디버그 로그 + 테스트)
|
||||
- maxIterations 100→300 상향
|
||||
- gateAndRun 에러 로깅
|
||||
- DiffView 삭제 라인 색상 조정 (#f85149 → #e8904e)
|
||||
|
||||
### 08-22 세션 #1 (5c3fcfd..5065990): 15개 업그레이드
|
||||
| # | 항목 | 상태 |
|
||||
|---|---|:---:|
|
||||
| 1 | 시스템 프롬프트 대폭 강화 (로컬/클라우드 분기 포함) | ✅ |
|
||||
| 2 | 멀티라인 입력 (Shift+Enter) + 브래킷 페이스트 | ✅ |
|
||||
| 3 | /undo 명령 — 마지막 턴 롤백 | ✅ |
|
||||
| 4 | /dashboard — 이미 구현됨 | ✅ |
|
||||
| 5 | 컨텍스트 사용률 진행 바 — 이미 구현됨 | ✅ |
|
||||
| 6 | 추론(thinking) 토큰 지원 | ✅ |
|
||||
| 7 | @ 멘션 퍼지 매칭 + 캐시 TTL | ✅ |
|
||||
| 8 | readFile 바이너리 가드 + 대용량 보호 | ✅ |
|
||||
| 9 | writeFile 원자 쓰기 (temp→rename) | ✅ |
|
||||
| 10 | bash 문자열 누적 O(n²)→O(n) | ✅ |
|
||||
| 11 | estimateTokens 정규식 고속화 | ✅ |
|
||||
| 12 | handleCompletedMessage any→Record | ✅ |
|
||||
| 13 | 세션 복원 시 권한 상태 보존 | ✅ |
|
||||
| 14 | 컨텍스트 윈도우 병렬 감지 | ✅ |
|
||||
| 15 | 스트리밍 텍스트 누적 O(n²)→O(n) | ✅ |
|
||||
|
||||
### 08-22 세션 #2 (47711a9..60c6021): 시스템 프롬프트 분리 + 안정성
|
||||
- 시스템 프롬프트 로컬/클라우드 분리 (`isLocalBackendURL`, `buildSystemPrompt(..., isLocal)`)
|
||||
- 빈 응답 재시도 1→3 (MAX_EMPTY_RESPONSE_RETRIES = 3)
|
||||
- 마우스 드래그 SGR-1006 버그 수정 (모션 비트 32 인식)
|
||||
- maxIterations 기본값 300 반영
|
||||
|
||||
### 08-22 세션 #3 (Claude Code, c539995): 크래시/매칭 버그 수정
|
||||
- 마우스 크래시 수정 (`effectiveScrollTopRef` 미선언 → ReferenceError)
|
||||
- CRLF 제어문자 JSON 파싱 버그 (`escapeRawControlCharsInStrings` in partialJson.ts + nativeAdapter.ts 리페어 폴백)
|
||||
- CRLF edit_file/multi_edit 매칭 버그 (LF 정규화로 매칭, 쓰기 전 원래 EOL 복원)
|
||||
- 🔥 번인레이트 오해 수정 (input+output → output만)
|
||||
|
||||
### 현재 미커밋 변경 (working tree)
|
||||
| 파일 | 변경 내용 |
|
||||
|---|---|
|
||||
| `package.json` / `package-lock.json` | 의존성 대거 업그레이드 (openai 6→7, commander 13→15, execa 9→10, vitest 3→4, node types 22→26, tsup target node20→node22 등) |
|
||||
| `src/ui/ink/mouseInput.ts` | **삭제됨** — 마우스 트래킹 전면 폐지 |
|
||||
| `src/ui/ink/index.tsx` | alternate screen buffer 제거, normal screen + `<Static>` 아키텍처로 전환 |
|
||||
| `src/ui/ink/App.tsx` | 마우스/가상스크롤 코드 제거, `<Static>` 기반 렌더링으로 재구조화 |
|
||||
| `src/ui/ink/ChatInput.tsx` | 마우스 관련 코드 제거, 멀티라인/브래킷 페이스트/@멘션 유지 |
|
||||
| `src/ui/ink/HistoryItemView.tsx` | 마우스 선택 관련 코드 제거 |
|
||||
| `src/ui/ink/FilePanel.tsx` | (변경 있음 — 상세 확인 필요) |
|
||||
| `src/agent/loop.ts` | (변경 있음 — 상세 확인 필요) |
|
||||
| `src/agent/loop.test.ts` | (변경 있음 — 테스트 추가/수정) |
|
||||
| `src/codeintel/lspManager.ts` | (변경 있음) |
|
||||
| `src/config/defaults.ts` | (변경 있음) |
|
||||
| `src/config/store.ts` | (변경 있음) |
|
||||
| `src/persistence/sessionStore.ts` / `.test.ts` | (변경 있음) |
|
||||
| `tsup.config.ts` | target: node20 → node22 |
|
||||
|
||||
---
|
||||
|
||||
## 핵심 아키텍처 변경: Normal Screen + Static
|
||||
|
||||
이전 아키텍처에서 대폭 전환:
|
||||
|
||||
### 이전 (삭제됨)
|
||||
- Alternate screen buffer 진입/종료 (`\x1b[?1049h` / `\x1b[?1049l`)
|
||||
- 인앱 가상 스크롤 (PageUp/PageDown, scrollTop/ref)
|
||||
- 마우스 트래킹 (SGR-1006, `\x1b[?1002h\x1b[?1006h`)
|
||||
- 마우스 드래그 텍스트 선택 + OSC 52 클립보드 복사
|
||||
- `mouseInput.ts`: `matchMouseSequence`, `logicalButton`, `copyToClipboard`
|
||||
- `effectiveScrollTopRef`, `selectionStart/End`, `extractSelectionText`
|
||||
|
||||
### 현재 (새 아키텍처)
|
||||
- Normal screen buffer — 터미널의 일반 스크롤백에 직접 출력
|
||||
- Ink `<Static>` 컴포넌트 — 완료된 히스토리 아이템을 한 번만 렌더링, 재렌더링 없음
|
||||
- 마우스 트래킹 없음 — 터미널 자체 네이티브 스크롤/선택/복사에 의존
|
||||
- `mouseInput.ts` 파일 삭제됨
|
||||
- 이점: 코드 대폭 감소, 터미널 호환성 향상, SSH/tmux 기본 작동
|
||||
|
||||
---
|
||||
|
||||
## 설정 기본값 (현재)
|
||||
## 설정 기본값
|
||||
|
||||
| 설정 | 기본값 | 비고 |
|
||||
|---|---|---|
|
||||
| `DEFAULT_CONTEXT_WINDOW` | 8192 | 자동 감지 실패 시 폴백 |
|
||||
| `DEFAULT_CONTEXT_WINDOW_LOCAL` | 8192 | 작은 로컬 모델 폴백 |
|
||||
| `DEFAULT_CONTEXT_WINDOW_CLOUD` | 131072 | 클라우드/클라우드 라우팅 폴백 |
|
||||
| `DEFAULT_MAX_ITERATIONS` | **300** | 50→100→300 상향 |
|
||||
| `DEFAULT_MAX_OUTPUT_TOKENS` | **131072** | 8192→131072 (128K). GLM 등 1M 컨텍스트 모델 대응 |
|
||||
| `DEFAULT_MAX_OUTPUT_TOKENS` | **131072** | 128K. GLM 등 1M 컨텍스트 모델 대응 |
|
||||
| `DEFAULT_MAX_RETRIES` | 0 | SDK 지수 백오프 |
|
||||
| `DEFAULT_AUTO_COMPACT_THRESHOLD` | 0.85 | |
|
||||
| `DEFAULT_REQUEST_TIMEOUT_MS` | 180,000 | 3분 |
|
||||
@@ -169,18 +69,17 @@
|
||||
---
|
||||
|
||||
## 트러블슈팅 힌트
|
||||
- "자꾸 에러"의 주요 원인: max_tokens 잘림 → malformed 툴콜 (✅ 해결됨 — 동적 max_tokens + CRLF 제어문자 이스케이프)
|
||||
- CRLF 파일 edit_file 매칭 버그: ✅ 해결됨 (LF 정규화 공간에서 매칭, 쓰기 전 원래 EOL 복원)
|
||||
- "Paused after N steps": `locode config set maxIterations <number>` (기본 300)
|
||||
- 클라우드 모델 빈 응답: MAX_EMPTY_RESPONSE_RETRIES=3으로 재시도
|
||||
- 시스템 프롬프트가 로컬/클라우드 자동 분기 — localhost 감지 시 로컬 프롬프트, 그 외 클라우드 프롬프트
|
||||
- 반복 루프 감지: `detectRepetitionLoop()` — 스트리밍 텍스트에서 짧은 반복 패턴 감지 시 중단
|
||||
- 번인레이트(🔥) 표시: outputTokens/min만 반영 (inputTokens는 제외)
|
||||
- **"자꾸 에러"**: 주요 원인은 max_tokens 잘림 → malformed 툴콜. 동적 max_tokens + CRLF 제어문자 이스케이프로 해결됨.
|
||||
- **CRLF edit_file 매칭 버그**: LF 정규화 공간에서 매칭, 쓰기 전 원래 EOL 복원으로 해결됨.
|
||||
- **"Paused after N steps"**: `locode config set maxIterations <number>` (기본 300)
|
||||
- **클라우드 모델 빈 응답**: `MAX_EMPTY_RESPONSE_RETRIES=3`으로 재시도
|
||||
- **로컬/클라우드 프롬프트 분기**: `isSmallLocalModel(baseURL, model)` — Ollama 클라우드 라우팅 모델(`:cloud` 태그)은 localhost여도 클라우드 프롬프트 사용
|
||||
- **반복 루프 감지**: `detectRepetitionLoop()` — 스트리밍 텍스트에서 짧은 반복 패턴 감지 시 중단
|
||||
- **번인레이트(🔥)**: `outputTokens ÷ modelTimeMs` 기준 (세션 경과 시간이 아닌 실제 모델 응답 시간)
|
||||
- **IPv6 localhost**: `isLocalBackendURL()`은 `[::1]` 형식(WHATWG URL 직렬화)도 인식
|
||||
|
||||
---
|
||||
|
||||
## 남은 후보 / TODO
|
||||
## TODO
|
||||
- LSP 실서버 통합 테스트 (실제 tsserver/pyright 띄워서 검증)
|
||||
- task store 영속화 (세션에 task 저장)
|
||||
- 의존성 업그레이드 커밋 (working tree에 미반영 변경 다수)
|
||||
- Normal screen 아키텍처 전환 커밋 (mouseInput.ts 삭제, index.tsx/App.tsx 재구조화)
|
||||
- task store 영속화 (세션에 task 저장)
|
||||
+17
-13
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
|
||||
import type OpenAI from "openai";
|
||||
import type { ChatCompletionMessageParam } from "openai/resources/chat/completions";
|
||||
import type { ToolCallMode } from "../backend/capabilityProbe.js";
|
||||
import { DEFAULT_AUTO_COMPACT_THRESHOLD, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_ITERATIONS } from "../config/defaults.js";
|
||||
import { DEFAULT_AUTO_COMPACT_THRESHOLD, DEFAULT_CONTEXT_WINDOW_LOCAL, DEFAULT_MAX_ITERATIONS } from "../config/defaults.js";
|
||||
import type { SessionRecord } from "../persistence/sessionStore.js";
|
||||
import { PermissionManager } from "../permissions/permissionManager.js";
|
||||
import type { ConfirmFn } from "../permissions/types.js";
|
||||
@@ -100,10 +100,12 @@ export interface Session {
|
||||
* so a top-level turn and its sub-agents all funnel through the same queue. Initialized as a
|
||||
* resolved promise so the first caller doesn't wait on anything. */
|
||||
mutationGate: Promise<void>;
|
||||
/** True when the backend is a local server (Ollama / LM Studio on localhost). Used to
|
||||
* tailor the system prompt — local models need extra guidance about their limitations;
|
||||
* cloud models get a leaner prompt without self-fulfilling "you may produce empty responses"
|
||||
* framing. Derived from the baseURL by isLocalBackendURL(). */
|
||||
/** True when this is a small/less-capable local model, not just a local *backend* — Ollama's
|
||||
* cloud-routed models (e.g. "glm-5.2:cloud") share a localhost endpoint with genuinely local
|
||||
* ones, so this is more than a baseURL check. Used to tailor the system prompt — small local
|
||||
* models need extra guidance about their limitations; everything else gets a leaner prompt
|
||||
* without self-fulfilling "you may produce empty responses" framing. Derived by
|
||||
* isSmallLocalModel(baseURL, model); recomputed on /model and /backend switches (see App.tsx). */
|
||||
isLocal: boolean;
|
||||
}
|
||||
|
||||
@@ -114,16 +116,17 @@ export function createSession(
|
||||
confirm: ConfirmFn,
|
||||
mode: ToolCallMode,
|
||||
tools: ToolDef[] = TOOLS,
|
||||
contextWindow: number = DEFAULT_CONTEXT_WINDOW,
|
||||
contextWindow: number = DEFAULT_CONTEXT_WINDOW_LOCAL,
|
||||
contextWindowIsEstimate: boolean = true,
|
||||
maxIterations: number = DEFAULT_MAX_ITERATIONS,
|
||||
autoCompactThreshold: number = DEFAULT_AUTO_COMPACT_THRESHOLD,
|
||||
projectInstructions: string | null = null,
|
||||
isLocal: boolean = true,
|
||||
isLocal?: boolean,
|
||||
): Session {
|
||||
const resolvedIsLocal = isLocal ?? false;
|
||||
const toolset = buildToolSet(tools);
|
||||
const messages: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: buildSystemPrompt(toolset.tools, mode, projectInstructions, isLocal) },
|
||||
{ role: "system", content: buildSystemPrompt(toolset.tools, mode, projectInstructions, resolvedIsLocal) },
|
||||
];
|
||||
return {
|
||||
id: randomUUID(),
|
||||
@@ -132,7 +135,7 @@ export function createSession(
|
||||
model,
|
||||
cwd,
|
||||
mode,
|
||||
isLocal,
|
||||
isLocal: resolvedIsLocal,
|
||||
messages,
|
||||
maxIterations,
|
||||
permissions: new PermissionManager(),
|
||||
@@ -162,16 +165,17 @@ export function createSessionFromRecord(
|
||||
cwd: string,
|
||||
confirm: ConfirmFn,
|
||||
tools: ToolDef[] = TOOLS,
|
||||
contextWindow: number = DEFAULT_CONTEXT_WINDOW,
|
||||
contextWindow: number = DEFAULT_CONTEXT_WINDOW_LOCAL,
|
||||
contextWindowIsEstimate: boolean = true,
|
||||
maxIterations: number = DEFAULT_MAX_ITERATIONS,
|
||||
autoCompactThreshold: number = DEFAULT_AUTO_COMPACT_THRESHOLD,
|
||||
projectInstructions: string | null = null,
|
||||
isLocal: boolean = true,
|
||||
isLocal?: boolean,
|
||||
): Session {
|
||||
const resolvedIsLocal = isLocal ?? false;
|
||||
const toolset = buildToolSet(tools);
|
||||
const messages: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: buildSystemPrompt(toolset.tools, record.mode, projectInstructions, isLocal) },
|
||||
{ role: "system", content: buildSystemPrompt(toolset.tools, record.mode, projectInstructions, resolvedIsLocal) },
|
||||
...record.messages,
|
||||
];
|
||||
const session: Session = {
|
||||
@@ -181,7 +185,7 @@ export function createSessionFromRecord(
|
||||
model: record.model,
|
||||
cwd,
|
||||
mode: record.mode,
|
||||
isLocal,
|
||||
isLocal: resolvedIsLocal,
|
||||
messages,
|
||||
maxIterations,
|
||||
permissions: new PermissionManager(),
|
||||
|
||||
@@ -49,22 +49,22 @@ describe("buildSystemPrompt", () => {
|
||||
|
||||
it("includes local model guidance when isLocal is true", () => {
|
||||
const prompt = buildSystemPrompt([readTool], "native", null, true);
|
||||
expect(prompt).toContain("local model");
|
||||
expect(prompt).toContain("Context windows are smaller");
|
||||
expect(prompt).toContain("Working with local models");
|
||||
expect(prompt).toContain("Tool-call formatting can be unreliable");
|
||||
expect(prompt).toContain("Empty or malformed responses can happen");
|
||||
});
|
||||
|
||||
it("excludes local model guidance when isLocal is false (cloud)", () => {
|
||||
const prompt = buildSystemPrompt([readTool], "native", null, false);
|
||||
expect(prompt).not.toContain("local model");
|
||||
expect(prompt).not.toContain("Context windows are smaller");
|
||||
expect(prompt).not.toContain("Working with local models");
|
||||
expect(prompt).not.toContain("Empty or malformed responses");
|
||||
expect(prompt).not.toContain("Tool-call formatting can be unreliable");
|
||||
expect(prompt).not.toContain("Empty or malformed responses can happen");
|
||||
});
|
||||
|
||||
it("defaults to local prompt when isLocal is not specified", () => {
|
||||
it("defaults to cloud prompt when isLocal is not specified", () => {
|
||||
const prompt = buildSystemPrompt([readTool], "native");
|
||||
expect(prompt).toContain("local model");
|
||||
expect(prompt).toContain("coding assistant");
|
||||
expect(prompt).not.toContain("Working with local models");
|
||||
});
|
||||
|
||||
it("includes safety guidelines for both local and cloud", () => {
|
||||
|
||||
@@ -17,10 +17,14 @@ function formatToolList(tools: ToolDef[]): string {
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
export function buildSystemPrompt(tools: ToolDef[], mode: ToolCallMode, projectInstructions?: string | null, isLocal: boolean = true): string {
|
||||
export function buildSystemPrompt(tools: ToolDef[], mode: ToolCallMode, projectInstructions?: string | null, isLocal?: boolean): string {
|
||||
const toolList = formatToolList(tools);
|
||||
|
||||
const base = isLocal
|
||||
// Auto-detect: if not explicitly specified, use the cloud prompt by default.
|
||||
// Callers (App.tsx) always pass isSmallLocalModel(baseURL, model) explicitly, so this
|
||||
// default only affects tests or edge cases without a baseURL/model.
|
||||
const useLocal = isLocal ?? false;
|
||||
const base = useLocal
|
||||
? buildLocalPrompt(toolList, mode)
|
||||
: buildCloudPrompt(toolList, mode);
|
||||
|
||||
@@ -28,10 +32,10 @@ export function buildSystemPrompt(tools: ToolDef[], mode: ToolCallMode, projectI
|
||||
}
|
||||
|
||||
/** System prompt for local models (Ollama / LM Studio) — includes extra guidance about their
|
||||
* limitations (smaller context windows, unreliable tool-call formatting, empty/malformed
|
||||
* responses). These models need the hints; cloud models do not, and may be confused by them. */
|
||||
* limitations (unreliable tool-call formatting, occasional empty/malformed responses).
|
||||
* Cloud models get a leaner prompt (buildCloudPrompt) that omits these assumptions. */
|
||||
function buildLocalPrompt(toolList: string, mode: ToolCallMode): string {
|
||||
return `You are a helpful local coding assistant with access to tools for exploring and editing a codebase on the user's machine. You run against a local model served via Ollama or LM Studio, which means you may have a smaller context window and less reliable tool-call formatting than large cloud models — adapt your behavior accordingly.
|
||||
return `You are a helpful coding assistant with access to tools for exploring and editing a codebase on the user's machine.
|
||||
|
||||
## Available tools
|
||||
|
||||
@@ -71,10 +75,9 @@ ${toolList}
|
||||
|
||||
## Working with local models
|
||||
|
||||
- **Context windows are smaller.** A typical local model has 8k–32k tokens. Prefer concise tool calls and don't re-read files you just edited — trust the edit result.
|
||||
- **Tool-call formatting can be unreliable.** If you're in fallback mode, follow the tool_call format strictly. If native mode produces errors, the system will automatically retry with fallback parsing.
|
||||
- **Empty or malformed responses can happen.** The system retries automatically, but if you see repeated failures, simplify your request — shorter prompts, fewer tools, smaller file reads.
|
||||
- **Output length is limited.** For large file generations, prefer edit_file over write_file when possible — it uses less output tokens.
|
||||
- **Empty or malformed responses can happen.** The system retries automatically, but if you see repeated failures, simplify your request.
|
||||
- **Output length may be limited.** For large file generations, prefer edit_file over write_file when possible — it uses fewer output tokens.
|
||||
|
||||
## Fallback mode
|
||||
|
||||
@@ -121,7 +124,7 @@ ${toolList}
|
||||
- **edit_file**: For small changes to existing files. old_string must match exactly — include enough surrounding context to be unique. On mismatch, the tool suggests the closest similar text.
|
||||
- **multi_edit**: Apply several edits to the same file in one call. Each edit sees the result of previous edits, so adjust old_string for context shifts.
|
||||
- **write_file**: For new files or complete rewrites. Overwrites the entire file — use with care.
|
||||
- **bash**: Run shell commands. Prefer targeted tools (grep, definition) over broad shell commands when possible.
|
||||
- **bash**: Run shell commands. Prefer targeted tools (grep, definition) over broad shell commands when possible. Use timeout_ms for long-running commands. Background with Ctrl+B for very long commands.
|
||||
- **git_status / git_commit**: Inspect repo state and commit changes. Always check status before committing.
|
||||
- **web_search / web_fetch**: Look up information not in the local codebase. For API docs, error messages, or unfamiliar libraries.
|
||||
- **agent**: Delegate a sub-task to a focused sub-agent. Good for researching many files in parallel. Sub-agents cannot spawn further sub-agents.
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { ToolCallMode } from "./capabilityProbe.js";
|
||||
const paths = envPaths("locode", { suffix: "" });
|
||||
const cacheFile = path.join(paths.config, "model-capabilities.json");
|
||||
|
||||
type Cache = Record<string, ToolCallMode>;
|
||||
type Cache = Record<string, { mode: ToolCallMode; cachedAt?: number }>;
|
||||
|
||||
function keyFor(baseURL: string, model: string): string {
|
||||
return `${baseURL}::${model}`;
|
||||
@@ -23,7 +23,19 @@ function load(): Cache {
|
||||
// Always re-read from disk if possible, so concurrent processes' writes aren't overwritten.
|
||||
if (existsSync(cacheFile)) {
|
||||
try {
|
||||
memoryCache = JSON.parse(readFileSync(cacheFile, "utf-8")) as Cache;
|
||||
const raw = JSON.parse(readFileSync(cacheFile, "utf-8")) as Record<string, unknown>;
|
||||
// Migrate legacy format: bare string values ("native" | "fallback") become { mode, cachedAt }.
|
||||
const cache: Cache = {};
|
||||
for (const [k, v] of Object.entries(raw)) {
|
||||
if (typeof v === "string" && (v === "native" || v === "fallback")) {
|
||||
// Legacy entry — no cachedAt, so it can be re-validated on next probe.
|
||||
cache[k] = { mode: v };
|
||||
} else if (typeof v === "object" && v !== null && "mode" in v) {
|
||||
cache[k] = v as Cache[string];
|
||||
}
|
||||
// Silently drop unrecognized entries.
|
||||
}
|
||||
memoryCache = cache;
|
||||
return memoryCache;
|
||||
} catch {
|
||||
memoryCache = {};
|
||||
@@ -41,12 +53,36 @@ function save(cache: Cache): void {
|
||||
void writeFileAtomic(cacheFile, JSON.stringify(cache, null, 2));
|
||||
}
|
||||
|
||||
/** How long a cached tool-call mode detection stays fresh before locode re-probes. A model's
|
||||
* tool-call capability rarely changes, but a transient probe failure (network timeout, 5xx)
|
||||
* can leave a stale "fallback" entry that permanently disables native tool calls. The TTL
|
||||
* ensures periodic re-validation. Set to 0 via LOCODE_CAPABILITY_CACHE_TTL_DAYS=0 to force
|
||||
* a re-probe every session. */
|
||||
const DEFAULT_CACHE_TTL_DAYS = 30;
|
||||
|
||||
function resolveCacheTtlDays(): number {
|
||||
const envValue = Number(process.env.LOCODE_CAPABILITY_CACHE_TTL_DAYS);
|
||||
if (Number.isFinite(envValue) && envValue >= 0 && envValue <= 365) return envValue;
|
||||
return DEFAULT_CACHE_TTL_DAYS;
|
||||
}
|
||||
|
||||
function isStale(entry: { cachedAt?: number }, ttlDays: number): boolean {
|
||||
if (ttlDays <= 0) return true;
|
||||
if (typeof entry.cachedAt !== "number") return true; // legacy entry — always re-probe
|
||||
const ageMs = Date.now() - entry.cachedAt;
|
||||
return ageMs > ttlDays * 24 * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
export function getCachedMode(baseURL: string, model: string): ToolCallMode | undefined {
|
||||
return load()[keyFor(baseURL, model)];
|
||||
const entry = load()[keyFor(baseURL, model)];
|
||||
if (entry === undefined) return undefined;
|
||||
// Treat stale or legacy entries as a miss so the backend is re-probed.
|
||||
if (isStale(entry, resolveCacheTtlDays())) return undefined;
|
||||
return entry.mode;
|
||||
}
|
||||
|
||||
export function setCachedMode(baseURL: string, model: string, mode: ToolCallMode): void {
|
||||
const cache = load();
|
||||
cache[keyFor(baseURL, model)] = mode;
|
||||
cache[keyFor(baseURL, model)] = { mode, cachedAt: Date.now() };
|
||||
save(cache);
|
||||
}
|
||||
@@ -90,5 +90,5 @@ export async function resolveContextWindow(baseURL: string, model: string): Prom
|
||||
return { value: detected, isEstimate: false };
|
||||
}
|
||||
|
||||
return { value: resolveContextWindowDefault(), isEstimate: true };
|
||||
return { value: resolveContextWindowDefault(baseURL, model), isEstimate: true };
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import path from "node:path";
|
||||
import os from "node:os";
|
||||
import { _setConfigFilePathForTest, loadStoredConfig, saveStoredConfig } from "./store.js";
|
||||
import { resolveAutoCompactThreshold, resolveContextWindowDefault, resolveMaxIterations, resolveMaxOutputTokens, resolveMaxRetries, resolveRequestTimeoutMs, resolveSubagentTimeoutMs } from "./config.js";
|
||||
import { DEFAULT_AUTO_COMPACT_THRESHOLD, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_ITERATIONS, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_MAX_RETRIES, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_SUBAGENT_TIMEOUT_MS } from "./defaults.js";
|
||||
import { DEFAULT_AUTO_COMPACT_THRESHOLD, DEFAULT_CONTEXT_WINDOW_LOCAL, DEFAULT_CONTEXT_WINDOW_CLOUD, DEFAULT_MAX_ITERATIONS, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_MAX_RETRIES, DEFAULT_REQUEST_TIMEOUT_MS, DEFAULT_SUBAGENT_TIMEOUT_MS } from "./defaults.js";
|
||||
|
||||
// Isolate the persisted config to a temp directory so the suite never reads or overwrites the
|
||||
// user's real ~/.config/locode/config.json (the previous afterEach { saveStoredConfig({}) } wiped
|
||||
@@ -53,8 +53,19 @@ describe("config resolution", () => {
|
||||
expect(resolveAutoCompactThreshold()).toBe(DEFAULT_AUTO_COMPACT_THRESHOLD);
|
||||
});
|
||||
|
||||
it("resolves context window default", () => {
|
||||
expect(resolveContextWindowDefault()).toBe(DEFAULT_CONTEXT_WINDOW);
|
||||
it("resolves context window default — small local model", () => {
|
||||
expect(resolveContextWindowDefault("http://localhost:11434/v1", "llama3.2:latest")).toBe(DEFAULT_CONTEXT_WINDOW_LOCAL);
|
||||
});
|
||||
|
||||
it("resolves context window default — remote cloud API", () => {
|
||||
expect(resolveContextWindowDefault("https://api.openai.com/v1", "gpt-4")).toBe(DEFAULT_CONTEXT_WINDOW_CLOUD);
|
||||
});
|
||||
|
||||
it("resolves context window default — Ollama's cloud-routed models on a local endpoint", () => {
|
||||
// Regression: glm-5.2:cloud etc. run through the same localhost Ollama daemon as a genuinely
|
||||
// local model, so the base URL alone can't distinguish them — see isSmallLocalModel().
|
||||
expect(resolveContextWindowDefault("http://localhost:11434/v1", "glm-5.2:cloud")).toBe(DEFAULT_CONTEXT_WINDOW_CLOUD);
|
||||
expect(resolveContextWindowDefault("http://localhost:11434/v1", "qwen3.5:397b-cloud")).toBe(DEFAULT_CONTEXT_WINDOW_CLOUD);
|
||||
});
|
||||
|
||||
it("resolves max iterations default", () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
DEFAULT_AUTO_COMPACT_THRESHOLD,
|
||||
DEFAULT_CONTEXT_WINDOW,
|
||||
DEFAULT_CONTEXT_WINDOW_LOCAL,
|
||||
DEFAULT_CONTEXT_WINDOW_CLOUD,
|
||||
DEFAULT_MAX_ITERATIONS,
|
||||
DEFAULT_MAX_OUTPUT_TOKENS,
|
||||
DEFAULT_MAX_RETRIES,
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
DEFAULT_SUBAGENT_TIMEOUT_MS,
|
||||
KNOWN_BACKENDS,
|
||||
type BackendName,
|
||||
isSmallLocalModel,
|
||||
} from "./defaults.js";
|
||||
import { loadStoredConfig } from "./store.js";
|
||||
|
||||
@@ -49,13 +51,16 @@ export function resolveModel(cliModel?: string): string | undefined {
|
||||
return cliModel ?? process.env.LOCODE_MODEL ?? stored.model;
|
||||
}
|
||||
|
||||
/** The fallback context window size to use when it can't be auto-detected from the backend. */
|
||||
export function resolveContextWindowDefault(): number {
|
||||
/** The fallback context window size to use when it can't be auto-detected from the backend. Picks a
|
||||
* small-local or cloud-scale default based on isSmallLocalModel() — the backend host alone isn't
|
||||
* enough, since Ollama's cloud-routed models (e.g. "glm-5.2:cloud") share a local host with
|
||||
* genuinely local ones. */
|
||||
export function resolveContextWindowDefault(baseURL: string, model: string): number {
|
||||
const stored = loadStoredConfig();
|
||||
const envValue = Number(process.env.LOCODE_CONTEXT_WINDOW);
|
||||
if (Number.isFinite(envValue) && envValue > 0) return envValue;
|
||||
if (typeof stored.contextWindow === "number" && stored.contextWindow > 0) return stored.contextWindow;
|
||||
return DEFAULT_CONTEXT_WINDOW;
|
||||
return isSmallLocalModel(baseURL, model) ? DEFAULT_CONTEXT_WINDOW_LOCAL : DEFAULT_CONTEXT_WINDOW_CLOUD;
|
||||
}
|
||||
|
||||
/** Ceiling on a single response's max_tokens (see DEFAULT_MAX_OUTPUT_TOKENS), independent of the
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isCloudRoutedModelName, isLocalBackendURL, isSmallLocalModel } from "./defaults.js";
|
||||
|
||||
describe("isLocalBackendURL", () => {
|
||||
it("recognizes localhost, 127.0.0.1, and ::1", () => {
|
||||
expect(isLocalBackendURL("http://localhost:11434/v1")).toBe(true);
|
||||
expect(isLocalBackendURL("http://127.0.0.1:1234/v1")).toBe(true);
|
||||
expect(isLocalBackendURL("http://[::1]:11434/v1")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a remote host", () => {
|
||||
expect(isLocalBackendURL("https://api.openai.com/v1")).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for an unparseable URL instead of throwing", () => {
|
||||
expect(isLocalBackendURL("not a url")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isCloudRoutedModelName", () => {
|
||||
it("recognizes Ollama's cloud tag conventions", () => {
|
||||
expect(isCloudRoutedModelName("glm-5.2:cloud")).toBe(true);
|
||||
expect(isCloudRoutedModelName("qwen3.5:397b-cloud")).toBe(true);
|
||||
expect(isCloudRoutedModelName("gpt-oss:120b-cloud")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not match a genuinely local model", () => {
|
||||
expect(isCloudRoutedModelName("llama3.2:latest")).toBe(false);
|
||||
expect(isCloudRoutedModelName("gemma3:4b")).toBe(false);
|
||||
expect(isCloudRoutedModelName("phi4:14b")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not false-positive on 'cloud' appearing outside the tag segment", () => {
|
||||
expect(isCloudRoutedModelName("cloudmodel:latest")).toBe(false);
|
||||
expect(isCloudRoutedModelName("cloud")).toBe(false); // no colon at all
|
||||
});
|
||||
});
|
||||
|
||||
describe("isSmallLocalModel", () => {
|
||||
it("is true for a genuinely local model on a local endpoint", () => {
|
||||
expect(isSmallLocalModel("http://localhost:11434/v1", "llama3.2:latest")).toBe(true);
|
||||
});
|
||||
|
||||
it("is false for a cloud-routed model even on a local endpoint", () => {
|
||||
expect(isSmallLocalModel("http://localhost:11434/v1", "glm-5.2:cloud")).toBe(false);
|
||||
});
|
||||
|
||||
it("is false for a remote backend regardless of model name", () => {
|
||||
expect(isSmallLocalModel("https://api.openai.com/v1", "gpt-4")).toBe(false);
|
||||
});
|
||||
});
|
||||
+28
-6
@@ -9,20 +9,42 @@ export const KNOWN_BACKENDS = {
|
||||
export type BackendName = keyof typeof KNOWN_BACKENDS;
|
||||
|
||||
/** Returns true if the given base URL looks like a local backend (Ollama or LM Studio on localhost).
|
||||
* Used to tailor the system prompt — local models get extra guidance about their limitations,
|
||||
* while cloud models (which are more capable and reliable) get a leaner prompt without that framing. */
|
||||
* On its own this is NOT enough to tell a small local model from a large one — see
|
||||
* isSmallLocalModel() below, which is what callers should actually use. */
|
||||
export function isLocalBackendURL(baseURL: string): boolean {
|
||||
try {
|
||||
const url = new URL(baseURL);
|
||||
return url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "::1";
|
||||
// WHATWG URL keeps the brackets on a literal IPv6 host in .hostname (e.g. "[::1]", not "::1") —
|
||||
// https://url.spec.whatwg.org/#concept-host-serializer.
|
||||
return url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Used when the context window can't be auto-detected from the backend (see backend/contextWindow.ts)
|
||||
* and the user hasn't configured one — a conservative size common among smaller local models. */
|
||||
export const DEFAULT_CONTEXT_WINDOW = 8192;
|
||||
/** Ollama's cloud-hosted models are proxied through the same local daemon as a genuinely local
|
||||
* model — same base URL, same host — so isLocalBackendURL() alone can't tell them apart. Ollama
|
||||
* names them with a "cloud" tag segment instead, e.g. "glm-5.2:cloud" or "qwen3.5:397b-cloud". */
|
||||
export function isCloudRoutedModelName(model: string): boolean {
|
||||
const tag = model.split(":")[1] ?? "";
|
||||
return tag === "cloud" || tag.endsWith("-cloud");
|
||||
}
|
||||
|
||||
/** Whether locode should treat this model as a small/less-capable local model — extra system-prompt
|
||||
* guidance about unreliable tool calls and limited output, plus a conservative context-window
|
||||
* fallback — rather than a large, reliable one. True only when the backend is local AND the model
|
||||
* isn't one of Ollama's cloud-routed models under that same local endpoint; a backend hosted
|
||||
* elsewhere (a real remote/cloud API) is never treated as "small local" regardless of model name. */
|
||||
export function isSmallLocalModel(baseURL: string, model: string): boolean {
|
||||
return isLocalBackendURL(baseURL) && !isCloudRoutedModelName(model);
|
||||
}
|
||||
|
||||
/** Fallback context window when auto-detection fails and the user hasn't configured one.
|
||||
* Small local models (see isSmallLocalModel()) typically have 8k–32k context, so 8192 is a safe
|
||||
* conservative default. Everything else (cloud APIs, and Ollama's own cloud-routed models) typically
|
||||
* has 128k–1M+ context, so 131072 (128K) avoids severely underutilizing them. */
|
||||
export const DEFAULT_CONTEXT_WINDOW_LOCAL = 8192;
|
||||
export const DEFAULT_CONTEXT_WINDOW_CLOUD = 131072;
|
||||
|
||||
/** Ceiling on a single response's `max_tokens`, independent of the model's context window. Most
|
||||
* backends cap how much a single completion can generate well below the total context window they
|
||||
|
||||
+10
-3
@@ -27,7 +27,7 @@ import { setCachedMode } from "../../backend/capabilityCache.js";
|
||||
import { resolveContextWindow } from "../../backend/contextWindow.js";
|
||||
import { resolveToolCallMode } from "../../backend/resolveMode.js";
|
||||
import { resolveAutoCompactThreshold, resolveMaxIterations } from "../../config/config.js";
|
||||
import { KNOWN_BACKENDS, type BackendName, isLocalBackendURL } from "../../config/defaults.js";
|
||||
import { KNOWN_BACKENDS, type BackendName, isSmallLocalModel } from "../../config/defaults.js";
|
||||
import { getMcpStatuses, reconnectMcpServers } from "../../mcp/manager.js";
|
||||
import type { PermissionDecision, PermissionMode } from "../../permissions/types.js";
|
||||
import { defaultExportFilename, exportSession, type ExportFormat } from "../../persistence/exportSession.js";
|
||||
@@ -347,7 +347,7 @@ export function App({
|
||||
resolveMaxIterations(),
|
||||
resolveAutoCompactThreshold(),
|
||||
projectInstructions,
|
||||
isLocalBackendURL(baseURLRef.current),
|
||||
isSmallLocalModel(baseURLRef.current, model),
|
||||
);
|
||||
onSessionIdChange?.(sessionRef.current.id);
|
||||
push({ kind: "banner", cwd, model, backend: baseURLRef.current });
|
||||
@@ -396,7 +396,7 @@ export function App({
|
||||
resolveMaxIterations(),
|
||||
resolveAutoCompactThreshold(),
|
||||
projectInstructions,
|
||||
isLocalBackendURL(record.baseURL),
|
||||
isSmallLocalModel(record.baseURL, record.model),
|
||||
);
|
||||
onSessionIdChange?.(sessionRef.current.id);
|
||||
push({
|
||||
@@ -497,6 +497,10 @@ export function App({
|
||||
resolveToolCallMode(session.client, baseURLRef.current, name),
|
||||
resolveContextWindow(baseURLRef.current, name),
|
||||
]);
|
||||
// Recompute before setMode's rebuild (see setMode) so switching e.g. a small local model ->
|
||||
// glm-5.2:cloud (or the reverse) mid-session gets the right system-prompt branch immediately,
|
||||
// not just on the next full session restart.
|
||||
session.isLocal = isSmallLocalModel(baseURLRef.current, name);
|
||||
setMode(session, newMode);
|
||||
session.contextWindow = newContextWindow.value;
|
||||
session.contextWindowIsEstimate = newContextWindow.isEstimate;
|
||||
@@ -527,6 +531,9 @@ export function App({
|
||||
resolveToolCallMode(session.client, baseURLRef.current, session.model),
|
||||
resolveContextWindow(baseURLRef.current, session.model),
|
||||
]);
|
||||
// See the same recompute in switchModel — a backend switch changes isLocalBackendURL()'s
|
||||
// input just as much as a model switch changes isCloudRoutedModelName()'s.
|
||||
session.isLocal = isSmallLocalModel(baseURLRef.current, session.model);
|
||||
setMode(session, newMode);
|
||||
session.contextWindow = newContextWindow.value;
|
||||
session.contextWindowIsEstimate = newContextWindow.isEstimate;
|
||||
|
||||
@@ -151,15 +151,21 @@ export function ChatInput({ value, onChange, onSubmit, cwd, history = [], availa
|
||||
const totalWidth = PROMPT_WIDTH + stringWidth(value.slice(0, cursorOffset));
|
||||
const row = Math.floor(totalWidth / contentWidth);
|
||||
const col = totalWidth % contentWidth;
|
||||
// +2 rows / +2 cols for the box's own top border and left border+padding —
|
||||
// getAbsolutePosition gives the box's outer (border) edge, not where its content actually
|
||||
// starts. Empirically 2 rows, not 1 — some ancestor's own contribution isn't visible from the
|
||||
// Yoga tree alone (Ink applies at least one more row of vertical offset somewhere between the
|
||||
// computed layout and the actual terminal row), so this constant is tuned to match reality
|
||||
// rather than derived purely from the box's own chrome.
|
||||
// +2 cols for the box's own left border+padding — getAbsolutePosition gives the box's outer
|
||||
// (border) edge, not where its content actually starts; this one is exact (1 border + 1
|
||||
// paddingX column), not empirical.
|
||||
//
|
||||
// The row offset used to be +2 (1 for the box's own top border, +1 unexplained — "some
|
||||
// ancestor's own contribution isn't visible from the Yoga tree alone", found empirically, not
|
||||
// derived) back when App.tsx nested this box inside an extra `bottomSectionRef` wrapper Box and
|
||||
// a fixed-height virtual-scroll viewport. Both are gone now (App.tsx moved history into Ink's
|
||||
// own <Static>, so this box sits directly in a plain live-region Box) — dropped back to +1,
|
||||
// the part that's actually justified by this box's own top border. Unverified in a real
|
||||
// terminal (this environment has none) — if the cursor's still off by a row, that "mystery"
|
||||
// contribution may not be fully gone.
|
||||
setCursorPosition({
|
||||
x: origin.x + 2 + col,
|
||||
y: origin.y + 2 + row,
|
||||
y: origin.y + 1 + row,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user