dsh-code 1.3.0 → 1.4.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 (92) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/lib/index.mjs +5115 -4390
  4. package/lib/types/app.d.ts +18 -51
  5. package/lib/types/completion.d.ts +29 -0
  6. package/lib/types/composer.d.ts +150 -0
  7. package/lib/types/git-workflow.d.ts +6 -0
  8. package/lib/types/index.d.ts +6 -188
  9. package/lib/types/locales/en.d.ts +16 -4
  10. package/lib/types/{authorization-panel.d.ts → panels/authorization-panel.d.ts} +6 -1
  11. package/lib/types/panels/completion-panel.d.ts +13 -0
  12. package/lib/types/panels/interaction-bars.d.ts +38 -0
  13. package/lib/types/{kernel-panels.d.ts → panels/kernel-panels.d.ts} +16 -37
  14. package/lib/types/{language-panel.d.ts → panels/language-panel.d.ts} +1 -1
  15. package/lib/types/panels/model-panels.d.ts +86 -0
  16. package/lib/types/{theme-panel.d.ts → panels/theme-panel.d.ts} +1 -1
  17. package/lib/types/{update-panel.d.ts → panels/update-panel.d.ts} +1 -1
  18. package/lib/types/provider-settings.d.ts +11 -0
  19. package/lib/types/render/inspector.d.ts +8 -0
  20. package/lib/types/render/text.d.ts +4 -0
  21. package/lib/types/runner/harness-gate.d.ts +83 -0
  22. package/lib/types/runner/input-history.d.ts +31 -0
  23. package/lib/types/runner/mode-cycle.d.ts +44 -0
  24. package/lib/types/runner/preferences.d.ts +40 -0
  25. package/lib/types/runner/quit.d.ts +27 -0
  26. package/lib/types/runner/search-rows.d.ts +38 -0
  27. package/lib/types/runner/session-io.d.ts +46 -0
  28. package/lib/types/runner/session-target.d.ts +42 -0
  29. package/lib/types/runner/startup-config.d.ts +33 -0
  30. package/lib/types/runner/submissions.d.ts +87 -0
  31. package/lib/types/session/attach.d.ts +39 -0
  32. package/lib/types/{store.d.ts → session/store.d.ts} +1 -1
  33. package/lib/types/{subagents.d.ts → session/subagents.d.ts} +8 -1
  34. package/lib/types/settings-file.d.ts +10 -0
  35. package/lib/types/{panel-accent.d.ts → ui/panel-accent.d.ts} +1 -1
  36. package/lib/types/ui/panel-gap.d.ts +6 -0
  37. package/lib/types/ui/query-editor.d.ts +10 -0
  38. package/lib/types/ui/styled-rows.d.ts +8 -0
  39. package/lib/types/{terminal-title.d.ts → ui/terminal-title.d.ts} +1 -1
  40. package/lib/types/ui/ui-contract.d.ts +12 -0
  41. package/lib/types/ui/use-frames.d.ts +6 -0
  42. package/lib/types/ui/use-stable-input.d.ts +7 -0
  43. package/package.json +1 -1
  44. package/src/app.ts +543 -4066
  45. package/src/completion.ts +117 -0
  46. package/src/composer.ts +1956 -0
  47. package/src/git-workflow.ts +18 -0
  48. package/src/index.ts +113 -633
  49. package/src/internals.ts +1 -1
  50. package/src/locales/en.ts +16 -4
  51. package/src/locales/zh.ts +16 -4
  52. package/src/{authorization-panel.ts → panels/authorization-panel.ts} +25 -6
  53. package/src/panels/completion-panel.ts +79 -0
  54. package/src/panels/interaction-bars.ts +567 -0
  55. package/src/{kernel-panels.ts → panels/kernel-panels.ts} +84 -65
  56. package/src/{language-panel.ts → panels/language-panel.ts} +4 -4
  57. package/src/panels/model-panels.ts +1021 -0
  58. package/src/{theme-panel.ts → panels/theme-panel.ts} +5 -5
  59. package/src/{update-panel.ts → panels/update-panel.ts} +6 -6
  60. package/src/provider-settings.ts +38 -0
  61. package/src/render/inspector.ts +23 -0
  62. package/src/render/text.ts +8 -0
  63. package/src/runner/harness-gate.ts +168 -0
  64. package/src/runner/input-history.ts +77 -0
  65. package/src/runner/mode-cycle.ts +49 -0
  66. package/src/runner/preferences.ts +67 -0
  67. package/src/runner/quit.ts +53 -0
  68. package/src/runner/search-rows.ts +55 -0
  69. package/src/runner/session-io.ts +206 -0
  70. package/src/runner/session-target.ts +81 -0
  71. package/src/runner/startup-config.ts +54 -0
  72. package/src/runner/submissions.ts +157 -0
  73. package/src/session/attach.ts +87 -0
  74. package/src/{session-directory.ts → session/session-directory.ts} +1 -1
  75. package/src/{store.ts → session/store.ts} +1 -1
  76. package/src/{subagents.ts → session/subagents.ts} +12 -1
  77. package/src/settings-file.ts +19 -1
  78. package/src/{panel-accent.ts → ui/panel-accent.ts} +1 -1
  79. package/src/ui/panel-gap.ts +9 -0
  80. package/src/ui/query-editor.ts +16 -0
  81. package/src/ui/styled-rows.ts +124 -0
  82. package/src/{terminal-title.ts → ui/terminal-title.ts} +1 -1
  83. package/src/ui/ui-contract.ts +10 -0
  84. package/src/ui/use-frames.ts +23 -0
  85. package/src/ui/use-stable-input.ts +17 -0
  86. /package/lib/types/{fork.d.ts → session/fork.d.ts} +0 -0
  87. /package/lib/types/{history.d.ts → session/history.d.ts} +0 -0
  88. /package/lib/types/{session-directory.d.ts → session/session-directory.d.ts} +0 -0
  89. /package/lib/types/{session-switch.d.ts → session/session-switch.d.ts} +0 -0
  90. /package/src/{fork.ts → session/fork.ts} +0 -0
  91. /package/src/{history.ts → session/history.ts} +0 -0
  92. /package/src/{session-switch.ts → session/session-switch.ts} +0 -0
@@ -9,11 +9,11 @@
9
9
 
10
10
  import { createElement, useState, type ReactElement } from 'react'
11
11
  import { Box, Text, useInput, useStdout } from 'ink'
12
- import { clampScroll, panelViewport } from './render/inspector.ts'
13
- import { truncateColumns } from './render/text.ts'
14
- import { panelAccent } from './panel-accent.ts'
15
- import { getPalette, inkColor, THEMES, type ThemeName } from './theme.ts'
16
- import { t } from './i18n.ts'
12
+ import { clampScroll, panelViewport } from '../render/inspector.ts'
13
+ import { truncateColumns } from '../render/text.ts'
14
+ import { panelAccent } from '../ui/panel-accent.ts'
15
+ import { getPalette, inkColor, THEMES, type ThemeName } from '../theme.ts'
16
+ import { t } from '../i18n.ts'
17
17
 
18
18
  /**
19
19
  * The /theme list: one row per theme, the current one marked with ●, the
@@ -11,12 +11,12 @@
11
11
 
12
12
  import { createElement, useEffect, useState, type ReactElement } from 'react'
13
13
  import { Box, Text, useInput, useStdout } from 'ink'
14
- import type { LauncherUpdatePlan, LauncherUpdateStatus } from './update.ts'
15
- import { clampScroll, panelViewport } from './render/inspector.ts'
16
- import { singleLineText, truncateColumns } from './render/text.ts'
17
- import { panelAccent } from './panel-accent.ts'
18
- import { getPalette, inkColor } from './theme.ts'
19
- import { t } from './i18n.ts'
14
+ import type { LauncherUpdatePlan, LauncherUpdateStatus } from '../update.ts'
15
+ import { clampScroll, panelViewport } from '../render/inspector.ts'
16
+ import { singleLineText, truncateColumns } from '../render/text.ts'
17
+ import { panelAccent } from '../ui/panel-accent.ts'
18
+ import { getPalette, inkColor } from '../theme.ts'
19
+ import { t } from '../i18n.ts'
20
20
 
21
21
  /** Retained apply-progress lines (ring tail; npm output is ephemeral). */
22
22
  export const UPDATE_OUTPUT_CAP = 800
@@ -666,6 +666,44 @@ export async function saveProviderConfiguration(
666
666
  }
667
667
  }
668
668
 
669
+ /**
670
+ * Switch one provider route to its subscription (plan sign-in) channel: the
671
+ * profile keeps neither a key reference nor an explicit model list, so the
672
+ * official catalog endpoint serves requests and the stored OAuth record — not
673
+ * a settings-named key override — authenticates them. Enabling a route that
674
+ * has no profile yet creates the empty profile that registers it.
675
+ * @param ctx - context carrying the `settings` service.
676
+ * @param target - provider row whose settings namespace owns the profile.
677
+ * @throws when the route is unmanaged or settings are read-only.
678
+ */
679
+ export async function enableProviderSubscription(ctx: Context, target: ProviderTargetView): Promise<void> {
680
+ if (target.settingsNs.length === 0) {
681
+ throw new ProviderSettingsError(`provider "${target.provider}" has no managed settings namespace; configure it in settings.yaml`)
682
+ }
683
+ const settings = ctx.get('settings') as SettingsFace | undefined
684
+ if (settings === undefined || settings.writable !== true) {
685
+ throw new ProviderSettingsError('settings are read-only; provider configuration cannot be changed here')
686
+ }
687
+ const root = target.settingsPath
688
+ const ops: SettingsPathOpFace[] = target.configured
689
+ ? [
690
+ // The key reference would resolve as a request-level override BEFORE
691
+ // the stored sign-in record, so the subscription channel must drop it;
692
+ // the endpoint and the explicit model list belong to the key channel.
693
+ { op: 'unset', path: [...root, 'apiKeyEnv'] },
694
+ { op: 'unset', path: [...root, 'baseURL'] },
695
+ { op: 'unset', path: [...root, 'models'] },
696
+ ]
697
+ // A route with no profile stays dormant: an empty profile registers it
698
+ // with the catalog endpoint and every catalog model.
699
+ : [{ op: 'set', path: [...root], value: {} }]
700
+ try {
701
+ await settings.mutate(target.settingsNs, ops, target.settingsRevision)
702
+ } catch (error) {
703
+ throw new ProviderSettingsError(singleLine(messageOf(error)))
704
+ }
705
+ }
706
+
669
707
  /**
670
708
  * Interrogate a provider endpoint for the models it really serves, through
671
709
  * the model-discovery capability the provider's settings namespace
@@ -99,6 +99,29 @@ export function panelViewport(columns: number, rows: number): InspectorViewport
99
99
  }
100
100
  }
101
101
 
102
+ /**
103
+ * Viewport for an expanded (near-fullscreen) document overlay: the document
104
+ * replaces the transcript area entirely, so the half-screen overlay cap and
105
+ * the inter-section gaps drop away while the bottom live region (composer,
106
+ * status) and the Static-rewrite margin stay reserved. The result stays
107
+ * below terminal height, which is what keeps Ink off its full-rewrite path.
108
+ */
109
+ export function expandedDocumentViewport(columns: number, rows: number): InspectorViewport {
110
+ const safeColumns = Math.max(1, Math.floor(columns))
111
+ const safeRows = Math.max(1, Math.floor(rows))
112
+ const maxHeight = Math.max(0, safeRows - 2 - INSPECTOR_CHROME_ROWS - layoutGutterRows(safeRows))
113
+ const compact = maxHeight < 5 || safeColumns < 8
114
+ const outerColumns = compact ? safeColumns : Math.max(1, safeColumns - 1)
115
+ return {
116
+ maxHeight,
117
+ bodyRows: compact ? 0 : maxHeight - 4,
118
+ gapRows: 0,
119
+ contentColumns: compact ? Math.max(1, safeColumns - 1) : Math.max(1, outerColumns - 4),
120
+ outerColumns,
121
+ compact,
122
+ }
123
+ }
124
+
102
125
  /** Backward-compatible name for the Ctrl+O-specific caller and tests. */
103
126
  export function inspectorViewport(columns: number, rows: number): InspectorViewport {
104
127
  return panelViewport(columns, rows)
@@ -14,6 +14,8 @@
14
14
 
15
15
  import { graphemeWidth, splitGraphemes, stringWidth } from './width.ts'
16
16
 
17
+ export { stringWidth }
18
+
17
19
  /**
18
20
  * Compact token count: exact below 1K, then one-decimal-ish K/M.
19
21
  * @param n - token count.
@@ -84,6 +86,12 @@ export function truncateColumns(text: string, columns: number): string {
84
86
  return `${result}…`
85
87
  }
86
88
 
89
+ /** Sanitize, clip, and right-pad one cell to an exact terminal-column width. */
90
+ export function padColumns(text: string, columns: number): string {
91
+ const clipped = truncateColumns(singleLineText(text), columns)
92
+ return clipped + ' '.repeat(Math.max(0, columns - stringWidth(clipped)))
93
+ }
94
+
87
95
  /** A display-safe suffix bounded by terminal rows and columns. */
88
96
  export interface DisplayTail {
89
97
  /** Sanitized suffix suitable for direct terminal rendering. */
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Load-time DeepSeek Harness version gate.
3
+ *
4
+ * The terminal driver is validated against exactly one Harness snapshot, and
5
+ * the host resolves every bare `@deepseek-ai/*` import the plugin makes
6
+ * against ITS OWN installed copies (the profile's `HostResolvedRootInclude`
7
+ * redirects bare names to the installed-host base). No install-time or
8
+ * load-time check exists anywhere on that path, so a user who updates `dsh`
9
+ * would otherwise run this build against unvetted upstream code silently.
10
+ *
11
+ * This gate mirrors how the host itself reads its identity: the running CLI
12
+ * entry (`process.argv[1]`) sits inside the `@deepseek-ai/dsh` package, whose
13
+ * manifest version is released in lockstep with the Harness packages bundled
14
+ * beside it. When the probe can identify the host it compares the running
15
+ * versions against the one this build declares and fails fast with an
16
+ * actionable message; when it cannot identify the host it stays silent rather
17
+ * than brick a supported embedding on a false positive.
18
+ *
19
+ * @module @deepseek-ai/dsh-code/runner/harness-gate
20
+ */
21
+
22
+ import { realpathSync, readFileSync } from 'node:fs'
23
+ import { dirname, join } from 'node:path'
24
+
25
+ /** The one Harness release this build was validated against. */
26
+ export const EXPECTED_HARNESS_VERSION = '0.1.5-rc.2'
27
+
28
+ /** Host packages whose bundled copy the plugin binds to at runtime. */
29
+ export const HARNESS_GATE_PACKAGES = [
30
+ '@deepseek-ai/dsh-agent',
31
+ '@deepseek-ai/dsh-session',
32
+ ] as const
33
+
34
+ /** The installed-host CLI package that carries the Harness runtime. */
35
+ const HOST_PACKAGE_NAME = '@deepseek-ai/dsh'
36
+
37
+ /** Filesystem slice the probe needs; injectable so tests stay pure. */
38
+ export interface HarnessFs {
39
+ /** Resolve a symlinked entry to its real path. */
40
+ realpathSync(path: string): string
41
+ /** Read and parse one package.json; undefined when absent or unreadable. */
42
+ readManifest(path: string): { name?: unknown; version?: unknown } | undefined
43
+ }
44
+
45
+ const defaultHarnessFs: HarnessFs = {
46
+ realpathSync: path => realpathSync(path),
47
+ readManifest: path => {
48
+ try {
49
+ return JSON.parse(readFileSync(path, 'utf8')) as { name?: unknown; version?: unknown }
50
+ } catch {
51
+ return undefined
52
+ }
53
+ },
54
+ }
55
+
56
+ /** What the probe learned about the running host. */
57
+ export interface HarnessProbe {
58
+ /** Installed-host package root, when identified. */
59
+ readonly hostRoot?: string
60
+ /** Installed-host CLI version (`@deepseek-ai/dsh`). */
61
+ readonly hostVersion?: string
62
+ /** Version of each gate package bundled beside the host, when present. */
63
+ readonly packages: Readonly<Record<string, string | undefined>>
64
+ }
65
+
66
+ const UNKNOWN_PROBE: HarnessProbe = { packages: {} }
67
+
68
+ /**
69
+ * Walk up from one directory to the nearest `@deepseek-ai/dsh` package root.
70
+ * @param start - directory of the running CLI entry (already realpath'd).
71
+ * @param fs - filesystem slice to walk with.
72
+ * @returns the host package root, or undefined when no ancestor matches.
73
+ */
74
+ function findHostRoot(start: string, fs: HarnessFs): string | undefined {
75
+ let directory = start
76
+ for (;;) {
77
+ const manifest = fs.readManifest(join(directory, 'package.json'))
78
+ if (manifest !== undefined && manifest.name === HOST_PACKAGE_NAME) return directory
79
+ const parent = dirname(directory)
80
+ if (parent === directory) return undefined
81
+ directory = parent
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Identify the running host and the Harness versions it provides.
87
+ * @param argv1 - `process.argv[1]`, the running CLI entry path.
88
+ * @param fs - filesystem slice; defaults to the real one.
89
+ * @returns the probe result; `packages` is empty when the host is unknown.
90
+ */
91
+ export function probeRunningHarness(argv1: string | undefined, fs: HarnessFs = defaultHarnessFs): HarnessProbe {
92
+ if (argv1 === undefined || argv1 === '') return UNKNOWN_PROBE
93
+ let entry: string
94
+ try {
95
+ entry = fs.realpathSync(argv1)
96
+ } catch {
97
+ return UNKNOWN_PROBE
98
+ }
99
+ const hostRoot = findHostRoot(dirname(entry), fs)
100
+ if (hostRoot === undefined) return UNKNOWN_PROBE
101
+ const hostManifest = fs.readManifest(join(hostRoot, 'package.json'))
102
+ const hostVersion = typeof hostManifest?.version === 'string' ? hostManifest.version : undefined
103
+ const packages: Record<string, string | undefined> = {}
104
+ for (const name of HARNESS_GATE_PACKAGES) {
105
+ const manifest = fs.readManifest(join(hostRoot, 'node_modules', name, 'package.json'))
106
+ if (typeof manifest?.version === 'string') packages[name] = manifest.version
107
+ }
108
+ return { hostRoot, hostVersion, packages }
109
+ }
110
+
111
+ /** One host fact that disagrees with the version this build declares. */
112
+ export interface HarnessMismatch {
113
+ /** What was compared: the host CLI or one bundled package. */
114
+ readonly source: string
115
+ /** The version this build was validated against. */
116
+ readonly expected: string
117
+ /** The version the running host actually provides. */
118
+ readonly provided: string
119
+ }
120
+
121
+ /**
122
+ * Compare one probe against the expected snapshot. Unknown facts never
123
+ * mismatch: the gate must stay silent when it cannot judge, not brick a
124
+ * supported embedding on missing evidence.
125
+ * @param expected - the Harness version this build declares.
126
+ * @param probe - the running host's identified versions.
127
+ * @returns every concrete disagreement, empty when compatible or unknown.
128
+ */
129
+ export function harnessVersionMismatches(expected: string, probe: HarnessProbe): readonly HarnessMismatch[] {
130
+ const mismatches: HarnessMismatch[] = []
131
+ if (probe.hostVersion !== undefined && probe.hostVersion !== expected) {
132
+ mismatches.push({ source: `${HOST_PACKAGE_NAME} host`, expected, provided: probe.hostVersion })
133
+ }
134
+ for (const name of HARNESS_GATE_PACKAGES) {
135
+ const provided = probe.packages[name]
136
+ if (provided !== undefined && provided !== expected) {
137
+ mismatches.push({ source: name, expected, provided })
138
+ }
139
+ }
140
+ return mismatches
141
+ }
142
+
143
+ /**
144
+ * Render the gate failure the user sees on stderr.
145
+ * @param expected - the Harness version this build declares.
146
+ * @param mismatches - the disagreements to report.
147
+ * @param hostRoot - installed-host root, when identified, for the fix hint.
148
+ * @returns the multi-line diagnostic.
149
+ */
150
+ export function harnessGateMessage(expected: string, mismatches: readonly HarnessMismatch[], hostRoot?: string): string {
151
+ const lines = [`dsh: this dsh-code build requires DeepSeek Harness ${expected}, but this dsh provides:`]
152
+ for (const mismatch of mismatches) lines.push(`dsh: ${mismatch.source} ${mismatch.provided}`)
153
+ lines.push('dsh: update dsh-code to a release built for this dsh, or use a dsh matching ' + expected + '.')
154
+ if (hostRoot !== undefined) lines.push(`dsh: running host: ${hostRoot}`)
155
+ return lines.join('\n')
156
+ }
157
+
158
+ /**
159
+ * Refuse to run against an identified-but-incompatible host.
160
+ * @param expected - the Harness version this build declares.
161
+ * @param probe - the running host's identified versions.
162
+ * @throws an Error carrying the gate diagnostic when a version disagrees.
163
+ */
164
+ export function requireHarnessVersion(expected: string, probe: HarnessProbe): void {
165
+ const mismatches = harnessVersionMismatches(expected, probe)
166
+ if (mismatches.length === 0) return
167
+ throw new Error(harnessGateMessage(expected, mismatches, probe.hostRoot))
168
+ }
@@ -0,0 +1,77 @@
1
+ /** Global input recall: the appended prompts and their durable JSONL file.
2
+ *
3
+ * One JSONL file under the DSH home. A missing file means an empty history and
4
+ * unreadable or corrupt content degrades to the valid lines it could parse,
5
+ * silently — recall is a convenience surface, never a gate.
6
+ *
7
+ * @module @deepseek-ai/dsh-code/input-history
8
+ */
9
+
10
+ import { readFileSync } from 'node:fs'
11
+ import { appendFile, mkdir } from 'node:fs/promises'
12
+ import { dirname } from 'node:path'
13
+ import {
14
+ historyLine,
15
+ HISTORY_MAX_ENTRIES,
16
+ needsCompaction,
17
+ parseHistoryFile,
18
+ serializeHistoryList,
19
+ } from '../session/history.ts'
20
+ import { writeFileAtomically } from '../settings-file.ts'
21
+
22
+ /** Live recall state plus its serialized durable writes. */
23
+ export interface InputHistoryStore {
24
+ /** The recall list, newest last; read live by the composer. */
25
+ readonly entries: () => readonly string[]
26
+ /** Append one submitted line and persist it; '' is ignored. */
27
+ readonly record: (text: string) => void
28
+ /** Await the pending writes (the quit flush). */
29
+ readonly flush: () => Promise<void>
30
+ }
31
+
32
+ /**
33
+ * Load the recall history and return its live store.
34
+ *
35
+ * Serialized history writes: each submission appends one JSON line at the end
36
+ * of the file, so concurrent terminals add entries after each other instead of
37
+ * overwriting snapshots they read at their own boot. A multi-line draft still
38
+ * occupies one physical line (JSON escapes the newline), and a regular-length
39
+ * line reaches the disk as one positioned write; an oversized paste may
40
+ * interleave mid-line, which the next parse simply drops.
41
+ *
42
+ * @param path - absolute path of the JSONL recall file.
43
+ * @param onFailure - receives the write failure message for a bounded notice.
44
+ */
45
+ export function createInputHistory(path: string, onFailure: (message: string) => void): InputHistoryStore {
46
+ let entries: readonly string[] = []
47
+ let chain: Promise<void> = Promise.resolve()
48
+ try {
49
+ const raw = readFileSync(path, 'utf8')
50
+ entries = parseHistoryFile(raw)
51
+ // Stale lines (adjacent duplicates, dropped garbage, an over-cap tail)
52
+ // accumulate in an append-only file; rewrite the canonical form once per
53
+ // boot. The rewrite rides the same chain, so it lands before any
54
+ // submission the user types next. An entry another terminal appends
55
+ // inside the read-to-rename window is dropped — a millisecond-scale gap
56
+ // at boot that recall tolerates by design.
57
+ if (needsCompaction(raw)) {
58
+ chain = chain.then(() => writeFileAtomically(path, serializeHistoryList(entries))).catch(() => {})
59
+ }
60
+ } catch {
61
+ entries = []
62
+ }
63
+ return {
64
+ entries: () => entries,
65
+ record: (text: string): void => {
66
+ if (text === '') return
67
+ entries = [...entries, text].slice(-HISTORY_MAX_ENTRIES)
68
+ chain = chain
69
+ .then(() => mkdir(dirname(path), { recursive: true }))
70
+ .then(() => appendFile(path, historyLine(text), 'utf8'))
71
+ .catch((error: unknown) => {
72
+ onFailure(error instanceof Error ? error.message : String(error))
73
+ })
74
+ },
75
+ flush: () => chain,
76
+ }
77
+ }
@@ -0,0 +1,49 @@
1
+ /** Shift+Tab mode-cycle stations for the terminal runner.
2
+ *
3
+ * Pure decision over the preset table and the committed plan fold: the runner
4
+ * applies the returned station, so the whole cycle is testable without a
5
+ * session.
6
+ *
7
+ * @module @deepseek-ai/dsh-code/mode-cycle
8
+ */
9
+
10
+ /** One Shift+Tab station decision for the mode cycle. */
11
+ export type ModeCycleDecision =
12
+ | { readonly kind: 'permission'; readonly preset: string }
13
+ | { readonly kind: 'plan-on' }
14
+ | { readonly kind: 'plan-off'; readonly preset: string }
15
+
16
+ /**
17
+ * Decide the next Shift+Tab station. The cycle keeps the preset table's
18
+ * own order (most restrictive first) and inserts ONE plan station between
19
+ * the most restrictive preset and the wrap target: with the shipped three
20
+ * presets the user sees workspace-write → danger-full-access → read-only
21
+ * → plan → workspace-write. Plan IS the most restrictive preset plus the
22
+ * plan prompt layer — entering it switches nothing (the cycle is already
23
+ * parked on read-only), and leaving it lands on the next preset after the
24
+ * most restrictive one. Without the /plan command the cycle is exactly the
25
+ * preset table.
26
+ *
27
+ * `planIntent` covers the committed fold's commit lag: upstream queues a
28
+ * plan switch during an open turn (and the command pipeline is async even
29
+ * idle), so the durable plan/mode event lands AFTER the press that chose
30
+ * it. While an intent from an earlier press is in flight it — not the
31
+ * stale committed fold — decides the station, so repeated presses advance
32
+ * the cycle instead of re-issuing the same plan transition (the stuck
33
+ * plan-on/plan-off toggle). Undefined falls back to the committed fold.
34
+ */
35
+ export function planCycleDecision(input: {
36
+ readonly names: readonly string[]
37
+ readonly current: string
38
+ readonly inPlan: boolean
39
+ readonly planAvailable: boolean
40
+ readonly planIntent?: boolean
41
+ }): ModeCycleDecision | undefined {
42
+ const names = input.names
43
+ if (names.length === 0) return undefined
44
+ const first = names[0]
45
+ if ((input.planIntent ?? input.inPlan) === true) return { kind: 'plan-off', preset: names[1] ?? first }
46
+ const at = names.indexOf(input.current)
47
+ if (at === 0 && input.planAvailable) return { kind: 'plan-on' }
48
+ return { kind: 'permission', preset: names[(at + 1) % names.length] ?? first }
49
+ }
@@ -0,0 +1,67 @@
1
+ /** User-level preference files under the DSH home.
2
+ *
3
+ * The statusline, theme, language, and animations customizations each live in
4
+ * one small JSON file. They share exactly two policies: a missing file is the
5
+ * default and stays silent while a corrupt one degrades to the default with a
6
+ * surfaced warning (a user-authored customization must never fail silently),
7
+ * and every save goes through the serialized crash-atomic writer.
8
+ *
9
+ * @module @deepseek-ai/dsh-code/preferences
10
+ */
11
+
12
+ import { homedir } from 'node:os'
13
+ import { join } from 'node:path'
14
+ import { readSettingsObject, type UserSettingsPersistence } from '../settings-file.ts'
15
+
16
+ /** Absolute path of one preference file under the DSH home. */
17
+ export function preferencePath(fileName: string): string {
18
+ return join(homedir(), '.dsh', 'dsh-code', fileName)
19
+ }
20
+
21
+ /** Outcome of reading one preference file. */
22
+ export interface PreferenceRead<T> {
23
+ /** Parsed value; undefined when the file is missing or corrupt (keep the default). */
24
+ readonly value?: T
25
+ /** Corruption message to surface; undefined for a missing or clean file. */
26
+ readonly warning?: string
27
+ }
28
+
29
+ /**
30
+ * Read one field of a preference file. A missing file is silence — the default
31
+ * stands and nothing is reported — while unreadable JSON or a non-object
32
+ * document both warn and keep the default.
33
+ * @param path - absolute path of the preference file.
34
+ * @param field - the JSON field the file carries.
35
+ * @param parse - narrows the raw field to the usable value.
36
+ * @returns the parsed value and/or the warning to surface.
37
+ */
38
+ export function readPreference<T>(path: string, field: string, parse: (raw: unknown) => T): PreferenceRead<T> {
39
+ try {
40
+ return { value: parse(readSettingsObject(path)[field]) }
41
+ } catch (error) {
42
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {}
43
+ return { warning: error instanceof Error ? error.message : String(error) }
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Persist one preference field through the serialized crash-atomic writer.
49
+ * A failed write is reported through `onFailure` instead of rejecting.
50
+ * @param persistence - the shared user-settings writer.
51
+ * @param path - absolute path of the preference file.
52
+ * @param field - the JSON field the file carries.
53
+ * @param value - the value to store under `field`.
54
+ * @param onFailure - receives the failure message for a bounded notice.
55
+ */
56
+ export function savePreference(
57
+ persistence: UserSettingsPersistence,
58
+ path: string,
59
+ field: string,
60
+ value: unknown,
61
+ onFailure: (message: string) => void,
62
+ ): void {
63
+ void persistence.save(path, JSON.stringify({ [field]: value }, null, 2) + '\n')
64
+ .catch((error: unknown) => {
65
+ onFailure(error instanceof Error ? error.message : String(error))
66
+ })
67
+ }
@@ -0,0 +1,53 @@
1
+ /** Ordered terminal quit cleanup.
2
+ *
3
+ * Pure sequencing: every step rejection is contained and the exit request is
4
+ * always reached exactly once, so a failing flush never strands the process.
5
+ *
6
+ * @module @deepseek-ai/dsh-code/quit
7
+ */
8
+
9
+ /** One ordered step of the terminal quit cleanup. */
10
+ export interface QuitCleanupStep {
11
+ /** Step label used in diagnostics and tests. */
12
+ readonly name: string
13
+ /** The step's async work; a rejection is contained by the sequence. */
14
+ readonly run: () => Promise<void>
15
+ }
16
+
17
+ /**
18
+ * Run the ordered quit cleanup, then request exit. Every step rejection is
19
+ * contained (reported through `onError`) so a failed flush or dispose never
20
+ * skips the remaining cleanup; the exit request is always reached exactly
21
+ * once.
22
+ * @param steps - the cleanup steps in dependency order (settle the visible
23
+ * session, await the final in-flight composition, await durable recall).
24
+ * @param exit - the terminal exit request (code 0).
25
+ * @param onError - optional failure sink; called once per failing step and
26
+ * itself contained, so a throwing sink cannot abort the sequence.
27
+ * @returns the names of the steps that started, in order (for tests).
28
+ */
29
+ export async function runQuitSequence(
30
+ steps: readonly QuitCleanupStep[],
31
+ exit: (code: number) => void,
32
+ onError?: (name: string, error: unknown) => void,
33
+ ): Promise<readonly string[]> {
34
+ const started: string[] = []
35
+ for (const step of steps) {
36
+ started.push(step.name)
37
+ try {
38
+ await step.run()
39
+ } catch (error) {
40
+ try {
41
+ onError?.(step.name, error)
42
+ } catch {
43
+ // The failure sink must never abort the cleanup sequence.
44
+ }
45
+ }
46
+ }
47
+ try {
48
+ exit(0)
49
+ } catch {
50
+ // The exit request itself must not become an unhandled rejection.
51
+ }
52
+ return started
53
+ }
@@ -0,0 +1,55 @@
1
+ /** Cross-session search rows for the /search panel.
2
+ *
3
+ * Owns the panel row shape and the pure mapping from a session-query hit, so
4
+ * the row contract does not live inside the panel component that renders it
5
+ * and the runner can build rows without importing the panel module.
6
+ *
7
+ * @module @deepseek-ai/dsh-code/search-rows
8
+ */
9
+
10
+ import type { SessionHeader } from '@deepseek-ai/dsh-session'
11
+
12
+ /** One cross-session full-text search hit mapped from the session-query engine. */
13
+ export interface SearchRow {
14
+ /** Session id (Enter resumes it through the switch machinery). */
15
+ readonly id: string
16
+ /** Display label: session title or the short id form. */
17
+ readonly label: string
18
+ /** Secondary facts line (workspace · preset markers). */
19
+ readonly detail: string
20
+ /** Bounded plain-text excerpt around the strongest match. */
21
+ readonly snippet: string
22
+ /** Match timestamp (relative labels derive from it). */
23
+ readonly updatedAt: number
24
+ /** Whether the hit is a delegated subagent conversation (not resumable). */
25
+ readonly subagent: boolean
26
+ /** Whether Enter may switch into it. */
27
+ readonly resumable: boolean
28
+ }
29
+
30
+ /**
31
+ * Map one cross-session full-text hit onto the /search panel's row (pure).
32
+ * Labels fall back to the short id form — the engine's hit carries the
33
+ * strongest matching event, not the title observation.
34
+ */
35
+ export function searchHitToRow(hit: {
36
+ header: SessionHeader
37
+ bestMatch: { snippet: string; time: number }
38
+ }): SearchRow {
39
+ const subagent = hit.header.origin === 'subagent'
40
+ const cwd = hit.header.cwd ?? ''
41
+ // Session cwds may arrive in either separator style regardless of the
42
+ // observing host (a workspace synced from Windows), so split on both.
43
+ const workspace = cwd.split(/[\\/]/u).filter(part => part !== '').at(-1) ?? ''
44
+ const preset = hit.header.agentPreset ?? ''
45
+ const flat = hit.bestMatch.snippet.replace(/\s+/gu, ' ').trim()
46
+ return {
47
+ id: hit.header.id,
48
+ label: hit.header.id.slice(-12),
49
+ detail: [workspace, preset].filter(part => part !== '').join(' · '),
50
+ snippet: flat.length > 158 ? `${flat.slice(0, 157)}…` : flat,
51
+ updatedAt: hit.bestMatch.time,
52
+ subagent,
53
+ resumable: !subagent,
54
+ }
55
+ }