dsh-code 0.9.1 → 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 (59) hide show
  1. package/README.en.md +29 -13
  2. package/README.md +264 -248
  3. package/bin/deepseek.mjs +100 -6
  4. package/cordis.patch.yml +29 -1
  5. package/lib/index.mjs +2223 -687
  6. package/lib/startup.mjs +21 -11
  7. package/lib/{theme-BEi4i_aN.mjs → theme-DCT8Y2xf.mjs} +13 -9
  8. package/lib/types/app.d.ts +66 -14
  9. package/lib/types/attachments.d.ts +7 -0
  10. package/lib/types/editor.d.ts +6 -0
  11. package/lib/types/fork.d.ts +8 -0
  12. package/lib/types/git-workflow.d.ts +23 -0
  13. package/lib/types/index.d.ts +6 -0
  14. package/lib/types/kernel-panels.d.ts +39 -0
  15. package/lib/types/keyboard.d.ts +43 -0
  16. package/lib/types/mentions.d.ts +28 -38
  17. package/lib/types/presets.d.ts +1 -3
  18. package/lib/types/provider-settings.d.ts +16 -0
  19. package/lib/types/render/animations.d.ts +10 -39
  20. package/lib/types/render/editor.d.ts +137 -0
  21. package/lib/types/render/export.d.ts +1 -1
  22. package/lib/types/render/lines.d.ts +6 -2
  23. package/lib/types/render/markdown.d.ts +3 -1
  24. package/lib/types/render/projection.d.ts +29 -3
  25. package/lib/types/render/status.d.ts +5 -12
  26. package/lib/types/session-directory.d.ts +1 -3
  27. package/lib/types/startup.d.ts +14 -11
  28. package/lib/types/store.d.ts +11 -9
  29. package/lib/types/subagents.d.ts +3 -3
  30. package/lib/types/theme.d.ts +14 -1
  31. package/lib/types/version.d.ts +15 -2
  32. package/package.json +153 -141
  33. package/src/app.ts +4455 -3917
  34. package/src/attachments.ts +44 -0
  35. package/src/editor.ts +51 -0
  36. package/src/fork.ts +31 -0
  37. package/src/git-workflow.ts +87 -0
  38. package/src/index.ts +1510 -1374
  39. package/src/internals.ts +14 -1
  40. package/src/kernel-panels.ts +914 -798
  41. package/src/keyboard.ts +125 -0
  42. package/src/mentions.ts +72 -117
  43. package/src/presets.ts +1 -4
  44. package/src/provider-settings.ts +94 -0
  45. package/src/render/animations.ts +25 -55
  46. package/src/render/editor.ts +398 -0
  47. package/src/render/export.ts +79 -79
  48. package/src/render/lines.ts +342 -236
  49. package/src/render/markdown.ts +99 -26
  50. package/src/render/projection.ts +102 -19
  51. package/src/render/status.ts +713 -650
  52. package/src/render/text.ts +150 -150
  53. package/src/render/tool-detail.ts +3 -1
  54. package/src/session-directory.ts +3 -3
  55. package/src/startup.ts +136 -119
  56. package/src/store.ts +23 -11
  57. package/src/subagents.ts +13 -5
  58. package/src/theme.ts +214 -206
  59. package/src/version.ts +58 -1
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Keyboard enhancement protocol (Codex `keyboard_modes` parity) and the
3
+ * kitty CSI-u normalization layer.
4
+ *
5
+ * The TUI pushes the kitty keyboard protocol with DISAMBIGUATE_ESCAPE_CODES
6
+ * and REPORT_ALTERNATE_KEYS (flags 1|4 = `\x1b[>5u`), which makes terminals
7
+ * report Shift+Enter as `CSI 13;2u` instead of a bare CR. Event types are
8
+ * deliberately NOT requested: Ink 5's parser cannot decode the
9
+ * `:event-type` suffix, and repeat/release reporting buys this surface
10
+ * nothing.
11
+ *
12
+ * Ink 5 also cannot parse most CSI-u forms at all — they fall through its
13
+ * regex as unnamed sequences and get INSERTED AS DRAFT TEXT. The composer's
14
+ * stdin read patch therefore rewrites every CSI-u form it can decode back
15
+ * to the legacy byte or canonical sequence the existing key handling
16
+ * already understands, before Ink ever parses the chunk.
17
+ *
18
+ * @module @deepseek-ai/dsh-code/keyboard
19
+ */
20
+
21
+ /** Push keyboard enhancement (modifyOtherKeys off, kitty flags 1|4). */
22
+ export const KEYBOARD_ENHANCE_ENABLE = '\x1b[>4;0m\x1b[>5u'
23
+
24
+ /** Pop the enhancement stack and reset modifyOtherKeys (exit path). */
25
+ export const KEYBOARD_ENHANCE_DISABLE = '\x1b[<u\x1b[>4;0m'
26
+
27
+ /** Enable bracketed paste reporting. */
28
+ export const BRACKETED_PASTE_ENABLE = '\x1b[?2004h'
29
+
30
+ /** Disable bracketed paste reporting. */
31
+ export const BRACKETED_PASTE_DISABLE = '\x1b[?2004l'
32
+
33
+ /** Bracketed paste markers as Ink delivers them (it strips the leading ESC). */
34
+ export const PASTE_START_MARKER = '[200~'
35
+ export const PASTE_END_MARKER = '[201~'
36
+
37
+ /**
38
+ * Remove bracketed paste markers from one input chunk. Panel drafts accept raw
39
+ * `input` text, where an unhandled paste would otherwise persist the literal
40
+ * "[200~"/"[201~" markers Ink leaves after stripping the ESC byte.
41
+ */
42
+ export function stripPasteMarkers(text: string): string {
43
+ return text.replaceAll(PASTE_START_MARKER, '').replaceAll(PASTE_END_MARKER, '')
44
+ }
45
+
46
+ /** One decoded CSI-u keypress: key code, 1-based modifier param, alternate code. */
47
+ interface CsiUKey {
48
+ code: number
49
+ modifiers: number
50
+ alternate?: number
51
+ }
52
+
53
+ /** Match one CSI-u sequence (code, optional ;modifiers, then :event or ;alternate). */
54
+ const CSI_U_SOURCE = '\x1b\\[(\\d+)(?:;(\\d+))?(?:[:;](\\d+))?u'
55
+
56
+ /** Legacy equivalent for one decoded CSI-u key, or undefined to pass through. */
57
+ function legacyForKey(key: CsiUKey): string | undefined {
58
+ const bits = Math.max(0, key.modifiers - 1)
59
+ const shift = (bits & 1) !== 0
60
+ const alt = (bits & 2) !== 0
61
+ const ctrl = (bits & 4) !== 0
62
+ if (key.code === 13) {
63
+ // Enter: shift keeps the canonical enhanced form the composer detects;
64
+ // ctrl maps to LF (the Ctrl+J newline binding), alt to ESC+CR.
65
+ if (shift) return '\x1b[13;2u'
66
+ if (ctrl) return '\n'
67
+ if (alt) return '\x1b\r'
68
+ return '\r'
69
+ }
70
+ if (key.code === 27) return '\x1b'
71
+ if (key.code === 9) return shift ? '\x1b[Z' : '\t'
72
+ if (key.code === 127) return alt || ctrl ? '\x1b\x7f' : '\x7f'
73
+ // Kitty disambiguate mode reports the six legacy functional keys as CSI u
74
+ // codes 1-6 (Home, Insert, Delete, End, PageUp, PageDown). Ink 5 cannot
75
+ // parse these forms and would insert literal "[3u" text into the draft, so
76
+ // rewrite them to the legacy sequences the input layer already annotates.
77
+ // The modifier parameter passes through: kitty and xterm share the same
78
+ // 1+bit-field encoding (shift 2, alt 3, ctrl 5, ...). Lock-key bits are
79
+ // dropped because the legacy sequences cannot express them.
80
+ if (key.code >= 1 && key.code <= 6) {
81
+ const mask = (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0)
82
+ const mods = mask === 0 ? '' : `;${mask + 1}`
83
+ if (key.code === 1) return mods === '' ? '\x1b[H' : `\x1b[1${mods}H`
84
+ if (key.code === 4) return mods === '' ? '\x1b[F' : `\x1b[1${mods}F`
85
+ return `\x1b[${key.code}${mods}~`
86
+ }
87
+ if (key.code >= 97 && key.code <= 122) {
88
+ const letter = String.fromCodePoint(key.code)
89
+ if (ctrl) return String.fromCodePoint(key.code - 96)
90
+ if (alt) return '\x1b' + letter
91
+ if (shift) return String.fromCodePoint(key.alternate ?? key.code - 32)
92
+ return letter
93
+ }
94
+ if (key.code >= 65 && key.code <= 90) {
95
+ if (ctrl) return String.fromCodePoint(key.code + 32 - 96)
96
+ if (alt) return '\x1b' + String.fromCodePoint(key.code + 32)
97
+ return String.fromCodePoint(key.code)
98
+ }
99
+ if (key.code >= 32 && key.code <= 126 && key.alternate !== undefined) {
100
+ const base = key.alternate >= 97 && key.alternate <= 122 ? key.alternate : key.code
101
+ if (ctrl && base - 96 >= 1 && base - 96 <= 26) return String.fromCodePoint(base - 96)
102
+ if (alt) return '\x1b' + String.fromCodePoint(key.alternate)
103
+ return String.fromCodePoint(key.alternate)
104
+ }
105
+ return undefined
106
+ }
107
+
108
+ /**
109
+ * Rewrite every decodable kitty CSI-u sequence in one stdin chunk to the
110
+ * legacy form the input layer already handles. Undecodable or non-key
111
+ * sequences pass through untouched, so terminals without the protocol are
112
+ * unaffected.
113
+ */
114
+ export function normalizeKeyboardChunk(chunk: string): string {
115
+ if (!chunk.includes('\x1b[') || !chunk.includes('u')) return chunk
116
+ const pattern = new RegExp(CSI_U_SOURCE, 'g')
117
+ return chunk.replace(pattern, (whole, code: string, mods?: string, third?: string) => {
118
+ const legacy = legacyForKey({
119
+ code: Number.parseInt(code, 10),
120
+ modifiers: mods === undefined || mods === '' ? 1 : Math.max(1, Number.parseInt(mods, 10)),
121
+ alternate: third !== undefined && third !== '' ? Number.parseInt(third, 10) : undefined,
122
+ })
123
+ return legacy ?? whole
124
+ })
125
+ }
package/src/mentions.ts CHANGED
@@ -1,25 +1,33 @@
1
1
  /**
2
- * Workspace @mention support: file and directory candidates from a bounded
3
- * async scan of the session cwd, session candidates from the opt-in
4
- * `sessionReferenceResolver` service, and submission preparation through its
5
- * `prepare()` API. Picked session mentions land as canonical
6
- * `@[label](dsh-session:…)` tokens; on submit the text is parsed back into
7
- * readable `@label` text plus structured references, snapshots are injected
8
- * via `agent.inject()` before the readable message wakes the driver
2
+ * Workspace @mention support: file and directory candidates from the
3
+ * `fileReferences` service (dsh-file-reference-local), session candidates
4
+ * from the opt-in `sessionReferenceResolver` service, and submission
5
+ * preparation through its `prepare()` API. Picked session mentions land as
6
+ * canonical `@[label](dsh-session:…)` tokens; on submit the text is parsed
7
+ * back into readable `@label` text plus structured references, snapshots are
8
+ * injected via `agent.inject()` before the readable message wakes the driver
9
9
  * (`followup` idle, `steer` running) — exactly the upstream README's wiring.
10
10
  *
11
- * Harness exposes no workspace-file mention service (only session references
12
- * plus a post-hoc produced-file linker), so the file index is the lightweight
13
- * bounded scan below, kept deliberately smaller than Codex's streaming
14
- * gitignore-aware walker.
11
+ * File discovery lives entirely in the Harness service (per-agent bounded
12
+ * index, `@dir/` listing, symlink guards, tool/result invalidation); this
13
+ * module only maps candidates to menu rows and never re-implements scanning.
14
+ * The service is agent-scoped (the agent supplies the session cwd and the
15
+ * cache key), so before the first session creates an agent the SAME official
16
+ * search class runs against the launch cwd — @ file completion works on a
17
+ * bare launch, model- and session-independent, and the agent-scoped service
18
+ * takes over once a session exists.
15
19
  *
16
20
  * @module @deepseek-ai/dsh-code/mentions
17
21
  */
18
22
 
19
- import { readdir } from 'node:fs/promises'
20
- import { join } from 'node:path'
21
23
  import type { Context } from '@deepseek-ai/cordis'
22
24
  import type { Agent } from '@deepseek-ai/dsh-agent'
25
+ import {
26
+ DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES,
27
+ DEFAULT_FILE_SEARCH_MAX_ENTRIES,
28
+ DEFAULT_FILE_SEARCH_MAX_RESULTS,
29
+ WorkspaceFileSearch,
30
+ } from '@deepseek-ai/dsh-file-reference-local'
23
31
  import {
24
32
  formatSessionReferenceMention,
25
33
  parseSessionReferenceText,
@@ -30,14 +38,6 @@ import {
30
38
  /** Parsed submission text: readable text plus structured references. */
31
39
  type ParsedSessionReferenceText = ReturnType<typeof parseSessionReferenceText>
32
40
 
33
- /** One filesystem entry the @ menu can complete. */
34
- export interface FileCandidate {
35
- /** Workspace-relative path with forward slashes. */
36
- path: string
37
- /** Entry kind; directories insert with a trailing slash. */
38
- kind: 'file' | 'directory'
39
- }
40
-
41
41
  /** One merged menu candidate (files and sessions, already ranked). */
42
42
  export interface MentionCandidate {
43
43
  /** Text inserted after the `@` (directories carry a trailing slash). */
@@ -58,76 +58,22 @@ export interface PreparedMention {
58
58
  additionalContext?: import('@deepseek-ai/dsh-session').UserMessage
59
59
  }
60
60
 
61
- /** Directories never entered and files never listed during the scan. */
62
- const SKIP_DIRS = new Set(['.git', 'node_modules', 'lib', 'dist', 'out', '.omc', 'coverage'])
63
- const MAX_FILES = 4000
64
- const MAX_DEPTH = 12
65
- /** Empty-query default rows: proves the index exists without typing (Codex's
66
- * popups show something on a bare sigil too). */
67
- const EMPTY_QUERY_ROWS = 20
68
-
69
- /**
70
- * Bounded async BFS scan of a workspace; unreadable entries are skipped.
71
- * Both files and directories are indexed (directories insert with a trailing
72
- * slash), mirroring Codex's `MatchType::{File,Directory}` index. Dotfiles and
73
- * the {@link SKIP_DIRS} list are excluded, which is a coarser filter than
74
- * Codex's gitignore-aware walker but stays dependency-free and bounded.
75
- */
76
- export async function scanWorkspaceFiles(root: string, signal?: AbortSignal): Promise<readonly FileCandidate[]> {
77
- const found: FileCandidate[] = []
78
- const pending: Array<{ absolute: string; relative: string; depth: number }> = [{ absolute: root, relative: '', depth: 0 }]
79
- const aborted = (): boolean => signal?.aborted === true
80
- while (pending.length > 0 && found.length < MAX_FILES && !aborted()) {
81
- const current = pending.shift()
82
- if (current === undefined) break
83
- let entries
84
- try {
85
- entries = await readdir(current.absolute, { withFileTypes: true })
86
- } catch {
87
- continue
88
- }
89
- for (const entry of entries) {
90
- if (found.length >= MAX_FILES || aborted()) return found
91
- if (entry.name.startsWith('.')) continue
92
- const relative = current.relative === '' ? entry.name : `${current.relative}/${entry.name}`
93
- if (entry.isDirectory()) {
94
- if (SKIP_DIRS.has(entry.name) || current.depth + 1 > MAX_DEPTH) continue
95
- found.push({ path: relative, kind: 'directory' })
96
- pending.push({ absolute: join(current.absolute, entry.name), relative, depth: current.depth + 1 })
97
- } else if (entry.isFile()) {
98
- found.push({ path: relative, kind: 'file' })
99
- }
100
- }
101
- }
102
- return found.sort((left, right) => left.path < right.path ? -1 : 1)
61
+ /** One path candidate the `ctx.fileReferences` service returns. */
62
+ interface ServiceFileCandidate {
63
+ readonly path: string
64
+ readonly kind: 'file' | 'directory'
103
65
  }
104
66
 
105
- /** True when every query character appears in order in the haystack. */
106
- function isSubsequence(query: string, haystack: string): boolean {
107
- let at = 0
108
- for (const char of haystack) {
109
- if (char === query[at]) at += 1
110
- if (at >= query.length) return true
111
- }
112
- return at >= query.length
67
+ /** The `ctx.fileReferences` service face (dsh-file-reference-local). */
68
+ interface FileReferenceServiceLike {
69
+ list(agent: Agent, query: string, signal: AbortSignal): Promise<readonly ServiceFileCandidate[]>
113
70
  }
114
71
 
115
- /** Rank one file path against the typed query (community-TUI scoring shape). */
116
- function scoreFile(path: string, query: string): number {
117
- const name = path.slice(path.lastIndexOf('/') + 1)
118
- if (query === '') return 0
119
- if (name === query) return 1000
120
- if (name.startsWith(query)) return 900
121
- if (name.includes(query)) return 700
122
- if (path.includes(query)) return 500
123
- if (isSubsequence(query, name)) return 300
124
- return 0
125
- }
72
+ /** Menu cap on file rows; the service owns ranking and default rows. */
73
+ const MAX_FILE_ROWS = 20
126
74
 
127
75
  /** The mention API the input editor and the runner share. */
128
76
  export interface MentionsApi {
129
- /** Scanned workspace files and directories, cached across one session. */
130
- files(): Promise<readonly FileCandidate[]>
131
77
  /** Ranked menu candidates for the typed `@` query. */
132
78
  candidates(query: string, signal?: AbortSignal): Promise<readonly MentionCandidate[]>
133
79
  /** Parse submission text into readable text plus structured references. */
@@ -143,53 +89,62 @@ export interface MentionsApi {
143
89
 
144
90
  /**
145
91
  * Create the mention API for one agent's workspace. A missing
146
- * session-reference service degrades to file mentions only (the scan still
147
- * works); `prepare` then passes text through untouched. An undefined agent
148
- * (a bare launch before any session exists) also degrades to file-only
149
- * mentions, so `@` file completion works before the first message.
92
+ * `fileReferences` service (with an agent present) or `sessionReferenceResolver`
93
+ * degrades that half to empty rows; `prepare` passes text through untouched
94
+ * without references. An undefined agent (a bare launch before any session
95
+ * exists) runs the official WorkspaceFileSearch over the launch cwd — the
96
+ * same class the mounted service uses per agent — so `@` file completion
97
+ * works from the first keystroke; session references wait for the session.
150
98
  *
151
- * `files` is hoisted into the closure so `candidates` never reaches for
152
- * `this` the runner hands `mentions.candidates` to the input editor as a
153
- * detached callback, and a `this`-bound method would throw on every `@` key.
154
- * @param ctx - context carrying the optional `sessionReferenceResolver`.
155
- * @param agent - the session owner; excluded from its own candidates.
156
- * @param cwd - workspace root to scan.
99
+ * `candidates` never reaches for `this` — the runner hands it to the input
100
+ * editor as a detached callback, and a `this`-bound method would throw on
101
+ * every `@` key.
102
+ * @param ctx - context carrying the optional `fileReferences` and
103
+ * `sessionReferenceResolver` services.
104
+ * @param agent - the session owner; excluded from its own session candidates.
105
+ * @param cwd - launch working directory; bounds the pre-session search.
157
106
  */
158
107
  export function createMentions(ctx: Context, agent: Agent | undefined, cwd: string): MentionsApi {
159
108
  const resolver = ctx.get('sessionReferenceResolver')
109
+ const fileReferences = (ctx as unknown as { get(name: string): unknown }).get('fileReferences') as
110
+ | FileReferenceServiceLike
111
+ | undefined
160
112
  const sessionCapable = agent !== undefined && resolver !== undefined
161
- let filesPromise: Promise<readonly FileCandidate[]> | undefined
162
- const files = (): Promise<readonly FileCandidate[]> => {
163
- filesPromise ??= scanWorkspaceFiles(cwd)
164
- return filesPromise
113
+ // Pre-session fallback: one lazily built search over the launch cwd with
114
+ // the official defaults pure in-memory index, no handles to release.
115
+ let preSessionSearch: WorkspaceFileSearch | undefined
116
+ const preSessionFiles = (query: string, signal?: AbortSignal): Promise<readonly ServiceFileCandidate[]> => {
117
+ preSessionSearch ??= new WorkspaceFileSearch(cwd, {
118
+ maxResults: DEFAULT_FILE_SEARCH_MAX_RESULTS,
119
+ maxEntries: DEFAULT_FILE_SEARCH_MAX_ENTRIES,
120
+ excludedDirectories: [...DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES],
121
+ })
122
+ return preSessionSearch.list(query, signal ?? new AbortController().signal)
165
123
  }
166
124
 
167
125
  return {
168
- files,
169
126
  async candidates(query: string, signal?: AbortSignal): Promise<readonly MentionCandidate[]> {
170
127
  const needle = query.trim()
171
- const [scanned, sessions] = await Promise.all([
172
- files(),
128
+ const [files, sessions] = await Promise.all([
129
+ agent !== undefined && fileReferences !== undefined
130
+ ? fileReferences
131
+ .list(agent, needle, signal ?? new AbortController().signal)
132
+ .catch(() => [] as readonly ServiceFileCandidate[])
133
+ : agent === undefined
134
+ ? preSessionFiles(needle, signal).catch(() => [] as readonly ServiceFileCandidate[])
135
+ : Promise.resolve([] as readonly ServiceFileCandidate[]),
173
136
  sessionCapable && needle !== '' && agent !== undefined
174
137
  ? resolver!.listCandidates(agent, needle, 10, signal).catch(() => [] as readonly SessionReferenceCandidate[])
175
138
  : Promise.resolve([] as readonly SessionReferenceCandidate[]),
176
139
  ])
177
- // A bare `@` lists the first path-sorted entries so the menu is live
178
- // before any typing; a non-empty needle ranks by the Codex-shaped score.
179
- const fileRows: MentionCandidate[] = (needle === ''
180
- ? scanned.slice(0, EMPTY_QUERY_ROWS)
181
- : scanned
182
- .filter(candidate => scoreFile(candidate.path, needle) > 0)
183
- .sort((left, right) => scoreFile(right.path, needle) - scoreFile(left.path, needle))
184
- .slice(0, 20))
185
- .map(candidate => ({
186
- label: candidate.path,
187
- description: candidate.kind === 'directory' ? 'Folder' : 'File',
188
- kind: candidate.kind,
189
- }))
190
- // Sessions join only with a typed needle and always AFTER the file
191
- // rows: `@` is a file mention first (Codex's semantics), and session
192
- // references are the secondary vocabulary.
140
+ // The service owns ranking (and the bare-@ default rows); the menu caps
141
+ // file rows and always places sessions after files `@` is a file
142
+ // mention first (Codex's semantics), session references second.
143
+ const fileRows: MentionCandidate[] = files.slice(0, MAX_FILE_ROWS).map(candidate => ({
144
+ label: candidate.path,
145
+ description: candidate.kind === 'directory' ? 'Folder' : 'File',
146
+ kind: candidate.kind,
147
+ }))
193
148
  const sessionRows: MentionCandidate[] = sessions.map(candidate => ({
194
149
  label: formatSessionReferenceMention(candidate),
195
150
  description: `Session · ${candidate.cwd ?? '(no cwd)'}`,
package/src/presets.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** Agent-preset policy kept independent from the Ink surface. */
2
2
 
3
3
  import type { Context } from '@deepseek-ai/cordis'
4
- import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent'
4
+ import type { Agent } from '@deepseek-ai/dsh-agent'
5
5
  import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
6
6
 
7
7
  /** One discoverable agent composition. */
@@ -71,6 +71,3 @@ export async function switchPreset(
71
71
  writable.append('agent-preset/selected', { agentPreset: preset.id })
72
72
  return preset
73
73
  }
74
-
75
- /** Minimal handle shape used by lifecycle tests without exposing Agent internals. */
76
- export type OwnedAgent = Pick<AgentHandle, 'agent' | 'dispose'>
@@ -129,6 +129,28 @@ function profileRefOf(profile: unknown): string | undefined {
129
129
  return typeof ref === 'string' && ref.length > 0 ? ref : undefined
130
130
  }
131
131
 
132
+ /** Extract only fields the terminal can round-trip without touching provider-specific extras. */
133
+ function configurationOf(profile: unknown): ProviderConfiguration {
134
+ if (typeof profile !== 'object' || profile === null) return { models: [] }
135
+ const record = profile as Record<string, unknown>
136
+ const source = Array.isArray(record.models) ? record.models : []
137
+ const models = source.flatMap((value): ProviderModelSettings[] => {
138
+ if (typeof value !== 'object' || value === null) return []
139
+ const entry = value as Record<string, unknown>
140
+ if (typeof entry.id !== 'string' || entry.id.trim() === '') return []
141
+ return [{
142
+ id: entry.id,
143
+ ...(typeof entry.name === 'string' && entry.name.trim() !== '' ? { name: entry.name } : {}),
144
+ ...(typeof entry.contextWindow === 'number' && Number.isFinite(entry.contextWindow) ? { contextWindow: entry.contextWindow } : {}),
145
+ ...(typeof entry.maxTokens === 'number' && Number.isFinite(entry.maxTokens) ? { maxTokens: entry.maxTokens } : {}),
146
+ }]
147
+ })
148
+ return {
149
+ ...(typeof record.baseURL === 'string' && record.baseURL.trim() !== '' ? { baseURL: record.baseURL } : {}),
150
+ models,
151
+ }
152
+ }
153
+
132
154
  /* ------------------------------------------------------------------ *
133
155
  * Exported contracts.
134
156
  * ------------------------------------------------------------------ */
@@ -166,6 +188,20 @@ export type ProviderCredentialView =
166
188
  | ({ readonly kind: 'facts' } & ProviderCredentialFacts)
167
189
  | { readonly kind: 'error'; readonly message: string }
168
190
 
191
+ /** One explicit model enabled for a provider profile. */
192
+ export interface ProviderModelSettings {
193
+ readonly id: string
194
+ readonly name?: string
195
+ readonly contextWindow?: number
196
+ readonly maxTokens?: number
197
+ }
198
+
199
+ /** The small, portable subset of a provider profile the terminal edits. */
200
+ export interface ProviderConfiguration {
201
+ readonly baseURL?: string
202
+ readonly models: readonly ProviderModelSettings[]
203
+ }
204
+
169
205
  /**
170
206
  * One provider row in the TUI provider-management panel: the configurable
171
207
  * directory entry joined with its settings profile and credential facts.
@@ -195,6 +231,8 @@ export interface ProviderTargetView {
195
231
  readonly suggestedRef: string
196
232
  /** Credential facts, a bounded describe error, or undefined when there is no ref to describe. */
197
233
  readonly credential: ProviderCredentialView | undefined
234
+ /** Endpoint and explicit model overrides visible to the provider editor. */
235
+ readonly configuration: ProviderConfiguration
198
236
  /** The owning adapter reports this route as hand-declared (absent when it draws no distinction). */
199
237
  readonly declared?: boolean
200
238
  }
@@ -339,6 +377,7 @@ export async function loadProviderSettings(ctx: Context): Promise<ProviderSettin
339
377
  settingsRevision: namespace?.revision ?? 0,
340
378
  configured,
341
379
  removable,
380
+ configuration: configurationOf(profile),
342
381
  ...credentialRef === undefined ? {} : { credentialRef },
343
382
  suggestedRef: deriveCredentialRef(base.provider),
344
383
  ...base.declared === undefined ? {} : { declared: base.declared },
@@ -441,6 +480,61 @@ export async function saveProviderCredential(ctx: Context, target: ProviderTarge
441
480
  }
442
481
  }
443
482
 
483
+ /** Save the endpoint and an explicit model allow-list without rebuilding the profile. */
484
+ export async function saveProviderConfiguration(
485
+ ctx: Context,
486
+ target: ProviderTargetView,
487
+ configuration: ProviderConfiguration,
488
+ ): Promise<void> {
489
+ if (target.settingsNs.length === 0) {
490
+ throw new ProviderSettingsError(`provider "${target.provider}" has no managed settings namespace; configure it in settings.yaml`)
491
+ }
492
+ const settings = ctx.get('settings') as SettingsFace | undefined
493
+ if (settings === undefined || settings.writable !== true) {
494
+ throw new ProviderSettingsError('settings are read-only; provider configuration cannot be changed here')
495
+ }
496
+ const baseURL = configuration.baseURL?.trim()
497
+ if (baseURL !== undefined && baseURL !== '') {
498
+ try {
499
+ const parsed = new URL(baseURL)
500
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') throw new Error('unsupported protocol')
501
+ } catch {
502
+ throw new ProviderSettingsError('base URL must be an absolute http or https URL')
503
+ }
504
+ }
505
+ const seen = new Set<string>()
506
+ const models = configuration.models.map((model) => {
507
+ const id = model.id.trim()
508
+ if (id === '' || seen.has(id)) throw new ProviderSettingsError('each selected model must have a unique non-empty id')
509
+ seen.add(id)
510
+ for (const [label, value] of [['context window', model.contextWindow], ['output window', model.maxTokens]] as const) {
511
+ if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) {
512
+ throw new ProviderSettingsError(`${label} must be a positive integer`)
513
+ }
514
+ }
515
+ return {
516
+ id,
517
+ ...(model.name === undefined || model.name.trim() === '' ? {} : { name: model.name.trim() }),
518
+ ...(model.contextWindow === undefined ? {} : { contextWindow: model.contextWindow }),
519
+ ...(model.maxTokens === undefined ? {} : { maxTokens: model.maxTokens }),
520
+ }
521
+ })
522
+ const root = target.settingsPath
523
+ const ops: SettingsPathOpFace[] = [
524
+ baseURL === undefined || baseURL === ''
525
+ ? { op: 'unset', path: [...root, 'baseURL'] }
526
+ : { op: 'set', path: [...root, 'baseURL'], value: baseURL },
527
+ // An explicit empty list is deliberate: it prevents a provider's shipped
528
+ // catalog from silently becoming the active selection.
529
+ { op: 'set', path: [...root, 'models'], value: models },
530
+ ]
531
+ try {
532
+ await settings.mutate(target.settingsNs, ops, target.settingsRevision)
533
+ } catch (error) {
534
+ throw new ProviderSettingsError(singleLine(messageOf(error)))
535
+ }
536
+ }
537
+
444
538
  /**
445
539
  * Remove the currently named credential without touching the provider
446
540
  * profile. Only the resolved profile's own reference is unset; a dormant or