dsh-code 1.0.4 → 1.0.6

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 (41) hide show
  1. package/README.en.md +287 -286
  2. package/README.md +16 -13
  3. package/bin/deepseek.mjs +336 -11
  4. package/cordis.patch.yml +26 -18
  5. package/lib/index.mjs +1310 -439
  6. package/lib/types/app.d.ts +25 -6
  7. package/lib/types/attachments.d.ts +36 -4
  8. package/lib/types/git-workflow.d.ts +7 -2
  9. package/lib/types/history.d.ts +18 -11
  10. package/lib/types/index.d.ts +11 -2
  11. package/lib/types/presets.d.ts +4 -1
  12. package/lib/types/provider-settings.d.ts +6 -11
  13. package/lib/types/questions.d.ts +16 -12
  14. package/lib/types/render/animations.d.ts +74 -7
  15. package/lib/types/render/export.d.ts +0 -6
  16. package/lib/types/render/fuzzy.d.ts +21 -0
  17. package/lib/types/render/projection.d.ts +47 -5
  18. package/lib/types/session-directory.d.ts +48 -13
  19. package/lib/types/settings-file.d.ts +8 -0
  20. package/lib/types/store.d.ts +3 -0
  21. package/package.json +168 -159
  22. package/src/app.ts +480 -199
  23. package/src/attachments.ts +110 -11
  24. package/src/commands.ts +35 -5
  25. package/src/git-workflow.ts +29 -10
  26. package/src/history.ts +22 -13
  27. package/src/index.ts +1868 -1752
  28. package/src/internals.ts +61 -40
  29. package/src/permissions.ts +1 -1
  30. package/src/presets.ts +19 -6
  31. package/src/provider-settings.ts +12 -12
  32. package/src/questions.ts +57 -74
  33. package/src/render/animations.ts +606 -403
  34. package/src/render/export.ts +20 -10
  35. package/src/render/fuzzy.ts +83 -0
  36. package/src/render/projection.ts +1833 -1620
  37. package/src/session-directory.ts +94 -16
  38. package/src/settings-file.ts +38 -6
  39. package/src/skills.ts +23 -9
  40. package/src/store.ts +39 -1
  41. package/src/subagents.ts +26 -3
package/src/index.ts CHANGED
@@ -1,1752 +1,1868 @@
1
- /**
2
- * @deepseek-ai/dsh-code — the interactive terminal driver. The bundle patch
3
- * rides over dsh-base without Host, HTTP, or browser plugins; this runner
4
- * creates or resumes preset-composed Agents through the core registry, keeps
5
- * one Ink owner while the active session changes, folds submitted prompts
6
- * into the selected durable session, answers approval asks with a y/n bar,
7
- * dispatches slash commands, and on quit flushes and requests process exit.
8
- *
9
- * @module @deepseek-ai/dsh-code
10
- */
11
-
12
- import { randomUUID } from 'node:crypto'
13
- import { readFileSync } from 'node:fs'
14
- import { homedir } from 'node:os'
15
- import { mkdir, rm, stat, writeFile as writeFileAsync } from 'node:fs/promises'
16
- import { basename, dirname, join } from 'node:path'
17
- import { createElement } from 'react'
18
- import type { Context } from '@deepseek-ai/cordis'
19
- import z from '@deepseek-ai/schemastery'
20
- import { installModelSelection } from '@deepseek-ai/dsh-agent'
21
- import type { Agent, AgentHandle, ModelSelection, ModelSelectionRef } from '@deepseek-ai/dsh-agent'
22
- import type {} from '@deepseek-ai/dsh-agent-default-model'
23
- import type {} from '@deepseek-ai/dsh-attachment'
24
- import { createUserMessage, MessageId, type ContentBlock, type ImageBlock } from '@deepseek-ai/dsh-llm'
25
- import type { JobSnapshot } from '@deepseek-ai/dsh-jobs'
26
- import { SessionId, type Session, type SessionEvent, type SessionHeader, type UserMessage } from '@deepseek-ai/dsh-session'
27
- import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
28
- // Type-only: carries the ctx.sessionTitle service merge for /title.
29
- import type {} from '@deepseek-ai/dsh-session-title'
30
- // Empty type imports carry the loader Context merge for the settlement await
31
- // and the cmdline Context merge for the appExit host value.
32
- import type {} from '@deepseek-ai/cordis-plugin-loader'
33
- import type {} from '@deepseek-ai/dsh-cmdline'
34
- import { App, type NoticeTone } from './app.ts'
35
- import { mountApprovalAnswerer, type ApprovalStore } from './approval.ts'
36
- import { isSlashLine, submissionPayload, watchCommands, type CommandsView } from './commands.ts'
37
- import { internals, type TuiMount } from './internals.ts'
38
- import { syncModelCapabilities } from './model-capabilities.ts'
39
- import { buildModelSelection, applyModelSelectionToConfig, loadModelDirectory, modelSelectionLabel, resolveEffectiveSelection, type ModelRow } from './models.ts'
40
- import {
41
- discoverProviderModels,
42
- loadProviderSettings,
43
- removeProviderSettings,
44
- saveProviderCredential,
45
- saveProviderConfiguration,
46
- subscribeProviderSettings,
47
- unsetProviderCredential,
48
- } from './provider-settings.ts'
49
- import { createMentions, type MentionsApi } from './mentions.ts'
50
- import { mountQuestionProvider, type QuestionStore } from './questions.ts'
51
- import { createTranscriptStore, type TranscriptStore } from './store.ts'
52
- import { createSubagentFeed, type SubagentFeedView } from './subagents.ts'
53
- import { parseStatuslineItems } from './render/status.ts'
54
- import { HISTORY_MAX_ENTRIES, parseHistoryFile, serializeHistoryList } from './history.ts'
55
- import { watchSkills, type SkillsView } from './skills.ts'
56
- import { toolArgumentsPreview } from './render/tool-preview.ts'
57
- import { buildExportMarkdown } from './render/export.ts'
58
- import { inspectImagePaths, saveImagePaths } from './attachments.ts'
59
- import { copyText, latestAssistantText } from './editor.ts'
60
- import { applyCtrlRPassthrough, resolveEditorKeysStartupHint, type EditorKeysEnv } from './editor-keys.ts'
61
- import {
62
- beginProviderAuthorization,
63
- cancelProviderAuthorization,
64
- loadProviderAuthorizations,
65
- logoutProviderAuthorization,
66
- openAuthorizationUrl,
67
- subscribeProviderAuthorizations,
68
- } from './authorization.ts'
69
- import { selectForkSeed } from './fork.ts'
70
- import { buildReviewPrompt, loadGitDiff } from './git-workflow.ts'
71
- import type { TuiStartup } from './startup.ts'
72
- import { SessionSwitchQueue } from './session-switch.ts'
73
- import { agentPresetsFrom, resolvePreset, selectPreset } from './presets.ts'
74
- import {
75
- applyPendingPermission,
76
- cyclePermission as cyclePermissionPreset,
77
- effectivePermission,
78
- listPermissionRows,
79
- permissionPresetsFrom,
80
- selectPermission,
81
- } from './permissions.ts'
82
- import { listPluginRows } from './plugin-inventory.ts'
83
- import { parseThemeName, setTheme, type ThemeName } from './theme.ts'
84
- import {
85
- isSubagentSession,
86
- matchSessionId,
87
- mergeSessionTitles,
88
- newestRootForCwd,
89
- planSessionDeletion,
90
- projectSessionRows,
91
- SESSION_ARTIFACT_NAMES,
92
- sessionArtifactDirectory,
93
- type SessionDirectoryOptions,
94
- type SessionQueryService,
95
- type SessionRow,
96
- } from './session-directory.ts'
97
- import { createUserSettingsPersistence } from './settings-file.ts'
98
-
99
- /** Stable Cordis plugin name. */
100
- export const name = 'tui-runner'
101
-
102
- /** Core services required before the interactive session can start. */
103
- export const inject = ['agentDefaultModel', 'agents', 'sessions']
104
-
105
- /** Plugin config: the startup resolved from this app's injected provider service. */
106
- export interface Config {
107
- /** How this invocation obtains its session identity (validated loosely; narrowed in {@link apply}). */
108
- startup: { kind: string; sessionId?: string; mode?: string; theme?: string; prompt?: string; images?: string[] }
109
- }
110
-
111
- export const Config: z<Config> = z.object({
112
- startup: z.object({
113
- kind: z.string().required(),
114
- sessionId: z.string(),
115
- mode: z.string(),
116
- theme: z.string(),
117
- prompt: z.string(),
118
- images: z.array(z.string()),
119
- }),
120
- })
121
-
122
- /** Process-facing effects of the runner: the Ink mount plus the launcher's exit request. */
123
- interface TuiIo {
124
- mount: typeof internals.mount
125
- exit(code: number): void
126
- }
127
-
128
- /** Report an unexpected direct-driver failure and request a failing exit. */
129
- function fail(io: TuiIo, error: unknown): void {
130
- internals.stderr.write(`dsh: ${error instanceof Error ? error.message : String(error)}\n`)
131
- io.exit(1)
132
- }
133
-
134
- /**
135
- * Snapshot caller-visible background jobs for the /jobs panel. Jobs the agent
136
- * started through run_in_background are fenced by their owner, so the CURRENT
137
- * agent is the caller. A missing registry is a harmless absence (the base
138
- * composition may not mount one) and collapses to the empty panel state —
139
- * the documented degradation for harmless probes, not an error.
140
- * @param ctx - context carrying the optional `jobs` registry.
141
- * @param caller - the active agent (undefined sees only unowned jobs).
142
- * @returns job rows in registration order; never throws.
143
- */
144
- function listJobs(ctx: Context, caller: Agent | undefined): readonly import('./kernel-panels.ts').JobRow[] {
145
- const jobs = ctx.get('jobs')
146
- if (jobs === undefined) return []
147
- try {
148
- return jobs.list(caller).map((job: JobSnapshot) => ({
149
- id: job.id,
150
- kind: job.kind,
151
- label: job.label,
152
- status: job.status,
153
- detail: job.detail,
154
- startedAt: job.startedAt,
155
- finishedAt: job.finishedAt,
156
- }))
157
- } catch {
158
- return []
159
- }
160
- }
161
-
162
- /**
163
- * Resolve the working directory's git branch for the status line.
164
- * @param cwd - the session's working directory.
165
- * @returns the branch name, or '' outside a repository or on a detached HEAD.
166
- */
167
- function gitBranch(cwd: string): string {
168
- try {
169
- const ref = readFileSync(join(cwd, '.git', 'HEAD'), 'utf8').trim().match(/^ref: refs\/heads\/(.+)$/)
170
- return ref?.[1] ?? ''
171
- } catch {
172
- // Only the single HEAD read is attempted, so the sole reachable failure is
173
- // a missing repository (or unreadable HEAD file): the branch group drops out.
174
- return ''
175
- }
176
- }
177
-
178
- /** The session identity this invocation will run, plus whether it is resumed. */
179
- interface Target {
180
- sessionId: string
181
- resume: boolean
182
- mode?: string
183
- cwd?: string
184
- seed?: readonly SessionEvent[]
185
- parentSession?: SessionId
186
- seedLength?: number
187
- }
188
-
189
- /**
190
- * Reduce a session id to a filename-safe /export default-name suffix. Session
191
- * ids are normally minted `session-<uuid>`, but `--session` accepts arbitrary
192
- * user text: path separators must never leak into the default export filename
193
- * (which would escape the session cwd).
194
- * @param id - the session id.
195
- * @returns at most the last 8 filename-safe characters.
196
- */
197
- export function exportSessionIdSuffix(id: string): string {
198
- return id.replace(/[^a-zA-Z0-9._-]/gu, '_').slice(-8)
199
- }
200
-
201
- /** One ordered step of the terminal quit cleanup. */
202
- export interface QuitCleanupStep {
203
- /** Step label used in diagnostics and tests. */
204
- readonly name: string
205
- /** The step's async work; a rejection is contained by the sequence. */
206
- readonly run: () => Promise<void>
207
- }
208
-
209
- /**
210
- * Run the ordered quit cleanup, then request exit. Every step rejection is
211
- * contained (reported through `onError`) so a failed flush or dispose never
212
- * skips the remaining cleanup; the exit request is always reached exactly
213
- * once.
214
- * @param steps - the cleanup steps in dependency order (settle the visible
215
- * session, await the final in-flight composition, await durable recall).
216
- * @param exit - the terminal exit request (code 0).
217
- * @param onError - optional failure sink; called once per failing step and
218
- * itself contained, so a throwing sink cannot abort the sequence.
219
- * @returns the names of the steps that started, in order (for tests).
220
- */
221
- export async function runQuitSequence(
222
- steps: readonly QuitCleanupStep[],
223
- exit: (code: number) => void,
224
- onError?: (name: string, error: unknown) => void,
225
- ): Promise<readonly string[]> {
226
- const started: string[] = []
227
- for (const step of steps) {
228
- started.push(step.name)
229
- try {
230
- await step.run()
231
- } catch (error) {
232
- try {
233
- onError?.(step.name, error)
234
- } catch {
235
- // The failure sink must never abort the cleanup sequence.
236
- }
237
- }
238
- }
239
- try {
240
- exit(0)
241
- } catch {
242
- // The exit request itself must not become an unhandled rejection.
243
- }
244
- return started
245
- }
246
-
247
- /** One composer submission waiting behind the startup delivery. */
248
- export interface QueuedSubmission {
249
- readonly text: string
250
- readonly mode: 'followup' | 'steer'
251
- readonly images: readonly ImageBlock[]
252
- }
253
-
254
- /**
255
- * Order-preserving gate for composer input while the startup prompt/images
256
- * are still preparing. Anything submitted before the startup delivery settles
257
- * queues and flushes afterwards in submit order, so the initial request can
258
- * never be overtaken by typing that raced a slow image preparation. The flush
259
- * also runs when the startup delivery fails: user input is never stranded.
260
- */
261
- export class StartupInputGate {
262
- private readonly queued: QueuedSubmission[] = []
263
- private pending = false
264
- constructor(private readonly deliver: (submission: QueuedSubmission) => void) {}
265
-
266
- /** Submit one line: delivered now while idle, queued behind the startup delivery otherwise. */
267
- submit(submission: QueuedSubmission): void {
268
- if (this.pending) this.queued.push(submission)
269
- else this.deliver(submission)
270
- }
271
-
272
- /**
273
- * Run the startup delivery the callback receives the direct-delivery sink
274
- * for the startup prompt itself then flush everything that queued behind
275
- * it, in order, even when the callback rejects.
276
- */
277
- async run(startup: (deliver: (submission: QueuedSubmission) => void) => Promise<void>): Promise<void> {
278
- this.pending = true
279
- try {
280
- await startup(submission => this.deliver(submission))
281
- } finally {
282
- this.pending = false
283
- const queued = this.queued.splice(0)
284
- for (const submission of queued) this.deliver(submission)
285
- }
286
- }
287
- }
288
-
289
- /**
290
- * Resolve the invocation's target session against the persisted headers.
291
- * @param startup - the parsed startup flags.
292
- * @param persistence - the persistence service; required for resume/latest.
293
- * @param cwd - the working directory `--continue` filters by.
294
- * @returns the target identity.
295
- * @throws with a user-facing message when the flags name nothing resolvable.
296
- */
297
- export async function resolveTarget(startup: TuiStartup, persistence: SessionPersistence | undefined, cwd: string): Promise<Target> {
298
- if (startup.kind === 'fresh') return { sessionId: `session-${randomUUID()}`, resume: false, mode: startup.mode }
299
- if (startup.kind === 'named') {
300
- // The id must not exist yet: reject before any Agent composition when the
301
- // backend can tell us (a live collision is still caught by the session
302
- // store at create time).
303
- if (persistence !== undefined) {
304
- const headers: readonly SessionHeader[] = await persistence.list()
305
- if (headers.some(header => header.id === startup.sessionId)) {
306
- throw new Error(`session "${startup.sessionId}" already exists; use --resume to continue it`)
307
- }
308
- }
309
- return { sessionId: startup.sessionId, resume: false, mode: startup.mode }
310
- }
311
- if (persistence === undefined) {
312
- throw new Error('cannot resolve the requested session: session persistence is not configured')
313
- }
314
- const headers: readonly SessionHeader[] = await persistence.list()
315
- if (startup.kind === 'resume') {
316
- const matched = matchSessionId(headers, startup.sessionId)
317
- // Subagent conversations are read-only everywhere else; the CLI must not
318
- // be a back door into appending root turns to a child's durable log.
319
- if (isSubagentSession(matched)) {
320
- throw new Error('subagent conversations are read-only; resume a root session')
321
- }
322
- return { sessionId: matched.id, resume: true }
323
- }
324
- // --continue: the newest persisted ROOT session whose header pins this cwd.
325
- const newest = newestRootForCwd(headers, cwd)
326
- if (newest === undefined) throw new Error(`no persisted session for this directory (${cwd}); start one without --continue`)
327
- return { sessionId: newest.id, resume: true }
328
- }
329
-
330
- /**
331
- * Resolve a bounded command preview for one pending approval: the request
332
- * contract carries no arguments, so the bar self-serves from the transcript
333
- * projection via `callId` (mirrors the web ApprovalPanel's argsRaw lookup).
334
- * @param events - the transcript entries to search.
335
- * @param callId - the tool call the question is about, when the asker had one.
336
- * @param toolName - the tool the question is about.
337
- * @returns a bounded preview line, '' when nothing useful resolves.
338
- */
339
- function approvalCommandPreview(events: readonly { kind: string }[], callId: string | undefined, toolName: string): string {
340
- if (callId === undefined) return ''
341
- const entry = events.find(candidate =>
342
- candidate.kind === 'tool' && (candidate as { callId?: string }).callId === callId)
343
- if (entry === undefined) return ''
344
- const args = (entry as { arguments?: string }).arguments ?? ''
345
- return toolArgumentsPreview(args, toolName)
346
- }
347
-
348
- /** The runner's connection between the React app and the process side. */
349
- interface AppBridge {
350
- /** Post one local notice line (feedback the transcript does not carry). */
351
- notify(text: string, tone?: NoticeTone): void
352
- }
353
-
354
- /**
355
- * Run the interactive terminal session: resolve the target session, create or
356
- * resume one Agent, mount the app, and keep the process alive until the user
357
- * quits.
358
- * @param ctx - plugin context carrying the Agent, default model, Session, and launcher IO services.
359
- * @param startup - the parsed invocation flags.
360
- * @param io - process-facing effects.
361
- */
362
- async function run(ctx: Context, startup: TuiStartup, io: TuiIo): Promise<void> {
363
- // Loader siblings mount concurrently. Await the complete application before
364
- // creating an Agent so its scoped tools and adapters are not half-composed.
365
- await ctx.get('loader')?.await()
366
- const agents = ctx.get('agents')
367
- const defaultModel = ctx.get('agentDefaultModel')
368
- const sessions = ctx.get('sessions')
369
- const persistence = ctx.get('sessionPersistence')
370
- const sessionQuery = (ctx as unknown as { get(name: string): unknown }).get('sessionQuery') as SessionQueryService | undefined
371
- // Early process shutdown can dispose the tree while settlement is pending.
372
- if (agents === undefined || defaultModel === undefined || sessions === undefined) return
373
-
374
- const cwd = process.cwd()
375
- // Live deployment default (web selectModel parity): read on every use, not
376
- // snapshotted at launch, so a /model pick this process saves becomes the
377
- // default for sessions composed afterwards without a restart.
378
- const currentDefaults = (): ModelSelection => defaultModel.currentSelection()
379
- const presets = agentPresetsFrom(ctx)
380
- if (presets === undefined) throw new Error('agent preset service is unavailable; check the dsh-code bundle patch')
381
- const permissionPresets = permissionPresetsFrom(ctx)
382
-
383
- // A bare fresh launch stays transient: no Agent or session is composed, and
384
- // nothing is persisted, until the user's first real input. Explicit flags
385
- // (--resume/--continue/--session/--mode) keep the eager create/resume path.
386
- const lazy = startup.kind === 'fresh' && startup.mode === undefined
387
-
388
- interface ActiveSession {
389
- handle: AgentHandle
390
- agent: Agent
391
- session: Session
392
- store: ReturnType<typeof createTranscriptStore>
393
- mentions: MentionsApi
394
- mode: string
395
- selection: { picked?: ModelSelection }
396
- resumed: boolean
397
- }
398
-
399
- /** Prepare a complete next session before disturbing the currently visible one. */
400
- const prepare = async (next: Target): Promise<ActiveSession> => {
401
- const nextCwd = next.cwd ?? cwd
402
- // A bare launch can pick a model before any session exists: the process
403
- // keeps that explicit choice and every prepared session starts from it
404
- // (the documented precedence: explicit pick > session header > default).
405
- const selectionState: { picked?: ModelSelection } = pendingSelection === undefined
406
- ? {}
407
- : { picked: pendingSelection }
408
- let mode = next.resume ? next.mode : next.mode ?? pendingMode
409
- if (!next.resume) mode = (await presets.resolve(mode)).id
410
- const setup = async (agentCtx: Context): Promise<void> => {
411
- const sessionPreset = next.resume
412
- ? resolvePreset(agentCtx.agent!.session)
413
- : mode
414
- const mounted = await presets.mount(agentCtx, sessionPreset)
415
- mode = mounted.id
416
- const selection: ModelSelectionRef = {
417
- get current(): ModelSelection | undefined {
418
- return resolveEffectiveSelection(selectionState.picked, agentCtx.agent?.session.requestHeader()?.config, currentDefaults())
419
- },
420
- set current(value: ModelSelection | undefined) { selectionState.picked = value },
421
- assembled: undefined,
422
- }
423
- installModelSelection(agentCtx, selection)
424
- }
425
- // AgentOptions seed the loop's fallback route; effort rides the selection
426
- // ref (installModelSelection), so only the provider/model pair is seeded.
427
- const seedOptions = pendingSelection === undefined
428
- ? { provider: currentDefaults().provider, model: currentDefaults().model }
429
- : { provider: pendingSelection.provider, model: pendingSelection.model }
430
- const handle = next.resume
431
- ? await agents.resume({
432
- resumeSessionId: SessionId(next.sessionId),
433
- agentOptions: seedOptions,
434
- // Quit aborts an in-flight composition so the exit wait never hangs
435
- // on a prepare that cannot settle; upstream rolls the creation back.
436
- signal: quitAbort.signal,
437
- setup,
438
- })
439
- : await agents.create({
440
- sessionId: SessionId(next.sessionId),
441
- meta: {
442
- cwd: nextCwd,
443
- agentPreset: mode,
444
- ...(next.parentSession === undefined ? {} : { parentSession: next.parentSession }),
445
- ...(next.seedLength === undefined ? {} : { seedLength: next.seedLength }),
446
- },
447
- ...(next.seed === undefined ? {} : { seed: next.seed }),
448
- agentOptions: seedOptions,
449
- signal: quitAbort.signal,
450
- setup,
451
- })
452
- const session = handle.agent.session
453
- if (!next.resume && permissionPresets !== undefined) {
454
- applyPendingPermission(permissionPresets, session, pendingPermission)
455
- }
456
- return {
457
- handle,
458
- agent: handle.agent,
459
- session,
460
- store: createTranscriptStore(session.events),
461
- mentions: createMentions(ctx, handle.agent, session.header.cwd ?? nextCwd),
462
- mode: mode ?? 'standard',
463
- selection: selectionState,
464
- resumed: next.resume,
465
- }
466
- }
467
-
468
- let active: ActiveSession | undefined
469
- let agent: Agent | undefined
470
- let session: Session | undefined
471
- let store: TranscriptStore = createTranscriptStore()
472
- // Live subagent activity (child sessions of the current root): one bounded
473
- // row per child, folded from the same event bus the transcript feeds on.
474
- const subagents: SubagentFeedView & { apply(sessionId: string, event: SessionEvent): void; reset(): void } = createSubagentFeed()
475
- // Pre-session @file completion runs the official search over the launch
476
- // cwd (model- and session-independent); the prepare/activate paths replace
477
- // this with the agent-scoped instance once a session exists.
478
- let mentions: MentionsApi = createMentions(ctx, undefined, cwd)
479
- /** Explicit model pick made before any session exists (a bare launch). */
480
- let pendingSelection: ModelSelection | undefined
481
- /** Agent preset selected before the first session exists. */
482
- let pendingMode: string | undefined
483
- /** Ordered pre-session preset resolutions; first composition awaits them. */
484
- let pendingModeWork: Promise<void> = Promise.resolve()
485
- /** Permission preset selected before the first session exists. */
486
- let pendingPermission: string | undefined
487
- /**
488
- * Monotonic session epoch: bumped on every successful activation, on every
489
- * first-session creation, and on quit. Async callbacks (mention prepares,
490
- * command executions) capture it at call time and drop their result when it
491
- * changed, so a stale callback can never deliver to an agent that is no
492
- * longer on screen.
493
- */
494
- let epoch = 0
495
- /** Aborted on quit: an in-flight agent composition (create/resume) races this signal. */
496
- const quitAbort = new AbortController()
497
- /** In-flight mention-prepare / command-execute controllers, aborted on any session transition. */
498
- const pendingControllers = new Set<AbortController>()
499
- const abortPendingControllers = (): void => {
500
- for (const controller of [...pendingControllers]) {
501
- pendingControllers.delete(controller)
502
- controller.abort()
503
- }
504
- }
505
- /** The in-flight session-composition turn (create/resume/activate), if any. */
506
- let composing: Promise<void> | undefined
507
- /**
508
- * Run one session composition exclusively: concurrent compositions wait
509
- * their turn, so a bare-launch first-session creation and a /resume
510
- * activation can never compose agents in parallel (the loser would leak its
511
- * agent or mis-deliver). Errors propagate to the caller; the shared slot
512
- * always continues.
513
- */
514
- const compose = (work: () => Promise<void>): Promise<void> => {
515
- const turn = (composing ?? Promise.resolve()).catch(() => {}).then(work)
516
- composing = turn.catch(() => {})
517
- return turn
518
- }
519
-
520
- if (!lazy) {
521
- const target = await resolveTarget(startup, persistence, cwd)
522
- const prepared = await prepare(target)
523
- active = prepared
524
- agent = prepared.agent
525
- session = prepared.session
526
- store = prepared.store
527
- mentions = prepared.mentions
528
- }
529
-
530
- // Seed the transcript from the full session log: constructor seeds never
531
- // fire on `session/event`, so a resumed session paints its history once
532
- // before the first render. The handler reads the current session/store, so
533
- // the deferred first session of a bare launch is covered by the same feed.
534
- const off = ctx.on('session/event', (subject: Session, event: SessionEvent) => {
535
- if (session === undefined) return
536
- if (subject.id === session.id) {
537
- store.apply(event)
538
- return
539
- }
540
- // Child sessions (subagent conversations this root spawned) fold into
541
- // the bounded live-activity feed, never the transcript: the root stays
542
- // the only durable transcript truth while a running subagent remains
543
- // visible. Lineage comes from the child header, same field the session
544
- // directory uses to tag `↳` rows.
545
- if (subject.header.parentSession === session.id && subject.header.origin === 'subagent') subagents.apply(subject.id, event)
546
- })
547
-
548
- const commands: CommandsView = watchCommands(ctx)
549
- if (agent !== undefined) commands.setAgent(agent)
550
-
551
- const skills: SkillsView = watchSkills(ctx, cwd)
552
- if (agent !== undefined) skills.setAgent(agent)
553
-
554
- // Approval answerer: renders the ask as a y/n bar; only this TUI's agent is
555
- // claimed, every other ask falls through to the fail-closed waterfall. The
556
- // owner predicate is empty until the first session exists.
557
- const approval: ApprovalStore = mountApprovalAnswerer(
558
- ctx,
559
- candidate => agent !== undefined && candidate.id === agent.id,
560
- request => approvalCommandPreview(store.getView().entries, request.callId, request.toolName),
561
- )
562
-
563
- // Subagent model routing. The kernel seeds child agents from the parent's
564
- // CREATE-TIME AgentOptions (resolveChildAgentOptions), which a mid-session
565
- // /model switch never touches delegated work would keep running on the
566
- // launch-time route. This plugin-level listener mirrors installModelSelection
567
- // for subagent-origin requests (scope filtering delivers the agent subject
568
- // inside the payload): the explicit /subagent override wins, else the root's
569
- // effective selection (explicit pick > session header > deployment default).
570
- // Effort rides the selection exactly like the kernel listener applies it.
571
- let subagentOverride: ModelSelection | undefined
572
- ctx.on('agent/request', (payload, next) => {
573
- const subject = payload.agent
574
- const header = subject.session.header
575
- if (header.parentSession === undefined && header.origin !== 'subagent') return next()
576
- // Only the ACTIVE session's explicit pick may steer a subagent request.
577
- // During a switch window the old agent can still be mid-flight; routing
578
- // it by the NEW session's pick sent one of its requests to the wrong
579
- // model. A subject outside the active tree falls back to its own request
580
- // header (plus any explicit /subagent override, which is user intent).
581
- const activeAgent = active
582
- const belongsToActive = activeAgent !== undefined
583
- && (header.parentSession ?? subject.session.id) === activeAgent.session.id
584
- const picked = subagentOverride
585
- ?? resolveEffectiveSelection(
586
- belongsToActive && activeAgent !== undefined ? (activeAgent.selection.picked ?? pendingSelection) : undefined,
587
- subject.session.requestHeader()?.config,
588
- currentDefaults(),
589
- )
590
- return next().then(resolved => applyModelSelectionToConfig(resolved, picked))
591
- })
592
-
593
- // ask_user_question provider: the single UI provider on the shared service,
594
- // one request on screen at a time. Plan reviews (exit_plan_mode) arrive
595
- // through this same pipe.
596
- const questions: QuestionStore = mountQuestionProvider(ctx)
597
-
598
- // The bridge the React app registers on mount: local notices from the
599
- // process side (unknown commands, switch confirmations, cancels).
600
- const bridge: AppBridge = { notify: () => {} }
601
-
602
- // Same-id capability inheritance. Catalog capabilities flow by route key,
603
- // not model id, so a hand-declared relay model without an explicit
604
- // reasoningEfforts declaration serves no reasoning levels and offers no
605
- // effort picker. This background pass materializes declarations from
606
- // same-id donors (sibling settings entries first, then other routes'
607
- // advertised levels) over the panel's settings.mutate path, where the
608
- // upstream serviceability gate still rejects invalid writes atomically.
609
- // The debounce coalesces the settings/adapters event pair; the applier
610
- // skips only a same-source same-revision echo of its own write, so the
611
- // loop converges without ever ignoring a real external edit.
612
- const capabilitySyncDebounceMs = 400
613
- const runCapabilitySync = (): void => {
614
- void syncModelCapabilities(ctx, bridge.notify)
615
- }
616
- let capabilitySyncTimer: ReturnType<typeof setTimeout> | undefined
617
- const scheduleCapabilitySync = (): void => {
618
- if (capabilitySyncTimer !== undefined) clearTimeout(capabilitySyncTimer)
619
- capabilitySyncTimer = setTimeout(() => {
620
- capabilitySyncTimer = undefined
621
- runCapabilitySync()
622
- }, capabilitySyncDebounceMs)
623
- }
624
- const offCapabilitySync = [
625
- ctx.on('settings/document-updated', scheduleCapabilitySync),
626
- ctx.on('llm/adapters-updated', scheduleCapabilitySync),
627
- ]
628
- scheduleCapabilitySync()
629
-
630
- // /statusline persistence: one user-level JSON file under the DSH home.
631
- // Missing file means defaults; a corrupt file degrades to defaults with a
632
- // surfaced warning (the customization is user-authored, never silent).
633
- const statuslinePath = join(homedir(), '.dsh', 'dsh-code', 'statusline.json')
634
- let statuslineWarning: string | undefined
635
- let statuslineItems: readonly string[] = []
636
- try {
637
- statuslineItems = parseStatuslineItems(JSON.parse(readFileSync(statuslinePath, 'utf8')).items)
638
- } catch (error) {
639
- statuslineItems = parseStatuslineItems(undefined)
640
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
641
- statuslineWarning = error instanceof Error ? error.message : String(error)
642
- }
643
- }
644
- // Serialized, crash-atomic writes for the user-level JSON files: the chain
645
- // orders rapid consecutive saves (the LAST snapshot wins on disk), each
646
- // write goes through a sibling temp file + rename, and quit waits for the
647
- // flush exactly like it waits for the recall history.
648
- const settingsPersistence = createUserSettingsPersistence()
649
- const saveStatusline = (items: readonly string[]): void => {
650
- statuslineItems = [...items]
651
- void settingsPersistence.save(statuslinePath, JSON.stringify({ items }, null, 2) + '\n')
652
- .catch((writeError: unknown) => {
653
- bridge.notify('statusline save failed: ' + (writeError instanceof Error ? writeError.message : String(writeError)), 'error')
654
- })
655
- }
656
-
657
- // /vscode-keys: detect the hosting editor's user keybindings.json and pass
658
- // Ctrl+R through the workbench. One marker file under the DSH home keeps
659
- // the startup hint a once-per-install event.
660
- const editorKeysEnv: EditorKeysEnv = {
661
- env: process.env,
662
- paths: { homedir: homedir(), appdata: process.env.APPDATA, platform: process.platform },
663
- flagPath: join(homedir(), '.dsh', 'dsh-code', 'editor-keys.json'),
664
- }
665
- const applyEditorKeys = (): Promise<string> => applyCtrlRPassthrough(editorKeysEnv)
666
-
667
- // /theme persistence: one user-level JSON file under the DSH home, mirroring
668
- // the statusline file. A missing file means the dark default; a corrupt file
669
- // degrades to dark with a surfaced warning. Precedence: CLI --theme > file >
670
- // auto detection > dark (auto detection itself is a later enhancement and
671
- // currently falls back to dark inside theme.ts).
672
- const themePath = join(homedir(), '.dsh', 'dsh-code', 'theme.json')
673
- let themeWarning: string | undefined
674
- if (startup.theme === undefined) {
675
- try {
676
- setTheme(parseThemeName(JSON.parse(readFileSync(themePath, 'utf8')).theme))
677
- } catch (error) {
678
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
679
- themeWarning = error instanceof Error ? error.message : String(error)
680
- }
681
- }
682
- } else {
683
- setTheme(startup.theme)
684
- }
685
- const saveTheme = (name: ThemeName): void => {
686
- setTheme(name)
687
- void settingsPersistence.save(themePath, JSON.stringify({ theme: name }, null, 2) + '\n')
688
- .catch((writeError: unknown) => {
689
- bridge.notify('theme save failed: ' + (writeError instanceof Error ? writeError.message : String(writeError)), 'error')
690
- })
691
- }
692
-
693
- // Global input recall (Codex composer-history contract): one JSONL file
694
- // under the DSH home. A missing file means an empty history; unreadable or
695
- // corrupt content degrades to the valid lines it could parse, silently —
696
- // recall is a convenience surface, never a gate.
697
- const historyPath = join(homedir(), '.dsh', 'dsh-code', 'history.jsonl')
698
- let inputHistory: readonly string[] = []
699
- try {
700
- inputHistory = parseHistoryFile(readFileSync(historyPath, 'utf8'))
701
- } catch {
702
- inputHistory = []
703
- }
704
- /** Serialized history writes: each submission rewrites the latest in-memory snapshot. */
705
- let historyWriteChain: Promise<void> = Promise.resolve()
706
- const recordHistory = (text: string): void => {
707
- if (text === '') return
708
- inputHistory = [...inputHistory, text].slice(-HISTORY_MAX_ENTRIES)
709
- // Write the whole current list, serialized per submission: the file is
710
- // never read back on the submit path, so rapid same-process submissions
711
- // cannot lose entries to a read-modify-write race.
712
- historyWriteChain = historyWriteChain
713
- .then(() => mkdir(dirname(historyPath), { recursive: true }))
714
- .then(() => writeFileAsync(historyPath, serializeHistoryList(inputHistory), 'utf8'))
715
- .catch((writeError: unknown) => {
716
- bridge.notify('history save failed: ' + (writeError instanceof Error ? writeError.message : String(writeError)), 'error')
717
- })
718
- }
719
-
720
- /** Cancel one queued inbox message (Delete on the empty composer); the durable splice retires its pending row. */
721
- const cancelQueued = (messageId: string): void => {
722
- if (agent === undefined) return
723
- try {
724
- if (agent.inbox.remove(MessageId(messageId))) {
725
- bridge.notify('queued message cancelled')
726
- }
727
- } catch (error: unknown) {
728
- bridge.notify('queue cancel failed: ' + (error instanceof Error ? error.message : String(error)), 'error')
729
- }
730
- }
731
-
732
- // The mount handle lives in a box: quit closes over it, while the mount
733
- // itself is created after quit (the App element needs quit as a prop).
734
- const mountRef: { current?: TuiMount } = {}
735
- let quitting = false
736
- const quit = (): void => {
737
- if (quitting) return
738
- quitting = true
739
- switchQueue.cancel()
740
- // Stale prepares/commands die with the session they were for. Aborting
741
- // the composition signal lets a never-settling prepare reject, so the
742
- // exit wait below cannot hang (upstream rolls the creation back).
743
- abortPendingControllers()
744
- quitAbort.abort()
745
- epoch += 1
746
- off()
747
- for (const dispose of offCapabilitySync) dispose()
748
- if (capabilitySyncTimer !== undefined) clearTimeout(capabilitySyncTimer)
749
- const currentSession = session
750
- const currentActive = active
751
- const report = (name: string, error: unknown): void => {
752
- internals.stderr.write(`dsh: quit ${name} failed: ${error instanceof Error ? error.message : String(error)}\n`)
753
- }
754
- // A throwing unmount must not strand the terminal (stdin tap alive,
755
- // keyboard protocol stacks unpopped) or skip the exit sequence below.
756
- try {
757
- mountRef.current?.unmount()
758
- } catch (error: unknown) {
759
- report('unmount', error)
760
- }
761
- // One ordered cleanup: settle the visible session (if any a bare launch
762
- // that never composed one resolves immediately), then wait for the final
763
- // in-flight composition (its work swallows errors and the quitting guard
764
- // disposes any half-prepared agent), then flush the durable recall and
765
- // the queued user-level settings writes, then request exit. `composing`
766
- // and `historyWriteChain` are read at step run
767
- // time, so a turn that was still being queued when quit ran is included.
768
- // A failing step must never skip the remaining cleanup.
769
- const steps: QuitCleanupStep[] = [
770
- ...(currentSession === undefined || currentActive === undefined
771
- ? []
772
- : [
773
- { name: 'flush', run: async () => { await sessions.flush(currentSession) } },
774
- { name: 'dispose', run: () => currentActive.handle.dispose() },
775
- ]),
776
- { name: 'composing', run: () => composing ?? Promise.resolve() },
777
- { name: 'history', run: () => historyWriteChain },
778
- { name: 'settings', run: () => settingsPersistence.flush() },
779
- ]
780
- void runQuitSequence(steps, io.exit, report)
781
- }
782
-
783
- /** Run one slash line through the command registry (closed namespace). */
784
- const runSlash = (line: string): void => {
785
- const currentAgent = agent
786
- if (currentAgent === undefined) return
787
- if (line.startsWith('/resume ')) {
788
- requestResume(line.slice(8).trim())
789
- return
790
- }
791
- const registry = ctx.get('commands')
792
- if (registry === undefined) {
793
- bridge.notify('no command registry is mounted in this composition', 'error')
794
- return
795
- }
796
- const controller = new AbortController()
797
- const atEpoch = epoch
798
- pendingControllers.add(controller)
799
- const finish = (): void => {
800
- pendingControllers.delete(controller)
801
- }
802
- // rc.8 registry.execute gained an `images` admission parameter; the TUI
803
- // composer never attaches images to a slash line, so every invocation is
804
- // the empty batch (commands declaring input.images still run image-free).
805
- void Promise.resolve().then(() => registry.execute(currentAgent, line, [], controller.signal)).then((execution) => {
806
- finish()
807
- // A switch/quit landed while the command ran: its fall-through must not
808
- // reach an agent that is no longer on screen.
809
- if (epoch !== atEpoch || agent !== currentAgent) return
810
- if (execution === undefined) {
811
- // No command owns this line: send it verbatim so a user-invocable
812
- // skill gesture (`/skill-name`) reaches the host's tool-skill
813
- // pre-step injection — the web composer's same fall-through.
814
- try {
815
- currentAgent.followup(createUserMessage({
816
- content: [{ type: 'text', text: line }],
817
- source: { kind: 'user' },
818
- }))
819
- } catch (error: unknown) {
820
- bridge.notify(`command fallback failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
821
- }
822
- }
823
- }, (error: unknown) => {
824
- finish()
825
- if (epoch !== atEpoch || agent !== currentAgent) return
826
- bridge.notify(`command failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
827
- })
828
- }
829
-
830
- /** Delivery serialization state: the chain's epoch pins it to one session. */
831
- let deliveryChain: { epoch: number; tail: Promise<void> } = { epoch: 0, tail: Promise.resolve() }
832
-
833
- /** Deliver one trimmed line to the live session, expanding mentions first. */
834
- const deliverLine = (line: string, mode: 'followup' | 'steer', images: readonly ImageBlock[] = []): void => {
835
- const currentAgent = agent!
836
- const currentMentions = mentions!
837
- // The command registry is a closed namespace: slash lines run out of
838
- // band and never reach the model through this path (steering keeps the
839
- // registry out of the inbox, so slash lines steer as literal text).
840
- if (images.length === 0 && isSlashLine(line) && mode === 'followup') {
841
- runSlash(line)
842
- return
843
- }
844
- let parsed: ReturnType<MentionsApi['parse']>
845
- try {
846
- parsed = currentMentions.parse(line)
847
- } catch (error: unknown) {
848
- bridge.notify(`invalid session reference: ${error instanceof Error ? error.message : String(error)}`, 'error')
849
- return
850
- }
851
- // Ordered delivery: the inbox order IS the user's message order. A line
852
- // with session mentions prepares asynchronously, and a later plain line
853
- // used to deliver synchronously past it. Every line now waits for the
854
- // previous line of the same session; an epoch change (switch/quit)
855
- // abandons the chain instead of gating the next session on the old one.
856
- if (deliveryChain.epoch !== epoch) deliveryChain = { epoch, tail: Promise.resolve() }
857
- const enqueueDelivery = (run: () => void): void => {
858
- deliveryChain.tail = deliveryChain.tail.then(run)
859
- }
860
- const atEpoch = epoch
861
- const deliver = (readable: string, context?: UserMessage): void => {
862
- // A switch/quit landed while the snapshot was being prepared: never
863
- // deliver to an agent that is no longer on screen.
864
- if (epoch !== atEpoch || agent !== currentAgent) return
865
- // Session snapshots ride the inbox as model-facing context ahead of
866
- // the readable message (upstream README wiring: inject before the
867
- // followup/steer that wakes the driver).
868
- try {
869
- if (context !== undefined) currentAgent.inject(context)
870
- const content: ContentBlock[] = [
871
- ...(readable === '' ? [] : [{ type: 'text' as const, text: readable }]),
872
- ...images,
873
- ]
874
- const message = createUserMessage({
875
- content,
876
- source: { kind: 'user' },
877
- })
878
- if (mode === 'steer') {
879
- // The queued message is visible as a pending transcript row (the
880
- // web queue-mirror contract); no notice noise on the happy path.
881
- currentAgent.steer(message)
882
- } else {
883
- currentAgent.followup(message)
884
- }
885
- } catch (error: unknown) {
886
- bridge.notify(`${mode === 'steer' ? 'steering' : 'message'} failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
887
- }
888
- }
889
- if (parsed.references.length === 0) {
890
- enqueueDelivery(() => deliver(parsed.text))
891
- return
892
- }
893
- const controller = new AbortController()
894
- pendingControllers.add(controller)
895
- enqueueDelivery(() => currentMentions.prepare(parsed, controller.signal).then((prepared) => {
896
- pendingControllers.delete(controller)
897
- deliver(prepared.text, prepared.additionalContext)
898
- }, (error: unknown) => {
899
- pendingControllers.delete(controller)
900
- if (controller.signal.aborted || epoch !== atEpoch) return
901
- bridge.notify(`session reference failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
902
- }))
903
- }
904
-
905
- // Deferred first-session creation for a bare launch: the session is composed
906
- // only when the user submits real input (or /new), and every line that
907
- // arrives during creation is delivered in order afterwards. A creation
908
- // failure reports and clears the queue, leaving the transient state ready
909
- // for the next attempt.
910
- const pendingInputs: Array<{ text: string; mode: 'followup' | 'steer'; images: readonly ImageBlock[] }> = []
911
- // A creation is queued/running: further submissions must not mint more
912
- // fresh sessions (their lines queue into pendingInputs instead).
913
- let creating = false
914
- const ensureSession = (mode?: string): void => {
915
- if (creating) return
916
- creating = true
917
- void compose(async () => {
918
- try {
919
- // A direct `/mode <preset>` resolves asynchronously. Preserve submit
920
- // order so the first composition cannot race ahead with the old mode.
921
- await pendingModeWork
922
- // Another composition (e.g. a /resume activated while this creation
923
- // waited its turn) may have published a session already: deliver the
924
- // queued lines there instead of minting a competing fresh session
925
- // (which would orphan the live one without a dispose).
926
- if (session !== undefined) {
927
- const queued = pendingInputs.splice(0)
928
- for (const item of queued) deliverLine(item.text, item.mode, item.images)
929
- return
930
- }
931
- const next = await prepare({
932
- sessionId: `session-${randomUUID()}`,
933
- resume: false,
934
- ...(mode === undefined ? {} : { mode }),
935
- })
936
- if (quitting) {
937
- void next.handle.dispose().catch(() => {})
938
- return
939
- }
940
- const previous = { active, agent, session, store, mentions }
941
- try {
942
- active = next
943
- agent = next.agent
944
- session = next.session
945
- store = next.store
946
- mentions = next.mentions
947
- subagents.reset()
948
- pendingMode = undefined
949
- pendingPermission = undefined
950
- commands.setAgent(agent)
951
- skills.setAgent(agent)
952
- // The App mounts with a placeholder key until the first input; the
953
- // key-change remount below must start from a clean screen or the ghost
954
- // static header stays visible above the new one (same source-backed
955
- // clear the session-switch path performs).
956
- process.stdout.write('\x1b[r\x1b[0m\x1b[H\x1b[2J\x1b[3J\x1b[H')
957
- renderCurrent()
958
- } catch (error: unknown) {
959
- // The session composed but the screen handoff threw (stdout EPIPE,
960
- // a render-time failure). Roll the published state back exactly
961
- // like the switch path does — otherwise the runner reports "session
962
- // creation failed" while the new session is actually live, clears
963
- // the queued inputs, and every later line lands in the ghost. The
964
- // queued inputs are KEPT for the next attempt.
965
- active = previous.active
966
- agent = previous.agent
967
- session = previous.session
968
- store = previous.store === undefined ? createTranscriptStore() : previous.store
969
- mentions = previous.mentions === undefined ? createMentions(ctx, undefined, cwd) : previous.mentions
970
- if (agent !== undefined) {
971
- commands.setAgent(agent)
972
- skills.setAgent(agent)
973
- }
974
- await next.handle.dispose().catch(() => {})
975
- if (!quitting) renderCurrent()
976
- bridge.notify(`session activation failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
977
- return
978
- }
979
- abortPendingControllers()
980
- epoch += 1
981
- const queued = pendingInputs.splice(0)
982
- for (const item of queued) deliverLine(item.text, item.mode, item.images)
983
- } finally {
984
- creating = false
985
- }
986
- }).catch((error: unknown) => {
987
- pendingInputs.length = 0
988
- bridge.notify(`session creation failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
989
- })
990
- }
991
-
992
- /** Deliver one readable line to the agent, expanding session mentions first. */
993
- const sendNow = (text: string, mode: 'followup' | 'steer', images: readonly ImageBlock[] = []): void => {
994
- // Blank check on the trimmed form; the payload itself keeps the draft's
995
- // exact whitespace unless the line is a syntactic slash command.
996
- const line = submissionPayload(text)
997
- if (line.trim() === '' && images.length === 0) return
998
- if (images.length === 0 && line.startsWith('/mode ')) {
999
- void switchModeAction(line.slice(6).trim()).then(
1000
- selected => bridge.notify(`mode → ${selected}`),
1001
- error => bridge.notify(`mode switch failed: ${error instanceof Error ? error.message : String(error)}`, 'error'),
1002
- )
1003
- return
1004
- }
1005
- if (images.length === 0 && line.startsWith('/permission ')) {
1006
- try {
1007
- const selected = setPermissionAction(line.slice(12).trim())
1008
- bridge.notify(`permission ${selected}`)
1009
- } catch (error: unknown) {
1010
- bridge.notify(`permission change failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1011
- }
1012
- return
1013
- }
1014
- if (session === undefined) {
1015
- pendingInputs.push({ text: line, mode, images })
1016
- ensureSession()
1017
- return
1018
- }
1019
- deliverLine(line, mode, images)
1020
- }
1021
-
1022
- // Startup serialization: input submitted while the startup prompt/images
1023
- // are still preparing queues behind the initial request.
1024
- const inputGate = new StartupInputGate(({ text, mode, images }) => sendNow(text, mode, images))
1025
- const send = (text: string, mode: 'followup' | 'steer', images: readonly ImageBlock[] = []): void => {
1026
- inputGate.submit({ text, mode, images })
1027
- }
1028
-
1029
- /** Dispatch one submitted line: slash commands to the registry, other text to the agent. */
1030
- const dispatch = (text: string, images: readonly ImageBlock[] = []): void => {
1031
- send(text, 'followup', images)
1032
- }
1033
-
1034
- /**
1035
- * Submit steering: a running driver consumes the text at its next step
1036
- * boundary (the inbox delivers between steps); an idle driver just starts
1037
- * a turn, so this doubles as the busy-state submit path.
1038
- */
1039
- const steer = (text: string, images: readonly ImageBlock[] = []): void => {
1040
- send(text, 'steer', images)
1041
- }
1042
-
1043
- /** Interrupt the running turn (Esc); true when a turn was actually cancelled. */
1044
- const interrupt = (): boolean => {
1045
- if (agent === undefined || agent.status !== 'running') return false
1046
- try {
1047
- agent.cancel({ kind: 'user' })
1048
- bridge.notify('turn cancelled Ctrl+C or /quit to exit')
1049
- return true
1050
- } catch (error: unknown) {
1051
- bridge.notify(`cancel failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1052
- return false
1053
- }
1054
- }
1055
-
1056
- /** Select one permission preset before the first session or on the active one. */
1057
- const setPermissionAction = (id: string): string => {
1058
- if (permissionPresets === undefined || permissionPresets.names.length === 0) {
1059
- throw new Error('permission presets are not mounted in this composition')
1060
- }
1061
- if (id === '') throw new Error('usage: /permission <preset>')
1062
- const selected = selectPermission(permissionPresets, session, id)
1063
- if (session === undefined) {
1064
- pendingPermission = selected
1065
- renderCurrent()
1066
- }
1067
- return selected
1068
- }
1069
-
1070
- /**
1071
- * Cycle to the next permission preset (Shift+Tab). Before the first session,
1072
- * the choice remains process-local and is materialized when Harness creates
1073
- * that session; afterwards the canonical service writes durable events.
1074
- */
1075
- const cyclePermission = (): string => {
1076
- if (permissionPresets === undefined || permissionPresets.names.length === 0) {
1077
- bridge.notify('permission presets are not mounted in this composition', 'warning')
1078
- return ''
1079
- }
1080
- try {
1081
- const next = cyclePermissionPreset(permissionPresets, session, pendingPermission)
1082
- if (session === undefined && next !== '') {
1083
- pendingPermission = next
1084
- renderCurrent()
1085
- }
1086
- return next
1087
- } catch (error: unknown) {
1088
- bridge.notify(`permission change failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1089
- return ''
1090
- }
1091
- }
1092
-
1093
- /**
1094
- * Apply one /model selection: takes effect from the next assembled step.
1095
- * The optional reasoning effort must be one the row advertises (the picker
1096
- * only offers those), so an unsupported value cannot reach the request
1097
- * pipeline; an absent effort restores the model's own default.
1098
- */
1099
- const selectModel = (row: ModelRow, effortId?: string): string => {
1100
- const selection = buildModelSelection(row, effortId)
1101
- if (active === undefined) {
1102
- // A bare launch has no session yet: keep the pick process-wide so the
1103
- // first composed session starts from it.
1104
- pendingSelection = selection
1105
- } else {
1106
- active.selection.picked = selection
1107
- }
1108
- // Global default (web selectModel parity): every pick is persisted as the
1109
- // deployment default through the same agentDefaultModel service the web
1110
- // host writes, so the choice survives restarts and other surfaces read
1111
- // it. Save failures degrade to a notice — the in-session switch already
1112
- // took effect and must not roll back (the web contract).
1113
- void defaultModel.saveSelection(selection).catch((error: unknown) => {
1114
- bridge.notify(`model switch applies to this session but was not saved as the default: ${error instanceof Error ? error.message : String(error)}`, 'warning')
1115
- })
1116
- // Advisory immediate validation (web selectModel parity): run the same
1117
- // local resolveCallConfig check the request pipeline would, so a stale
1118
- // directory an effort the adapter withdrew since /model loaded —
1119
- // surfaces as a pick-time notice instead of failing the next assembled
1120
- // step. Best-effort: an llm service without the resolver keeps the
1121
- // existing request-boundary rejection. Called as a method (`this`-bound)
1122
- // like resolveModelInfo in models.ts.
1123
- const llm = ctx.get('llm')
1124
- const resolveCallConfig = (llm as {
1125
- resolveCallConfig?: (this: unknown, config: { provider: string; model: string; reasoningEffort?: string }) => Promise<unknown>
1126
- } | undefined)?.resolveCallConfig
1127
- if (llm !== undefined && typeof resolveCallConfig === 'function') {
1128
- void Promise.resolve(resolveCallConfig.call(llm, {
1129
- provider: selection.provider,
1130
- model: selection.model,
1131
- ...selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort },
1132
- })).catch((error: unknown) => {
1133
- bridge.notify(`model selection rejected: ${error instanceof Error ? error.message : String(error)} reopen /model to pick again`, 'error')
1134
- })
1135
- }
1136
- return `${row.provider}/${row.model}`
1137
- }
1138
-
1139
- /** The /subagent override label, '' when delegated agents follow the current model. */
1140
- const subagentModelLabel = (): string => subagentOverride === undefined ? '' : modelSelectionLabel(subagentOverride)
1141
-
1142
- /** Apply one /subagent model pick; returns the override label. */
1143
- const setSubagentModel = (row: ModelRow, effortId?: string): string => {
1144
- subagentOverride = buildModelSelection(row, effortId)
1145
- renderCurrent()
1146
- return modelSelectionLabel(subagentOverride)
1147
- }
1148
-
1149
- /** Drop the /subagent override: delegated agents follow the current model again. */
1150
- const clearSubagentModel = (): void => {
1151
- subagentOverride = undefined
1152
- renderCurrent()
1153
- }
1154
-
1155
- /**
1156
- * Export the folded transcript to a markdown file (/export). The default
1157
- * target sits beside the session's cwd so the file lands in the user's
1158
- * workspace; an absolute or cwd-relative argument overrides it.
1159
- */
1160
- const exportTranscript = async (argument: string): Promise<void> => {
1161
- if (session === undefined) {
1162
- bridge.notify('no session yet submit a message to start', 'warning')
1163
- return
1164
- }
1165
- const wanted = argument.trim()
1166
- const sessionCwd = session.header.cwd ?? cwd
1167
- // The default name derives from the session id, which `--session` lets the
1168
- // user spell freely: reduce it to filename-safe characters first so the
1169
- // default target can never escape the session cwd.
1170
- const defaultName = `dsh-session-${exportSessionIdSuffix(session.id)}.md`
1171
- const target = wanted === ''
1172
- ? join(sessionCwd, defaultName)
1173
- : /^[a-zA-Z]:[\\/]/u.test(wanted) || wanted.startsWith('/')
1174
- ? wanted
1175
- : join(sessionCwd, wanted)
1176
- const markdown = buildExportMarkdown(store.getView(), session.id)
1177
- try {
1178
- await writeFileAsync(target, `${markdown}\n`, 'utf8')
1179
- bridge.notify(`exported to ${target}`)
1180
- } catch (error: unknown) {
1181
- bridge.notify(`export failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1182
- }
1183
- }
1184
-
1185
- /**
1186
- * Rename the session (/title): a user title pins the session and stops
1187
- * automatic generation (the service's own contract). The appended
1188
- * `session/title` event flows back through the store into the status line.
1189
- */
1190
- const renameTitle = (argument: string): string => {
1191
- const title = argument.trim()
1192
- if (title === '') return 'usage: /title <text>'
1193
- if (session === undefined) return 'no session yet — submit a message to start'
1194
- const service = ctx.get('sessionTitle')
1195
- if (service === undefined) return 'session titles are unavailable in this profile'
1196
- try {
1197
- service.rename(session, title)
1198
- return `title ${title}`
1199
- } catch (error: unknown) {
1200
- return `rename failed: ${error instanceof Error ? error.message : String(error)}`
1201
- }
1202
- }
1203
-
1204
- const loadSessions = async (options: SessionDirectoryOptions, signal?: AbortSignal): Promise<readonly SessionRow[]> => {
1205
- if (sessionQuery === undefined) throw new Error('session query is unavailable in this profile')
1206
- const records = await sessionQuery.listSessions(signal)
1207
- // Last-activity timestamps for sorting (codex UpdatedAt default): the
1208
- // JSONL artifact's mtime via locate()+stat the upstream api-proxy's own
1209
- // cold-probe pattern. O(1) per session; backends without a location (or
1210
- // vanished files) fall back to createdAt inside the projection.
1211
- const updated = new Map<string, number>()
1212
- for (const record of records) {
1213
- const location = persistence?.locate(record.header)
1214
- if (location === undefined) continue
1215
- try {
1216
- updated.set(record.header.id, (await stat(location.path)).mtimeMs)
1217
- } catch {
1218
- // Artifact gone or unreadable: the projection falls back to createdAt.
1219
- }
1220
- }
1221
- const projected = projectSessionRows(records, options, updated)
1222
- // Titles are the expensive fold. Fetch only the first bounded picker page;
1223
- // navigation/filter changes trigger a fresh, cancellable observation.
1224
- const page = projected.slice(0, 32)
1225
- if (page.length === 0) return projected
1226
- const observations = await sessionQuery.readTitleSnapshots(page.map(row => row.id), signal)
1227
- return mergeSessionTitles(projected, observations)
1228
- }
1229
-
1230
- /**
1231
- * Delete one session subtree (/delete, codex semantics: subagent threads go
1232
- * with their root). The kernel persistence seam has NO deletion API by
1233
- * design logs accumulate "until removed externally" — so this is the
1234
- * controlled external removal, in three phases with a hard boundary
1235
- * between planning and touching the filesystem:
1236
- *
1237
- * 1. `planSessionDeletion` collects the subtree and refuses when the root
1238
- * or ANY member is live (a live child would outlive its deleted
1239
- * parent), ordering the plan children-first.
1240
- * 2. Every plan node must locate to a guarded artifact directory
1241
- * (`encodeSegment(id)`/`session.jsonl` layout). Backends without a
1242
- * locatable artifact (SQLite) refuse the WHOLE deletion here — no
1243
- * file has been touched yet, so a backend or layout surprise can
1244
- * never strand a half-deleted subtree.
1245
- * 3. Artifacts are removed children-first: only an I/O error mid-delete
1246
- * can stop it short (reported with removed/total counts), leaving the
1247
- * shallowest lineage intact.
1248
- *
1249
- * @param id - the root session id to delete.
1250
- * @returns the outcome line for the panel/notice.
1251
- */
1252
- const deleteSession = async (id: string): Promise<string> => {
1253
- if (sessionQuery === undefined) return 'session query is unavailable in this profile'
1254
- if (session !== undefined && session.id === id) return 'cannot delete the session you are using — switch or /new first'
1255
- const records = await sessionQuery.listSessions()
1256
- const plan = planSessionDeletion(records, id)
1257
- if (!plan.ok) return plan.reason
1258
- // Phase 2 completes the plan before the first rm: locate and
1259
- // layout-check every node up front, so a refusal never leaves a
1260
- // partially removed subtree behind.
1261
- const byId = new Map<string, (typeof records)[number]>(records.map(record => [record.header.id, record]))
1262
- const dirs = new Map<string, string>()
1263
- for (const node of plan.nodes) {
1264
- const record = byId.get(node.id)
1265
- if (record === undefined) return `no persisted session matches "${node.id}"`
1266
- const location = persistence?.locate(record.header)
1267
- if (location === undefined) {
1268
- return `session backend exposes no deletable artifact for ${node.id.slice(-12)} (deletion is unsupported on this backend)`
1269
- }
1270
- const dir = sessionArtifactDirectory(location.path, node.id)
1271
- if (dir === undefined) {
1272
- return `refusing to delete: unexpected artifact layout at ${location.path}`
1273
- }
1274
- dirs.set(node.id, dir)
1275
- }
1276
- let removed = 0
1277
- for (const node of plan.nodes) {
1278
- const dir = dirs.get(node.id)!
1279
- try {
1280
- for (const name of SESSION_ARTIFACT_NAMES) {
1281
- await rm(join(dir, name), { force: true })
1282
- }
1283
- // Remove the now-empty session directory; a non-empty one stays (an
1284
- // unexpected sibling file is never ours to delete).
1285
- await rm(dir, { force: true, recursive: false }).catch(() => {})
1286
- removed += 1
1287
- } catch (error: unknown) {
1288
- return `delete failed for ${node.id.slice(-12)} after ${removed} of ${plan.nodes.length}: ${error instanceof Error ? error.message : String(error)}`
1289
- }
1290
- }
1291
- return `deleted ${removed} session${removed === 1 ? '' : 's'}`
1292
- }
1293
-
1294
- const loadSessionTranscript = async (id: string, signal?: AbortSignal): Promise<string> => {
1295
- if (sessionQuery === undefined) throw new Error('session query is unavailable in this profile')
1296
- const snapshot = await sessionQuery.readSession(id, signal)
1297
- return buildExportMarkdown(createTranscriptStore(snapshot.events).getView(), snapshot.session.id)
1298
- }
1299
-
1300
- const switchModeAction = async (id: string): Promise<string> => {
1301
- if (id === '') throw new Error('usage: /mode <preset>')
1302
- const currentAgent = agent
1303
- if (currentAgent === undefined) {
1304
- const choice = pendingModeWork.then(async () => {
1305
- const preset = await selectPreset(presets, undefined, id)
1306
- // A resume may have won while this roster read was in flight; never
1307
- // leak the old pending choice into a later /new session.
1308
- if (agent === undefined) {
1309
- pendingMode = preset.id
1310
- renderCurrent()
1311
- }
1312
- return preset.id
1313
- })
1314
- pendingModeWork = choice.then(() => {}, () => {})
1315
- return choice
1316
- }
1317
-
1318
-
1319
- // Serialize the recomposition with session activations: a /mode that
1320
- // interleaves a switch must not rebind the shared command/skill
1321
- // registries while the switch is composing the next agent.
1322
- const currentActive = active
1323
- const atEpoch = epoch
1324
- let selected: string | undefined
1325
- await compose(async () => {
1326
- const preset = await selectPreset(presets, currentAgent, id)
1327
- // A switch/quit landed while the recomposition ran: applying here
1328
- // would write the old choice into the new session's state and rebind
1329
- // the registries back to a disposed agent. The preset-selection log
1330
- // entry rode the old agent's session; only the local application is
1331
- // dropped.
1332
- if (epoch !== atEpoch || agent !== currentAgent || active !== currentActive) {
1333
- throw new Error('session changed while switching mode — nothing applied; retry in the active session')
1334
- }
1335
- if (active === undefined) throw new Error('active Agent has no session state')
1336
- active.mode = preset.id
1337
- commands.setAgent(currentAgent)
1338
- skills.setAgent(currentAgent)
1339
- selected = preset.id
1340
- renderCurrent()
1341
- })
1342
- return selected!
1343
- }
1344
-
1345
- interface PendingSwitch { readonly target: Target; readonly label: string }
1346
-
1347
- const activate = (nextTarget: Target): Promise<void> => {
1348
- if (quitting) return Promise.resolve()
1349
- // Serialized with every other composition (bare-launch creation, queued
1350
- // switches): at most one agent is composed at a time.
1351
- return compose(async () => {
1352
- const previous = active
1353
- const next = await prepare(nextTarget)
1354
- // Quit landed while the next session was being composed: dispose the
1355
- // half-ready agent and leave the current session untouched.
1356
- if (quitting) {
1357
- await next.handle.dispose().catch(() => {})
1358
- return
1359
- }
1360
- active = next
1361
- agent = next.agent
1362
- session = next.session
1363
- store = next.store
1364
- mentions = next.mentions
1365
- commands.setAgent(agent)
1366
- skills.setAgent(agent)
1367
- try {
1368
- process.stdout.write('\x1b[r\x1b[0m\x1b[H\x1b[2J\x1b[3J\x1b[H')
1369
- renderCurrent()
1370
- // Only a successful handoff may clear the transient per-session
1371
- // surfaces: a rolled-back switch keeps the previous session's
1372
- // subagent feed plus the user's pre-session /mode and permission
1373
- // picks (the bare-launch promise: explicit choices survive until
1374
- // composition takes them).
1375
- subagents.reset()
1376
- pendingMode = undefined
1377
- pendingPermission = undefined
1378
- } catch (error: unknown) {
1379
- active = previous
1380
- agent = previous?.agent
1381
- session = previous?.session
1382
- store = previous === undefined ? createTranscriptStore() : previous.store
1383
- mentions = previous === undefined ? createMentions(ctx, undefined, cwd) : previous.mentions
1384
- if (agent !== undefined) commands.setAgent(agent)
1385
- if (agent !== undefined) skills.setAgent(agent)
1386
- await next.handle.dispose()
1387
- if (!quitting) renderCurrent()
1388
- throw error
1389
- }
1390
- // From here the new session is live: in-flight prepares/commands for
1391
- // the previous agent are stale and must be aborted and ignored.
1392
- abortPendingControllers()
1393
- epoch += 1
1394
- // No previous session (a bare launch switched straight into a resume):
1395
- // nothing to flush or dispose, so just confirm the activation.
1396
- if (previous === undefined) {
1397
- // The key-change remount above swaps the App in this same synchronous
1398
- // continuation; the new App registers its bridge.notify in a passive
1399
- // effect AFTER it, so an immediate notice reaches the UNMOUNTED
1400
- // instance and React drops it silently. Defer past the commit.
1401
- setTimeout(() => {
1402
- bridge.notify(`${next.resumed ? 'resumed' : 'created'} ${next.session.id.slice(-12)} · mode ${next.mode}`)
1403
- }, 0)
1404
- return
1405
- }
1406
- let cleanupWarning: string | undefined
1407
- try {
1408
- await sessions.flush(previous.session)
1409
- } catch (error: unknown) {
1410
- cleanupWarning = `previous session flush failed: ${error instanceof Error ? error.message : String(error)}`
1411
- }
1412
- try {
1413
- await previous.handle.dispose()
1414
- } catch (error: unknown) {
1415
- cleanupWarning = `${cleanupWarning === undefined ? '' : `${cleanupWarning}; `}previous agent release failed: ${error instanceof Error ? error.message : String(error)}`
1416
- }
1417
- bridge.notify(cleanupWarning === undefined
1418
- ? `${next.resumed ? 'resumed' : 'created'} ${next.session.id.slice(-12)} · mode ${next.mode}`
1419
- : `switched to ${next.session.id.slice(-12)}, but ${cleanupWarning}`,
1420
- cleanupWarning === undefined ? 'info' : 'warning')
1421
- })
1422
- }
1423
-
1424
- const switchQueue = new SessionSwitchQueue<PendingSwitch>(
1425
- async request => { if (!quitting) await activate(request.target) },
1426
- error => bridge.notify(`session switch failed: ${error instanceof Error ? error.message : String(error)}`, 'error'),
1427
- )
1428
-
1429
- const requestSwitch = (request: PendingSwitch): void => {
1430
- if (session === undefined) {
1431
- // No session yet (a bare launch using /resume before any input): activate
1432
- // the target directly there is no running turn to wait on and nothing
1433
- // to flush.
1434
- void activate(request.target).catch((error: unknown) => {
1435
- bridge.notify(`session switch failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1436
- })
1437
- return
1438
- }
1439
- if (request.target.sessionId === session.id) {
1440
- bridge.notify('that session is already active', 'warning')
1441
- return
1442
- }
1443
- const outcome = switchQueue.request(agent!, request)
1444
- if (outcome === 'queued') {
1445
- bridge.notify(`will switch to ${request.label} when the current turn finishes · /resume cancel to abort`)
1446
- }
1447
- }
1448
-
1449
- const resolveResumeId = async (wanted: string): Promise<string> => {
1450
- if (wanted === '') throw new Error('usage: /resume <id|prefix>')
1451
- if (sessionQuery === undefined) throw new Error('session query is unavailable in this profile')
1452
- const records = await sessionQuery.listSessions()
1453
- const exact = records.filter(record => record.header.id === wanted)
1454
- const matches = exact.length > 0 ? exact : records.filter(record => record.header.id.startsWith(wanted))
1455
- if (matches.length === 0) throw new Error(`no session matches "${wanted}"`)
1456
- if (matches.length > 1) throw new Error(`session prefix "${wanted}" is ambiguous (${matches.length} matches)`)
1457
- const matched = matches[0]!
1458
- // Same lineage gate as the CLI --resume path and the picker.
1459
- if (isSubagentSession(matched.header)) {
1460
- throw new Error('subagent conversations are read-only; resume a root session')
1461
- }
1462
- if (session !== undefined && agents.get(SessionId(matched.header.id)) !== undefined && matched.header.id !== session.id) {
1463
- throw new Error('that session is already live in another owner')
1464
- }
1465
- return matched.header.id
1466
- }
1467
-
1468
- const requestResume = (wanted: string): void => {
1469
- void resolveResumeId(wanted).then(id => {
1470
- requestSwitch({ target: { sessionId: id, resume: true }, label: id.slice(-12) })
1471
- }, (error: unknown) => bridge.notify(`resume failed: ${error instanceof Error ? error.message : String(error)}`, 'error'))
1472
- }
1473
-
1474
- const createSession = (mode?: string): void => {
1475
- // /new before any input is the first-session creation itself, not a switch.
1476
- if (session === undefined) {
1477
- ensureSession(mode)
1478
- return
1479
- }
1480
- const nextCwd = session.header.cwd ?? cwd
1481
- const id = `session-${randomUUID()}`
1482
- requestSwitch({ target: { sessionId: id, resume: false, mode, cwd: nextCwd }, label: id.slice(-12) })
1483
- }
1484
-
1485
- const reviewChanges = (argument: string): void => {
1486
- const currentAgent = agent
1487
- if (currentAgent === undefined) {
1488
- bridge.notify('no session yet - submit a message to start', 'warning')
1489
- return
1490
- }
1491
- // The diff loads from the CALLING session's cwd; capture that
1492
- // workspace and this turn's identity so a switch mid-load can neither
1493
- // flip the new session read-only nor send the old workspace's review
1494
- // into it. The controller rides pendingControllers, so a switch/quit
1495
- // kills the git subprocess itself instead of only ignoring its result.
1496
- const atEpoch = epoch
1497
- const reviewCwd = session?.header.cwd ?? cwd
1498
- const controller = new AbortController()
1499
- pendingControllers.add(controller)
1500
- const finish = (): void => {
1501
- pendingControllers.delete(controller)
1502
- }
1503
- void loadGitDiff(reviewCwd, argument, controller.signal).then(({ title, files }) => {
1504
- finish()
1505
- if (controller.signal.aborted || epoch !== atEpoch || agent !== currentAgent) return
1506
- try {
1507
- setPermissionAction('read-only')
1508
- } catch (error: unknown) {
1509
- bridge.notify(`review unavailable: ${error instanceof Error ? error.message : String(error)}`, 'error')
1510
- return
1511
- }
1512
- send(buildReviewPrompt(files.flatMap(file => file.lines).join('\n'), title), 'followup')
1513
- bridge.notify('review started under read-only permissions')
1514
- }, (error: unknown) => {
1515
- finish()
1516
- if (controller.signal.aborted || epoch !== atEpoch) return
1517
- bridge.notify(`review failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1518
- })
1519
- }
1520
-
1521
- const forkSession = (argument: string): void => {
1522
- if (session === undefined || active === undefined) {
1523
- bridge.notify('no session yet - submit a message to start', 'warning')
1524
- return
1525
- }
1526
- try {
1527
- const text = argument.trim()
1528
- const atSeq = text === '' ? undefined : Number(text)
1529
- if (text !== '' && (!Number.isSafeInteger(atSeq) || (atSeq ?? -1) < 0)) {
1530
- throw new Error('usage: /fork [event-seq]')
1531
- }
1532
- const seed = selectForkSeed(session.events, atSeq)
1533
- const id = `session-${randomUUID()}`
1534
- requestSwitch({
1535
- target: {
1536
- sessionId: id,
1537
- resume: false,
1538
- mode: active.mode,
1539
- cwd: session.header.cwd ?? cwd,
1540
- seed: seed.events,
1541
- parentSession: session.id,
1542
- seedLength: seed.events.length,
1543
- },
1544
- label: id.slice(-12),
1545
- })
1546
- } catch (error: unknown) {
1547
- bridge.notify(`fork failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1548
- }
1549
- }
1550
-
1551
- const switchSession = (row: SessionRow): void => {
1552
- if (!row.resumable) {
1553
- bridge.notify('subagent conversations are read-only', 'warning')
1554
- return
1555
- }
1556
- requestSwitch({ target: { sessionId: row.id, resume: true }, label: row.title ?? row.id.slice(-12) })
1557
- }
1558
-
1559
- const cancelSessionSwitch = (): boolean => {
1560
- return switchQueue.cancel()
1561
- }
1562
-
1563
- const appElement = (): ReturnType<typeof createElement> => {
1564
- // A bare launch mounts with pending/default model, mode, and permission
1565
- // facts until the first input composes the real session. These choices stay
1566
- // process-local and create no durable state before that composition.
1567
- const sessionCwd = session?.header.cwd ?? cwd
1568
- const currentView = store.getView()
1569
- const defaults = currentDefaults()
1570
- const model = currentView.model !== ''
1571
- ? currentView.model
1572
- : pendingSelection !== undefined
1573
- ? `${pendingSelection.provider}/${pendingSelection.model}`
1574
- : `${defaults.provider}/${defaults.model}`
1575
- const effort = resolveEffectiveSelection(
1576
- active?.selection.picked ?? pendingSelection,
1577
- session?.requestHeader()?.config,
1578
- defaults,
1579
- ).reasoningEffort
1580
- const permission = permissionPresets === undefined
1581
- ? currentView.permission
1582
- : effectivePermission(permissionPresets, session, pendingPermission)
1583
- return createElement(App, {
1584
- key: session?.id ?? 'pending',
1585
- store,
1586
- approval,
1587
- questions,
1588
- subagents,
1589
- commands,
1590
- skills,
1591
- model,
1592
- effort,
1593
- cwd: basename(sessionCwd),
1594
- workspaceRoot: sessionCwd,
1595
- branch: gitBranch(sessionCwd),
1596
- sessionId: session === undefined ? '' : session.id.slice(-8),
1597
- resumed: active?.resumed ?? false,
1598
- mode: active?.mode ?? pendingMode ?? presets.defaultId,
1599
- permission,
1600
- dispatch,
1601
- steer,
1602
- interrupt,
1603
- quit,
1604
- loadModels: () => loadModelDirectory(ctx),
1605
- loadModelProviders: () => loadProviderSettings(ctx),
1606
- subscribeModelProviders: listener => subscribeProviderSettings(ctx, listener),
1607
- saveModelProviderCredential: (target, key) => saveProviderCredential(ctx, target, key),
1608
- saveModelProviderConfiguration: (target, configuration) => saveProviderConfiguration(ctx, target, configuration),
1609
- discoverModelProvider: (target, request, signal) => discoverProviderModels(ctx, target, request, signal),
1610
- unsetModelProviderCredential: target => unsetProviderCredential(ctx, target),
1611
- removeModelProvider: target => removeProviderSettings(ctx, target),
1612
- loadProviderAuthorizations: () => loadProviderAuthorizations(ctx),
1613
- subscribeProviderAuthorizations: listener => subscribeProviderAuthorizations(ctx, listener),
1614
- beginProviderAuthorization: (row, method, interaction, signal) => (
1615
- beginProviderAuthorization(ctx, row, method, interaction, signal)
1616
- ),
1617
- cancelProviderAuthorization: row => cancelProviderAuthorization(ctx, row.key),
1618
- logoutProviderAuthorization: row => logoutProviderAuthorization(ctx, row),
1619
- openAuthorizationUrl,
1620
- copyTextValue: copyText,
1621
- loadMentions: (query: string, signal?: AbortSignal) => mentions.candidates(query, signal),
1622
- inspectImages: paths => inspectImagePaths(paths, ctx.get('attachments'), session?.header.cwd ?? cwd),
1623
- prepareImages: (paths, signal) => saveImagePaths(paths, ctx.get('attachments'), signal),
1624
- cyclePermission,
1625
- setPermission: setPermissionAction,
1626
- selectModel,
1627
- subagentModel: subagentModelLabel(),
1628
- setSubagentModel,
1629
- clearSubagentModel,
1630
- deleteSession,
1631
- exportTranscript,
1632
- renameTitle,
1633
- copyLastResponse,
1634
- loadGitDiff: (argument: string) => loadGitDiff(session?.header.cwd ?? cwd, argument),
1635
- reviewChanges,
1636
- loadPresets: () => presets.list(),
1637
- switchMode: switchModeAction,
1638
- loadPermissions: () => permissionPresets === undefined
1639
- ? Promise.reject(new Error('permission presets are not mounted in this composition'))
1640
- : Promise.resolve(listPermissionRows(permissionPresets)),
1641
- createSession,
1642
- forkSession,
1643
- loadSessions,
1644
- loadSessionTranscript,
1645
- loadSubagents: () => {
1646
- const current = session
1647
- if (current === undefined || sessionQuery === undefined) return Promise.resolve([])
1648
- return loadSessions({ sessions: 'all', cwd: 'all', sort: 'newest', currentCwd: current.header.cwd ?? cwd, query: '' })
1649
- .then(rows => rows.filter(row => row.parent === current.id && row.subagent))
1650
- },
1651
- switchSession,
1652
- cancelSessionSwitch,
1653
- loadPlugins: () => listPluginRows(ctx),
1654
- loadJobs: () => listJobs(ctx, active?.agent),
1655
- statusline: statuslineItems,
1656
- saveStatusline,
1657
- applyEditorKeys,
1658
- saveTheme,
1659
- history: inputHistory,
1660
- recordHistory,
1661
- cancelQueued,
1662
- onBridgeReady: (instance: AppBridge) => { bridge.notify = instance.notify },
1663
- })
1664
- }
1665
-
1666
- const renderCurrent = (): void => {
1667
- mountRef.current?.rerender(appElement())
1668
- }
1669
-
1670
- mountRef.current = io.mount(appElement())
1671
-
1672
- // Startup prompt/images use the same durable delivery path as composer
1673
- // submissions. Image bytes are committed before the user/message event, and
1674
- // input typed during that preparation queues behind the initial request so
1675
- // the agent always receives the startup prompt first.
1676
- if (startup.prompt !== undefined || (startup.images?.length ?? 0) > 0) {
1677
- if ((startup.images?.length ?? 0) > 0) {
1678
- bridge.notify(`processing ${startup.images!.length} startup image${startup.images!.length === 1 ? '' : 's'}…`)
1679
- }
1680
- void inputGate.run(async deliver => {
1681
- const images = await saveImagePaths(startup.images ?? [], ctx.get('attachments'))
1682
- if (images.length > 0) bridge.notify(`${images.length} startup image${images.length === 1 ? '' : 's'} attached`)
1683
- deliver({ text: startup.prompt ?? '', mode: 'followup', images })
1684
- }).catch((error: unknown) => {
1685
- bridge.notify(`initial prompt failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1686
- })
1687
- }
1688
-
1689
- async function copyLastResponse(): Promise<string> {
1690
- const text = latestAssistantText(store.getView())
1691
- if (text === undefined) return 'nothing to copy yet'
1692
- await copyText(text)
1693
- return 'copied latest response'
1694
- }
1695
-
1696
- // A corrupt statusline config must not vanish silently: surface it once
1697
- // the notice channel is live, after the first frame settles.
1698
- if (statuslineWarning !== undefined) {
1699
- setTimeout(() => {
1700
- bridge.notify('statusline config unreadable, using defaults: ' + statuslineWarning, 'warning')
1701
- }, 50)
1702
- }
1703
- // Same one-shot surface for a corrupt theme file (dark fallback stays live).
1704
- if (themeWarning !== undefined) {
1705
- setTimeout(() => {
1706
- bridge.notify('theme config unreadable, using dark: ' + themeWarning, 'warning')
1707
- }, 50)
1708
- }
1709
-
1710
- // One-shot VS Code Ctrl+R hint: resolveEditorKeysStartupHint checks the
1711
- // marker file and the live keybindings config; surfacing waits for the
1712
- // notice channel like the other startup warnings. A failed probe stays
1713
- // silent the hint is cosmetic and /vscode-keys remains discoverable.
1714
- void resolveEditorKeysStartupHint(editorKeysEnv).then(hint => {
1715
- if (hint === undefined) return
1716
- setTimeout(() => {
1717
- bridge.notify(hint)
1718
- }, 50)
1719
- }, () => {})
1720
- }
1721
-
1722
- /**
1723
- * Mount the interactive terminal driver.
1724
- * @param ctx - plugin context carrying core services and the launcher-provided exit request.
1725
- * @param config - validated startup config resolved from the tuiStartup provider.
1726
- */
1727
- export function apply(ctx: Context, config: Config): void {
1728
- // The CLI validated --theme at parse time; the loose config schema falls
1729
- // back to dark for anything unexpected.
1730
- const theme = config.startup.theme === undefined ? undefined : parseThemeName(config.startup.theme)
1731
- const input = {
1732
- ...(theme === undefined ? {} : { theme }),
1733
- ...(config.startup.prompt === undefined ? {} : { prompt: config.startup.prompt }),
1734
- ...(config.startup.images === undefined ? {} : { images: config.startup.images }),
1735
- }
1736
- const startup: TuiStartup =
1737
- config.startup.kind === 'resume' && config.startup.sessionId !== undefined
1738
- ? { kind: 'resume', sessionId: config.startup.sessionId, ...input }
1739
- : config.startup.kind === 'latest'
1740
- ? { kind: 'latest', ...input }
1741
- : config.startup.kind === 'named' && config.startup.sessionId !== undefined
1742
- ? { kind: 'named', sessionId: config.startup.sessionId, ...config.startup.mode === undefined ? {} : { mode: config.startup.mode }, ...input }
1743
- : { kind: 'fresh', ...config.startup.mode === undefined ? {} : { mode: config.startup.mode }, ...input }
1744
- // Read through the global service store, not the property proxy: appExit is
1745
- // an optional host value, never an injected dependency.
1746
- const exit = ctx.get('appExit')
1747
- if (exit === undefined) {
1748
- throw new Error('tui-runner: the launcher must provide ctx.appExit before the tree mounts')
1749
- }
1750
- const io: TuiIo = { mount: internals.mount, exit }
1751
- void run(ctx, startup, io).catch((error: unknown) => { fail(io, error) })
1752
- }
1
+ /**
2
+ * @deepseek-ai/dsh-code — the interactive terminal driver. The bundle patch
3
+ * rides over dsh-base without Host, HTTP, or browser plugins; this runner
4
+ * creates or resumes preset-composed Agents through the core registry, keeps
5
+ * one Ink owner while the active session changes, folds submitted prompts
6
+ * into the selected durable session, answers approval asks with a y/n bar,
7
+ * dispatches slash commands, and on quit flushes and requests process exit.
8
+ *
9
+ * @module @deepseek-ai/dsh-code
10
+ */
11
+
12
+ import { randomUUID } from 'node:crypto'
13
+ import { readFileSync } from 'node:fs'
14
+ import { homedir } from 'node:os'
15
+ import { appendFile as appendFileAsync, mkdir, readdir, rm, stat, writeFile as writeFileAsync } from 'node:fs/promises'
16
+ import { basename, dirname, join } from 'node:path'
17
+ import { createElement } from 'react'
18
+ import type { Context } from '@deepseek-ai/cordis'
19
+ import z from '@deepseek-ai/schemastery'
20
+ import { installModelSelection } from '@deepseek-ai/dsh-agent'
21
+ import type { Agent, AgentHandle, ModelSelection, ModelSelectionRef } from '@deepseek-ai/dsh-agent'
22
+ import type {} from '@deepseek-ai/dsh-agent-default-model'
23
+ import type {} from '@deepseek-ai/dsh-attachment'
24
+ import { createUserMessage, MessageId, type ContentBlock } from '@deepseek-ai/dsh-llm'
25
+ import type { JobSnapshot } from '@deepseek-ai/dsh-jobs'
26
+ import { SessionId, SessionLogOffset, type Session, type SessionEvent, type SessionHeader, type UserMessage } from '@deepseek-ai/dsh-session'
27
+ import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
28
+ // Type-only: carries the ctx.sessionTitle service merge for /title.
29
+ import type {} from '@deepseek-ai/dsh-session-title'
30
+ // Empty type imports carry the loader Context merge for the settlement await
31
+ // and the cmdline Context merge for the appExit host value.
32
+ import type {} from '@deepseek-ai/cordis-plugin-loader'
33
+ import type {} from '@deepseek-ai/dsh-cmdline'
34
+ import { App, type NoticeTone } from './app.ts'
35
+ import { mountApprovalAnswerer, type ApprovalStore } from './approval.ts'
36
+ import { isSlashLine, submissionPayload, watchCommands, type CommandsView } from './commands.ts'
37
+ import { internals, type TuiMount } from './internals.ts'
38
+ import { syncModelCapabilities } from './model-capabilities.ts'
39
+ import { buildModelSelection, applyModelSelectionToConfig, loadModelDirectory, modelSelectionLabel, resolveEffectiveSelection, type ModelRow } from './models.ts'
40
+ import {
41
+ discoverProviderModels,
42
+ loadProviderSettings,
43
+ removeProviderSettings,
44
+ saveProviderCredential,
45
+ saveProviderConfiguration,
46
+ subscribeProviderSettings,
47
+ unsetProviderCredential,
48
+ } from './provider-settings.ts'
49
+ import { createMentions, type MentionsApi } from './mentions.ts'
50
+ import { mountQuestionProvider, type QuestionStore } from './questions.ts'
51
+ // Type-only import merges the settings Events declarations ('settings/updated',
52
+ // 'settings/document-updated') into this program's Cordis bus typing.
53
+ import type {} from '@deepseek-ai/dsh-settings'
54
+ import { createTranscriptStore, type TranscriptStore } from './store.ts'
55
+ import { createSubagentFeed, type SubagentFeedView } from './subagents.ts'
56
+ import { parseStatuslineItems } from './render/status.ts'
57
+ import { historyLine, HISTORY_MAX_ENTRIES, needsCompaction, parseHistoryFile, serializeHistoryList } from './history.ts'
58
+ import { watchSkills, type SkillsView } from './skills.ts'
59
+ import { toolArgumentsPreview } from './render/tool-preview.ts'
60
+ import { buildExportMarkdown } from './render/export.ts'
61
+ import { inspectFilePaths, inspectImagePaths, saveFilePaths, saveImagePaths } from './attachments.ts'
62
+ import { copyText, latestAssistantText } from './editor.ts'
63
+ import { applyCtrlRPassthrough, resolveEditorKeysStartupHint, type EditorKeysEnv } from './editor-keys.ts'
64
+ import {
65
+ beginProviderAuthorization,
66
+ cancelProviderAuthorization,
67
+ loadProviderAuthorizations,
68
+ logoutProviderAuthorization,
69
+ openAuthorizationUrl,
70
+ subscribeProviderAuthorizations,
71
+ } from './authorization.ts'
72
+ import { selectForkSeed } from './fork.ts'
73
+ import { buildReviewPrompt, loadGitDiff } from './git-workflow.ts'
74
+ import type { TuiStartup } from './startup.ts'
75
+ import { SessionSwitchQueue } from './session-switch.ts'
76
+ import { agentPresetsFrom, normalizePresetId, resolvePreset, selectPreset } from './presets.ts'
77
+ import {
78
+ applyPendingPermission,
79
+ cyclePermission as cyclePermissionPreset,
80
+ effectivePermission,
81
+ listPermissionRows,
82
+ permissionPresetsFrom,
83
+ selectPermission,
84
+ } from './permissions.ts'
85
+ import { listPluginRows } from './plugin-inventory.ts'
86
+ import { parseAnimationsPref } from './render/animations.ts'
87
+ import { parseThemeName, setTheme, type ThemeName } from './theme.ts'
88
+ import {
89
+ isSubagentSession,
90
+ matchSessionId,
91
+ mergeSessionTitles,
92
+ newestRootForCwd,
93
+ isSessionArtifactName,
94
+ jsonlSessionRoot,
95
+ planSessionDeletion,
96
+ projectSessionRows,
97
+ sessionArtifactDirectory,
98
+ sessionDirectoryFor,
99
+ type SessionDirectoryOptions,
100
+ type SessionQueryService,
101
+ type SessionRow,
102
+ } from './session-directory.ts'
103
+ import { createUserSettingsPersistence, writeFileAtomically } from './settings-file.ts'
104
+
105
+ /** Stable Cordis plugin name. */
106
+ export const name = 'tui-runner'
107
+
108
+ /** Core services required before the interactive session can start. */
109
+ export const inject = ['agentDefaultModel', 'agents', 'sessions']
110
+
111
+ /** Plugin config: the startup resolved from this app's injected provider service. */
112
+ export interface Config {
113
+ /** How this invocation obtains its session identity (validated loosely; narrowed in {@link apply}). */
114
+ startup: { kind: string; sessionId?: string; mode?: string; theme?: string; prompt?: string; images?: string[] }
115
+ }
116
+
117
+ export const Config: z<Config> = z.object({
118
+ startup: z.object({
119
+ kind: z.string().required(),
120
+ sessionId: z.string(),
121
+ mode: z.string(),
122
+ theme: z.string(),
123
+ prompt: z.string(),
124
+ images: z.array(z.string()),
125
+ }),
126
+ })
127
+
128
+ /** Process-facing effects of the runner: the Ink mount plus the launcher's exit request. */
129
+ interface TuiIo {
130
+ mount: typeof internals.mount
131
+ exit(code: number): void
132
+ }
133
+
134
+ /** Report an unexpected direct-driver failure and request a failing exit. */
135
+ function fail(io: TuiIo, error: unknown): void {
136
+ internals.stderr.write(`dsh: ${error instanceof Error ? error.message : String(error)}\n`)
137
+ io.exit(1)
138
+ }
139
+
140
+ /**
141
+ * Snapshot caller-visible background jobs for the /jobs panel. Jobs the agent
142
+ * started through run_in_background are fenced by their owner, so the CURRENT
143
+ * agent is the caller. A missing registry is a harmless absence (the base
144
+ * composition may not mount one) and collapses to the empty panel state —
145
+ * the documented degradation for harmless probes, not an error.
146
+ * @param ctx - context carrying the optional `jobs` registry.
147
+ * @param caller - the active agent (undefined sees only unowned jobs).
148
+ * @returns job rows in registration order; never throws.
149
+ */
150
+ function listJobs(ctx: Context, caller: Agent | undefined): readonly import('./kernel-panels.ts').JobRow[] {
151
+ const jobs = ctx.get('jobs')
152
+ if (jobs === undefined) return []
153
+ try {
154
+ return jobs.list(caller).map((job: JobSnapshot) => ({
155
+ id: job.id,
156
+ kind: job.kind,
157
+ label: job.label,
158
+ status: job.status,
159
+ detail: job.detail,
160
+ startedAt: job.startedAt,
161
+ finishedAt: job.finishedAt,
162
+ }))
163
+ } catch {
164
+ return []
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Resolve the working directory's git branch for the status line.
170
+ * @param cwd - the session's working directory.
171
+ * @returns the branch name, or '' outside a repository or on a detached HEAD.
172
+ */
173
+ function gitBranch(cwd: string): string {
174
+ try {
175
+ const ref = readFileSync(join(cwd, '.git', 'HEAD'), 'utf8').trim().match(/^ref: refs\/heads\/(.+)$/)
176
+ return ref?.[1] ?? ''
177
+ } catch {
178
+ // Only the single HEAD read is attempted, so the sole reachable failure is
179
+ // a missing repository (or unreadable HEAD file): the branch group drops out.
180
+ return ''
181
+ }
182
+ }
183
+
184
+ /** The session identity this invocation will run, plus whether it is resumed. */
185
+ interface Target {
186
+ sessionId: string
187
+ resume: boolean
188
+ mode?: string
189
+ cwd?: string
190
+ seed?: readonly SessionEvent[]
191
+ parentSession?: SessionId
192
+ seedLength?: number
193
+ }
194
+
195
+ /**
196
+ * Reduce a session id to a filename-safe /export default-name suffix. Session
197
+ * ids are normally minted `session-<uuid>`, but `--session` accepts arbitrary
198
+ * user text: path separators must never leak into the default export filename
199
+ * (which would escape the session cwd).
200
+ * @param id - the session id.
201
+ * @returns at most the last 8 filename-safe characters.
202
+ */
203
+ export function exportSessionIdSuffix(id: string): string {
204
+ return id.replace(/[^a-zA-Z0-9._-]/gu, '_').slice(-8)
205
+ }
206
+
207
+ /** One ordered step of the terminal quit cleanup. */
208
+ export interface QuitCleanupStep {
209
+ /** Step label used in diagnostics and tests. */
210
+ readonly name: string
211
+ /** The step's async work; a rejection is contained by the sequence. */
212
+ readonly run: () => Promise<void>
213
+ }
214
+
215
+ /**
216
+ * Run the ordered quit cleanup, then request exit. Every step rejection is
217
+ * contained (reported through `onError`) so a failed flush or dispose never
218
+ * skips the remaining cleanup; the exit request is always reached exactly
219
+ * once.
220
+ * @param steps - the cleanup steps in dependency order (settle the visible
221
+ * session, await the final in-flight composition, await durable recall).
222
+ * @param exit - the terminal exit request (code 0).
223
+ * @param onError - optional failure sink; called once per failing step and
224
+ * itself contained, so a throwing sink cannot abort the sequence.
225
+ * @returns the names of the steps that started, in order (for tests).
226
+ */
227
+ export async function runQuitSequence(
228
+ steps: readonly QuitCleanupStep[],
229
+ exit: (code: number) => void,
230
+ onError?: (name: string, error: unknown) => void,
231
+ ): Promise<readonly string[]> {
232
+ const started: string[] = []
233
+ for (const step of steps) {
234
+ started.push(step.name)
235
+ try {
236
+ await step.run()
237
+ } catch (error) {
238
+ try {
239
+ onError?.(step.name, error)
240
+ } catch {
241
+ // The failure sink must never abort the cleanup sequence.
242
+ }
243
+ }
244
+ }
245
+ try {
246
+ exit(0)
247
+ } catch {
248
+ // The exit request itself must not become an unhandled rejection.
249
+ }
250
+ return started
251
+ }
252
+
253
+ /** One composer submission waiting behind the startup delivery. */
254
+ export interface QueuedSubmission {
255
+ readonly text: string
256
+ readonly mode: 'followup' | 'steer'
257
+ readonly images: readonly ContentBlock[]
258
+ }
259
+
260
+ /**
261
+ * Whether a tagged submission still belongs to the active session. Attachment
262
+ * prepares resolve on the microtask timeline, while a queued session switch
263
+ * remounts the app asynchronously — the composing instance's unmount cleanup
264
+ * runs too late to abort, so the delivery itself carries the composing
265
+ * session's full id and the runner drops it here when the world moved on.
266
+ * An untagged (synchronous) or pending-session ('') submission always passes.
267
+ */
268
+ export function submissionBelongsToSession(origin: string | undefined, activeSessionId: string | undefined): boolean {
269
+ return origin === undefined || origin === '' || origin === activeSessionId
270
+ }
271
+
272
+ /**
273
+ * Order-preserving gate for composer input while the startup prompt/images
274
+ * are still preparing. Anything submitted before the startup delivery settles
275
+ * queues and flushes afterwards in submit order, so the initial request can
276
+ * never be overtaken by typing that raced a slow image preparation. The flush
277
+ * also runs when the startup delivery fails: user input is never stranded.
278
+ */
279
+ export class StartupInputGate {
280
+ private readonly queued: QueuedSubmission[] = []
281
+ private pending = false
282
+ constructor(private readonly deliver: (submission: QueuedSubmission) => void) {}
283
+
284
+ /** Submit one line: delivered now while idle, queued behind the startup delivery otherwise. */
285
+ submit(submission: QueuedSubmission): void {
286
+ if (this.pending) this.queued.push(submission)
287
+ else this.deliver(submission)
288
+ }
289
+
290
+ /**
291
+ * Run the startup delivery the callback receives the direct-delivery sink
292
+ * for the startup prompt itself then flush everything that queued behind
293
+ * it, in order, even when the callback rejects.
294
+ */
295
+ async run(startup: (deliver: (submission: QueuedSubmission) => void) => Promise<void>): Promise<void> {
296
+ this.pending = true
297
+ try {
298
+ await startup(submission => this.deliver(submission))
299
+ } finally {
300
+ this.pending = false
301
+ const queued = this.queued.splice(0)
302
+ for (const submission of queued) this.deliver(submission)
303
+ }
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Resolve the invocation's target session against the persisted headers.
309
+ * @param startup - the parsed startup flags.
310
+ * @param persistence - the persistence service; required for resume/latest.
311
+ * @param cwd - the working directory `--continue` filters by.
312
+ * @returns the target identity.
313
+ * @throws with a user-facing message when the flags name nothing resolvable.
314
+ */
315
+ export async function resolveTarget(startup: TuiStartup, persistence: SessionPersistence | undefined, cwd: string): Promise<Target> {
316
+ if (startup.kind === 'fresh') return { sessionId: `session-${randomUUID()}`, resume: false, mode: startup.mode }
317
+ if (startup.kind === 'named') {
318
+ // The id must not exist yet: reject before any Agent composition when the
319
+ // backend can tell us (a live collision is still caught by the session
320
+ // store at create time).
321
+ if (persistence !== undefined) {
322
+ const headers: readonly SessionHeader[] = (await persistence.list()).map(snapshot => snapshot.header)
323
+ if (headers.some(header => header.id === startup.sessionId)) {
324
+ throw new Error(`session "${startup.sessionId}" already exists; use --resume to continue it`)
325
+ }
326
+ }
327
+ return { sessionId: startup.sessionId, resume: false, mode: startup.mode }
328
+ }
329
+ if (persistence === undefined) {
330
+ throw new Error('cannot resolve the requested session: session persistence is not configured')
331
+ }
332
+ const headers: readonly SessionHeader[] = (await persistence.list()).map(snapshot => snapshot.header)
333
+ if (startup.kind === 'resume') {
334
+ const matched = matchSessionId(headers, startup.sessionId)
335
+ // Subagent conversations are read-only everywhere else; the CLI must not
336
+ // be a back door into appending root turns to a child's durable log.
337
+ if (isSubagentSession(matched)) {
338
+ throw new Error('subagent conversations are read-only; resume a root session')
339
+ }
340
+ return { sessionId: matched.id, resume: true }
341
+ }
342
+ // --continue: the newest persisted ROOT session whose header pins this cwd.
343
+ const newest = newestRootForCwd(headers, cwd)
344
+ if (newest === undefined) throw new Error(`no persisted session for this directory (${cwd}); start one without --continue`)
345
+ return { sessionId: newest.id, resume: true }
346
+ }
347
+
348
+ /**
349
+ * Resolve a bounded command preview for one pending approval: the request
350
+ * contract carries no arguments, so the bar self-serves from the transcript
351
+ * projection via `callId` (mirrors the web ApprovalPanel's argsRaw lookup).
352
+ * @param events - the transcript entries to search.
353
+ * @param callId - the tool call the question is about, when the asker had one.
354
+ * @param toolName - the tool the question is about.
355
+ * @returns a bounded preview line, '' when nothing useful resolves.
356
+ */
357
+ function approvalCommandPreview(events: readonly { kind: string }[], callId: string | undefined, toolName: string): string {
358
+ if (callId === undefined) return ''
359
+ const entry = events.find(candidate =>
360
+ candidate.kind === 'tool' && (candidate as { callId?: string }).callId === callId)
361
+ if (entry === undefined) return ''
362
+ const args = (entry as { arguments?: string }).arguments ?? ''
363
+ return toolArgumentsPreview(args, toolName)
364
+ }
365
+
366
+ /** The runner's connection between the React app and the process side. */
367
+ interface AppBridge {
368
+ /** Post one local notice line (feedback the transcript does not carry). */
369
+ notify(text: string, tone?: NoticeTone): void
370
+ }
371
+
372
+ /**
373
+ * Run the interactive terminal session: resolve the target session, create or
374
+ * resume one Agent, mount the app, and keep the process alive until the user
375
+ * quits.
376
+ * @param ctx - plugin context carrying the Agent, default model, Session, and launcher IO services.
377
+ * @param startup - the parsed invocation flags.
378
+ * @param io - process-facing effects.
379
+ */
380
+ async function run(ctx: Context, startup: TuiStartup, io: TuiIo): Promise<void> {
381
+ // Loader siblings mount concurrently. Await the complete application before
382
+ // creating an Agent so its scoped tools and adapters are not half-composed.
383
+ await ctx.get('loader')?.await()
384
+ const agents = ctx.get('agents')
385
+ const defaultModel = ctx.get('agentDefaultModel')
386
+ const sessions = ctx.get('sessions')
387
+ const persistence = ctx.get('sessionPersistence')
388
+ const sessionQuery = (ctx as unknown as { get(name: string): unknown }).get('sessionQuery') as SessionQueryService | undefined
389
+ // Early process shutdown can dispose the tree while settlement is pending.
390
+ if (agents === undefined || defaultModel === undefined || sessions === undefined) return
391
+
392
+ const cwd = process.cwd()
393
+ // Live deployment default (web selectModel parity): read on every use, not
394
+ // snapshotted at launch, so a /model pick this process saves becomes the
395
+ // default for sessions composed afterwards without a restart.
396
+ const currentDefaults = (): ModelSelection => defaultModel.currentSelection()
397
+ const presets = agentPresetsFrom(ctx)
398
+ if (presets === undefined) throw new Error('agent preset service is unavailable; check the dsh-code bundle patch')
399
+ const permissionPresets = permissionPresetsFrom(ctx)
400
+
401
+ // A bare fresh launch stays transient: no Agent or session is composed, and
402
+ // nothing is persisted, until the user's first real input. Explicit flags
403
+ // (--resume/--continue/--session/--mode) keep the eager create/resume path.
404
+ const lazy = startup.kind === 'fresh' && startup.mode === undefined
405
+
406
+ interface ActiveSession {
407
+ handle: AgentHandle
408
+ agent: Agent
409
+ session: Session
410
+ store: ReturnType<typeof createTranscriptStore>
411
+ mentions: MentionsApi
412
+ mode: string
413
+ selection: { picked?: ModelSelection }
414
+ resumed: boolean
415
+ }
416
+
417
+ /** Prepare a complete next session before disturbing the currently visible one. */
418
+ const prepare = async (next: Target): Promise<ActiveSession> => {
419
+ const nextCwd = next.cwd ?? cwd
420
+ // A bare launch can pick a model before any session exists: the process
421
+ // keeps that explicit choice and every prepared session starts from it
422
+ // (the documented precedence: explicit pick > session header > default).
423
+ const selectionState: { picked?: ModelSelection } = pendingSelection === undefined
424
+ ? {}
425
+ : { picked: pendingSelection }
426
+ let mode = next.resume ? next.mode : next.mode ?? pendingMode
427
+ // An explicit `--mode` or the settings-layer service default may still name
428
+ // an id an upstream rename retired (code → ptc); normalize both.
429
+ if (!next.resume) mode = (await presets.resolve(normalizePresetId(mode ?? presets.defaultId))).id
430
+ // 0.1.5 AgentSetup passes the composed agent as its second argument (the
431
+ // former `ctx.agent` accessor is gone); the preset mount still needs the
432
+ // agent-scoped context.
433
+ const setup = async (agentCtx: Context, agent: Agent): Promise<void> => {
434
+ const sessionPreset = next.resume
435
+ ? resolvePreset(agent.session)
436
+ : mode
437
+ const mounted = await presets.mount(agentCtx, sessionPreset)
438
+ mode = mounted.id
439
+ const selection: ModelSelectionRef = {
440
+ get current(): ModelSelection | undefined {
441
+ return resolveEffectiveSelection(selectionState.picked, agent.session.requestHeader()?.config, currentDefaults())
442
+ },
443
+ set current(value: ModelSelection | undefined) { selectionState.picked = value },
444
+ assembled: undefined,
445
+ }
446
+ installModelSelection(agentCtx, selection)
447
+ }
448
+ // AgentOptions seed the loop's fallback route; effort rides the selection
449
+ // ref (installModelSelection), so only the provider/model pair is seeded.
450
+ const seedOptions = pendingSelection === undefined
451
+ ? { provider: currentDefaults().provider, model: currentDefaults().model }
452
+ : { provider: pendingSelection.provider, model: pendingSelection.model }
453
+ const handle = next.resume
454
+ ? await agents.resume({
455
+ resumeSessionId: SessionId(next.sessionId),
456
+ agentOptions: seedOptions,
457
+ // Quit aborts an in-flight composition so the exit wait never hangs
458
+ // on a prepare that cannot settle; upstream rolls the creation back.
459
+ signal: quitAbort.signal,
460
+ setup,
461
+ })
462
+ : await agents.create({
463
+ sessionId: SessionId(next.sessionId),
464
+ meta: {
465
+ cwd: nextCwd,
466
+ agentPreset: mode,
467
+ ...(next.parentSession === undefined ? {} : { parentSession: next.parentSession }),
468
+ // 0.1.5 fork lineage: the seed marker lives on the metadata and the
469
+ // inherited prefix length on the top-level option (the v0 header's
470
+ // numeric `seedLength` field is gone from the create contract).
471
+ ...(next.seedLength === undefined ? {} : { isSeeded: true }),
472
+ },
473
+ ...(next.seedLength === undefined ? {} : { inheritedEventCount: SessionLogOffset(next.seedLength) }),
474
+ ...(next.seed === undefined ? {} : { seed: next.seed }),
475
+ agentOptions: seedOptions,
476
+ signal: quitAbort.signal,
477
+ setup,
478
+ })
479
+ const session = handle.agent.session
480
+ if (!next.resume && permissionPresets !== undefined) {
481
+ applyPendingPermission(permissionPresets, session, pendingPermission)
482
+ }
483
+ return {
484
+ handle,
485
+ agent: handle.agent,
486
+ session,
487
+ store: createTranscriptStore(session.snapshotEvents()),
488
+ mentions: createMentions(ctx, handle.agent, session.header.cwd ?? nextCwd),
489
+ mode: mode ?? 'standard',
490
+ selection: selectionState,
491
+ resumed: next.resume,
492
+ }
493
+ }
494
+
495
+ let active: ActiveSession | undefined
496
+ let agent: Agent | undefined
497
+ let session: Session | undefined
498
+ let store: TranscriptStore = createTranscriptStore()
499
+ // Live subagent activity (child sessions of the current root): one bounded
500
+ // row per child, folded from the same event bus the transcript feeds on.
501
+ const subagents: SubagentFeedView & { apply(sessionId: string, event: SessionEvent): void; reset(): void } = createSubagentFeed()
502
+ // Pre-session @file completion runs the official search over the launch
503
+ // cwd (model- and session-independent); the prepare/activate paths replace
504
+ // this with the agent-scoped instance once a session exists.
505
+ let mentions: MentionsApi = createMentions(ctx, undefined, cwd)
506
+ /** Explicit model pick made before any session exists (a bare launch). */
507
+ let pendingSelection: ModelSelection | undefined
508
+ /** Agent preset selected before the first session exists. */
509
+ let pendingMode: string | undefined
510
+ /** Ordered pre-session preset resolutions; first composition awaits them. */
511
+ let pendingModeWork: Promise<void> = Promise.resolve()
512
+ /** Permission preset selected before the first session exists. */
513
+ let pendingPermission: string | undefined
514
+ /**
515
+ * Monotonic session epoch: bumped on every successful activation, on every
516
+ * first-session creation, and on quit. Async callbacks (mention prepares,
517
+ * command executions) capture it at call time and drop their result when it
518
+ * changed, so a stale callback can never deliver to an agent that is no
519
+ * longer on screen.
520
+ */
521
+ let epoch = 0
522
+ /** Aborted on quit: an in-flight agent composition (create/resume) races this signal. */
523
+ const quitAbort = new AbortController()
524
+ /** In-flight mention-prepare / command-execute controllers, aborted on any session transition. */
525
+ const pendingControllers = new Set<AbortController>()
526
+ const abortPendingControllers = (): void => {
527
+ for (const controller of [...pendingControllers]) {
528
+ pendingControllers.delete(controller)
529
+ controller.abort()
530
+ }
531
+ }
532
+ /** The in-flight session-composition turn (create/resume/activate), if any. */
533
+ let composing: Promise<void> | undefined
534
+ /**
535
+ * Run one session composition exclusively: concurrent compositions wait
536
+ * their turn, so a bare-launch first-session creation and a /resume
537
+ * activation can never compose agents in parallel (the loser would leak its
538
+ * agent or mis-deliver). Errors propagate to the caller; the shared slot
539
+ * always continues.
540
+ */
541
+ const compose = (work: () => Promise<void>): Promise<void> => {
542
+ const turn = (composing ?? Promise.resolve()).catch(() => {}).then(work)
543
+ composing = turn.catch(() => {})
544
+ return turn
545
+ }
546
+
547
+ if (!lazy) {
548
+ const target = await resolveTarget(startup, persistence, cwd)
549
+ const prepared = await prepare(target)
550
+ active = prepared
551
+ agent = prepared.agent
552
+ session = prepared.session
553
+ store = prepared.store
554
+ mentions = prepared.mentions
555
+ }
556
+
557
+ // Seed the transcript from the full session log: constructor seeds never
558
+ // fire on `session/event`, so a resumed session paints its history once
559
+ // before the first render. The handler reads the current session/store, so
560
+ // the deferred first session of a bare launch is covered by the same feed.
561
+ const off = ctx.on('session/event', (subject: Session, event: SessionEvent) => {
562
+ if (session === undefined) return
563
+ if (subject.id === session.id) {
564
+ store.apply(event)
565
+ // The parent-owned subagent catalog rides the ROOT log (0.1.5); each
566
+ // fact describes one child, so it feeds that child's live row.
567
+ if (event.type === 'subagent/catalog' && event.data.childId !== '') subagents.apply(event.data.childId, event)
568
+ return
569
+ }
570
+ // Child sessions (subagent conversations this root spawned) fold into
571
+ // the bounded live-activity feed, never the transcript: the root stays
572
+ // the only durable transcript truth while a running subagent remains
573
+ // visible. Lineage comes from the child header, same field the session
574
+ // directory uses to tag `↳` rows.
575
+ if (subject.header.parentSession === session.id && subject.header.origin === 'subagent') subagents.apply(subject.id, event)
576
+ })
577
+
578
+ // Live assistant typing (session-log v2+): durable logs are settlement-only,
579
+ // so the streaming tails ride the process-local `agent/assistant-stream`
580
+ // frames of the current root agent. Settlement events clear the tails when
581
+ // they land (always before a committed end frame); an abandoned attempt's
582
+ // partial tail is dropped by the store on its end frame.
583
+ ctx.on('agent/assistant-stream', ({ agent: source, frame }) => {
584
+ if (agent === undefined || source.id !== agent.id) return
585
+ store.applyStreamFrame(frame)
586
+ })
587
+
588
+ const commands: CommandsView = watchCommands(ctx)
589
+ if (agent !== undefined) commands.setAgent(agent)
590
+
591
+ const skills: SkillsView = watchSkills(ctx, cwd)
592
+ if (agent !== undefined) skills.setAgent(agent)
593
+
594
+ // Approval answerer: renders the ask as a y/n bar; only this TUI's agent is
595
+ // claimed, every other ask falls through to the fail-closed waterfall. The
596
+ // owner predicate is empty until the first session exists.
597
+ const approval: ApprovalStore = mountApprovalAnswerer(
598
+ ctx,
599
+ candidate => agent !== undefined && candidate.id === agent.id,
600
+ request => approvalCommandPreview(store.getView().entries, request.callId, request.toolName),
601
+ )
602
+
603
+ // Subagent model routing. The kernel seeds child agents from the parent's
604
+ // CREATE-TIME AgentOptions (resolveChildAgentOptions), which a mid-session
605
+ // /model switch never touches delegated work would keep running on the
606
+ // launch-time route. This plugin-level listener mirrors installModelSelection
607
+ // for subagent-origin requests (scope filtering delivers the agent subject
608
+ // inside the payload): the explicit /subagent override wins, else the root's
609
+ // effective selection (explicit pick > session header > deployment default).
610
+ // Effort rides the selection exactly like the kernel listener applies it.
611
+ let subagentOverride: ModelSelection | undefined
612
+ ctx.on('agent/request', (payload, next) => {
613
+ const subject = payload.agent
614
+ const header = subject.session.header
615
+ if (header.parentSession === undefined && header.origin !== 'subagent') return next()
616
+ // Only the ACTIVE session's explicit pick may steer a subagent request.
617
+ // During a switch window the old agent can still be mid-flight; routing
618
+ // it by the NEW session's pick sent one of its requests to the wrong
619
+ // model. A subject outside the active tree falls back to its own request
620
+ // header (plus any explicit /subagent override, which is user intent).
621
+ const activeAgent = active
622
+ const belongsToActive = activeAgent !== undefined
623
+ && (header.parentSession ?? subject.session.id) === activeAgent.session.id
624
+ const picked = subagentOverride
625
+ ?? resolveEffectiveSelection(
626
+ belongsToActive && activeAgent !== undefined ? (activeAgent.selection.picked ?? pendingSelection) : undefined,
627
+ subject.session.requestHeader()?.config,
628
+ currentDefaults(),
629
+ )
630
+ return next().then(resolved => applyModelSelectionToConfig(resolved, picked))
631
+ })
632
+
633
+ // ask_user_question answerer: one waterfall listener, one request on
634
+ // screen at a time. Plan reviews (exit_plan_mode) arrive through this same
635
+ // pipe; sibling answerers stay usable through the claim/defer split.
636
+ const questions: QuestionStore = mountQuestionProvider(
637
+ ctx,
638
+ candidate => agent !== undefined && candidate.id === agent.id,
639
+ )
640
+
641
+ // The bridge the React app registers on mount: local notices from the
642
+ // process side (unknown commands, switch confirmations, cancels).
643
+ const bridge: AppBridge = { notify: () => {} }
644
+
645
+ // Same-id capability inheritance. Catalog capabilities flow by route key,
646
+ // not model id, so a hand-declared relay model without an explicit
647
+ // reasoningEfforts declaration serves no reasoning levels and offers no
648
+ // effort picker. This background pass materializes declarations from
649
+ // same-id donors (sibling settings entries first, then other routes'
650
+ // advertised levels) over the panel's settings.mutate path, where the
651
+ // upstream serviceability gate still rejects invalid writes atomically.
652
+ // The debounce coalesces the settings/adapters event pair; the applier
653
+ // skips only a same-source same-revision echo of its own write, so the
654
+ // loop converges without ever ignoring a real external edit.
655
+ const capabilitySyncDebounceMs = 400
656
+ const runCapabilitySync = (): void => {
657
+ void syncModelCapabilities(ctx, bridge.notify)
658
+ }
659
+ let capabilitySyncTimer: ReturnType<typeof setTimeout> | undefined
660
+ const scheduleCapabilitySync = (): void => {
661
+ if (capabilitySyncTimer !== undefined) clearTimeout(capabilitySyncTimer)
662
+ capabilitySyncTimer = setTimeout(() => {
663
+ capabilitySyncTimer = undefined
664
+ runCapabilitySync()
665
+ }, capabilitySyncDebounceMs)
666
+ }
667
+ const offCapabilitySync = [
668
+ ctx.on('settings/document-updated', scheduleCapabilitySync),
669
+ ctx.on('llm/adapters-updated', scheduleCapabilitySync),
670
+ ]
671
+ scheduleCapabilitySync()
672
+
673
+ // /statusline persistence: one user-level JSON file under the DSH home.
674
+ // Missing file means defaults; a corrupt file degrades to defaults with a
675
+ // surfaced warning (the customization is user-authored, never silent).
676
+ const statuslinePath = join(homedir(), '.dsh', 'dsh-code', 'statusline.json')
677
+ let statuslineWarning: string | undefined
678
+ let statuslineItems: readonly string[] = []
679
+ try {
680
+ statuslineItems = parseStatuslineItems(JSON.parse(readFileSync(statuslinePath, 'utf8')).items)
681
+ } catch (error) {
682
+ statuslineItems = parseStatuslineItems(undefined)
683
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
684
+ statuslineWarning = error instanceof Error ? error.message : String(error)
685
+ }
686
+ }
687
+ // Serialized, crash-atomic writes for the user-level JSON files: the chain
688
+ // orders rapid consecutive saves (the LAST snapshot wins on disk), each
689
+ // write goes through a sibling temp file + rename, and quit waits for the
690
+ // flush exactly like it waits for the recall history.
691
+ const settingsPersistence = createUserSettingsPersistence()
692
+ const saveStatusline = (items: readonly string[]): void => {
693
+ statuslineItems = [...items]
694
+ void settingsPersistence.save(statuslinePath, JSON.stringify({ items }, null, 2) + '\n')
695
+ .catch((writeError: unknown) => {
696
+ bridge.notify('statusline save failed: ' + (writeError instanceof Error ? writeError.message : String(writeError)), 'error')
697
+ })
698
+ }
699
+
700
+ // /vscode-keys: detect the hosting editor's user keybindings.json and pass
701
+ // Ctrl+R through the workbench. One marker file under the DSH home keeps
702
+ // the startup hint a once-per-install event.
703
+ const editorKeysEnv: EditorKeysEnv = {
704
+ env: process.env,
705
+ paths: { homedir: homedir(), appdata: process.env.APPDATA, platform: process.platform },
706
+ flagPath: join(homedir(), '.dsh', 'dsh-code', 'editor-keys.json'),
707
+ }
708
+ const applyEditorKeys = (): Promise<string> => applyCtrlRPassthrough(editorKeysEnv)
709
+
710
+ // /theme persistence: one user-level JSON file under the DSH home, mirroring
711
+ // the statusline file. A missing file means the dark default; a corrupt file
712
+ // degrades to dark with a surfaced warning. Precedence: CLI --theme > file >
713
+ // auto detection > dark (auto detection itself is a later enhancement and
714
+ // currently falls back to dark inside theme.ts).
715
+ const themePath = join(homedir(), '.dsh', 'dsh-code', 'theme.json')
716
+ let themeWarning: string | undefined
717
+ if (startup.theme === undefined) {
718
+ try {
719
+ setTheme(parseThemeName(JSON.parse(readFileSync(themePath, 'utf8')).theme))
720
+ } catch (error) {
721
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
722
+ themeWarning = error instanceof Error ? error.message : String(error)
723
+ }
724
+ }
725
+ } else {
726
+ setTheme(startup.theme)
727
+ }
728
+ const saveTheme = (name: ThemeName): void => {
729
+ setTheme(name)
730
+ void settingsPersistence.save(themePath, JSON.stringify({ theme: name }, null, 2) + '\n')
731
+ .catch((writeError: unknown) => {
732
+ bridge.notify('theme save failed: ' + (writeError instanceof Error ? writeError.message : String(writeError)), 'error')
733
+ })
734
+ }
735
+
736
+ // /animation persistence: one user-level JSON file under the DSH home,
737
+ // mirroring the theme file. A missing file means animations are on; a
738
+ // corrupt file degrades to on with a surfaced warning. Only an explicit
739
+ // `false` disables (parseAnimationsPref), so hand-edited or partial files
740
+ // never silently freeze the UI.
741
+ const animationsPath = join(homedir(), '.dsh', 'dsh-code', 'animations.json')
742
+ let animationsEnabled = true
743
+ let animationsWarning: string | undefined
744
+ try {
745
+ // `?? {}` keeps a literal `null` file from surfacing a cryptic TypeError.
746
+ animationsEnabled = parseAnimationsPref((JSON.parse(readFileSync(animationsPath, 'utf8')) ?? {}).animations)
747
+ } catch (error) {
748
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
749
+ animationsWarning = error instanceof Error ? error.message : String(error)
750
+ }
751
+ }
752
+ const saveAnimations = (enabled: boolean): void => {
753
+ void settingsPersistence.save(animationsPath, JSON.stringify({ animations: enabled }, null, 2) + '\n')
754
+ .catch((writeError: unknown) => {
755
+ bridge.notify('animations save failed: ' + (writeError instanceof Error ? writeError.message : String(writeError)), 'error')
756
+ })
757
+ }
758
+
759
+ // Global input recall (Codex composer-history contract): one JSONL file
760
+ // under the DSH home. A missing file means an empty history; unreadable or
761
+ // corrupt content degrades to the valid lines it could parse, silently
762
+ // recall is a convenience surface, never a gate.
763
+ const historyPath = join(homedir(), '.dsh', 'dsh-code', 'history.jsonl')
764
+ let inputHistory: readonly string[] = []
765
+ let historyWriteChain: Promise<void> = Promise.resolve()
766
+ try {
767
+ const rawHistory = readFileSync(historyPath, 'utf8')
768
+ inputHistory = parseHistoryFile(rawHistory)
769
+ // Stale lines (adjacent duplicates, dropped garbage, an over-cap tail)
770
+ // accumulate in an append-only file; rewrite the canonical form once
771
+ // per boot. The rewrite rides the same chain, so it lands before any
772
+ // submission the user types next. An entry another terminal appends
773
+ // inside the read-to-rename window is dropped a millisecond-scale
774
+ // gap at boot that recall tolerates by design.
775
+ if (needsCompaction(rawHistory)) {
776
+ historyWriteChain = historyWriteChain
777
+ .then(() => writeFileAtomically(historyPath, serializeHistoryList(inputHistory)))
778
+ .catch(() => {})
779
+ }
780
+ } catch {
781
+ inputHistory = []
782
+ }
783
+ /**
784
+ * Serialized history writes: each submission appends one JSON line at the
785
+ * end of the file, so concurrent terminals add entries after each other
786
+ * instead of overwriting snapshots they read at their own boot. A
787
+ * multi-line draft still occupies one physical line (JSON escapes the
788
+ * newline), and a regular-length line reaches the disk as one positioned
789
+ * write; an oversized paste may interleave mid-line, which the next
790
+ * parse simply drops.
791
+ */
792
+ const recordHistory = (text: string): void => {
793
+ if (text === '') return
794
+ inputHistory = [...inputHistory, text].slice(-HISTORY_MAX_ENTRIES)
795
+ historyWriteChain = historyWriteChain
796
+ .then(() => mkdir(dirname(historyPath), { recursive: true }))
797
+ .then(() => appendFileAsync(historyPath, historyLine(text), 'utf8'))
798
+ .catch((writeError: unknown) => {
799
+ bridge.notify('history save failed: ' + (writeError instanceof Error ? writeError.message : String(writeError)), 'error')
800
+ })
801
+ }
802
+
803
+ /** Cancel one queued inbox message (Delete on the empty composer); the durable splice retires its pending row. */
804
+ const cancelQueued = (messageId: string): void => {
805
+ if (agent === undefined) return
806
+ try {
807
+ if (agent.inbox.remove(MessageId(messageId))) {
808
+ bridge.notify('queued message cancelled')
809
+ }
810
+ } catch (error: unknown) {
811
+ bridge.notify('queue cancel failed: ' + (error instanceof Error ? error.message : String(error)), 'error')
812
+ }
813
+ }
814
+
815
+ // The mount handle lives in a box: quit closes over it, while the mount
816
+ // itself is created after quit (the App element needs quit as a prop).
817
+ const mountRef: { current?: TuiMount } = {}
818
+ let quitting = false
819
+ const quit = (): void => {
820
+ if (quitting) return
821
+ quitting = true
822
+ switchQueue.cancel()
823
+ // Stale prepares/commands die with the session they were for. Aborting
824
+ // the composition signal lets a never-settling prepare reject, so the
825
+ // exit wait below cannot hang (upstream rolls the creation back).
826
+ abortPendingControllers()
827
+ quitAbort.abort()
828
+ epoch += 1
829
+ off()
830
+ for (const dispose of offCapabilitySync) dispose()
831
+ if (capabilitySyncTimer !== undefined) clearTimeout(capabilitySyncTimer)
832
+ const currentSession = session
833
+ const currentActive = active
834
+ const report = (name: string, error: unknown): void => {
835
+ internals.stderr.write(`dsh: quit ${name} failed: ${error instanceof Error ? error.message : String(error)}\n`)
836
+ }
837
+ // A throwing unmount must not strand the terminal (stdin tap alive,
838
+ // keyboard protocol stacks unpopped) or skip the exit sequence below.
839
+ try {
840
+ mountRef.current?.unmount()
841
+ } catch (error: unknown) {
842
+ report('unmount', error)
843
+ }
844
+ // One ordered cleanup: settle the visible session (if any — a bare launch
845
+ // that never composed one resolves immediately), then wait for the final
846
+ // in-flight composition (its work swallows errors and the quitting guard
847
+ // disposes any half-prepared agent), then flush the durable recall and
848
+ // the queued user-level settings writes, then request exit. `composing`
849
+ // and `historyWriteChain` are read at step run
850
+ // time, so a turn that was still being queued when quit ran is included.
851
+ // A failing step must never skip the remaining cleanup.
852
+ const steps: QuitCleanupStep[] = [
853
+ ...(currentSession === undefined || currentActive === undefined
854
+ ? []
855
+ : [
856
+ { name: 'flush', run: async () => { await sessions.flush(currentSession) } },
857
+ { name: 'dispose', run: () => currentActive.handle.dispose() },
858
+ ]),
859
+ { name: 'composing', run: () => composing ?? Promise.resolve() },
860
+ { name: 'history', run: () => historyWriteChain },
861
+ { name: 'settings', run: () => settingsPersistence.flush() },
862
+ ]
863
+ void runQuitSequence(steps, io.exit, report)
864
+ }
865
+
866
+ /** Run one slash line through the command registry (closed namespace). */
867
+ const runSlash = (line: string): void => {
868
+ const currentAgent = agent
869
+ if (currentAgent === undefined) return
870
+ if (line.startsWith('/resume ')) {
871
+ requestResume(line.slice(8).trim())
872
+ return
873
+ }
874
+ const registry = ctx.get('commands')
875
+ if (registry === undefined) {
876
+ bridge.notify('no command registry is mounted in this composition', 'error')
877
+ return
878
+ }
879
+ const controller = new AbortController()
880
+ const atEpoch = epoch
881
+ pendingControllers.add(controller)
882
+ const finish = (): void => {
883
+ pendingControllers.delete(controller)
884
+ }
885
+ // 0.1.5 registry.execute's third parameter admits submitted attachments
886
+ // (images and file receipts); the TUI composer never attaches images to a
887
+ // slash line, so every invocation is the empty batch (commands declaring
888
+ // input.attachments still run attachment-free).
889
+ void Promise.resolve().then(() => registry.execute(currentAgent, line, [], controller.signal)).then((execution) => {
890
+ finish()
891
+ // A switch/quit landed while the command ran: its fall-through must not
892
+ // reach an agent that is no longer on screen.
893
+ if (epoch !== atEpoch || agent !== currentAgent) return
894
+ if (execution === undefined) {
895
+ // No command owns this line: send it verbatim so a user-invocable
896
+ // skill gesture (`/skill-name`) reaches the host's tool-skill
897
+ // pre-step injection — the web composer's same fall-through.
898
+ try {
899
+ currentAgent.followup(createUserMessage({
900
+ content: [{ type: 'text', text: line }],
901
+ source: { kind: 'user' },
902
+ }))
903
+ } catch (error: unknown) {
904
+ bridge.notify(`command fallback failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
905
+ }
906
+ }
907
+ }, (error: unknown) => {
908
+ finish()
909
+ if (epoch !== atEpoch || agent !== currentAgent) return
910
+ bridge.notify(`command failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
911
+ })
912
+ }
913
+
914
+ /** Delivery serialization state: the chain's epoch pins it to one session. */
915
+ let deliveryChain: { epoch: number; tail: Promise<void> } = { epoch: 0, tail: Promise.resolve() }
916
+
917
+ /** Deliver one trimmed line to the live session, expanding mentions first. */
918
+ const deliverLine = (line: string, mode: 'followup' | 'steer', images: readonly ContentBlock[] = []): void => {
919
+ const currentAgent = agent!
920
+ const currentMentions = mentions!
921
+ // The command registry is a closed namespace: slash lines run out of
922
+ // band and never reach the model through this path (steering keeps the
923
+ // registry out of the inbox, so slash lines steer as literal text).
924
+ if (images.length === 0 && isSlashLine(line) && mode === 'followup') {
925
+ runSlash(line)
926
+ return
927
+ }
928
+ let parsed: ReturnType<MentionsApi['parse']>
929
+ try {
930
+ parsed = currentMentions.parse(line)
931
+ } catch (error: unknown) {
932
+ bridge.notify(`invalid session reference: ${error instanceof Error ? error.message : String(error)}`, 'error')
933
+ return
934
+ }
935
+ // Ordered delivery: the inbox order IS the user's message order. A line
936
+ // with session mentions prepares asynchronously, and a later plain line
937
+ // used to deliver synchronously past it. Every line now waits for the
938
+ // previous line of the same session; an epoch change (switch/quit)
939
+ // abandons the chain instead of gating the next session on the old one.
940
+ if (deliveryChain.epoch !== epoch) deliveryChain = { epoch, tail: Promise.resolve() }
941
+ const enqueueDelivery = (run: () => void): void => {
942
+ deliveryChain.tail = deliveryChain.tail.then(run)
943
+ }
944
+ const atEpoch = epoch
945
+ const deliver = (readable: string, context?: UserMessage): void => {
946
+ // A switch/quit landed while the snapshot was being prepared: never
947
+ // deliver to an agent that is no longer on screen.
948
+ if (epoch !== atEpoch || agent !== currentAgent) return
949
+ // Session snapshots ride the inbox as model-facing context ahead of
950
+ // the readable message (upstream README wiring: inject before the
951
+ // followup/steer that wakes the driver).
952
+ try {
953
+ if (context !== undefined) currentAgent.inject(context)
954
+ const content: ContentBlock[] = [
955
+ ...(readable === '' ? [] : [{ type: 'text' as const, text: readable }]),
956
+ ...images,
957
+ ]
958
+ const message = createUserMessage({
959
+ content,
960
+ source: { kind: 'user' },
961
+ })
962
+ if (mode === 'steer') {
963
+ // The queued message is visible as a pending transcript row (the
964
+ // web queue-mirror contract); no notice noise on the happy path.
965
+ currentAgent.steer(message)
966
+ } else {
967
+ currentAgent.followup(message)
968
+ }
969
+ } catch (error: unknown) {
970
+ bridge.notify(`${mode === 'steer' ? 'steering' : 'message'} failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
971
+ }
972
+ }
973
+ if (parsed.references.length === 0) {
974
+ enqueueDelivery(() => deliver(parsed.text))
975
+ return
976
+ }
977
+ const controller = new AbortController()
978
+ pendingControllers.add(controller)
979
+ enqueueDelivery(() => currentMentions.prepare(parsed, controller.signal).then((prepared) => {
980
+ pendingControllers.delete(controller)
981
+ deliver(prepared.text, prepared.additionalContext)
982
+ }, (error: unknown) => {
983
+ pendingControllers.delete(controller)
984
+ if (controller.signal.aborted || epoch !== atEpoch) return
985
+ bridge.notify(`session reference failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
986
+ }))
987
+ }
988
+
989
+ // Deferred first-session creation for a bare launch: the session is composed
990
+ // only when the user submits real input (or /new), and every line that
991
+ // arrives during creation is delivered in order afterwards. A creation
992
+ // failure reports and clears the queue, leaving the transient state ready
993
+ // for the next attempt.
994
+ const pendingInputs: Array<{ text: string; mode: 'followup' | 'steer'; images: readonly ContentBlock[] }> = []
995
+ // A creation is queued/running: further submissions must not mint more
996
+ // fresh sessions (their lines queue into pendingInputs instead).
997
+ let creating = false
998
+ const ensureSession = (mode?: string): void => {
999
+ if (creating) return
1000
+ creating = true
1001
+ void compose(async () => {
1002
+ try {
1003
+ // A direct `/mode <preset>` resolves asynchronously. Preserve submit
1004
+ // order so the first composition cannot race ahead with the old mode.
1005
+ await pendingModeWork
1006
+ // Another composition (e.g. a /resume activated while this creation
1007
+ // waited its turn) may have published a session already: deliver the
1008
+ // queued lines there instead of minting a competing fresh session
1009
+ // (which would orphan the live one without a dispose).
1010
+ if (session !== undefined) {
1011
+ const queued = pendingInputs.splice(0)
1012
+ for (const item of queued) deliverLine(item.text, item.mode, item.images)
1013
+ return
1014
+ }
1015
+ const next = await prepare({
1016
+ sessionId: `session-${randomUUID()}`,
1017
+ resume: false,
1018
+ ...(mode === undefined ? {} : { mode }),
1019
+ })
1020
+ if (quitting) {
1021
+ void next.handle.dispose().catch(() => {})
1022
+ return
1023
+ }
1024
+ const previous = { active, agent, session, store, mentions }
1025
+ try {
1026
+ active = next
1027
+ agent = next.agent
1028
+ session = next.session
1029
+ store = next.store
1030
+ mentions = next.mentions
1031
+ subagents.reset()
1032
+ pendingMode = undefined
1033
+ pendingPermission = undefined
1034
+ commands.setAgent(agent)
1035
+ skills.setAgent(agent)
1036
+ // The App mounts with a placeholder key until the first input; the
1037
+ // key-change remount below must start from a clean screen or the ghost
1038
+ // static header stays visible above the new one (same source-backed
1039
+ // clear the session-switch path performs).
1040
+ process.stdout.write('\x1b[r\x1b[0m\x1b[H\x1b[2J\x1b[3J\x1b[H')
1041
+ renderCurrent()
1042
+ } catch (error: unknown) {
1043
+ // The session composed but the screen handoff threw (stdout EPIPE,
1044
+ // a render-time failure). Roll the published state back exactly
1045
+ // like the switch path does otherwise the runner reports "session
1046
+ // creation failed" while the new session is actually live, clears
1047
+ // the queued inputs, and every later line lands in the ghost. The
1048
+ // queued inputs are KEPT for the next attempt.
1049
+ active = previous.active
1050
+ agent = previous.agent
1051
+ session = previous.session
1052
+ store = previous.store === undefined ? createTranscriptStore() : previous.store
1053
+ mentions = previous.mentions === undefined ? createMentions(ctx, undefined, cwd) : previous.mentions
1054
+ if (agent !== undefined) {
1055
+ commands.setAgent(agent)
1056
+ skills.setAgent(agent)
1057
+ }
1058
+ await next.handle.dispose().catch(() => {})
1059
+ if (!quitting) renderCurrent()
1060
+ bridge.notify(`session activation failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1061
+ return
1062
+ }
1063
+ abortPendingControllers()
1064
+ epoch += 1
1065
+ const queued = pendingInputs.splice(0)
1066
+ for (const item of queued) deliverLine(item.text, item.mode, item.images)
1067
+ } finally {
1068
+ creating = false
1069
+ }
1070
+ }).catch((error: unknown) => {
1071
+ pendingInputs.length = 0
1072
+ bridge.notify(`session creation failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1073
+ })
1074
+ }
1075
+
1076
+ /** Deliver one readable line to the agent, expanding session mentions first. */
1077
+ const sendNow = (text: string, mode: 'followup' | 'steer', images: readonly ContentBlock[] = []): void => {
1078
+ // Blank check on the trimmed form; the payload itself keeps the draft's
1079
+ // exact whitespace unless the line is a syntactic slash command.
1080
+ const line = submissionPayload(text)
1081
+ if (line.trim() === '' && images.length === 0) return
1082
+ if (images.length === 0 && line.startsWith('/mode ')) {
1083
+ void switchModeAction(line.slice(6).trim()).then(
1084
+ selected => bridge.notify(`mode → ${selected}`),
1085
+ error => bridge.notify(`mode switch failed: ${error instanceof Error ? error.message : String(error)}`, 'error'),
1086
+ )
1087
+ return
1088
+ }
1089
+ if (images.length === 0 && line.startsWith('/permission ')) {
1090
+ try {
1091
+ const selected = setPermissionAction(line.slice(12).trim())
1092
+ bridge.notify(`permission → ${selected}`)
1093
+ } catch (error: unknown) {
1094
+ bridge.notify(`permission change failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1095
+ }
1096
+ return
1097
+ }
1098
+ if (session === undefined) {
1099
+ pendingInputs.push({ text: line, mode, images })
1100
+ ensureSession()
1101
+ return
1102
+ }
1103
+ deliverLine(line, mode, images)
1104
+ }
1105
+
1106
+ // Startup serialization: input submitted while the startup prompt/images
1107
+ // are still preparing queues behind the initial request.
1108
+ const inputGate = new StartupInputGate(({ text, mode, images }) => sendNow(text, mode, images))
1109
+ const send = (text: string, mode: 'followup' | 'steer', images: readonly ContentBlock[] = []): void => {
1110
+ inputGate.submit({ text, mode, images })
1111
+ }
1112
+
1113
+ /** Dispatch one submitted line: slash commands to the registry, other text to the agent. */
1114
+ const dispatch = (text: string, images: readonly ContentBlock[] = [], origin?: string): void => {
1115
+ // An attachment prepare resolved after the app remounted onto another
1116
+ // session (queued switch): the composing session is gone, so the stale
1117
+ // delivery is dropped instead of landing in the new session's inbox.
1118
+ if (!submissionBelongsToSession(origin, session?.id)) return
1119
+ send(text, 'followup', images)
1120
+ }
1121
+
1122
+ /**
1123
+ * Submit steering: a running driver consumes the text at its next step
1124
+ * boundary (the inbox delivers between steps); an idle driver just starts
1125
+ * a turn, so this doubles as the busy-state submit path.
1126
+ */
1127
+ const steer = (text: string, images: readonly ContentBlock[] = [], origin?: string): void => {
1128
+ if (!submissionBelongsToSession(origin, session?.id)) return
1129
+ send(text, 'steer', images)
1130
+ }
1131
+
1132
+ /** Interrupt the running turn (Esc); true when a turn was actually cancelled. */
1133
+ const interrupt = (): boolean => {
1134
+ if (agent === undefined || agent.status !== 'running') return false
1135
+ try {
1136
+ agent.cancel({ kind: 'user' })
1137
+ bridge.notify('turn cancelled — Ctrl+C or /quit to exit')
1138
+ return true
1139
+ } catch (error: unknown) {
1140
+ bridge.notify(`cancel failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1141
+ return false
1142
+ }
1143
+ }
1144
+
1145
+ /** Select one permission preset before the first session or on the active one. */
1146
+ const setPermissionAction = (id: string): string => {
1147
+ if (permissionPresets === undefined || permissionPresets.names.length === 0) {
1148
+ throw new Error('permission presets are not mounted in this composition')
1149
+ }
1150
+ if (id === '') throw new Error('usage: /permission <preset>')
1151
+ const selected = selectPermission(permissionPresets, session, id)
1152
+ if (session === undefined) {
1153
+ pendingPermission = selected
1154
+ renderCurrent()
1155
+ }
1156
+ return selected
1157
+ }
1158
+
1159
+ /**
1160
+ * Cycle to the next permission preset (Shift+Tab). Before the first session,
1161
+ * the choice remains process-local and is materialized when Harness creates
1162
+ * that session; afterwards the canonical service writes durable events.
1163
+ */
1164
+ const cyclePermission = (): string => {
1165
+ if (permissionPresets === undefined || permissionPresets.names.length === 0) {
1166
+ bridge.notify('permission presets are not mounted in this composition', 'warning')
1167
+ return ''
1168
+ }
1169
+ try {
1170
+ const next = cyclePermissionPreset(permissionPresets, session, pendingPermission)
1171
+ if (session === undefined && next !== '') {
1172
+ pendingPermission = next
1173
+ renderCurrent()
1174
+ }
1175
+ return next
1176
+ } catch (error: unknown) {
1177
+ bridge.notify(`permission change failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1178
+ return ''
1179
+ }
1180
+ }
1181
+
1182
+ /**
1183
+ * Apply one /model selection: takes effect from the next assembled step.
1184
+ * The optional reasoning effort must be one the row advertises (the picker
1185
+ * only offers those), so an unsupported value cannot reach the request
1186
+ * pipeline; an absent effort restores the model's own default.
1187
+ */
1188
+ const selectModel = (row: ModelRow, effortId?: string): string => {
1189
+ const selection = buildModelSelection(row, effortId)
1190
+ if (active === undefined) {
1191
+ // A bare launch has no session yet: keep the pick process-wide so the
1192
+ // first composed session starts from it.
1193
+ pendingSelection = selection
1194
+ } else {
1195
+ active.selection.picked = selection
1196
+ }
1197
+ // Global default (web selectModel parity): every pick is persisted as the
1198
+ // deployment default through the same agentDefaultModel service the web
1199
+ // host writes, so the choice survives restarts and other surfaces read
1200
+ // it. Save failures degrade to a notice the in-session switch already
1201
+ // took effect and must not roll back (the web contract).
1202
+ void defaultModel.saveSelection(selection).catch((error: unknown) => {
1203
+ bridge.notify(`model switch applies to this session but was not saved as the default: ${error instanceof Error ? error.message : String(error)}`, 'warning')
1204
+ })
1205
+ // Advisory immediate validation (web selectModel parity): run the same
1206
+ // local resolveCallConfig check the request pipeline would, so a stale
1207
+ // directory an effort the adapter withdrew since /model loaded —
1208
+ // surfaces as a pick-time notice instead of failing the next assembled
1209
+ // step. Best-effort: an llm service without the resolver keeps the
1210
+ // existing request-boundary rejection. Called as a method (`this`-bound)
1211
+ // like resolveModelInfo in models.ts.
1212
+ const llm = ctx.get('llm')
1213
+ const resolveCallConfig = (llm as {
1214
+ resolveCallConfig?: (this: unknown, config: { provider: string; model: string; reasoningEffort?: string }) => Promise<unknown>
1215
+ } | undefined)?.resolveCallConfig
1216
+ if (llm !== undefined && typeof resolveCallConfig === 'function') {
1217
+ void Promise.resolve(resolveCallConfig.call(llm, {
1218
+ provider: selection.provider,
1219
+ model: selection.model,
1220
+ ...selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort },
1221
+ })).catch((error: unknown) => {
1222
+ bridge.notify(`model selection rejected: ${error instanceof Error ? error.message : String(error)} reopen /model to pick again`, 'error')
1223
+ })
1224
+ }
1225
+ return `${row.provider}/${row.model}`
1226
+ }
1227
+
1228
+ /** The /subagent override label, '' when delegated agents follow the current model. */
1229
+ const subagentModelLabel = (): string => subagentOverride === undefined ? '' : modelSelectionLabel(subagentOverride)
1230
+
1231
+ /** Apply one /subagent model pick; returns the override label. */
1232
+ const setSubagentModel = (row: ModelRow, effortId?: string): string => {
1233
+ subagentOverride = buildModelSelection(row, effortId)
1234
+ renderCurrent()
1235
+ return modelSelectionLabel(subagentOverride)
1236
+ }
1237
+
1238
+ /** Drop the /subagent override: delegated agents follow the current model again. */
1239
+ const clearSubagentModel = (): void => {
1240
+ subagentOverride = undefined
1241
+ renderCurrent()
1242
+ }
1243
+
1244
+ /**
1245
+ * Export the folded transcript to a markdown file (/export). The default
1246
+ * target sits beside the session's cwd so the file lands in the user's
1247
+ * workspace; an absolute or cwd-relative argument overrides it.
1248
+ */
1249
+ const exportTranscript = async (argument: string): Promise<void> => {
1250
+ if (session === undefined) {
1251
+ bridge.notify('no session yet — submit a message to start', 'warning')
1252
+ return
1253
+ }
1254
+ const wanted = argument.trim()
1255
+ const sessionCwd = session.header.cwd ?? cwd
1256
+ // The default name derives from the session id, which `--session` lets the
1257
+ // user spell freely: reduce it to filename-safe characters first so the
1258
+ // default target can never escape the session cwd.
1259
+ const defaultName = `dsh-session-${exportSessionIdSuffix(session.id)}.md`
1260
+ const target = wanted === ''
1261
+ ? join(sessionCwd, defaultName)
1262
+ : /^[a-zA-Z]:[\\/]/u.test(wanted) || wanted.startsWith('/')
1263
+ ? wanted
1264
+ : join(sessionCwd, wanted)
1265
+ const markdown = buildExportMarkdown(store.getView(), session.id)
1266
+ try {
1267
+ await writeFileAsync(target, `${markdown}\n`, 'utf8')
1268
+ bridge.notify(`exported to ${target}`)
1269
+ } catch (error: unknown) {
1270
+ bridge.notify(`export failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1271
+ }
1272
+ }
1273
+
1274
+ /**
1275
+ * Rename the session (/title): a user title pins the session and stops
1276
+ * automatic generation (the service's own contract). The appended
1277
+ * `session/title` event flows back through the store into the status line.
1278
+ */
1279
+ const renameTitle = (argument: string): string => {
1280
+ const title = argument.trim()
1281
+ if (title === '') return 'usage: /title <text>'
1282
+ if (session === undefined) return 'no session yet — submit a message to start'
1283
+ const service = ctx.get('sessionTitle')
1284
+ if (service === undefined) return 'session titles are unavailable in this profile'
1285
+ try {
1286
+ service.rename(session, title)
1287
+ return `title ${title}`
1288
+ } catch (error: unknown) {
1289
+ return `rename failed: ${error instanceof Error ? error.message : String(error)}`
1290
+ }
1291
+ }
1292
+
1293
+ const loadSessions = async (options: SessionDirectoryOptions, signal?: AbortSignal): Promise<readonly SessionRow[]> => {
1294
+ if (sessionQuery === undefined) throw new Error('session query is unavailable in this profile')
1295
+ const records = await sessionQuery.listSessions(signal)
1296
+ // Last-activity timestamps for sorting (codex UpdatedAt default): the
1297
+ // newest generation artifact's mtime under the JSONL layout. 0.1.5 dropped
1298
+ // the persistence `locate()` query, so paths are derived from the
1299
+ // backend's public config root. Backends without a JSONL config (or
1300
+ // vanished directories) fall back to createdAt inside the projection.
1301
+ const root = jsonlSessionRoot(persistence)
1302
+ const updated = new Map<string, number>()
1303
+ if (root !== undefined) {
1304
+ await Promise.all(records.map(async record => {
1305
+ try {
1306
+ const dir = sessionDirectoryFor(root, record.header.cwd, record.header.id)
1307
+ const entries = await readdir(dir, { withFileTypes: true })
1308
+ const stats = await Promise.all(
1309
+ entries.filter(entry => entry.isFile() && isSessionArtifactName(entry.name))
1310
+ .map(entry => stat(join(dir, entry.name))),
1311
+ )
1312
+ const newest = Math.max(...stats.map(info => info.mtimeMs))
1313
+ if (Number.isFinite(newest)) updated.set(record.header.id, newest)
1314
+ } catch {
1315
+ // Artifact gone or unreadable: the projection falls back to createdAt.
1316
+ }
1317
+ }))
1318
+ }
1319
+ const projected = projectSessionRows(records, options, updated)
1320
+ // Titles are the expensive fold. Fetch only the first bounded picker page;
1321
+ // navigation/filter changes trigger a fresh, cancellable observation.
1322
+ const page = projected.slice(0, 32)
1323
+ if (page.length === 0) return projected
1324
+ const observations = await sessionQuery.readTitleSnapshots(page.map(row => row.id), signal)
1325
+ return mergeSessionTitles(projected, observations)
1326
+ }
1327
+
1328
+ /**
1329
+ * Delete one session subtree (/delete, codex semantics: subagent threads go
1330
+ * with their root). The kernel persistence seam has NO deletion API by
1331
+ * design — logs accumulate "until removed externally" — so this is the
1332
+ * controlled external removal, in three phases with a hard boundary
1333
+ * between planning and touching the filesystem:
1334
+ *
1335
+ * 1. `planSessionDeletion` collects the subtree and refuses when the root
1336
+ * or ANY member is live (a live child would outlive its deleted
1337
+ * parent), ordering the plan children-first.
1338
+ * 2. Every plan node must derive to a guarded artifact directory
1339
+ * (`encodeSegment(id)` layout beneath the backend's config root).
1340
+ * Backends without a derivable artifact (non-JSONL) refuse the WHOLE
1341
+ * deletion here — no file has been touched yet, so a backend or layout
1342
+ * surprise can never strand a half-deleted subtree.
1343
+ * 3. Artifacts are removed children-first: only an I/O error mid-delete
1344
+ * can stop it short (reported with removed/total counts), leaving the
1345
+ * shallowest lineage intact.
1346
+ *
1347
+ * @param id - the root session id to delete.
1348
+ * @returns the outcome line for the panel/notice.
1349
+ */
1350
+ const deleteSession = async (id: string): Promise<string> => {
1351
+ if (sessionQuery === undefined) return 'session query is unavailable in this profile'
1352
+ if (session !== undefined && session.id === id) return 'cannot delete the session you are using — switch or /new first'
1353
+ const records = await sessionQuery.listSessions()
1354
+ const plan = planSessionDeletion(records, id)
1355
+ if (!plan.ok) return plan.reason
1356
+ // Phase 2 completes the plan before the first rm: derive and
1357
+ // layout-check every node up front, so a refusal never leaves a
1358
+ // partially removed subtree behind.
1359
+ const root = jsonlSessionRoot(persistence)
1360
+ if (root === undefined) {
1361
+ return 'session backend exposes no deletable artifact (deletion is unsupported on this backend)'
1362
+ }
1363
+ const byId = new Map<string, (typeof records)[number]>(records.map(record => [record.header.id, record]))
1364
+ const dirs = new Map<string, string>()
1365
+ for (const node of plan.nodes) {
1366
+ const record = byId.get(node.id)
1367
+ if (record === undefined) return `no persisted session matches "${node.id}"`
1368
+ const dir = sessionArtifactDirectory(sessionDirectoryFor(root, record.header.cwd, node.id), node.id)
1369
+ if (dir === undefined) {
1370
+ return `refusing to delete: unexpected artifact layout for ${node.id.slice(-12)}`
1371
+ }
1372
+ dirs.set(node.id, dir)
1373
+ }
1374
+ let removed = 0
1375
+ for (const node of plan.nodes) {
1376
+ const dir = dirs.get(node.id)!
1377
+ try {
1378
+ // Remove every canonical generation artifact this build knows; other
1379
+ // sibling files are never ours to delete, and the directory itself is
1380
+ // only removed once empty. An unreadable directory counts as a
1381
+ // failure (not a silent success) so the outcome line stays honest.
1382
+ const entries = await readdir(dir, { withFileTypes: true })
1383
+ for (const entry of entries) {
1384
+ if (entry.isFile() && isSessionArtifactName(entry.name)) {
1385
+ await rm(join(dir, entry.name), { force: true })
1386
+ }
1387
+ }
1388
+ await rm(dir, { force: true, recursive: false }).catch(() => {})
1389
+ removed += 1
1390
+ } catch (error: unknown) {
1391
+ return `delete failed for ${node.id.slice(-12)} after ${removed} of ${plan.nodes.length}: ${error instanceof Error ? error.message : String(error)}`
1392
+ }
1393
+ }
1394
+ return `deleted ${removed} session${removed === 1 ? '' : 's'}`
1395
+ }
1396
+
1397
+ const loadSessionTranscript = async (id: string, signal?: AbortSignal): Promise<string> => {
1398
+ if (sessionQuery === undefined) throw new Error('session query is unavailable in this profile')
1399
+ const snapshot = await sessionQuery.readSession(id, signal)
1400
+ return buildExportMarkdown(createTranscriptStore(snapshot.events).getView(), snapshot.session.id)
1401
+ }
1402
+
1403
+ const switchModeAction = async (id: string): Promise<string> => {
1404
+ if (id === '') throw new Error('usage: /mode <preset>')
1405
+ const currentAgent = agent
1406
+ if (currentAgent === undefined) {
1407
+ const choice = pendingModeWork.then(async () => {
1408
+ const preset = await selectPreset(presets, undefined, id)
1409
+ // A resume may have won while this roster read was in flight; never
1410
+ // leak the old pending choice into a later /new session.
1411
+ if (agent === undefined) {
1412
+ pendingMode = preset.id
1413
+ renderCurrent()
1414
+ }
1415
+ return preset.id
1416
+ })
1417
+ pendingModeWork = choice.then(() => {}, () => {})
1418
+ return choice
1419
+ }
1420
+
1421
+
1422
+ // Serialize the recomposition with session activations: a /mode that
1423
+ // interleaves a switch must not rebind the shared command/skill
1424
+ // registries while the switch is composing the next agent.
1425
+ const currentActive = active
1426
+ const atEpoch = epoch
1427
+ let selected: string | undefined
1428
+ await compose(async () => {
1429
+ const preset = await selectPreset(presets, currentAgent, id)
1430
+ // A switch/quit landed while the recomposition ran: applying here
1431
+ // would write the old choice into the new session's state and rebind
1432
+ // the registries back to a disposed agent. The preset-selection log
1433
+ // entry rode the old agent's session; only the local application is
1434
+ // dropped.
1435
+ if (epoch !== atEpoch || agent !== currentAgent || active !== currentActive) {
1436
+ throw new Error('session changed while switching mode — nothing applied; retry in the active session')
1437
+ }
1438
+ if (active === undefined) throw new Error('active Agent has no session state')
1439
+ active.mode = preset.id
1440
+ commands.setAgent(currentAgent)
1441
+ skills.setAgent(currentAgent)
1442
+ selected = preset.id
1443
+ renderCurrent()
1444
+ })
1445
+ return selected!
1446
+ }
1447
+
1448
+ interface PendingSwitch { readonly target: Target; readonly label: string }
1449
+
1450
+ const activate = (nextTarget: Target): Promise<void> => {
1451
+ if (quitting) return Promise.resolve()
1452
+ // Serialized with every other composition (bare-launch creation, queued
1453
+ // switches): at most one agent is composed at a time.
1454
+ return compose(async () => {
1455
+ const previous = active
1456
+ const next = await prepare(nextTarget)
1457
+ // Quit landed while the next session was being composed: dispose the
1458
+ // half-ready agent and leave the current session untouched.
1459
+ if (quitting) {
1460
+ await next.handle.dispose().catch(() => {})
1461
+ return
1462
+ }
1463
+ active = next
1464
+ agent = next.agent
1465
+ session = next.session
1466
+ store = next.store
1467
+ mentions = next.mentions
1468
+ commands.setAgent(agent)
1469
+ skills.setAgent(agent)
1470
+ try {
1471
+ process.stdout.write('\x1b[r\x1b[0m\x1b[H\x1b[2J\x1b[3J\x1b[H')
1472
+ renderCurrent()
1473
+ // Only a successful handoff may clear the transient per-session
1474
+ // surfaces: a rolled-back switch keeps the previous session's
1475
+ // subagent feed plus the user's pre-session /mode and permission
1476
+ // picks (the bare-launch promise: explicit choices survive until
1477
+ // composition takes them).
1478
+ subagents.reset()
1479
+ pendingMode = undefined
1480
+ pendingPermission = undefined
1481
+ } catch (error: unknown) {
1482
+ active = previous
1483
+ agent = previous?.agent
1484
+ session = previous?.session
1485
+ store = previous === undefined ? createTranscriptStore() : previous.store
1486
+ mentions = previous === undefined ? createMentions(ctx, undefined, cwd) : previous.mentions
1487
+ if (agent !== undefined) commands.setAgent(agent)
1488
+ if (agent !== undefined) skills.setAgent(agent)
1489
+ await next.handle.dispose()
1490
+ if (!quitting) renderCurrent()
1491
+ throw error
1492
+ }
1493
+ // From here the new session is live: in-flight prepares/commands for
1494
+ // the previous agent are stale and must be aborted and ignored.
1495
+ abortPendingControllers()
1496
+ epoch += 1
1497
+ // No previous session (a bare launch switched straight into a resume):
1498
+ // nothing to flush or dispose, so just confirm the activation.
1499
+ if (previous === undefined) {
1500
+ // The key-change remount above swaps the App in this same synchronous
1501
+ // continuation; the new App registers its bridge.notify in a passive
1502
+ // effect AFTER it, so an immediate notice reaches the UNMOUNTED
1503
+ // instance and React drops it silently. Defer past the commit.
1504
+ setTimeout(() => {
1505
+ bridge.notify(`${next.resumed ? 'resumed' : 'created'} ${next.session.id.slice(-12)} · mode ${next.mode}`)
1506
+ }, 0)
1507
+ return
1508
+ }
1509
+ let cleanupWarning: string | undefined
1510
+ try {
1511
+ await sessions.flush(previous.session)
1512
+ } catch (error: unknown) {
1513
+ cleanupWarning = `previous session flush failed: ${error instanceof Error ? error.message : String(error)}`
1514
+ }
1515
+ try {
1516
+ await previous.handle.dispose()
1517
+ } catch (error: unknown) {
1518
+ cleanupWarning = `${cleanupWarning === undefined ? '' : `${cleanupWarning}; `}previous agent release failed: ${error instanceof Error ? error.message : String(error)}`
1519
+ }
1520
+ bridge.notify(cleanupWarning === undefined
1521
+ ? `${next.resumed ? 'resumed' : 'created'} ${next.session.id.slice(-12)} · mode ${next.mode}`
1522
+ : `switched to ${next.session.id.slice(-12)}, but ${cleanupWarning}`,
1523
+ cleanupWarning === undefined ? 'info' : 'warning')
1524
+ })
1525
+ }
1526
+
1527
+ const switchQueue = new SessionSwitchQueue<PendingSwitch>(
1528
+ async request => { if (!quitting) await activate(request.target) },
1529
+ error => bridge.notify(`session switch failed: ${error instanceof Error ? error.message : String(error)}`, 'error'),
1530
+ )
1531
+
1532
+ const requestSwitch = (request: PendingSwitch): void => {
1533
+ if (session === undefined) {
1534
+ // No session yet (a bare launch using /resume before any input): activate
1535
+ // the target directly — there is no running turn to wait on and nothing
1536
+ // to flush.
1537
+ void activate(request.target).catch((error: unknown) => {
1538
+ bridge.notify(`session switch failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1539
+ })
1540
+ return
1541
+ }
1542
+ if (request.target.sessionId === session.id) {
1543
+ bridge.notify('that session is already active', 'warning')
1544
+ return
1545
+ }
1546
+ const outcome = switchQueue.request(agent!, request)
1547
+ if (outcome === 'queued') {
1548
+ bridge.notify(`will switch to ${request.label} when the current turn finishes · /resume cancel to abort`)
1549
+ }
1550
+ }
1551
+
1552
+ const resolveResumeId = async (wanted: string): Promise<string> => {
1553
+ if (wanted === '') throw new Error('usage: /resume <id|prefix>')
1554
+ if (sessionQuery === undefined) throw new Error('session query is unavailable in this profile')
1555
+ const records = await sessionQuery.listSessions()
1556
+ const exact = records.filter(record => record.header.id === wanted)
1557
+ const matches = exact.length > 0 ? exact : records.filter(record => record.header.id.startsWith(wanted))
1558
+ if (matches.length === 0) throw new Error(`no session matches "${wanted}"`)
1559
+ if (matches.length > 1) throw new Error(`session prefix "${wanted}" is ambiguous (${matches.length} matches)`)
1560
+ const matched = matches[0]!
1561
+ // Same lineage gate as the CLI --resume path and the picker.
1562
+ if (isSubagentSession(matched.header)) {
1563
+ throw new Error('subagent conversations are read-only; resume a root session')
1564
+ }
1565
+ if (session !== undefined && agents.get(SessionId(matched.header.id)) !== undefined && matched.header.id !== session.id) {
1566
+ throw new Error('that session is already live in another owner')
1567
+ }
1568
+ return matched.header.id
1569
+ }
1570
+
1571
+ const requestResume = (wanted: string): void => {
1572
+ void resolveResumeId(wanted).then(id => {
1573
+ requestSwitch({ target: { sessionId: id, resume: true }, label: id.slice(-12) })
1574
+ }, (error: unknown) => bridge.notify(`resume failed: ${error instanceof Error ? error.message : String(error)}`, 'error'))
1575
+ }
1576
+
1577
+ const createSession = (mode?: string): void => {
1578
+ // /new before any input is the first-session creation itself, not a switch.
1579
+ if (session === undefined) {
1580
+ ensureSession(mode)
1581
+ return
1582
+ }
1583
+ const nextCwd = session.header.cwd ?? cwd
1584
+ const id = `session-${randomUUID()}`
1585
+ requestSwitch({ target: { sessionId: id, resume: false, mode, cwd: nextCwd }, label: id.slice(-12) })
1586
+ }
1587
+
1588
+ const reviewChanges = (argument: string): void => {
1589
+ // Works from a bare launch too: with no session yet the read-only
1590
+ // choice goes to pendingPermission (materialized when the first
1591
+ // session composes) and the review prompt queues behind that
1592
+ // creation exactly like a typed first submission. The identity guard
1593
+ // below still aborts a load that outlives a mid-flight switch —
1594
+ // including one landing on an undefined agent.
1595
+ const currentAgent = agent
1596
+ // The diff loads from the CALLING session's cwd; capture that
1597
+ // workspace and this turn's identity so a switch mid-load can neither
1598
+ // flip the new session read-only nor send the old workspace's review
1599
+ // into it. The controller rides pendingControllers, so a switch/quit
1600
+ // kills the git subprocess itself instead of only ignoring its result.
1601
+ const atEpoch = epoch
1602
+ const reviewCwd = session?.header.cwd ?? cwd
1603
+ const controller = new AbortController()
1604
+ pendingControllers.add(controller)
1605
+ const finish = (): void => {
1606
+ pendingControllers.delete(controller)
1607
+ }
1608
+ void loadGitDiff(reviewCwd, argument, controller.signal).then(({ title, files }) => {
1609
+ finish()
1610
+ if (controller.signal.aborted || epoch !== atEpoch || agent !== currentAgent) return
1611
+ try {
1612
+ setPermissionAction('read-only')
1613
+ } catch (error: unknown) {
1614
+ bridge.notify(`review unavailable: ${error instanceof Error ? error.message : String(error)}`, 'error')
1615
+ return
1616
+ }
1617
+ send(buildReviewPrompt(files.flatMap(file => file.lines).join('\n'), title), 'followup')
1618
+ bridge.notify('review started under read-only permissions')
1619
+ }, (error: unknown) => {
1620
+ finish()
1621
+ if (controller.signal.aborted || epoch !== atEpoch) return
1622
+ bridge.notify(`review failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1623
+ })
1624
+ }
1625
+
1626
+ const forkSession = (argument: string): void => {
1627
+ if (session === undefined || active === undefined) {
1628
+ bridge.notify('no session yet - submit a message to start', 'warning')
1629
+ return
1630
+ }
1631
+ try {
1632
+ const text = argument.trim()
1633
+ const atSeq = text === '' ? undefined : Number(text)
1634
+ if (text !== '' && (!Number.isSafeInteger(atSeq) || (atSeq ?? -1) < 0)) {
1635
+ throw new Error('usage: /fork [event-seq]')
1636
+ }
1637
+ const seed = selectForkSeed(session.snapshotEvents(), atSeq)
1638
+ const id = `session-${randomUUID()}`
1639
+ requestSwitch({
1640
+ target: {
1641
+ sessionId: id,
1642
+ resume: false,
1643
+ mode: active.mode,
1644
+ cwd: session.header.cwd ?? cwd,
1645
+ seed: seed.events,
1646
+ parentSession: session.id,
1647
+ seedLength: seed.events.length,
1648
+ },
1649
+ label: id.slice(-12),
1650
+ })
1651
+ } catch (error: unknown) {
1652
+ bridge.notify(`fork failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1653
+ }
1654
+ }
1655
+
1656
+ const switchSession = (row: SessionRow): void => {
1657
+ if (!row.resumable) {
1658
+ bridge.notify('subagent conversations are read-only', 'warning')
1659
+ return
1660
+ }
1661
+ requestSwitch({ target: { sessionId: row.id, resume: true }, label: row.title ?? row.id.slice(-12) })
1662
+ }
1663
+
1664
+ const cancelSessionSwitch = (): boolean => {
1665
+ return switchQueue.cancel()
1666
+ }
1667
+
1668
+ const appElement = (): ReturnType<typeof createElement> => {
1669
+ // A bare launch mounts with pending/default model, mode, and permission
1670
+ // facts until the first input composes the real session. These choices stay
1671
+ // process-local and create no durable state before that composition.
1672
+ const sessionCwd = session?.header.cwd ?? cwd
1673
+ const currentView = store.getView()
1674
+ const defaults = currentDefaults()
1675
+ const model = currentView.model !== ''
1676
+ ? currentView.model
1677
+ : pendingSelection !== undefined
1678
+ ? `${pendingSelection.provider}/${pendingSelection.model}`
1679
+ : `${defaults.provider}/${defaults.model}`
1680
+ const effort = resolveEffectiveSelection(
1681
+ active?.selection.picked ?? pendingSelection,
1682
+ session?.requestHeader()?.config,
1683
+ defaults,
1684
+ ).reasoningEffort
1685
+ const permission = permissionPresets === undefined
1686
+ ? currentView.permission
1687
+ : effectivePermission(permissionPresets, session, pendingPermission)
1688
+ return createElement(App, {
1689
+ key: session?.id ?? 'pending',
1690
+ sessionKey: session?.id ?? '',
1691
+ store,
1692
+ approval,
1693
+ questions,
1694
+ subagents,
1695
+ commands,
1696
+ skills,
1697
+ model,
1698
+ effort,
1699
+ cwd: basename(sessionCwd),
1700
+ workspaceRoot: sessionCwd,
1701
+ branch: gitBranch(sessionCwd),
1702
+ sessionId: session === undefined ? '' : session.id.slice(-8),
1703
+ resumed: active?.resumed ?? false,
1704
+ mode: active?.mode ?? pendingMode ?? normalizePresetId(presets.defaultId),
1705
+ permission,
1706
+ dispatch,
1707
+ steer,
1708
+ interrupt,
1709
+ quit,
1710
+ loadModels: () => loadModelDirectory(ctx),
1711
+ loadModelProviders: () => loadProviderSettings(ctx),
1712
+ subscribeModelProviders: listener => subscribeProviderSettings(ctx, listener),
1713
+ saveModelProviderCredential: (target, key) => saveProviderCredential(ctx, target, key),
1714
+ saveModelProviderConfiguration: (target, configuration) => saveProviderConfiguration(ctx, target, configuration),
1715
+ discoverModelProvider: (target, request, signal) => discoverProviderModels(ctx, target, request, signal),
1716
+ unsetModelProviderCredential: target => unsetProviderCredential(ctx, target),
1717
+ removeModelProvider: target => removeProviderSettings(ctx, target),
1718
+ loadProviderAuthorizations: () => loadProviderAuthorizations(ctx),
1719
+ subscribeProviderAuthorizations: listener => subscribeProviderAuthorizations(ctx, listener),
1720
+ beginProviderAuthorization: (row, method, interaction, signal) => (
1721
+ beginProviderAuthorization(ctx, row, method, interaction, signal)
1722
+ ),
1723
+ cancelProviderAuthorization: row => cancelProviderAuthorization(ctx, row.key),
1724
+ logoutProviderAuthorization: row => logoutProviderAuthorization(ctx, row),
1725
+ openAuthorizationUrl,
1726
+ copyTextValue: copyText,
1727
+ loadMentions: (query: string, signal?: AbortSignal) => mentions.candidates(query, signal),
1728
+ inspectImages: paths => inspectImagePaths(paths, ctx.get('attachments'), session?.header.cwd ?? cwd),
1729
+ prepareImages: (paths, signal) => saveImagePaths(paths, ctx.get('attachments'), signal),
1730
+ inspectFiles: paths => inspectFilePaths(paths, ctx.get('attachments'), session?.header.cwd ?? cwd),
1731
+ prepareFiles: (paths, signal) => saveFilePaths(paths, ctx.get('attachments'), signal),
1732
+ cyclePermission,
1733
+ setPermission: setPermissionAction,
1734
+ selectModel,
1735
+ subagentModel: subagentModelLabel(),
1736
+ setSubagentModel,
1737
+ clearSubagentModel,
1738
+ deleteSession,
1739
+ exportTranscript,
1740
+ renameTitle,
1741
+ copyLastResponse,
1742
+ loadGitDiff: (argument: string) => loadGitDiff(session?.header.cwd ?? cwd, argument),
1743
+ reviewChanges,
1744
+ loadPresets: () => presets.list(),
1745
+ switchMode: switchModeAction,
1746
+ loadPermissions: () => permissionPresets === undefined
1747
+ ? Promise.reject(new Error('permission presets are not mounted in this composition'))
1748
+ : Promise.resolve(listPermissionRows(permissionPresets)),
1749
+ createSession,
1750
+ forkSession,
1751
+ loadSessions,
1752
+ loadSessionTranscript,
1753
+ loadSubagents: () => {
1754
+ const current = session
1755
+ if (current === undefined || sessionQuery === undefined) return Promise.resolve([])
1756
+ return loadSessions({ sessions: 'all', cwd: 'all', sort: 'newest', currentCwd: current.header.cwd ?? cwd, query: '' })
1757
+ .then(rows => rows.filter(row => row.parent === current.id && row.subagent))
1758
+ },
1759
+ switchSession,
1760
+ cancelSessionSwitch,
1761
+ loadPlugins: () => listPluginRows(ctx),
1762
+ loadJobs: () => listJobs(ctx, active?.agent),
1763
+ statusline: statuslineItems,
1764
+ saveStatusline,
1765
+ applyEditorKeys,
1766
+ saveTheme,
1767
+ animations: animationsEnabled,
1768
+ saveAnimations,
1769
+ history: inputHistory,
1770
+ recordHistory,
1771
+ cancelQueued,
1772
+ onBridgeReady: (instance: AppBridge) => { bridge.notify = instance.notify },
1773
+ })
1774
+ }
1775
+
1776
+ const renderCurrent = (): void => {
1777
+ mountRef.current?.rerender(appElement())
1778
+ }
1779
+
1780
+ mountRef.current = io.mount(appElement())
1781
+
1782
+ // Startup prompt/images use the same durable delivery path as composer
1783
+ // submissions. Image bytes are committed before the user/message event, and
1784
+ // input typed during that preparation queues behind the initial request so
1785
+ // the agent always receives the startup prompt first.
1786
+ if (startup.prompt !== undefined || (startup.images?.length ?? 0) > 0) {
1787
+ if ((startup.images?.length ?? 0) > 0) {
1788
+ bridge.notify(`processing ${startup.images!.length} startup image${startup.images!.length === 1 ? '' : 's'}…`)
1789
+ }
1790
+ void inputGate.run(async deliver => {
1791
+ const images = await saveImagePaths(startup.images ?? [], ctx.get('attachments'))
1792
+ if (images.length > 0) bridge.notify(`${images.length} startup image${images.length === 1 ? '' : 's'} attached`)
1793
+ deliver({ text: startup.prompt ?? '', mode: 'followup', images })
1794
+ }).catch((error: unknown) => {
1795
+ bridge.notify(`initial prompt failed: ${error instanceof Error ? error.message : String(error)}`, 'error')
1796
+ })
1797
+ }
1798
+
1799
+ async function copyLastResponse(): Promise<string> {
1800
+ const text = latestAssistantText(store.getView())
1801
+ if (text === undefined) return 'nothing to copy yet'
1802
+ await copyText(text)
1803
+ return 'copied latest response'
1804
+ }
1805
+
1806
+ // A corrupt statusline config must not vanish silently: surface it once
1807
+ // the notice channel is live, after the first frame settles.
1808
+ if (statuslineWarning !== undefined) {
1809
+ setTimeout(() => {
1810
+ bridge.notify('statusline config unreadable, using defaults: ' + statuslineWarning, 'warning')
1811
+ }, 50)
1812
+ }
1813
+ // Same one-shot surface for a corrupt theme file (dark fallback stays live).
1814
+ if (themeWarning !== undefined) {
1815
+ setTimeout(() => {
1816
+ bridge.notify('theme config unreadable, using dark: ' + themeWarning, 'warning')
1817
+ }, 50)
1818
+ }
1819
+ // And for a corrupt animations file (on-by-default fallback stays live).
1820
+ if (animationsWarning !== undefined) {
1821
+ setTimeout(() => {
1822
+ bridge.notify('animations config unreadable, animations stay on: ' + animationsWarning, 'warning')
1823
+ }, 50)
1824
+ }
1825
+
1826
+ // One-shot VS Code Ctrl+R hint: resolveEditorKeysStartupHint checks the
1827
+ // marker file and the live keybindings config; surfacing waits for the
1828
+ // notice channel like the other startup warnings. A failed probe stays
1829
+ // silent — the hint is cosmetic and /vscode-keys remains discoverable.
1830
+ void resolveEditorKeysStartupHint(editorKeysEnv).then(hint => {
1831
+ if (hint === undefined) return
1832
+ setTimeout(() => {
1833
+ bridge.notify(hint)
1834
+ }, 50)
1835
+ }, () => {})
1836
+ }
1837
+
1838
+ /**
1839
+ * Mount the interactive terminal driver.
1840
+ * @param ctx - plugin context carrying core services and the launcher-provided exit request.
1841
+ * @param config - validated startup config resolved from the tuiStartup provider.
1842
+ */
1843
+ export function apply(ctx: Context, config: Config): void {
1844
+ // The CLI validated --theme at parse time; the loose config schema falls
1845
+ // back to dark for anything unexpected.
1846
+ const theme = config.startup.theme === undefined ? undefined : parseThemeName(config.startup.theme)
1847
+ const input = {
1848
+ ...(theme === undefined ? {} : { theme }),
1849
+ ...(config.startup.prompt === undefined ? {} : { prompt: config.startup.prompt }),
1850
+ ...(config.startup.images === undefined ? {} : { images: config.startup.images }),
1851
+ }
1852
+ const startup: TuiStartup =
1853
+ config.startup.kind === 'resume' && config.startup.sessionId !== undefined
1854
+ ? { kind: 'resume', sessionId: config.startup.sessionId, ...input }
1855
+ : config.startup.kind === 'latest'
1856
+ ? { kind: 'latest', ...input }
1857
+ : config.startup.kind === 'named' && config.startup.sessionId !== undefined
1858
+ ? { kind: 'named', sessionId: config.startup.sessionId, ...config.startup.mode === undefined ? {} : { mode: config.startup.mode }, ...input }
1859
+ : { kind: 'fresh', ...config.startup.mode === undefined ? {} : { mode: config.startup.mode }, ...input }
1860
+ // Read through the global service store, not the property proxy: appExit is
1861
+ // an optional host value, never an injected dependency.
1862
+ const exit = ctx.get('appExit')
1863
+ if (exit === undefined) {
1864
+ throw new Error('tui-runner: the launcher must provide ctx.appExit before the tree mounts')
1865
+ }
1866
+ const io: TuiIo = { mount: internals.mount, exit }
1867
+ void run(ctx, startup, io).catch((error: unknown) => { fail(io, error) })
1868
+ }