@soffits/dsh-channel-core 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ - Session helpers both bridges used in their own copies: resolving and creating sessions, claiming a new one so the Web UI does not reuse it, workspaces, unarchiving, admitting a prompt once per request id (with sender, envelope and time zone), clearing a chat's pending prompts, recording a note without a turn, reading recent answers and titles, and the access-mode fallback.
6
+ - The file spool for requests from outside the Host, with the directory passed by the bridge. A spool stopped while it was starting no longer keeps polling, and a request's claim is removed before its result shows, so a stop in between can never send it twice.
7
+ - The subagent status card (`createAgentBoards`) and the `/agents` text (`subagentsText`), from the Telegram bridge.
8
+ - `@soffits/dsh-channel-core/testing`: fakes of DSH's pre-step gate, title service and model selection for bridge tests.
9
+ - `readLive` for settings that may be live references.
10
+
11
+ ## 0.1.0
12
+
13
+ - First release: the final answer of a turn and the silent marker, session model selection from the Web catalog, voice transcription, and the sender principal and envelope recorded on prompts, taken from dsh-telegram-bot and dsh-matrix-bot so both use one copy.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sakina
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # dsh-channel-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared building blocks for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) chat bridges, the plugins that connect DSH sessions to a chat network. Each bridge keeps its own network code (receiving, sending, editing, ids); what should behave the same on every network lives here:
4
+
5
+ - **Final answer of a turn** (`messageAnswer`, `answerSegments`, `turnAnswer`, `isInterjection`): the last text block of each assistant message that called no tool, split where someone sent a message into the running turn. Narration between tool calls is not part of it.
6
+ - **Silent marker** (`SILENT_REPLY`, `cutSilent`): an answer ending in `[SILENT]` posts nothing more; while streaming, a trailing part that may still become the marker is held back.
7
+ - **Session models** (`sessionModelOf`, `selectSessionModel`, `createModelCatalog`, `modelName`, `effortChoices`, `effortName`, `pickedSelection`, `isGoneModel`, `sameSelection`, `defaultModelOf`, `findModel`): read and switch one session's model with the same catalog and rules as the Web model picker, without changing the default for new sessions.
8
+ - **Voice** (`transcribe`, `transcriptNote`, `pcmToWave`, `runProgram`): transcribe a recording with DSH speech-to-text (through ffmpeg) or a configured command, and the note the agent reads next to it.
9
+ - **Sessions** (`resolveAgent`, `createSession`, `claimSession`, `attachToWorkspace`, `unarchive`, `admitPrompt`, `hasRequest`, `removePending`, `hasPendingInput`, `recordMessage`, `recentAssistantTexts`, `storedTitle`, `listWorkspaces`, `sessionsInWorkspace`, `appendAccessMode`): find, create and prompt a chat's session through the Web UI's own session controller, with the agent registry as the fallback; a new session is never left blank for the Web UI's New conversation to take; prompts are admitted once per request id; notes go into a session without starting a turn.
10
+ - **Spool** (`enqueue`, `waitForResult`, `withdraw`, `createSpool`): a file queue in a directory the bridge picks, so a command line or a scheduled job can hand requests to the running bridge without a token or a network route to the Host.
11
+ - **Subagents** (`createAgentBoards`, `subagentsText`, `subagentLabel`, `boardText`, `agentsListText`, `collectSubagents`, `childState`, `reportOf`, `formatElapsed`): one status card per chat for the subagents a session starts, edited as they start and finish (kept at the bottom on networks whose message ids grow), and the `/agents` list read from DSH's durable catalogs.
12
+ - **Testing** (`@soffits/dsh-channel-core/testing`: `followupThroughGate`, `makeTitleService`, `makeAgentModel`): fakes of DSH behaviour for a bridge's own test Host.
13
+ - **Config** (`readLive`): read a plugin setting that may be a live reference.
14
+ - **Sender** (`sendPrincipal`, `withMetadata`, `createPrincipalTagger`, `senderSession`, `nonEmpty`): who sent a prompt as `source.principal`, and when and in reply to what as `source.envelope`, recorded on the message itself and never in its text. Network-specific principals (a Telegram user, a Matrix user) stay in each bridge and use the same fields.
15
+
16
+ It is a plain library, not a DSH plugin: bridges list it as a dependency. Used by [dsh-telegram-bot](https://github.com/soffits/dsh-telegram-bot) and [dsh-matrix-bot](https://github.com/soffits/dsh-matrix-bot).
17
+
18
+ ```js
19
+ import { cutSilent, turnAnswer } from '@soffits/dsh-channel-core'
20
+
21
+ const { text, silent } = cutSilent(turnAnswer(events, turn))
22
+ ```
23
+
24
+ ## Development
25
+
26
+ `npm test`, `npm run check`. Node 22 or newer, no dependencies.
27
+
28
+ ## License
29
+
30
+ MIT
package/index.js ADDED
@@ -0,0 +1,49 @@
1
+ export { readLive } from './src/config.js'
2
+ export { SILENT_REPLY, answerSegments, cutSilent, isInterjection, messageAnswer, turnAnswer } from './src/answer.js'
3
+ export {
4
+ createModelCatalog,
5
+ defaultModelOf,
6
+ effortChoices,
7
+ effortName,
8
+ findModel,
9
+ isGoneModel,
10
+ modelName,
11
+ pickedSelection,
12
+ sameSelection,
13
+ selectSessionModel,
14
+ sessionModelOf,
15
+ } from './src/models.js'
16
+ export { MAX_PENDING_PRINCIPALS, createPrincipalTagger, nonEmpty, sendPrincipal, senderSession, withMetadata } from './src/principal.js'
17
+ export { pcmToWave, runProgram, transcribe, transcriptNote } from './src/voice.js'
18
+ export {
19
+ admitPrompt,
20
+ appendAccessMode,
21
+ attachToWorkspace,
22
+ claimSession,
23
+ controllerOf,
24
+ createSession,
25
+ hasPendingInput,
26
+ hasRequest,
27
+ hasSystemHead,
28
+ inInbox,
29
+ listWorkspaces,
30
+ recentAssistantTexts,
31
+ recordMessage,
32
+ removePending,
33
+ resolveAgent,
34
+ sessionsInWorkspace,
35
+ storedTitle,
36
+ unarchive,
37
+ } from './src/sessions.js'
38
+ export { createSpool, enqueue, waitForResult, withdraw } from './src/spool.js'
39
+ export {
40
+ agentsListText,
41
+ boardText,
42
+ childState,
43
+ collectSubagents,
44
+ createAgentBoards,
45
+ formatElapsed,
46
+ reportOf,
47
+ subagentLabel,
48
+ subagentsText,
49
+ } from './src/subagents.js'
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@soffits/dsh-channel-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Shared core for DeepSeek Harness chat bridges: the final answer of a turn and the silent marker, session model selection from the Web catalog, voice transcription, and the sender principal recorded on prompts.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./testing": "./testing.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "files": [
13
+ "index.js",
14
+ "testing.js",
15
+ "src/*.js",
16
+ "README.md",
17
+ "CHANGELOG.md",
18
+ "LICENSE"
19
+ ],
20
+ "engines": {
21
+ "node": ">=22"
22
+ },
23
+ "scripts": {
24
+ "test": "node --test \"test/*.test.js\"",
25
+ "check": "for f in index.js testing.js src/*.js test/*.js; do node --check \"$f\" || exit 1; done"
26
+ },
27
+ "keywords": [
28
+ "dsh",
29
+ "deepseek-harness",
30
+ "chat-bridge",
31
+ "bot"
32
+ ],
33
+ "author": "Sakina",
34
+ "license": "MIT",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/soffits/dsh-channel-core.git"
38
+ },
39
+ "homepage": "https://github.com/soffits/dsh-channel-core#readme",
40
+ "bugs": {
41
+ "url": "https://github.com/soffits/dsh-channel-core/issues"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ }
46
+ }
package/src/answer.js ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The text a finished turn leaves in its chat.
3
+ *
4
+ * Text written between tool calls ("Now the board entries.") streams into the
5
+ * live reply like everything else, but it is working narration, not part of
6
+ * the answer. So the final reply keeps, from each assistant message of the
7
+ * turn, only an answer: the last text block of a message that called no tool.
8
+ * A message that called a tool is mid-chain, so its text goes. The last block,
9
+ * not all of them: Claude Code through dsh-oh-my-claude puts every text block
10
+ * of its own tool loop into one message, with its tools recorded beside it.
11
+ * Answers of several tool-free messages in one turn are kept, in order, up to
12
+ * a message someone sent into the running turn (an interjection): the chat
13
+ * shows that message where it was sent, so the answers before it stay above
14
+ * it and the answers after it go below (`answerSegments`).
15
+ *
16
+ * An answer ending in the silent marker asks the bridge to post nothing more
17
+ * (`cutSilent`): a model cannot end a turn with no text at all, since DSH
18
+ * treats that as an empty response.
19
+ */
20
+
21
+ /** The marker a final answer ends with to post nothing more. */
22
+ export const SILENT_REPLY = '[SILENT]'
23
+
24
+ /**
25
+ * The answer one assistant message holds, or '' when it holds none.
26
+ * @param message - an assistant message (`{ content: [...] }`).
27
+ * @returns the last text block when the message called no tool.
28
+ */
29
+ export function messageAnswer(message) {
30
+ const content = Array.isArray(message?.content) ? message.content : []
31
+ if (content.some((block) => block?.type === 'tool-call')) return ''
32
+ const texts = content
33
+ .filter((block) => block?.type === 'text' && typeof block.text === 'string')
34
+ .map((block) => block.text.trim())
35
+ .filter((text) => text.length > 0)
36
+ return texts.at(-1) ?? ''
37
+ }
38
+
39
+ /**
40
+ * Whether a recorded user message is one a person or a scheduled task sent,
41
+ * not context a plugin added.
42
+ * @param message - a `user/message` event's data.
43
+ */
44
+ export function isInterjection(message) {
45
+ const kind = message?.source?.kind
46
+ return kind === 'user' || kind === 'schedule'
47
+ }
48
+
49
+ /**
50
+ * The answers of one turn, split at messages sent into it after it started
51
+ * replying: one string per part, earliest first.
52
+ * @param events - session events (`{ type, data }`).
53
+ * @param turn - DSH turn number.
54
+ * @returns at least one string; '' for a part with no answer.
55
+ */
56
+ export function answerSegments(events, turn) {
57
+ const segments = [[]]
58
+ if (!Array.isArray(events) || turn === undefined) return ['']
59
+ let replied = false
60
+ for (const event of events) {
61
+ if (event?.type === 'turn/end' && event.data?.turn === turn) break
62
+ if (event?.type === 'assistant/message') {
63
+ if (event.data?.turn !== turn) {
64
+ if (replied) break
65
+ continue
66
+ }
67
+ replied = true
68
+ const answer = messageAnswer(event.data?.message ?? event.data)
69
+ if (answer.length > 0) segments.at(-1).push(answer)
70
+ continue
71
+ }
72
+ if (replied && event?.type === 'user/message' && isInterjection(event.data)) segments.push([])
73
+ }
74
+ return segments.map((answers) => answers.join('\n\n'))
75
+ }
76
+
77
+ /**
78
+ * The answer a turn's last reply message shows: its answers after the last
79
+ * message sent into it.
80
+ * @param events - session events (`{ type, data }`).
81
+ * @param turn - DSH turn number.
82
+ * @returns the answers joined by blank lines, or '' when none.
83
+ */
84
+ export function turnAnswer(events, turn) {
85
+ return answerSegments(events, turn).at(-1)
86
+ }
87
+
88
+ /**
89
+ * Remove the silent marker from the end of an answer. A turn can hold several
90
+ * assistant messages, so the marker may follow real text instead of standing
91
+ * alone.
92
+ * @param text - answer text.
93
+ * @param options - `{ streaming }`: the text is still growing, so a trailing
94
+ * part that may yet become the marker is held back too.
95
+ * @returns `{ text, silent }`: the text to show, and whether it ended with the marker.
96
+ */
97
+ export function cutSilent(text, { streaming = false } = {}) {
98
+ const trimmed = String(text ?? '').trim()
99
+ if (trimmed.endsWith(SILENT_REPLY)) return { text: trimmed.slice(0, -SILENT_REPLY.length).trim(), silent: true }
100
+ if (streaming) {
101
+ const start = trimmed.lastIndexOf('[')
102
+ if (start !== -1 && SILENT_REPLY.startsWith(trimmed.slice(start))) return { text: trimmed.slice(0, start).trim(), silent: false }
103
+ }
104
+ return { text: trimmed, silent: false }
105
+ }
package/src/config.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Read a plugin config field that may be a plain value or a live reference
3
+ * (an object with `get`, as DSH passes volatile settings and credentials).
4
+ * @param value - config field.
5
+ * @param fallback - value used when the field is absent or cannot be read.
6
+ * @returns the current value.
7
+ */
8
+ export function readLive(value, fallback) {
9
+ if (value !== null && typeof value === 'object' && typeof value.get === 'function') {
10
+ try {
11
+ const current = value.get()
12
+ return current === undefined ? fallback : current
13
+ } catch {
14
+ return fallback
15
+ }
16
+ }
17
+ return value === undefined || value === null ? fallback : value
18
+ }
package/src/models.js ADDED
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Model selection for a chat bound to a session. The session's live agent
3
+ * owns its model (`agent.model.current()`); a bridge keeps no copy of it.
4
+ * Lists come from the same catalog as the Web model picker
5
+ * (`sessionController.modelCatalog()`), so every configured provider and
6
+ * model shows with its Web display name.
7
+ */
8
+
9
+ /** How long one catalog read is reused for labels and menus. */
10
+ const CATALOG_TTL_MS = 60_000
11
+
12
+ /**
13
+ * Copy a selection, dropping an absent effort.
14
+ * @param selection - provider, model and optional effort.
15
+ * @returns a detached selection.
16
+ */
17
+ function toSelection({ provider, model, reasoningEffort }) {
18
+ return { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) }
19
+ }
20
+
21
+ /**
22
+ * Read a session's current model: the live agent's own choice, or, for a
23
+ * session that is not running, its recorded selection.
24
+ * @param ctx - Host context.
25
+ * @param sessionId - DSH session id.
26
+ * @returns the selection, or undefined when the session has none recorded.
27
+ */
28
+ export async function sessionModelOf(ctx, sessionId) {
29
+ if (typeof sessionId !== 'string') return undefined
30
+ const agent = ctx.get('agents')?.get(sessionId)
31
+ if (typeof agent?.model?.current === 'function') {
32
+ const current = agent.model.current()
33
+ return current === undefined ? undefined : toSelection(current)
34
+ }
35
+ const query = ctx.get('sessionQuery')
36
+ if (typeof query?.observeSession !== 'function') return undefined
37
+ let observation
38
+ try {
39
+ observation = await query.observeSession(sessionId)
40
+ // The modelSelection projection's view: `next` is the pending choice or
41
+ // the route of the last request.
42
+ const view = observation?.projections?.values?.modelSelection
43
+ const recorded = view?.next ?? view?.pending ?? view?.lastUsed
44
+ return typeof recorded?.provider === 'string' && typeof recorded?.model === 'string' ? toSelection(recorded) : undefined
45
+ } catch {
46
+ return undefined
47
+ } finally {
48
+ observation?.[Symbol.dispose]?.()
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Switch one session to a model without touching the default for new
54
+ * sessions. The Web picker's `sessionController.selectModel` saves every pick
55
+ * as that default, so a switch in one chat would move every chat's next
56
+ * session; this takes its other steps instead: the host checks it can route
57
+ * the model (`llm.resolveCallConfig`, which throws with the reason when it
58
+ * cannot), then the live agent records it.
59
+ * @param ctx - Host context.
60
+ * @param agent - the session's live agent.
61
+ * @param selection - provider, model and optional effort.
62
+ */
63
+ export async function selectSessionModel(ctx, agent, selection) {
64
+ const picked = toSelection(selection)
65
+ const llm = ctx.get('llm')
66
+ if (typeof llm?.resolveCallConfig === 'function') await llm.resolveCallConfig({ ...picked })
67
+ agent.model.select(picked)
68
+ }
69
+
70
+ /**
71
+ * Read the deployment default model (the one the Web UI saves).
72
+ * @param ctx - Host context.
73
+ * @returns the selection, or undefined without a default-model service.
74
+ */
75
+ export function defaultModelOf(ctx) {
76
+ try {
77
+ const selection = ctx.get('agentDefaultModel')?.currentSelection()
78
+ if (typeof selection?.provider === 'string' && typeof selection?.model === 'string') return toSelection(selection)
79
+ } catch {
80
+ // No default configured.
81
+ }
82
+ return undefined
83
+ }
84
+
85
+ /**
86
+ * Whether the catalog no longer offers a selection's provider or model, for
87
+ * example after a provider was removed from the profile. A provider the
88
+ * catalog reports as failing is not counted: its models are unknown now, not
89
+ * gone. Without a catalog nothing is called gone.
90
+ * @param catalog - loaded catalog, or undefined.
91
+ * @param selection - provider and model, or undefined.
92
+ * @returns true when the selection names something the catalog dropped.
93
+ */
94
+ export function isGoneModel(catalog, selection) {
95
+ if (catalog === undefined || typeof selection?.provider !== 'string' || typeof selection?.model !== 'string') return false
96
+ if (catalog.failures.some((failure) => failure?.id === selection.provider)) return false
97
+ return findModel(catalog, selection) === undefined
98
+ }
99
+
100
+ /**
101
+ * Whether two selections name the same provider, model and effort.
102
+ * @param left - first selection.
103
+ * @param right - second selection.
104
+ * @returns true when they agree.
105
+ */
106
+ export function sameSelection(left, right) {
107
+ return left?.provider === right?.provider && left?.model === right?.model && left?.reasoningEffort === right?.reasoningEffort
108
+ }
109
+
110
+ /**
111
+ * Cached reader for the Web model catalog.
112
+ * @param ctx - Host context.
113
+ * @returns `load()` resolving the catalog, or undefined when it is unavailable.
114
+ */
115
+ export function createModelCatalog(ctx) {
116
+ let cached
117
+ let loadedAt = 0
118
+ let pending
119
+ return {
120
+ /**
121
+ * @param fresh - skip the short-lived cache (used before applying a pick).
122
+ * @returns `{ groups, failures }` as the Web picker gets it, or undefined.
123
+ */
124
+ async load(fresh = false) {
125
+ if (!fresh && cached !== undefined && Date.now() - loadedAt < CATALOG_TTL_MS) return cached
126
+ pending ??= (async () => {
127
+ const controller = ctx.get('sessionController')
128
+ if (typeof controller?.modelCatalog !== 'function') return undefined
129
+ const catalog = await controller.modelCatalog()
130
+ cached = { groups: Array.isArray(catalog?.groups) ? catalog.groups : [], failures: Array.isArray(catalog?.failures) ? catalog.failures : [] }
131
+ loadedAt = Date.now()
132
+ return cached
133
+ })().finally(() => { pending = undefined })
134
+ try {
135
+ return await pending
136
+ } catch {
137
+ return cached
138
+ }
139
+ },
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Find a catalog entry for a selection.
145
+ * @param catalog - loaded catalog.
146
+ * @param selection - provider and model.
147
+ * @returns `{ group, model }`, or undefined.
148
+ */
149
+ export function findModel(catalog, selection) {
150
+ const group = catalog?.groups.find((entry) => entry.id === selection?.provider)
151
+ const model = group?.models.find((entry) => entry.id === selection?.model)
152
+ return model === undefined ? undefined : { group, model }
153
+ }
154
+
155
+ /**
156
+ * Display name of a selection's model, as the Web picker shows it.
157
+ * @param catalog - loaded catalog, or undefined.
158
+ * @param selection - provider and model.
159
+ * @returns the name, or the raw model id.
160
+ */
161
+ export function modelName(catalog, selection) {
162
+ if (selection === undefined) return '?'
163
+ return findModel(catalog, selection)?.model.name ?? selection.model
164
+ }
165
+
166
+ /**
167
+ * Effort choices for one catalog model, the same list the Web picker builds:
168
+ * a provider-default entry when the model has no default effort, then its
169
+ * efforts. A model without reasoning has none.
170
+ * @param model - catalog model entry.
171
+ * @param defaultLabel - label for the provider default.
172
+ * @returns `{ id, name }` entries; `id` undefined means the provider default.
173
+ */
174
+ export function effortChoices(model, defaultLabel) {
175
+ const reasoning = model?.reasoning
176
+ if (reasoning === undefined) return []
177
+ return [
178
+ ...(reasoning.defaultEffort === undefined ? [{ id: undefined, name: defaultLabel }] : []),
179
+ ...reasoning.efforts.map((effort) => ({ id: effort.id, name: effort.name })),
180
+ ]
181
+ }
182
+
183
+ /**
184
+ * Display name of a selection's effective effort.
185
+ * @param catalog - loaded catalog, or undefined.
186
+ * @param selection - current selection.
187
+ * @param defaultLabel - label for the provider default.
188
+ * @returns the name.
189
+ */
190
+ export function effortName(catalog, selection, defaultLabel) {
191
+ const reasoning = findModel(catalog, selection)?.model.reasoning
192
+ const effective = selection?.reasoningEffort ?? reasoning?.defaultEffort
193
+ if (effective === undefined) return defaultLabel
194
+ return reasoning?.efforts.find((effort) => effort.id === effective)?.name ?? effective
195
+ }
196
+
197
+ /**
198
+ * The selection a model pick makes, by the Web picker's rule: the same model
199
+ * keeps its effort, another model starts at its default effort.
200
+ * @param current - the session's current selection.
201
+ * @param provider - picked provider id.
202
+ * @param model - picked catalog model entry.
203
+ * @returns the selection to apply.
204
+ */
205
+ export function pickedSelection(current, provider, model) {
206
+ const same = current?.provider === provider && current?.model === model.id
207
+ const reasoningEffort = same ? current.reasoningEffort ?? model.reasoning?.defaultEffort : model.reasoning?.defaultEffort
208
+ return toSelection({ provider, model: model.id, reasoningEffort })
209
+ }
210
+
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Who sent a message, as data on the message itself.
3
+ *
4
+ * DSH's field for the caller behind a user message is `source.principal`:
5
+ * the session controller writes it for callers other than the owner, so an
6
+ * absent principal means the owner. A bridge admits every prompt from its
7
+ * network as the owner, so it fills the field itself, and also on the copies
8
+ * of sends it records in bound sessions. Readers get the sender from it, not
9
+ * from text.
10
+ *
11
+ * Every principal has `kind`, `channel` and `id`, and `name` when one is
12
+ * known; the other fields depend on the kind. None carries a credential, so
13
+ * all are safe in a session log.
14
+ *
15
+ * When the message was sent and what it replies to go on `source.envelope`,
16
+ * the metadata dsh-message-context renders for the model. A bridge never adds
17
+ * them to the text: DSH titles a session from the first words of its first
18
+ * human message, and those must be the person's own.
19
+ */
20
+
21
+ /** Remembered prompts waiting for their step; the oldest go first past this. */
22
+ export const MAX_PENDING_PRINCIPALS = 1024
23
+
24
+ /**
25
+ * A trimmed string, or undefined for anything blank or not a string: the
26
+ * rule every principal field follows, so a principal never has empty fields.
27
+ * @param value - any value.
28
+ */
29
+ export function nonEmpty(value) {
30
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined
31
+ }
32
+
33
+ /**
34
+ * The sender of a send into a chat, from the request's `from`: a scheduled
35
+ * job, else a DSH session, else the free-form label of an outside caller.
36
+ * @param from - `{ job?, jobId?, sessionId?, label? }`.
37
+ * @returns the principal, or undefined when the request names no sender.
38
+ */
39
+ export function sendPrincipal(from) {
40
+ const job = nonEmpty(from?.job)
41
+ const jobId = nonEmpty(from?.jobId)
42
+ const sessionId = nonEmpty(from?.sessionId)
43
+ const label = nonEmpty(from?.label)
44
+ if (job !== undefined || jobId !== undefined) {
45
+ return {
46
+ kind: 'cron-job',
47
+ channel: 'cron',
48
+ id: jobId ?? job,
49
+ ...(job === undefined ? {} : { name: job }),
50
+ ...(sessionId === undefined ? {} : { sessionId }),
51
+ }
52
+ }
53
+ if (sessionId !== undefined) {
54
+ return { kind: 'dsh-session', channel: 'dsh', id: sessionId, ...(label === undefined ? {} : { name: label }) }
55
+ }
56
+ if (label !== undefined) return { kind: 'external', channel: 'external', id: label, name: label }
57
+ return undefined
58
+ }
59
+
60
+ /**
61
+ * The DSH session that sent a prompt, when its recorded sender is one: an
62
+ * agent's brief or follow-up (`open_session`, `prompt_session`), which DSH
63
+ * otherwise shows like something the owner typed in the Web UI.
64
+ * @param principal - the message's `source.principal`, if any.
65
+ * @returns the session id, or undefined for any other sender.
66
+ */
67
+ export function senderSession(principal) {
68
+ return principal?.kind === 'dsh-session' ? nonEmpty(principal.id) : undefined
69
+ }
70
+
71
+ /**
72
+ * A frozen copy of a message whose source records its sender and envelope.
73
+ * Fields the message already has are kept.
74
+ * @param message - the user message.
75
+ * @param metadata - `{ principal, envelope }`, each optional.
76
+ * @returns the copy; the message itself when there is nothing to add.
77
+ */
78
+ export function withMetadata(message, { principal, envelope } = {}) {
79
+ const addPrincipal = principal !== undefined && message.source.principal === undefined
80
+ const addEnvelope = envelope !== undefined && message.source.envelope === undefined
81
+ if (!addPrincipal && !addEnvelope) return message
82
+ return Object.freeze({
83
+ ...message,
84
+ source: Object.freeze({
85
+ ...message.source,
86
+ ...(addPrincipal ? { principal: deepFreeze(principal) } : {}),
87
+ ...(addEnvelope ? { envelope: deepFreeze(envelope) } : {}),
88
+ }),
89
+ })
90
+ }
91
+
92
+ function deepFreeze(value) {
93
+ if (typeof value === 'object' && value !== null && !Object.isFrozen(value)) {
94
+ for (const child of Object.values(value)) deepFreeze(child)
95
+ Object.freeze(value)
96
+ }
97
+ return value
98
+ }
99
+
100
+ /**
101
+ * Metadata for prompts a bridge hands to DSH's session controller, which
102
+ * builds the message itself. The bridge remembers the sender by request id
103
+ * before the hand-over; `preStep`, an `agent/pre-step` listener, records it
104
+ * and the envelope on the message as it enters a step, so they are in the
105
+ * session log with the message (DSH lets that hook replace the messages of a
106
+ * step). It is registered without `prepend`, so a prepended renderer sees them.
107
+ * @param limit - most principals remembered at once.
108
+ */
109
+ export function createPrincipalTagger(limit = MAX_PENDING_PRINCIPALS) {
110
+ const pending = new Map()
111
+ return {
112
+ /**
113
+ * Remember the sender and envelope of the prompt with this request id
114
+ * (or, for a message the bridge builds itself, this message id).
115
+ * @param requestId - the request or message id.
116
+ * @param metadata - `{ principal, envelope }`, each optional.
117
+ */
118
+ remember(requestId, { principal, envelope } = {}) {
119
+ if (typeof requestId !== 'string' || (principal === undefined && envelope === undefined)) return
120
+ pending.delete(requestId)
121
+ pending.set(requestId, { principal, envelope })
122
+ if (pending.size > limit) pending.delete(pending.keys().next().value)
123
+ },
124
+ /** Pending prompts, for tests. */
125
+ get size() {
126
+ return pending.size
127
+ },
128
+ /**
129
+ * `agent/pre-step` listener: record remembered senders and envelopes on
130
+ * the step's messages.
131
+ */
132
+ async preStep(_payload, next) {
133
+ const decision = await next()
134
+ if (decision?.kind !== 'enter' || !Array.isArray(decision.messages)) return decision
135
+ let changed = false
136
+ const messages = []
137
+ for (const original of decision.messages) {
138
+ let message = original
139
+ const user = message?.source?.kind === 'user'
140
+ const key = !user ? undefined : (typeof message.source.rpcId === 'string' && pending.has(message.source.rpcId) ? message.source.rpcId : message.id)
141
+ const entry = typeof key === 'string' ? pending.get(key) : undefined
142
+ if (entry !== undefined) pending.delete(key)
143
+ if (entry !== undefined) {
144
+ const tagged = withMetadata(message, entry)
145
+ if (tagged !== message) changed = true
146
+ message = tagged
147
+ }
148
+ messages.push(message)
149
+ }
150
+ return changed ? { ...decision, messages } : decision
151
+ },
152
+ }
153
+ }