ethagent 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +114 -32
  3. package/bin/ethagent.js +11 -2
  4. package/package.json +30 -8
  5. package/src/app/FirstRun.tsx +412 -0
  6. package/src/app/hooks/useCancelRequest.ts +22 -0
  7. package/src/app/hooks/useDoublePress.ts +46 -0
  8. package/src/app/hooks/useExitOnCtrlC.ts +36 -0
  9. package/src/app/input/AppInputProvider.tsx +116 -0
  10. package/src/app/input/appInputParser.ts +279 -0
  11. package/src/app/keybindings/KeybindingProvider.tsx +134 -0
  12. package/src/app/keybindings/resolver.ts +42 -0
  13. package/src/app/keybindings/types.ts +26 -0
  14. package/src/chat/ChatBottomPane.tsx +280 -0
  15. package/src/chat/ChatInput.tsx +722 -0
  16. package/src/chat/ChatScreen.tsx +1575 -0
  17. package/src/chat/ContextLimitView.tsx +95 -0
  18. package/src/chat/ContinuityEditReviewView.tsx +48 -0
  19. package/src/chat/ConversationStack.tsx +47 -0
  20. package/src/chat/CopyPicker.tsx +52 -0
  21. package/src/chat/MessageList.tsx +609 -0
  22. package/src/chat/PermissionPrompt.tsx +153 -0
  23. package/src/chat/PermissionsView.tsx +159 -0
  24. package/src/chat/PlanApprovalView.tsx +91 -0
  25. package/src/chat/ResumeView.tsx +267 -0
  26. package/src/chat/RewindView.tsx +386 -0
  27. package/src/chat/SessionStatus.tsx +51 -0
  28. package/src/chat/TranscriptView.tsx +202 -0
  29. package/src/chat/chatInputState.ts +247 -0
  30. package/src/chat/chatPaste.ts +49 -0
  31. package/src/chat/chatScreenUtils.ts +187 -0
  32. package/src/chat/chatSessionState.ts +142 -0
  33. package/src/chat/chatTurnOrchestrator.ts +701 -0
  34. package/src/chat/commands.ts +673 -0
  35. package/src/chat/textCursor.ts +202 -0
  36. package/src/chat/toolResultDisplay.ts +8 -0
  37. package/src/chat/transcriptViewport.ts +247 -0
  38. package/src/cli/ResetConfirmView.tsx +61 -0
  39. package/src/cli/main.tsx +177 -0
  40. package/src/cli/preview.tsx +19 -0
  41. package/src/cli/reset.ts +106 -0
  42. package/src/identity/continuity/editor.ts +149 -0
  43. package/src/identity/continuity/envelope.ts +345 -0
  44. package/src/identity/continuity/history.ts +153 -0
  45. package/src/identity/continuity/privateEdit.ts +334 -0
  46. package/src/identity/continuity/publicSkills.ts +173 -0
  47. package/src/identity/continuity/snapshots.ts +183 -0
  48. package/src/identity/continuity/storage.ts +507 -0
  49. package/src/identity/crypto/backupEnvelope.ts +486 -0
  50. package/src/identity/crypto/eth.ts +137 -0
  51. package/src/identity/hub/IdentityHub.tsx +868 -0
  52. package/src/identity/hub/identityHubEffects.ts +1146 -0
  53. package/src/identity/hub/identityHubModel.ts +291 -0
  54. package/src/identity/hub/identityHubReducer.ts +212 -0
  55. package/src/identity/hub/screens/BusyScreen.tsx +26 -0
  56. package/src/identity/hub/screens/ContinuityDashboardScreen.tsx +144 -0
  57. package/src/identity/hub/screens/CreateFlow.tsx +206 -0
  58. package/src/identity/hub/screens/DetailsScreen.tsx +64 -0
  59. package/src/identity/hub/screens/EditProfileFlow.tsx +145 -0
  60. package/src/identity/hub/screens/ErrorScreen.tsx +35 -0
  61. package/src/identity/hub/screens/IdentitySummary.tsx +70 -0
  62. package/src/identity/hub/screens/MenuScreen.tsx +117 -0
  63. package/src/identity/hub/screens/NetworkScreen.tsx +41 -0
  64. package/src/identity/hub/screens/RebackupStorageScreen.tsx +50 -0
  65. package/src/identity/hub/screens/RecoveryConfirmScreen.tsx +85 -0
  66. package/src/identity/hub/screens/RestoreFlow.tsx +206 -0
  67. package/src/identity/hub/screens/StorageCredentialScreen.tsx +128 -0
  68. package/src/identity/hub/screens/WalletApprovalScreen.tsx +43 -0
  69. package/src/identity/profile/imagePicker.ts +180 -0
  70. package/src/identity/registry/erc8004.ts +1106 -0
  71. package/src/identity/registry/registryConfig.ts +69 -0
  72. package/src/identity/storage/ipfs.ts +212 -0
  73. package/src/identity/storage/pinataJwt.ts +53 -0
  74. package/src/identity/wallet/browserWallet.ts +393 -0
  75. package/src/identity/wallet/wallet-page/wallet.html +1082 -0
  76. package/src/mcp/approvals.ts +113 -0
  77. package/src/mcp/config.ts +235 -0
  78. package/src/mcp/manager.ts +541 -0
  79. package/src/mcp/names.ts +19 -0
  80. package/src/mcp/output.ts +96 -0
  81. package/src/models/ModelPicker.tsx +1446 -0
  82. package/src/models/catalog.ts +296 -0
  83. package/src/models/huggingface.ts +651 -0
  84. package/src/models/llamacpp.ts +810 -0
  85. package/src/models/llamacppPreflight.ts +150 -0
  86. package/src/models/modelDisplay.ts +105 -0
  87. package/src/models/modelPickerOptions.ts +421 -0
  88. package/src/models/modelRecommendation.ts +140 -0
  89. package/src/models/runtimeDetection.ts +81 -0
  90. package/src/models/uncensoredCatalog.ts +86 -0
  91. package/src/providers/anthropic.ts +259 -0
  92. package/src/providers/contracts.ts +62 -0
  93. package/src/providers/errors.ts +62 -0
  94. package/src/providers/gemini.ts +152 -0
  95. package/src/providers/openai-chat.ts +472 -0
  96. package/src/providers/registry.ts +42 -0
  97. package/src/providers/retry.ts +58 -0
  98. package/src/providers/sse.ts +93 -0
  99. package/src/runtime/compaction.ts +389 -0
  100. package/src/runtime/cwd.ts +43 -0
  101. package/src/runtime/sessionMode.ts +55 -0
  102. package/src/runtime/systemPrompt.ts +209 -0
  103. package/src/runtime/toolClaimGuards.ts +143 -0
  104. package/src/runtime/toolExecution.ts +304 -0
  105. package/src/runtime/toolIntent.ts +163 -0
  106. package/src/runtime/turn.ts +858 -0
  107. package/src/storage/atomicWrite.ts +68 -0
  108. package/src/storage/config.ts +189 -0
  109. package/src/storage/factoryReset.ts +130 -0
  110. package/src/storage/history.ts +58 -0
  111. package/src/storage/identity.ts +99 -0
  112. package/src/storage/permissions.ts +76 -0
  113. package/src/storage/rewind.ts +246 -0
  114. package/src/storage/secrets.ts +181 -0
  115. package/src/storage/sessionExport.ts +49 -0
  116. package/src/storage/sessions.ts +482 -0
  117. package/src/tools/bashSafety.ts +174 -0
  118. package/src/tools/bashTool.ts +140 -0
  119. package/src/tools/changeDirectoryTool.ts +213 -0
  120. package/src/tools/contracts.ts +179 -0
  121. package/src/tools/deleteFileTool.ts +111 -0
  122. package/src/tools/editTool.ts +160 -0
  123. package/src/tools/editUtils.ts +170 -0
  124. package/src/tools/listDirectoryTool.ts +55 -0
  125. package/src/tools/mcpResourceTools.ts +95 -0
  126. package/src/tools/permissionRules.ts +85 -0
  127. package/src/tools/privateContinuityEditTool.ts +178 -0
  128. package/src/tools/privateContinuityReadTool.ts +107 -0
  129. package/src/tools/readTool.ts +85 -0
  130. package/src/tools/registry.ts +67 -0
  131. package/src/tools/writeFileTool.ts +142 -0
  132. package/src/ui/BrandSplash.tsx +193 -0
  133. package/src/ui/ProgressBar.tsx +34 -0
  134. package/src/ui/Select.tsx +143 -0
  135. package/src/ui/Spinner.tsx +269 -0
  136. package/src/ui/Surface.tsx +47 -0
  137. package/src/ui/TextInput.tsx +97 -0
  138. package/src/ui/theme.ts +59 -0
  139. package/src/utils/clipboard.ts +216 -0
  140. package/src/utils/markdownSegments.ts +51 -0
  141. package/src/utils/messages.ts +35 -0
  142. package/src/utils/withRetry.ts +280 -0
  143. package/src/cli.tsx +0 -147
@@ -0,0 +1,58 @@
1
+ import type { ProviderRetryStreamEvent } from './contracts.js'
2
+ import { fetchWithRetry, type FetchWithRetryOptions, type RetryEvent } from '../utils/withRetry.js'
3
+
4
+ type FetchSettled =
5
+ | { state: 'resolved'; response: Response }
6
+ | { state: 'rejected'; error: unknown }
7
+
8
+ export async function* fetchWithRetryStreamEvents(
9
+ input: string,
10
+ init: RequestInit,
11
+ options: FetchWithRetryOptions = {},
12
+ ): AsyncGenerator<ProviderRetryStreamEvent, Response, void> {
13
+ const retryEvents: ProviderRetryStreamEvent[] = []
14
+ let settled: FetchSettled | undefined
15
+ let wake: (() => void) | undefined
16
+
17
+ const wakeWaiter = () => {
18
+ const current = wake
19
+ wake = undefined
20
+ current?.()
21
+ }
22
+
23
+ const waitForChange = (): Promise<void> => new Promise(resolve => {
24
+ wake = resolve
25
+ if (settled || retryEvents.length > 0) wakeWaiter()
26
+ })
27
+
28
+ const fetchPromise = fetchWithRetry(input, init, {
29
+ ...options,
30
+ onRetry: (event: RetryEvent) => {
31
+ options.onRetry?.(event)
32
+ retryEvents.push({ type: 'retry', ...event })
33
+ wakeWaiter()
34
+ },
35
+ }).then(
36
+ response => {
37
+ settled = { state: 'resolved', response }
38
+ wakeWaiter()
39
+ },
40
+ error => {
41
+ settled = { state: 'rejected', error }
42
+ wakeWaiter()
43
+ },
44
+ )
45
+
46
+ while (!settled || retryEvents.length > 0) {
47
+ while (retryEvents.length > 0) {
48
+ yield retryEvents.shift()!
49
+ }
50
+ if (settled) break
51
+ await waitForChange()
52
+ }
53
+
54
+ await fetchPromise
55
+ if (settled?.state === 'resolved') return settled.response
56
+ if (settled?.state === 'rejected') throw settled.error
57
+ throw new Error('fetch retry completed without a response')
58
+ }
@@ -0,0 +1,93 @@
1
+ export type SseEvent = {
2
+ event: string | null
3
+ data: string
4
+ }
5
+
6
+ export async function* iterSseFrames(
7
+ body: ReadableStream<Uint8Array>,
8
+ signal: AbortSignal,
9
+ readTimeoutMs: number,
10
+ ): AsyncIterable<string> {
11
+ for await (const event of iterSseEvents(body, signal, readTimeoutMs)) {
12
+ yield event.data
13
+ }
14
+ }
15
+
16
+ export async function* iterSseEvents(
17
+ body: ReadableStream<Uint8Array>,
18
+ signal: AbortSignal,
19
+ readTimeoutMs: number,
20
+ ): AsyncIterable<SseEvent> {
21
+ const reader = body.getReader()
22
+ const decoder = new TextDecoder()
23
+ let buffer = ''
24
+ try {
25
+ while (!signal.aborted) {
26
+ const { done, value } = await readWithTimeout(reader, readTimeoutMs)
27
+ if (done) break
28
+ buffer += decoder.decode(value, { stream: true })
29
+ let boundary = findFrameBoundary(buffer)
30
+ while (boundary !== -1) {
31
+ const raw = buffer.slice(0, boundary)
32
+ const separator = buffer.slice(boundary).match(/^\r?\n\r?\n/)?.[0] ?? '\n\n'
33
+ buffer = buffer.slice(boundary + separator.length)
34
+ const event = extractSseEvent(raw)
35
+ if (event) yield event
36
+ boundary = findFrameBoundary(buffer)
37
+ }
38
+ }
39
+
40
+ const tail = buffer.trim()
41
+ if (tail) {
42
+ const event = extractSseEvent(tail)
43
+ if (event) yield event
44
+ }
45
+ } finally {
46
+ try { reader.releaseLock() } catch { void 0 }
47
+ }
48
+ }
49
+
50
+ export async function readWithTimeout(
51
+ reader: ReadableStreamDefaultReader<Uint8Array>,
52
+ timeoutMs: number,
53
+ ): Promise<ReadableStreamReadResult<Uint8Array>> {
54
+ let timer: NodeJS.Timeout | undefined
55
+ const timeout = new Promise<never>((_, reject) => {
56
+ timer = setTimeout(() => {
57
+ reject(new Error(`no response from model in ${Math.round(timeoutMs / 1000)}s`))
58
+ }, timeoutMs)
59
+ })
60
+ try {
61
+ return await Promise.race([reader.read(), timeout])
62
+ } finally {
63
+ if (timer) clearTimeout(timer)
64
+ }
65
+ }
66
+
67
+ export function extractDataPayload(frame: string): string | null {
68
+ return extractSseEvent(frame)?.data ?? null
69
+ }
70
+
71
+ function extractSseEvent(frame: string): SseEvent | null {
72
+ const lines = frame.split(/\r?\n/)
73
+ const dataLines: string[] = []
74
+ let eventName: string | null = null
75
+
76
+ for (const line of lines) {
77
+ if (line.startsWith('event:')) {
78
+ eventName = line.slice(6).trim() || null
79
+ continue
80
+ }
81
+ if (line.startsWith('data:')) {
82
+ dataLines.push(line.slice(5).replace(/^ /, ''))
83
+ }
84
+ }
85
+
86
+ if (dataLines.length === 0) return null
87
+ return { event: eventName, data: dataLines.join('\n') }
88
+ }
89
+
90
+ function findFrameBoundary(buffer: string): number {
91
+ const match = /\r?\n\r?\n/.exec(buffer)
92
+ return match?.index ?? -1
93
+ }
@@ -0,0 +1,389 @@
1
+ import type { Message, Provider } from '../providers/contracts.js'
2
+ import { approximateTokens, messageTextContent } from '../utils/messages.js'
3
+ import type { SessionMessage } from '../storage/sessions.js'
4
+
5
+ const COMPACT_SYSTEM = `Create a continuation handoff for this coding-agent conversation.
6
+ Keep it concise but complete. Preserve the current goal, user constraints, key decisions, relevant files, tool results, pending tasks, and known failures. Do not claim unverified work was completed. No preamble.`
7
+
8
+ const LOCAL_COMPACTION_INPUT_TOKENS = 6_000
9
+ const CLOUD_COMPACTION_INPUT_TOKENS = 24_000
10
+ const LOCAL_COMPACTION_OUTPUT_TOKENS = 1_000
11
+ const CLOUD_COMPACTION_OUTPUT_TOKENS = 1_600
12
+ const LOCAL_RECENT_MESSAGE_COUNT = 28
13
+ const CLOUD_RECENT_MESSAGE_COUNT = 80
14
+ const LOCAL_MESSAGE_CHAR_LIMIT = 900
15
+ const CLOUD_MESSAGE_CHAR_LIMIT = 2_000
16
+
17
+ export type CompactionStage =
18
+ | 'preparing transcript'
19
+ | 'compressing long context'
20
+ | 'summarizing with local model'
21
+ | 'summarizing with provider'
22
+
23
+ export type CompactTranscriptOptions = {
24
+ signal?: AbortSignal
25
+ onStage?: (stage: CompactionStage) => void
26
+ maxInputTokens?: number
27
+ maxOutputTokens?: number
28
+ }
29
+
30
+ export type CompactTranscriptResult =
31
+ | { ok: true; summary: string; inputTokens: number; compressed: boolean }
32
+ | { ok: false; reason: string; cancelled?: boolean; inputTokens?: number; compressed?: boolean }
33
+
34
+ export type CompactionSource = {
35
+ text: string
36
+ inputTokens: number
37
+ compressed: boolean
38
+ }
39
+
40
+ export type ContextWindowConfidence = 'exact' | 'inferred' | 'fallback'
41
+
42
+ export type ContextWindowInfo = {
43
+ tokens: number
44
+ confidence: ContextWindowConfidence
45
+ source: string
46
+ }
47
+
48
+ export type ContextUsage = {
49
+ usedTokens: number
50
+ windowTokens: number
51
+ percent: number
52
+ confidence: ContextWindowConfidence
53
+ source: string
54
+ }
55
+
56
+ export function contextWindow(model: string): number {
57
+ return contextWindowInfo('', model).tokens
58
+ }
59
+
60
+ export function contextWindowInfo(provider: string, model: string): ContextWindowInfo {
61
+ const lower = model.toLowerCase()
62
+ const providerLower = provider.toLowerCase()
63
+ if (lower.startsWith('qwen3:4b') || lower.startsWith('qwen3:30b') || lower.startsWith('qwen3:235b')) {
64
+ return { tokens: 256_000, confidence: 'inferred', source: 'qwen3 long-context tag' }
65
+ }
66
+ if (lower.includes('qwen3')) {
67
+ return { tokens: 40_000, confidence: 'inferred', source: 'qwen3 default' }
68
+ }
69
+ if (lower.includes('qwen')) {
70
+ return { tokens: 32_768, confidence: 'inferred', source: 'qwen default' }
71
+ }
72
+ if (lower.includes('llama3')) {
73
+ return { tokens: 128_000, confidence: 'inferred', source: 'llama3 family default' }
74
+ }
75
+ if (providerLower === 'anthropic' || lower.includes('claude')) {
76
+ return { tokens: 200_000, confidence: 'inferred', source: 'claude family default' }
77
+ }
78
+ if (providerLower === 'gemini' || lower.includes('gemini')) {
79
+ return { tokens: 1_000_000, confidence: 'inferred', source: 'gemini family default' }
80
+ }
81
+ if (
82
+ lower.includes('gpt-4.1')
83
+ ) {
84
+ return { tokens: 1_000_000, confidence: 'inferred', source: 'gpt-4.1 family default' }
85
+ }
86
+ if (
87
+ providerLower === 'openai'
88
+ || lower.includes('gpt-4o')
89
+ || /^o[134](?:-|$)/.test(lower)
90
+ ) {
91
+ return { tokens: 128_000, confidence: 'inferred', source: 'openai chat default' }
92
+ }
93
+ return { tokens: 128_000, confidence: 'fallback', source: 'ethagent fallback' }
94
+ }
95
+
96
+ export function contextUsage(messages: Message[], provider: string, model: string): ContextUsage {
97
+ return contextUsageFromTokens(approximateTokens(messages), provider, model)
98
+ }
99
+
100
+ export function contextUsageFromTokens(tokens: number, provider: string, model: string): ContextUsage {
101
+ const info = contextWindowInfo(provider, model)
102
+ const usedTokens = Math.max(0, Math.ceil(tokens))
103
+ return {
104
+ usedTokens,
105
+ windowTokens: info.tokens,
106
+ percent: info.tokens > 0 ? Math.round((usedTokens / info.tokens) * 100) : 0,
107
+ confidence: info.confidence,
108
+ source: info.source,
109
+ }
110
+ }
111
+
112
+ export function shouldConfirmContextUsage(usage: Pick<ContextUsage, 'percent'>, thresholdPercent = 90): boolean {
113
+ return usage.percent >= thresholdPercent
114
+ }
115
+
116
+ export async function compactTranscript(
117
+ provider: Provider,
118
+ transcript: Message[],
119
+ options: CompactTranscriptOptions = {},
120
+ ): Promise<CompactTranscriptResult> {
121
+ const nonSystem = transcript.filter(m => m.role !== 'system')
122
+ if (nonSystem.length < 2) {
123
+ return { ok: false, reason: 'not enough turns to compact' }
124
+ }
125
+
126
+ options.onStage?.('preparing transcript')
127
+ const source = buildCompactionSource(transcript, provider.id, {
128
+ maxInputTokens: options.maxInputTokens,
129
+ })
130
+ if (source.compressed) options.onStage?.('compressing long context')
131
+
132
+ const prompt: Message[] = [
133
+ { role: 'system', content: COMPACT_SYSTEM },
134
+ { role: 'user', content: `Create a continuation handoff from this conversation context:\n\n${source.text}` },
135
+ ]
136
+
137
+ const controller = options.signal ? null : new AbortController()
138
+ const signal = options.signal ?? controller!.signal
139
+ let summary = ''
140
+ const local = isLocalProviderId(provider.id)
141
+ options.onStage?.(local ? 'summarizing with local model' : 'summarizing with provider')
142
+ try {
143
+ for await (const ev of provider.complete(prompt, signal, {
144
+ maxTokens: options.maxOutputTokens ?? (local ? LOCAL_COMPACTION_OUTPUT_TOKENS : CLOUD_COMPACTION_OUTPUT_TOKENS),
145
+ })) {
146
+ if (signal.aborted) return { ok: false, reason: 'cancelled', cancelled: true, inputTokens: source.inputTokens, compressed: source.compressed }
147
+ if (ev.type === 'text') summary += ev.delta
148
+ else if (ev.type === 'error') return { ok: false, reason: ev.message }
149
+ else if (ev.type === 'done') break
150
+ }
151
+ } catch (err: unknown) {
152
+ if (signal.aborted) return { ok: false, reason: 'cancelled', cancelled: true, inputTokens: source.inputTokens, compressed: source.compressed }
153
+ return { ok: false, reason: (err as Error).message || 'compact stream error' }
154
+ }
155
+
156
+ if (signal.aborted) return { ok: false, reason: 'cancelled', cancelled: true, inputTokens: source.inputTokens, compressed: source.compressed }
157
+ summary = summary.trim()
158
+ if (summary.length < 40) return { ok: false, reason: 'summary too short', inputTokens: source.inputTokens, compressed: source.compressed }
159
+
160
+ return { ok: true, summary, inputTokens: source.inputTokens, compressed: source.compressed }
161
+ }
162
+
163
+ export function buildCompactionSource(
164
+ transcript: Message[],
165
+ providerId: Provider['id'],
166
+ options: { maxInputTokens?: number } = {},
167
+ ): CompactionSource {
168
+ const nonSystem = transcript.filter(m => m.role !== 'system')
169
+ const local = isLocalProviderId(providerId)
170
+ const tokenBudget = options.maxInputTokens ?? (local ? LOCAL_COMPACTION_INPUT_TOKENS : CLOUD_COMPACTION_INPUT_TOKENS)
171
+ const charBudget = Math.max(1_000, tokenBudget * 4)
172
+ const recentMessageCount = local ? LOCAL_RECENT_MESSAGE_COUNT : CLOUD_RECENT_MESSAGE_COUNT
173
+ const messageCharLimit = local ? LOCAL_MESSAGE_CHAR_LIMIT : CLOUD_MESSAGE_CHAR_LIMIT
174
+ const rawTokenEstimate = approximateTokens(nonSystem)
175
+ const mustCompress = rawTokenEstimate > tokenBudget || nonSystem.length > recentMessageCount
176
+
177
+ if (!mustCompress) {
178
+ const text = nonSystem.map((message, index) =>
179
+ formatCompactionMessage(message, index + 1, messageCharLimit),
180
+ ).join('\n\n')
181
+ return {
182
+ text,
183
+ inputTokens: approximateTextTokens(text),
184
+ compressed: false,
185
+ }
186
+ }
187
+
188
+ const recent = nonSystem.slice(-recentMessageCount)
189
+ const earlier = nonSystem.slice(0, Math.max(0, nonSystem.length - recent.length))
190
+ const parts: string[] = []
191
+ parts.push('Deterministic pre-summary of earlier context:')
192
+ parts.push(summarizeTranscriptLocally(earlier.length > 0 ? earlier : nonSystem, 'input was bounded before model summarization'))
193
+ parts.push('')
194
+ parts.push('Recent transcript excerpts:')
195
+ parts.push(...recent.map((message, index) =>
196
+ formatCompactionMessage(message, nonSystem.length - recent.length + index + 1, messageCharLimit),
197
+ ))
198
+
199
+ const bounded = limitCompactionText(parts.join('\n\n'), charBudget)
200
+ return {
201
+ text: bounded,
202
+ inputTokens: approximateTextTokens(bounded),
203
+ compressed: true,
204
+ }
205
+ }
206
+
207
+ export function summarizeTranscriptLocally(
208
+ transcript: Message[],
209
+ reason?: string,
210
+ ): string {
211
+ const nonSystem = transcript.filter(m => m.role !== 'system')
212
+ const userRequests: string[] = []
213
+ const assistantReplies: string[] = []
214
+ const toolNotes: string[] = []
215
+
216
+ for (const message of nonSystem) {
217
+ const text = oneLine(messageTextContent(message), 240)
218
+ if (!text) continue
219
+ if (message.role === 'user') userRequests.push(text)
220
+ else if (message.role === 'assistant') assistantReplies.push(text)
221
+ else toolNotes.push(`${message.role}: ${text}`)
222
+ }
223
+
224
+ const parts = [
225
+ 'Local conversation summary for continuation.',
226
+ reason ? `Provider summary was unavailable: ${oneLine(reason, 180)}.` : '',
227
+ ].filter(Boolean)
228
+
229
+ if (userRequests.length > 0) {
230
+ parts.push('Recent user requests:')
231
+ parts.push(...userRequests.slice(-8).map(item => `- ${item}`))
232
+ }
233
+ if (assistantReplies.length > 0) {
234
+ parts.push('Recent assistant progress:')
235
+ parts.push(...assistantReplies.slice(-6).map(item => `- ${item}`))
236
+ }
237
+ if (toolNotes.length > 0) {
238
+ parts.push('Recent tool context:')
239
+ parts.push(...toolNotes.slice(-6).map(item => `- ${item}`))
240
+ }
241
+ parts.push('Continue from this summary, and verify current files or external state before relying on stale details.')
242
+
243
+ return parts.join('\n')
244
+ }
245
+
246
+ export type MicroCompactOptions = {
247
+ activeTurnId?: string
248
+ }
249
+
250
+ export type MicroCompactResult = {
251
+ messages: SessionMessage[]
252
+ compactedTurns: number
253
+ }
254
+
255
+ const RECENT_TURN_BUDGET = 15
256
+ const TRIGGER_MESSAGE_COUNT = 50
257
+
258
+ export function shouldMicroCompact(messages: SessionMessage[]): boolean {
259
+ return messages.length > TRIGGER_MESSAGE_COUNT
260
+ }
261
+
262
+ export function microCompactSessionMessages(
263
+ messages: SessionMessage[],
264
+ options: MicroCompactOptions = {},
265
+ ): MicroCompactResult {
266
+ if (!shouldMicroCompact(messages)) {
267
+ return { messages, compactedTurns: 0 }
268
+ }
269
+
270
+ const turnOrder: string[] = []
271
+ const turnsSeen = new Set<string>()
272
+ for (const message of messages) {
273
+ if (message.role !== 'user') continue
274
+ const turnId = (message as { turnId?: string }).turnId
275
+ if (!turnId || turnsSeen.has(turnId)) continue
276
+ turnsSeen.add(turnId)
277
+ turnOrder.push(turnId)
278
+ }
279
+
280
+ if (turnOrder.length <= RECENT_TURN_BUDGET) {
281
+ return { messages, compactedTurns: 0 }
282
+ }
283
+
284
+ const keepTurnIds = new Set(turnOrder.slice(turnOrder.length - RECENT_TURN_BUDGET))
285
+ if (options.activeTurnId) keepTurnIds.add(options.activeTurnId)
286
+
287
+ const oldMessages: SessionMessage[] = []
288
+ const kept: SessionMessage[] = []
289
+ for (const message of messages) {
290
+ const turnId = (message as { turnId?: string }).turnId
291
+ if (!turnId) {
292
+ kept.push(message)
293
+ continue
294
+ }
295
+ if (keepTurnIds.has(turnId)) {
296
+ kept.push(message)
297
+ } else {
298
+ oldMessages.push(message)
299
+ }
300
+ }
301
+
302
+ if (oldMessages.length === 0) {
303
+ return { messages, compactedTurns: 0 }
304
+ }
305
+
306
+ const compactedTurns = new Set(
307
+ oldMessages
308
+ .map(message => (message as { turnId?: string }).turnId)
309
+ .filter((id): id is string => typeof id === 'string'),
310
+ )
311
+
312
+ const summary = summarizeCompactedTurns(oldMessages)
313
+ const firstKeptIndex = messages.findIndex(m => kept.includes(m))
314
+ const summaryMessage: SessionMessage = {
315
+ role: 'assistant',
316
+ content: summary,
317
+ createdAt: oldMessages[oldMessages.length - 1]!.createdAt,
318
+ }
319
+
320
+ const out: SessionMessage[] = []
321
+ if (firstKeptIndex > 0) {
322
+ out.push(...messages.slice(0, firstKeptIndex).filter(m => !oldMessages.includes(m)))
323
+ }
324
+ out.push(summaryMessage)
325
+ out.push(...kept)
326
+ return { messages: out, compactedTurns: compactedTurns.size }
327
+ }
328
+
329
+ function summarizeCompactedTurns(messages: SessionMessage[]): string {
330
+ const userRequests: string[] = []
331
+ const assistantReplies: string[] = []
332
+
333
+ for (const message of messages) {
334
+ if (message.role === 'user') {
335
+ const content = typeof message.content === 'string' ? message.content : ''
336
+ if (content.trim()) userRequests.push(oneLine(content, 140))
337
+ } else if (message.role === 'assistant') {
338
+ const content = typeof message.content === 'string' ? message.content : ''
339
+ if (content.trim()) assistantReplies.push(oneLine(content, 140))
340
+ }
341
+ }
342
+
343
+ const parts = ['[Earlier conversation context was compacted to fit the model\'s context window.]']
344
+ if (userRequests.length > 0) {
345
+ const sample = userRequests.slice(-5)
346
+ parts.push(`Most recent earlier user requests: ${sample.map(item => `"${item}"`).join('; ')}`)
347
+ }
348
+ if (assistantReplies.length > 0) {
349
+ const last = assistantReplies[assistantReplies.length - 1]!
350
+ parts.push(`Most recent earlier assistant reply: "${last}"`)
351
+ }
352
+ parts.push('Treat the above as background; respond to the current user message next.')
353
+ return parts.join(' ')
354
+ }
355
+
356
+ function oneLine(text: string, limit: number): string {
357
+ const normalized = text.replace(/\s+/g, ' ').trim()
358
+ if (normalized.length <= limit) return normalized
359
+ return `${normalized.slice(0, Math.max(0, limit - 3))}...`
360
+ }
361
+
362
+ function isLocalProviderId(providerId: Provider['id']): boolean {
363
+ return providerId === 'llamacpp'
364
+ }
365
+
366
+ function formatCompactionMessage(message: Message, index: number, limit: number): string {
367
+ const text = oneLine(messageTextContent(message), limit)
368
+ return `${index}. ${message.role}: ${text || '[empty]'}`
369
+ }
370
+
371
+ function limitCompactionText(text: string, charBudget: number): string {
372
+ if (text.length <= charBudget) return text
373
+ const recentHeader = 'Recent transcript excerpts:'
374
+ const recentIndex = text.indexOf(recentHeader)
375
+ if (recentIndex !== -1) {
376
+ const prefixEnd = recentIndex + recentHeader.length
377
+ const prefix = text.slice(0, prefixEnd)
378
+ const marker = '[Earlier recent transcript excerpts omitted to keep local summarization responsive.]'
379
+ const tailBudget = Math.max(0, charBudget - prefix.length - marker.length - 4)
380
+ return `${prefix}\n\n${marker}\n\n${text.slice(Math.max(prefixEnd, text.length - tailBudget))}`
381
+ }
382
+ const marker = '[Earlier bounded compaction text omitted to keep local summarization responsive.]'
383
+ const tailBudget = Math.max(0, charBudget - marker.length - 2)
384
+ return `${marker}\n\n${text.slice(Math.max(0, text.length - tailBudget))}`
385
+ }
386
+
387
+ function approximateTextTokens(text: string): number {
388
+ return Math.ceil(text.length / 4)
389
+ }
@@ -0,0 +1,43 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+
5
+ let cwdState = normalizeExistingPath(process.cwd())
6
+
7
+ export function getCwd(): string {
8
+ return cwdState
9
+ }
10
+
11
+ export function syncCwdFromProcess(): string {
12
+ cwdState = normalizeExistingPath(process.cwd())
13
+ return cwdState
14
+ }
15
+
16
+ export function setCwd(next: string, relativeTo = cwdState): string {
17
+ const resolved = normalizeRequestedPath(next, relativeTo)
18
+ process.chdir(resolved)
19
+ cwdState = normalizeExistingPath(process.cwd())
20
+ return cwdState
21
+ }
22
+
23
+ export function resolveUserPath(input: string, relativeTo = cwdState): string {
24
+ return normalizeRequestedPath(input, relativeTo)
25
+ }
26
+
27
+ function normalizeRequestedPath(input: string, relativeTo: string): string {
28
+ const expanded = input.startsWith('~')
29
+ ? path.join(os.homedir(), input.slice(1))
30
+ : input
31
+ const resolved = path.isAbsolute(expanded)
32
+ ? expanded
33
+ : path.resolve(relativeTo, expanded)
34
+ return normalizeExistingPath(resolved)
35
+ }
36
+
37
+ function normalizeExistingPath(input: string): string {
38
+ try {
39
+ return fs.realpathSync.native(input)
40
+ } catch {
41
+ return path.resolve(input)
42
+ }
43
+ }
@@ -0,0 +1,55 @@
1
+ import type { ToolKind } from '../tools/contracts.js'
2
+
3
+ export type SessionMode = 'chat' | 'plan' | 'accept-edits'
4
+
5
+ export type PermissionMode = 'default' | 'plan' | 'accept-edits'
6
+
7
+ type PolicyMode = SessionMode | 'default'
8
+
9
+ export type ModePolicy = {
10
+ mode: PolicyMode
11
+ exposesToolKind: (kind: ToolKind) => boolean
12
+ autoAllowToolKind: (kind: ToolKind) => boolean
13
+ promptLabel: string
14
+ }
15
+
16
+ export function toPermissionMode(mode: SessionMode): PermissionMode {
17
+ if (mode === 'plan') return 'plan'
18
+ if (mode === 'accept-edits') return 'accept-edits'
19
+ return 'default'
20
+ }
21
+
22
+ export function nextSessionMode(mode: SessionMode): SessionMode {
23
+ return mode === 'chat' ? 'plan' : mode === 'plan' ? 'accept-edits' : 'chat'
24
+ }
25
+
26
+ export function sessionModeLabel(mode: SessionMode): string {
27
+ return mode === 'plan' ? 'plan mode' : mode === 'accept-edits' ? 'accept edits on' : ''
28
+ }
29
+
30
+ export function modePolicy(mode: PolicyMode): ModePolicy {
31
+ if (mode === 'plan') {
32
+ return {
33
+ mode,
34
+ exposesToolKind: kind => kind === 'read' || kind === 'private-continuity-read' || kind === 'mcp',
35
+ autoAllowToolKind: kind => kind === 'private-continuity-read',
36
+ promptLabel: 'plan mode',
37
+ }
38
+ }
39
+
40
+ if (mode === 'accept-edits') {
41
+ return {
42
+ mode,
43
+ exposesToolKind: () => true,
44
+ autoAllowToolKind: kind => kind === 'read' || kind === 'edit' || kind === 'write' || kind === 'private-continuity-read',
45
+ promptLabel: 'accept edits',
46
+ }
47
+ }
48
+
49
+ return {
50
+ mode,
51
+ exposesToolKind: () => true,
52
+ autoAllowToolKind: kind => kind === 'private-continuity-read',
53
+ promptLabel: 'default chat',
54
+ }
55
+ }