@aspen138/dsh-btw 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 yhm138
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,96 @@
1
- # Temporary Holding Version
1
+ # dsh-btw — 侧问(`/btw`)
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
+ 给 DeepSeek Harness 加一条 Antigravity 风格的侧问命令:**开发中途问一句,它自己会去查,答案不污染主干会话的模型上下文。**
4
+
5
+ ```
6
+ /btw 那个函数签名到底是什么?用到哪些参数?
7
+ ```
8
+
9
+ 答案出现在**右侧边栏的「侧问」页签**里;对话流里只留一行安静的小标记。侧问跑在一个**临时 fork 子 agent** 里:继承当前会话已完成的轮次,工具全开,有自己的工作目录和沙箱策略,答完就释放。
10
+
11
+ **安装**:npm 包 `@aspen138/dsh-btw@0.1.1`([npm](https://www.npmjs.com/package/@aspen138/dsh-btw) · [GitHub](https://github.com/yhm138/dsh-btw))。收录后也可在 DSH「发现」页搜 `btw` / `侧问` 一键安装。
12
+
13
+ ![右侧侧问面板](docs/screenshot-panel.png)
14
+
15
+ ## 它到底是什么
16
+
17
+ | | 普通 fork / branch | `/btw`(本插件) |
18
+ |---|---|---|
19
+ | 生命周期 | 新会话持久化、侧边栏可见、可继续跑 | 一次性子 agent,答完释放执行句柄 |
20
+ | 工具 | 完整 agent | **完整 agent:工具全开** |
21
+ | 回写 | 分支里的事属于分支 | 结果只交给调用者(`delivery: 'caller'`),父会话**收不到**完成通知 |
22
+ | 并发 | 通常要切过去 | 主轮在跑时也能起(独立子会话) |
23
+
24
+ 技术上它是 `ctx.subagents.startActivation({ provider: 'fork' })`:fork 种子是父会话**已完成轮次**的前缀(进行中的那一轮不进种子),子 agent 用父会话的 preset,因此工具集、权限、沙箱语义都跟主对话一致。父会话只多出 `command/run` + `command/done` 两条 log-only 事件(类型上没有 `surfaceOp`),`deriveMessages()` 与之后的每一次请求不变。
25
+
26
+ ## 用法
27
+
28
+ | 输入 | 结果 |
29
+ |---|---|
30
+ | `/btw <问题>` | 起一个子 agent 去查,右侧「侧问」页签自动打开并列出问答 |
31
+ | `/btw` | 返回用法提示 |
32
+ | 点击对话流里的 `◈ 侧问 …` | 重新打开「侧问」页签 |
33
+ | 「开始」页里的「侧问」卡片 | 打开「侧问」页签 |
34
+
35
+ 页签里每条记录有状态(正在跑 / 已答 / 失败)和「复制问答」。记录来自当前会话的命令生命周期,换会话就是另一份列表。
36
+
37
+ ## 上下文边界
38
+
39
+ - **进入**:当前会话已完成的对话(含工具结果)、模型路由、工具集与 preset。
40
+ - **不进入**:问题、答案、子会话里的任何内容。父会话的模型可见序列前后一致(实测摘要一致)。
41
+ - **代价**:侧问是一次**完整 agent 轮**(可能多轮工具),比"一次模型调用"贵得多,也慢得多(实测读文件 12s、写文件 28s)。
42
+
43
+ ## 权限(实测结论,和"弹审批"的预期不一致)
44
+
45
+ 设计预期是「侧问里的写操作弹审批」。实测下来,**DSH 对文件写入没有"先审批再写"这条路**:写入由子会话的**沙箱策略**直接裁决。
46
+
47
+ | 子 agent 的权限包 | 写工作区内 | 写工作区外 |
48
+ |---|---|---|
49
+ | `read-only` | `sandbox: file access denied under read-only mode` | 同左 |
50
+ | `workspace-write`(当前默认) | 允许 | 沙箱直接拒绝(`SetNamedSecurityInfoW … Win32 5`),**不弹审批** |
51
+ | `danger-full-access` | 允许 | 允许,静默 |
52
+
53
+ 子 agent 在 `workspace-write` 下想写工作区外时的原话:「本会话是受限 subagent,审批被自动拒绝,无法提权」。审批 UI 只服务 `ask` 决策(例如沙箱化 shell 的升权),文件写入不在此列。
54
+
55
+ 所以现在给的保障是:**侧问只能改当前工作区里的东西,碰不到工作区外**;它做的每一步都能在它自己的页签里看到(工具调用、命令输出、最终答案)。
56
+
57
+ ## 配置
58
+
59
+ 在 profile 的 `cordis.patch.yml` 里按 `id: dsh-btw` 覆盖(整块 `config` 替换,想保留的要重写):
60
+
61
+ ```yaml
62
+ - id: dsh-btw
63
+ config:
64
+ maxQuestionChars: 8000 # 太长的问题直接拒绝
65
+ childProvider: fork # fork=继承上下文;spawn=空白起步
66
+ approvalPolicy: ask # 子 agent 的审批策略
67
+ sideAgentPreset: read-only # 子 agent 的权限包:read-only / workspace-write / danger-full-access / inherit
68
+ disposeChild: true # 答完释放执行句柄(子会话本身仍持久)
69
+ answerMaxChars: 12000 # 答案截断上限
70
+ provider: '' # 固定子 agent 模型;空=继承父会话
71
+ model: ''
72
+ ```
73
+
74
+ ## 已知限制
75
+
76
+ - **不流式**:答案随命令结果一次性返回(子 agent 的工作过程在它自己的会话里)。
77
+ - **审批面缺失**:见上。
78
+ - **子会话持久化**:每次 `/btw` 会在父会话下留一个 `continuable` 子会话(标签是问题前 48 字),可在子智能体视图里看到;执行句柄会释放,会话文件不自动删。
79
+ - **一次一个**:同一会话上一个侧问未结束时,第二个被拒绝。
80
+ - 仅 Web/桌面客户端有这套 UI;headless / ACP / JSON-RPC 没有命令入口。
81
+
82
+ ## 开发
83
+
84
+ ```text
85
+ dsh-btw/
86
+ index.js Host:/btw 命令 → fork 子 agent → 结果
87
+ client.js Client:右侧页签类型 + 页面 + 对话流 chip
88
+ cordis.patch.yml bundle patch(权限包默认值在这里)
89
+ locale/*.json 插件管理里的标题/描述
90
+ icon.svg 插件图标
91
+ docs/ 验收截图与报告
92
+ ```
93
+
94
+ 安装:npm 包 `@aspen138/dsh-btw`;本地开发时用 `plugin_manager install_bundle` 指向本目录(`link:` 安装不受 `files` 过滤)。Host 代码改动在下次 profile recomposition 生效,Client 代码改动下次页面加载生效(客户端模块 `id` 必须等于包名)。
95
+
96
+ 调试句柄:`window.__DSH_BTW__` 暴露 `{ tabs, right, lastError, open }`。
package/client.js ADDED
@@ -0,0 +1,583 @@
1
+ // dsh-btw — Client half: the right-Sidebar "Side question" page and the
2
+ // compact transcript chip.
3
+ //
4
+ // Data source: the Chat layer's own command nodes. `/btw` is a Host command, so
5
+ // its lifecycle is already projected into the conversation as a `command` node
6
+ // (name 'btw', args = the question, outcome.text = the answer). This module
7
+ // reads those nodes through the `useChat` standard prop and renders them as a
8
+ // right-Sidebar page (`ctx.sidebarRightTabs` + `sidebar.right.pane.tab`), so the
9
+ // answer docks in the column the user already works in instead of floating over
10
+ // the composer. The generic command card is replaced with a one-line chip that
11
+ // reopens the page.
12
+ //
13
+ // Nothing here talks to the Host: no route, no RPC, no extra persistence. The
14
+ // page is a view over the same durable command records the Chat already has.
15
+
16
+ window.__ModuleLoader__.load({
17
+ id: '@aspen138/dsh-btw',
18
+ factory(require) {
19
+ const React = require('react')
20
+ const h = React.createElement
21
+
22
+ /** Implementation identity: unique in the tab system, and the body slot key. */
23
+ const TYPE_ID = 'dsh-btw/side-questions'
24
+
25
+ /** Page kind the navigation controller opens by name. */
26
+ const KIND = 'btw'
27
+
28
+ /** Set by `apply`; the transcript chip uses it to reveal the page. */
29
+ const navigation = { open: undefined, openChild: undefined }
30
+
31
+ /** Diagnostic surface for verification runs; never user-visible. */
32
+ const debug = { tabs: false, right: false, lastError: null, open: undefined }
33
+ try {
34
+ if (typeof window !== 'undefined') window.__DSH_BTW__ = debug
35
+ } catch {
36
+ /* a read-only window is not worth breaking the plugin over */
37
+ }
38
+
39
+ // ---------------------------------------------------------------- strings
40
+
41
+ const STRINGS = {
42
+ zh: {
43
+ badge: '侧问',
44
+ badgeHint: '继承当前对话、不带工具,答案不进入主干上下文',
45
+ typeLabel: '侧问',
46
+ guideTitle: '侧问',
47
+ guideDescription: '问一句小细节,不动主线任务',
48
+ running: '正在回答…',
49
+ done: '已答',
50
+ failed: '失败',
51
+ emptyQuestion: '(空问题)',
52
+ emptyTitle: '还没有侧问',
53
+ emptyHint: '在输入框输入 /btw <问题>,答案会出现在这里,且不进入模型上下文。',
54
+ copy: '复制问答',
55
+ copied: '已复制',
56
+ openChild: '查看子会话',
57
+ openChildHint: '在右侧打开这条侧问的子会话:它的工具调用和审批都在那里',
58
+ chipOpen: '在右侧打开这条侧问的子会话',
59
+ questionPrefix: '问',
60
+ answerPrefix: '答',
61
+ degraded: '仅文本历史',
62
+ count: (n) => `${n} 条`,
63
+ },
64
+ en: {
65
+ badge: 'Side question',
66
+ badgeHint: 'Inherits this conversation, no tools; never enters the main context',
67
+ typeLabel: 'Side question',
68
+ guideTitle: 'Side question',
69
+ guideDescription: 'Ask one small thing without touching the task',
70
+ running: 'Answering…',
71
+ done: 'Answered',
72
+ failed: 'Failed',
73
+ emptyQuestion: '(empty question)',
74
+ emptyTitle: 'No side questions yet',
75
+ emptyHint: 'Type /btw <question> in the composer. Answers appear here and never enter the model context.',
76
+ copy: 'Copy question and answer',
77
+ copied: 'Copied',
78
+ openChild: 'Open sub-session',
79
+ openChildHint: "Open this side question's own session: its tool calls and approval prompts live there",
80
+ chipOpen: "Open this side question's sub-session",
81
+ questionPrefix: 'Q',
82
+ answerPrefix: 'A',
83
+ degraded: 'text history only',
84
+ count: (n) => `${n} item${n === 1 ? '' : 's'}`,
85
+ },
86
+ }
87
+
88
+ /** Language used when no locale service is mounted. */
89
+ function documentLanguage() {
90
+ try {
91
+ const lang = String((typeof document !== 'undefined' && document.documentElement && document.documentElement.lang) || 'zh')
92
+ return lang.toLowerCase().startsWith('zh') ? 'zh' : 'en'
93
+ } catch {
94
+ return 'zh'
95
+ }
96
+ }
97
+
98
+ // -------------------------------------------------------------------- css
99
+
100
+ const CSS = [
101
+ '.dshbtw-page{display:flex;flex-direction:column;gap:10px;padding:12px 12px 24px;font-size:13px;line-height:20px;',
102
+ 'color:var(--dsw-alias-label-primary);overflow:auto;height:100%}',
103
+ '.dshbtw-empty{display:flex;flex-direction:column;gap:6px;padding:28px 8px;color:var(--dsw-alias-label-secondary);text-align:center}',
104
+ '.dshbtw-empty-title{font-weight:600;color:var(--dsw-alias-label-primary)}',
105
+ '.dshbtw-empty-hint{font-size:12px;line-height:18px}',
106
+ '.dshbtw-card{display:flex;flex-direction:column;gap:6px;padding:10px 12px;border:0.5px solid var(--dsw-alias-border-l1);',
107
+ 'border-radius:10px;background:var(--dsw-alias-bg-layer-1)}',
108
+ '.dshbtw-card-head{display:flex;align-items:flex-start;gap:6px}',
109
+ '.dshbtw-q{flex:1;min-width:0;font-weight:600;white-space:pre-wrap;word-break:break-word}',
110
+ '.dshbtw-state{flex:none;font-size:12px;color:var(--dsw-alias-label-secondary)}',
111
+ '.dshbtw-state.is-error{color:var(--dsw-alias-state-error-primary)}',
112
+ '.dshbtw-a{white-space:pre-wrap;word-break:break-word}',
113
+ '.dshbtw-a.is-error{color:var(--dsw-alias-state-error-primary)}',
114
+ '.dshbtw-a.is-running{color:var(--dsw-alias-label-secondary);animation:dshbtw-pulse 1.4s ease-in-out infinite}',
115
+ '@keyframes dshbtw-pulse{0%,100%{opacity:.55}50%{opacity:1}}',
116
+ '@media(prefers-reduced-motion:reduce){.dshbtw-a.is-running{animation:none}}',
117
+ '.dshbtw-actions{display:flex;align-items:center;gap:6px;margin-top:2px}',
118
+ '.dshbtw-btn{display:inline-flex;align-items:center;justify-content:center;gap:4px;height:22px;padding:0 8px;',
119
+ 'border:0.5px solid var(--dsw-alias-border-l1);border-radius:6px;background:transparent;',
120
+ 'color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;cursor:pointer}',
121
+ '.dshbtw-btn:hover{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}',
122
+ '.dshbtw-meta{flex:1;min-width:0;font-size:11px;color:var(--dsw-alias-state-idle-primary);overflow:hidden;',
123
+ 'text-overflow:ellipsis;white-space:nowrap}',
124
+ '.dshbtw-chip{display:flex;align-items:center;gap:6px;width:100%;max-width:100%;padding:2px 0;',
125
+ 'border:0;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;',
126
+ 'line-height:18px;text-align:left;cursor:pointer}',
127
+ '.dshbtw-chip:hover{color:var(--dsw-alias-label-primary)}',
128
+ '.dshbtw-chip-mark{flex:none;color:var(--dsw-alias-brand-primary)}',
129
+ '.dshbtw-chip-label{flex:none;font-weight:600}',
130
+ '.dshbtw-chip-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
131
+ '.dshbtw-chip-state{flex:none;color:var(--dsw-alias-state-idle-primary)}',
132
+ '.dshbtw-chip-state.is-error{color:var(--dsw-alias-state-error-primary)}',
133
+ ].join('')
134
+
135
+ // ------------------------------------------------------------------ error
136
+
137
+ /** Keep one crashing view from blanking the whole slot entry. */
138
+ class Boundary extends React.Component {
139
+ constructor(props) {
140
+ super(props)
141
+ this.state = { error: null }
142
+ }
143
+ static getDerivedStateFromError(error) {
144
+ return { error }
145
+ }
146
+ componentDidCatch(error) {
147
+ try {
148
+ console.error('[dsh-btw] view crashed', error)
149
+ } catch {
150
+ /* logging must never throw */
151
+ }
152
+ }
153
+ render() {
154
+ if (this.state.error !== null) return this.props.fallback === undefined ? null : this.props.fallback
155
+ return this.props.children
156
+ }
157
+ }
158
+
159
+ // ------------------------------------------------------------------- data
160
+
161
+ const EMPTY = Object.freeze([])
162
+
163
+ /**
164
+ * Collect the `/btw` command nodes of the current Chat target.
165
+ *
166
+ * A command node is `{kind:'command', data:{commandId,name,args,outcome,…}}`.
167
+ * `outcome === null` means the handler is still running; otherwise
168
+ * `outcome.kind` is 'success' | 'error' and `outcome.text` may carry the
169
+ * answer. The selector never throws: a slot entry that throws is removed by
170
+ * the host, so every access is defensive.
171
+ */
172
+ function selectBtwRecords(snapshot) {
173
+ try {
174
+ const nodes = snapshot && snapshot.nodes
175
+ if (!nodes || typeof nodes.values !== 'function') return EMPTY
176
+ const records = []
177
+ for (const node of nodes.values()) {
178
+ if (!node || typeof node !== 'object') continue
179
+ const data = node.data !== null && typeof node.data === 'object' ? node.data : node
180
+ if (data.name !== 'btw') continue
181
+ records.push(data)
182
+ }
183
+ if (records.length === 0) return EMPTY
184
+ records.sort((left, right) => (Number(left.seq) || 0) - (Number(right.seq) || 0))
185
+ return records
186
+ } catch {
187
+ return EMPTY
188
+ }
189
+ }
190
+
191
+ /** Field-wise stability so a fresh array does not re-render on every snapshot. */
192
+ function sameRecords(left, right) {
193
+ if (left === right) return true
194
+ if (!left || !right || left.length !== right.length) return false
195
+ for (let index = 0; index < left.length; index += 1) {
196
+ const a = left[index]
197
+ const b = right[index]
198
+ if (a === b) continue
199
+ if (a.commandId !== b.commandId || a.args !== b.args || a.time !== b.time) return false
200
+ const ao = a.outcome
201
+ const bo = b.outcome
202
+ if (ao === bo) continue
203
+ if (!ao || !bo) return false
204
+ if (ao.kind !== bo.kind || ao.text !== bo.text) return false
205
+ }
206
+ return true
207
+ }
208
+
209
+ /** Read the session's side-question records through the Chat hook. */
210
+ function useBtwRecords(useChat) {
211
+ const records = typeof useChat === 'function' ? useChat(selectBtwRecords, sameRecords) : EMPTY
212
+ return Array.isArray(records) ? records : EMPTY
213
+ }
214
+
215
+ /** Trailer the Host appends to every answer to name its child session. */
216
+ const CHILD_MARKER = /\[\[dsh-btw:child=([^\]\s]+)\]\]/u
217
+
218
+ /**
219
+ * Normalize one command record for rendering.
220
+ *
221
+ * Strips the child marker out of the visible answer, and keeps the child
222
+ * session id when the Host published one: that id is what opens the side
223
+ * agent's own conversation (tool calls and native approval prompts) in the
224
+ * right Sidebar.
225
+ */
226
+ function viewOf(record) {
227
+ const outcome = record.outcome !== null && typeof record.outcome === 'object' ? record.outcome : undefined
228
+ const raw = outcome !== undefined && typeof outcome.text === 'string' ? outcome.text : ''
229
+ const match = CHILD_MARKER.exec(raw)
230
+ return {
231
+ commandId: String(record.commandId ?? ''),
232
+ question: typeof record.args === 'string' ? record.args.trim() : '',
233
+ answer: raw.replace(CHILD_MARKER, '').replace(/\s+$/u, ''),
234
+ childId: match === null ? undefined : match[1],
235
+ running: record.outcome === null,
236
+ failed: outcome !== undefined && outcome.kind === 'error',
237
+ }
238
+ }
239
+
240
+ // ------------------------------------------------------------------ glyph
241
+
242
+ /** Guide artwork for the "开始" page entry: a bubble with a question spark. */
243
+ function BtwGlyph(props) {
244
+ const size = props !== null && typeof props === 'object' && Number.isFinite(props.size) ? props.size : 20
245
+ return h(
246
+ 'svg',
247
+ { viewBox: '0 0 24 24', width: size, height: size, fill: 'none', 'aria-hidden': true },
248
+ h('path', {
249
+ d: 'M4 6.5A2.5 2.5 0 0 1 6.5 4h7A2.5 2.5 0 0 1 16 6.5v4A2.5 2.5 0 0 1 13.5 13H9l-3.2 2.9V13H6.5A2.5 2.5 0 0 1 4 10.5z',
250
+ stroke: 'currentColor',
251
+ strokeWidth: 1.4,
252
+ strokeLinejoin: 'round',
253
+ }),
254
+ h('path', {
255
+ d: 'M18.6 10.2l.9 2 2 .9-2 .9-.9 2-.9-2-2-.9 2-.9z',
256
+ fill: 'currentColor',
257
+ opacity: 0.85,
258
+ }),
259
+ )
260
+ }
261
+
262
+ // ------------------------------------------------------------------- chip
263
+
264
+ /**
265
+ * Transcript chip registered on `conversation.chat.commandview` key 'btw'.
266
+ *
267
+ * It replaces the generic command card for `/btw` only: the answer belongs
268
+ * to the right-Sidebar page, and the transcript keeps a single quiet line
269
+ * that reveals it. A fresh question opens the page automatically; an old one
270
+ * only opens when clicked, so reopening a session does not move the column.
271
+ */
272
+ function BtwChip(props) {
273
+ const t = props.__btwStrings
274
+ const data = props.node !== null && typeof props.node === 'object' ? props.node : {}
275
+ const view = viewOf(data)
276
+ const state = view.running ? t.running : view.failed ? t.failed : t.done
277
+
278
+ // A fresh question reveals the side agent's own conversation: that is
279
+ // where its tool calls and approval prompts live. The child id only
280
+ // arrives with the settled answer, so this also fires on completion.
281
+ React.useEffect(() => {
282
+ if (view.childId === undefined) return
283
+ const at = Number(data.time)
284
+ const fresh = Number.isFinite(at) ? Date.now() - at < 300000 : false
285
+ if (!fresh) return
286
+ if (typeof navigation.openChild === 'function') navigation.openChild(view.childId, props.sessionId)
287
+ }, [view.childId, data.time])
288
+
289
+ return h(
290
+ 'button',
291
+ {
292
+ type: 'button',
293
+ className: 'dshbtw-chip',
294
+ title: t.chipOpen,
295
+ onClick: () => {
296
+ if (view.childId !== undefined && typeof navigation.openChild === 'function') {
297
+ navigation.openChild(view.childId, props.sessionId)
298
+ return
299
+ }
300
+ if (typeof navigation.open === 'function') navigation.open()
301
+ },
302
+ },
303
+ h('style', { key: 'style' }, CSS),
304
+ h('span', { key: 'mark', className: 'dshbtw-chip-mark', 'aria-hidden': true }, '◈'),
305
+ h('span', { key: 'label', className: 'dshbtw-chip-label' }, t.badge),
306
+ h('span', { key: 'text', className: 'dshbtw-chip-text' }, view.question === '' ? t.emptyQuestion : view.question),
307
+ h('span', { key: 'state', className: view.failed ? 'dshbtw-chip-state is-error' : 'dshbtw-chip-state' }, state),
308
+ )
309
+ }
310
+
311
+ // ------------------------------------------------------------------ page
312
+
313
+ /** One side question: question, answer, and its copy / sub-session actions. */
314
+ function SideQuestionCard(props) {
315
+ const t = props.strings
316
+ const record = props.record
317
+ const view = viewOf(record)
318
+ const [copied, setCopied] = React.useState(false)
319
+
320
+ const copy = () => {
321
+ const text = `${t.questionPrefix}: ${view.question}\n\n${t.answerPrefix}: ${view.answer}`
322
+ try {
323
+ navigator.clipboard.writeText(text).then(
324
+ () => setCopied(true),
325
+ () => setCopied(false),
326
+ )
327
+ } catch {
328
+ setCopied(false)
329
+ }
330
+ }
331
+
332
+ return h(
333
+ 'div',
334
+ { className: 'dshbtw-card' },
335
+ h(
336
+ 'div',
337
+ { className: 'dshbtw-card-head' },
338
+ h('div', { className: 'dshbtw-q' }, view.question === '' ? t.emptyQuestion : view.question),
339
+ h(
340
+ 'span',
341
+ { className: view.failed ? 'dshbtw-state is-error' : 'dshbtw-state' },
342
+ view.running ? t.running : view.failed ? t.failed : t.done,
343
+ ),
344
+ ),
345
+ h(
346
+ 'div',
347
+ { className: view.running ? 'dshbtw-a is-running' : view.failed ? 'dshbtw-a is-error' : 'dshbtw-a' },
348
+ view.running ? t.running : view.answer,
349
+ ),
350
+ view.running
351
+ ? null
352
+ : h(
353
+ 'div',
354
+ { className: 'dshbtw-actions' },
355
+ h(
356
+ 'button',
357
+ { type: 'button', className: 'dshbtw-btn', onClick: copy },
358
+ copied ? t.copied : t.copy,
359
+ ),
360
+ view.childId === undefined
361
+ ? null
362
+ : h(
363
+ 'button',
364
+ {
365
+ type: 'button',
366
+ className: 'dshbtw-btn',
367
+ title: t.openChildHint,
368
+ onClick: () => {
369
+ if (typeof navigation.openChild === 'function') navigation.openChild(view.childId, props.sessionId)
370
+ },
371
+ },
372
+ t.openChild,
373
+ ),
374
+ ),
375
+ )
376
+ }
377
+
378
+ /**
379
+ * The right-Sidebar page body: newest side question first.
380
+ *
381
+ * Rendered through `sidebar.right.pane.tab` under this package's type id, so
382
+ * the tab system owns the pane, the chip, the split and the floating form;
383
+ * this component owns only the content.
384
+ */
385
+ function BtwPage(props) {
386
+ const t = props.__btwStrings
387
+ const records = useBtwRecords(props.useChat)
388
+ const ordered = React.useMemo(() => [...records].reverse(), [records])
389
+
390
+ return h(
391
+ 'div',
392
+ { className: 'dshbtw-page', role: 'region', 'aria-label': t.badge },
393
+ h('style', { key: 'style' }, CSS),
394
+ ordered.length === 0
395
+ ? h(
396
+ 'div',
397
+ { key: 'empty', className: 'dshbtw-empty' },
398
+ h('div', { key: 'title', className: 'dshbtw-empty-title' }, t.emptyTitle),
399
+ h('div', { key: 'hint', className: 'dshbtw-empty-hint' }, t.emptyHint),
400
+ )
401
+ : ordered.map((record) =>
402
+ h(SideQuestionCard, {
403
+ key: String(record.commandId ?? record.seq),
404
+ record,
405
+ strings: t,
406
+ }),
407
+ ),
408
+ )
409
+ }
410
+
411
+ // -------------------------------------------------------------- bootstrap
412
+
413
+ /** Strings that may go into a locale dictionary (values must be plain text). */
414
+ function stringsOnly(dict) {
415
+ const out = {}
416
+ for (const key of Object.keys(dict)) {
417
+ if (typeof dict[key] === 'string') out[key] = dict[key]
418
+ }
419
+ return out
420
+ }
421
+
422
+ /** Active language id, preferring the locale service over the document. */
423
+ function activeLanguage(ctx) {
424
+ const locale = ctx.get('locale')
425
+ if (locale !== null && locale !== undefined && typeof locale.getLocale === 'function') {
426
+ try {
427
+ const snapshot = locale.getLocale()
428
+ // LocaleSnapshot is `{ active, locales, revision }`.
429
+ const id = snapshot !== null && typeof snapshot === 'object' ? snapshot.active : undefined
430
+ if (typeof id === 'string' && id !== '') return id.toLowerCase().startsWith('zh') ? 'zh' : 'en'
431
+ } catch {
432
+ /* fall through to the document language */
433
+ }
434
+ }
435
+ return documentLanguage()
436
+ }
437
+
438
+ /** Resolve visible copy: the locale service when present, else `en`/`zh`. */
439
+ function resolveStrings(ctx) {
440
+ const base = STRINGS[activeLanguage(ctx)]
441
+ const locale = ctx.get('locale')
442
+ if (locale === null || locale === undefined || typeof locale.register !== 'function' || typeof locale.bind !== 'function') {
443
+ return base
444
+ }
445
+ let translate
446
+ try {
447
+ ctx.effect(() => {
448
+ const disposers = [
449
+ locale.register('dsh-btw', 'zh', stringsOnly(STRINGS.zh)),
450
+ locale.register('dsh-btw', 'en', stringsOnly(STRINGS.en)),
451
+ ]
452
+ return () => {
453
+ for (const dispose of disposers) {
454
+ try {
455
+ dispose()
456
+ } catch {
457
+ /* a failed dictionary removal must not break unload */
458
+ }
459
+ }
460
+ }
461
+ }, 'dsh-btw locale')
462
+ translate = locale.bind('dsh-btw')
463
+ } catch {
464
+ return base
465
+ }
466
+ if (typeof translate !== 'function') return base
467
+ const merged = { ...base }
468
+ for (const key of Object.keys(base)) {
469
+ if (typeof base[key] !== 'string') continue
470
+ try {
471
+ const value = translate(key)
472
+ if (typeof value === 'string' && value !== '') merged[key] = value
473
+ } catch {
474
+ /* keep the built-in copy for this key */
475
+ }
476
+ }
477
+ // Pluralizing helpers stay language-specific closures.
478
+ merged.count = base.count
479
+ return merged
480
+ }
481
+
482
+ return {
483
+ // Hard dependencies of the hand-written module: the slot seat, and the
484
+ // right-Sidebar tab registry + navigation controller. Declaring them here
485
+ // is what makes `ctx.get` resolve them; the transcript chip still renders
486
+ // if the right column is absent from the composition.
487
+ inject: ['slots', 'sidebarRightTabs', 'sidebarRight'],
488
+ apply(ctx) {
489
+ const strings = resolveStrings(ctx)
490
+ const tabs = ctx.get('sidebarRightTabs')
491
+ const right = ctx.get('sidebarRight')
492
+
493
+ navigation.open = () => {
494
+ try {
495
+ if (right !== null && right !== undefined && typeof right.openTab === 'function') {
496
+ right.openTab(KIND)
497
+ debug.lastError = null
498
+ } else {
499
+ debug.lastError = 'sidebarRight.openTab unavailable'
500
+ }
501
+ } catch (error) {
502
+ debug.lastError = error instanceof Error ? error.message : String(error)
503
+ try {
504
+ console.error('[dsh-btw] could not open the side-question page', error)
505
+ } catch {
506
+ /* ignore */
507
+ }
508
+ }
509
+ }
510
+
511
+ /**
512
+ * Open one side agent's own conversation in the right Sidebar.
513
+ *
514
+ * This is the built-in subagent tab: it renders the child's live
515
+ * conversation, so the side agent's tool calls and its **approval
516
+ * prompts** appear exactly where DSH puts them. Falls back to the
517
+ * side-question page when the address is rejected.
518
+ */
519
+ navigation.openChild = (childId, parentId) => {
520
+ if (typeof childId !== 'string' || childId === '') {
521
+ navigation.open()
522
+ return
523
+ }
524
+ const address = `dsh-resource://subagentchat/session/${childId}?parent=${parentId ?? ''}&mode=continuable`
525
+ try {
526
+ if (right !== null && right !== undefined && typeof right.openResource === 'function') {
527
+ right.openResource(address)
528
+ debug.lastError = null
529
+ return
530
+ }
531
+ debug.lastError = 'sidebarRight.openResource unavailable'
532
+ } catch (error) {
533
+ debug.lastError = error instanceof Error ? error.message : String(error)
534
+ }
535
+ navigation.open()
536
+ }
537
+
538
+ debug.tabs = tabs !== null && tabs !== undefined
539
+ debug.right = right !== null && right !== undefined
540
+ debug.open = navigation.open
541
+ debug.openChild = navigation.openChild
542
+
543
+ // The page type: a page (no resource patterns), opened by kind.
544
+ if (tabs !== null && tabs !== undefined && typeof tabs.register === 'function') {
545
+ ctx.effect(
546
+ () =>
547
+ tabs.register({
548
+ id: TYPE_ID,
549
+ kind: KIND,
550
+ priority: 'extension',
551
+ title: () => strings.typeLabel,
552
+ guide: [
553
+ {
554
+ id: 'questions',
555
+ order: 20,
556
+ title: () => strings.guideTitle,
557
+ description: () => strings.guideDescription,
558
+ icon: BtwGlyph,
559
+ },
560
+ ],
561
+ }),
562
+ 'dsh-btw tab type',
563
+ )
564
+
565
+ ctx.slots.inject('sidebar.right.pane.tab', () =>
566
+ ctx.slots.register(
567
+ { name: 'sidebar.right.pane.tab', key: TYPE_ID },
568
+ (props) => h(Boundary, { fallback: null }, h(BtwPage, { ...props, __btwStrings: strings })),
569
+ ),
570
+ )
571
+ }
572
+
573
+ // The transcript chip works even without the right-Sidebar registry.
574
+ ctx.slots.inject('conversation.chat.commandview', () =>
575
+ ctx.slots.register(
576
+ { name: 'conversation.chat.commandview', key: 'btw' },
577
+ (props) => h(Boundary, { fallback: null }, h(BtwChip, { ...props, __btwStrings: strings })),
578
+ ),
579
+ )
580
+ },
581
+ }
582
+ },
583
+ })
@@ -0,0 +1,38 @@
1
+ # dsh-btw bundle patch layer.
2
+ #
3
+ # Listing `dsh-btw` in a profile's `dsh.profile.bundles` applies this layer. The
4
+ # row name is the BARE package name so pnpm resolves it from the profile.
5
+ #
6
+ # Every field below is optional; the plugin falls back to these defaults when a
7
+ # row omits them. A profile patch that overrides this row by `id` replaces the
8
+ # whole `config` object, so restate every key you still want.
9
+ - insert:
10
+ - id: dsh-btw
11
+ name: '@aspen138/dsh-btw'
12
+ config:
13
+ # Refuse absurdly long questions before spending a child agent.
14
+ maxQuestionChars: 8000
15
+ # Subagent backend used for the disposable side agent. `fork` seeds the
16
+ # child with this conversation's completed turns; `spawn` would start it
17
+ # without any inherited context.
18
+ childProvider: fork
19
+ # 'ask' pauses approval-gated tools for a user decision. The prompt is
20
+ # rendered in the side agent's own conversation, which this plugin opens
21
+ # in the right Sidebar, so the answer lands where the user can see it.
22
+ approvalPolicy: ask
23
+ # Permission bundle applied to the disposable side agent: reads pass,
24
+ # writes ask. `inherit` would follow this profile's danger-full-access
25
+ # default and let the side agent write silently.
26
+ sideAgentPreset: workspace-write
27
+ # Release the child's execution handle once its answer is in hand. The
28
+ # child session itself stays durable (it is a normal Session).
29
+ disposeChild: true
30
+ # Hard ceiling for one side question. A child whose approval prompt is
31
+ # never answered is cancelled instead of holding the command open.
32
+ sideAgentTimeoutMs: 180000
33
+ # Ceiling for one answer, so a runaway child cannot fill the command row.
34
+ answerMaxChars: 12000
35
+ # Pin the child's model route. Empty inherits the parent's route, which
36
+ # also keeps the inherited prefix cache-reusable.
37
+ provider: ''
38
+ model: ''
package/icon.svg ADDED
@@ -0,0 +1,15 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Side question">
2
+ <defs>
3
+ <linearGradient id="btw-g" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0" stop-color="#4b8bff"/>
5
+ <stop offset="1" stop-color="#7a5cff"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <rect x="4" y="4" width="56" height="56" rx="16" fill="url(#btw-g)"/>
9
+ <path d="M18 21h20a8 8 0 0 1 8 8v6a8 8 0 0 1-8 8H30l-8 7v-7h-4a4 4 0 0 1-4-4V25a4 4 0 0 1 4-4z"
10
+ fill="#ffffff" fill-opacity="0.94"/>
11
+ <path d="M46 33.5l1.9 4.1 4.1 1.9-4.1 1.9-1.9 4.1-1.9-4.1-4.1-1.9 4.1-1.9z" fill="#ffffff"/>
12
+ <path d="M28 27.5c1.9 0 3.4 1.4 3.4 3.3 0 2.6-3.4 3.4-3.4 5.6" stroke="#4a5cc7" stroke-width="2.4"
13
+ stroke-linecap="round" fill="none"/>
14
+ <circle cx="28" cy="40.4" r="1.5" fill="#4a5cc7"/>
15
+ </svg>
package/index.js ADDED
@@ -0,0 +1,312 @@
1
+ /**
2
+ * dsh-btw — Antigravity-style `/btw` side questions for DeepSeek Harness.
3
+ *
4
+ * A `/btw <question>` line asks one question "by the way" while a task is in
5
+ * progress. It must not steer the main task, so this plugin does **not** write
6
+ * anything the main conversation can see: the question starts one **forked
7
+ * child agent** (seeded with the parent's completed turns, full tool set), the
8
+ * child works in its own session, and its final answer comes back as the
9
+ * command result. The child is disposed once it settles. The parent session
10
+ * gains only the log-only `command/run` + `command/done` pair.
11
+ *
12
+ * Why a child agent instead of one bare model call: the side question is
13
+ * allowed to *check things* — read a file, grep, run a command — using the
14
+ * same tool pipeline, sandbox, and approval policy as the main conversation.
15
+ * It therefore cannot answer from stale context alone, which is the whole
16
+ * difference from a plain "ask about the transcript" feature.
17
+ *
18
+ * Design limits (documented in README.md):
19
+ * - the child is a real agent: every tool, its own turn, its own tokens;
20
+ * - results are delivered to this caller only (`delivery: 'caller'`), so no
21
+ * completion notice is injected into the parent conversation;
22
+ * - the child session persists (durable), the execution handle does not.
23
+ *
24
+ * @module dsh-btw
25
+ */
26
+
27
+ /** Command name without the slash. */
28
+ const COMMAND_NAME = 'btw'
29
+
30
+ /** Command identity reported to clients that select first-party row faces. */
31
+ const DEFINITION_ID = '@local/dsh-btw'
32
+
33
+ /** Defaults for every tunable value; the bundle patch may override each one. */
34
+ const DEFAULTS = Object.freeze({
35
+ maxQuestionChars: 8000,
36
+ childProvider: 'fork',
37
+ approvalPolicy: 'ask',
38
+ sideAgentPreset: 'read-only',
39
+ disposeChild: true,
40
+ sideAgentTimeoutMs: 180000,
41
+ answerMaxChars: 12000,
42
+ })
43
+
44
+ /**
45
+ * Machine-readable trailer that names the child session behind one answer.
46
+ *
47
+ * The Client half uses it to open that child's conversation in the right
48
+ * Sidebar, which is where DSH renders the side agent's tool calls and its native
49
+ * approval prompts. It is stripped from every rendered answer.
50
+ */
51
+ const CHILD_MARKER = 'dsh-btw:child='
52
+
53
+ /**
54
+ * Wrap one raw question into the child's task text.
55
+ *
56
+ * The child inherits the parent conversation as its seed, so this prompt only
57
+ * has to state the side-question contract: answer this one thing, do not take
58
+ * over the main task, and prefer checking the workspace over guessing.
59
+ *
60
+ * @param question - trimmed user question.
61
+ * @returns the task text handed to the child agent.
62
+ */
63
+ function frameQuestion(question) {
64
+ return [
65
+ '【侧问】这是一次不打断主线任务的侧问。',
66
+ '',
67
+ `问题:${question}`,
68
+ '',
69
+ '要求:',
70
+ '1. 只回答这一个问题。不要继续、改写或推进主线任务;不要修改与回答问题无关的文件。',
71
+ '2. 需要事实依据就去查:读文件、搜索、跑只读命令都可以;不要凭印象猜。',
72
+ '3. 如果确实需要写操作(改文件、执行有副作用的命令),先说明你要做什么;需要审批时等待审批。',
73
+ '4. 答案要短,直接给结论和依据;不要复述上面已经说过的整段对话。',
74
+ ].join('\n')
75
+ }
76
+
77
+ /**
78
+ * Normalize the raw bundle config into the options this plugin understands.
79
+ *
80
+ * A plain Host bundle cannot import the Loader's schema package, so values are
81
+ * read defensively instead of being validated by a `Config` export.
82
+ *
83
+ * @param raw - untrusted row config.
84
+ * @returns normalized options.
85
+ */
86
+ function normalizeConfig(raw) {
87
+ const input = raw !== null && typeof raw === 'object' ? raw : {}
88
+ const number = (value, fallback, min, max) =>
89
+ typeof value === 'number' && Number.isFinite(value) && value >= min && value <= max ? value : fallback
90
+ const text = (value, fallback) => (typeof value === 'string' && value !== '' ? value : fallback)
91
+ return {
92
+ maxQuestionChars: number(input.maxQuestionChars, DEFAULTS.maxQuestionChars, 1, 100000),
93
+ childProvider: text(input.childProvider, DEFAULTS.childProvider),
94
+ approvalPolicy: input.approvalPolicy === 'inherit' ? 'inherit' : DEFAULTS.approvalPolicy,
95
+ sideAgentPreset: text(input.sideAgentPreset, DEFAULTS.sideAgentPreset),
96
+ disposeChild: typeof input.disposeChild === 'boolean' ? input.disposeChild : DEFAULTS.disposeChild,
97
+ sideAgentTimeoutMs: number(input.sideAgentTimeoutMs, DEFAULTS.sideAgentTimeoutMs, 5000, 3600000),
98
+ answerMaxChars: number(input.answerMaxChars, DEFAULTS.answerMaxChars, 200, 200000),
99
+ provider: typeof input.provider === 'string' ? input.provider : '',
100
+ model: typeof input.model === 'string' ? input.model : '',
101
+ }
102
+ }
103
+
104
+ /** Concatenate the text blocks of a child's final answer. */
105
+ function answerText(output) {
106
+ if (!Array.isArray(output)) return ''
107
+ const parts = []
108
+ for (const block of output) {
109
+ if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
110
+ parts.push(block.text)
111
+ }
112
+ }
113
+ return parts.join('\n').trim()
114
+ }
115
+
116
+ /** Trim one answer to the configured ceiling without cutting a word in half. */
117
+ function clip(text, maxChars) {
118
+ if (text.length <= maxChars) return text
119
+ return `${text.slice(0, maxChars)}\n\n…(答案过长,已截断到 ${maxChars} 字符)`
120
+ }
121
+
122
+ /** Human sentence for one failed child run. */
123
+ function failureText(result) {
124
+ const diagnostic = result !== null && typeof result === 'object' && typeof result.diagnostic === 'string' ? result.diagnostic : ''
125
+ const stop = result !== null && typeof result === 'object' && typeof result.stopReason === 'string' ? result.stopReason : 'error'
126
+ if (diagnostic !== '') return `侧问失败(${stop}):${diagnostic}`
127
+ return `侧问失败(${stop}):子 agent 没有产出答案。`
128
+ }
129
+
130
+ /**
131
+ * Run one side question as a disposable forked child agent.
132
+ *
133
+ * The child is seeded from the parent's completed turns, inherits the parent's
134
+ * preset (therefore the same tool set), and reports only to this caller. When
135
+ * the configured approval policy is `ask`, write tools pause for the same
136
+ * approval flow the main conversation uses instead of running unattended.
137
+ *
138
+ * @param ctx - Host plugin context.
139
+ * @param invocation - the settled command invocation.
140
+ * @param question - trimmed question.
141
+ * @param config - normalized options.
142
+ * @returns `{ text, childId }` on success.
143
+ */
144
+ async function runSideAgent(ctx, invocation, question, config) {
145
+ const agents = ctx.get('agents')
146
+ const subagents = ctx.get('subagents')
147
+ if (subagents === null || subagents === undefined || typeof subagents.startActivation !== 'function') {
148
+ throw new Error('当前 profile 没有 subagent 服务,/btw 无法运行子 agent。')
149
+ }
150
+ const parent = agents !== null && agents !== undefined && typeof agents.get === 'function'
151
+ ? agents.get(invocation.agent.id)
152
+ : undefined
153
+ if (parent === undefined) throw new Error('当前会话不是本进程的活会话,/btw 无法继承上下文。')
154
+
155
+ const agentOptions = {}
156
+ if (config.provider !== '' && config.model !== '') {
157
+ agentOptions.provider = config.provider
158
+ agentOptions.model = config.model
159
+ }
160
+
161
+ // One cancellation owning both the caller's signal and this plugin's ceiling:
162
+ // a child whose approval never gets answered must not keep the command open
163
+ // forever.
164
+ const controller = new AbortController()
165
+ const forwardAbort = () => controller.abort()
166
+ const callerSignal = invocation.signal
167
+ if (callerSignal !== undefined && callerSignal !== null) {
168
+ if (callerSignal.aborted === true) controller.abort()
169
+ else if (typeof callerSignal.addEventListener === 'function') callerSignal.addEventListener('abort', forwardAbort, { once: true })
170
+ }
171
+ const timer = setTimeout(() => controller.abort(), config.sideAgentTimeoutMs)
172
+
173
+ let activation
174
+ try {
175
+ activation = await subagents.startActivation({
176
+ provider: config.childProvider,
177
+ label: `侧问:${question.slice(0, 48)}`,
178
+ request: {
179
+ prompt: [{ type: 'text', text: frameQuestion(question) }],
180
+ parent,
181
+ ...(Object.keys(agentOptions).length === 0 ? {} : { agentOptions }),
182
+ },
183
+ signal: controller.signal,
184
+ delivery: 'caller',
185
+ })
186
+ } catch (error) {
187
+ clearTimeout(timer)
188
+ if (callerSignal !== undefined && callerSignal !== null && typeof callerSignal.removeEventListener === 'function') {
189
+ callerSignal.removeEventListener('abort', forwardAbort)
190
+ }
191
+ throw error
192
+ }
193
+
194
+ try {
195
+ // Apply the side agent's permission bundle before its first tool call can
196
+ // settle. `read-only` / `workspace-write` carry approval: 'ask', which is
197
+ // what turns a write into a permission request instead of a silent write.
198
+ if (config.sideAgentPreset !== 'inherit') {
199
+ const presets = ctx.get('permissionPresets')
200
+ const sessions = ctx.get('sessions')
201
+ const childSession = sessions !== null && sessions !== undefined && typeof sessions.get === 'function'
202
+ ? sessions.get(activation.childId)
203
+ : undefined
204
+ if (presets !== null && presets !== undefined && typeof presets.set === 'function' && childSession !== undefined) {
205
+ try {
206
+ presets.set(childSession, config.sideAgentPreset)
207
+ } catch {
208
+ /* unknown preset or a child that already settled */
209
+ }
210
+ }
211
+ }
212
+
213
+ // Write tools ask, like the main conversation under an ask policy. The
214
+ // child starts on activation, so this runs immediately after creation —
215
+ // before its first tool call can settle.
216
+ if (config.approvalPolicy === 'ask') {
217
+ const approval = ctx.get('approval')
218
+ const child = agents !== null && agents !== undefined && typeof agents.get === 'function'
219
+ ? agents.get(activation.childId)
220
+ : undefined
221
+ if (approval !== null && approval !== undefined && typeof approval.setPolicy === 'function' && child !== undefined) {
222
+ try {
223
+ approval.setPolicy(child, 'ask')
224
+ } catch {
225
+ /* a child that already settled needs no policy */
226
+ }
227
+ }
228
+ }
229
+
230
+ const result = await activation.result
231
+ if (result === null || typeof result !== 'object') throw new Error('子 agent 没有返回结果。')
232
+ if (result.stopReason !== 'completed') throw new Error(failureText(result))
233
+ const text = answerText(result.output)
234
+ if (text === '') throw new Error('子 agent 没有产出正文。')
235
+ return { text: clip(text, config.answerMaxChars), childId: String(activation.childId) }
236
+ } finally {
237
+ clearTimeout(timer)
238
+ if (callerSignal !== undefined && callerSignal !== null && typeof callerSignal.removeEventListener === 'function') {
239
+ callerSignal.removeEventListener('abort', forwardAbort)
240
+ }
241
+ if (config.disposeChild) {
242
+ try {
243
+ await activation.dispose()
244
+ } catch {
245
+ /* the answer already exists; a failed release must not hide it */
246
+ }
247
+ }
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Register `/btw` for every composed human-command adapter.
253
+ *
254
+ * The handler settles the whole child run before returning, so the answer
255
+ * arrives as the command result in the same lifecycle record that the Chat
256
+ * layer already renders. Only one side question per parent session may run at
257
+ * a time: a second one is refused rather than queued behind the first.
258
+ *
259
+ * @param ctx - Host plugin context.
260
+ * @param rawConfig - raw bundle config from the Loader row.
261
+ */
262
+ export function apply(ctx, rawConfig) {
263
+ const config = normalizeConfig(rawConfig)
264
+ const inFlight = new Map()
265
+
266
+ const handler = async (invocation) => {
267
+ const question = typeof invocation.rawInput === 'string' ? invocation.rawInput.trim() : ''
268
+ if (question === '') {
269
+ return {
270
+ kind: 'success',
271
+ text: '用法:/btw <问题>\n侧问会起一个继承当前上下文的临时子 agent(可用工具、写操作需审批),答案不进主干上下文。',
272
+ }
273
+ }
274
+ if (question.length > config.maxQuestionChars) {
275
+ return { kind: 'error', text: `问题过长(${question.length} 字符,上限 ${config.maxQuestionChars})。` }
276
+ }
277
+ const sessionId = invocation.agent.id
278
+ if (inFlight.has(sessionId)) {
279
+ return { kind: 'error', text: '上一个侧问还在跑,等它结束再问。' }
280
+ }
281
+ inFlight.set(sessionId, invocation.commandId)
282
+ try {
283
+ const result = await runSideAgent(ctx, invocation, question, config)
284
+ // The trailer names the child session so the Client can open that
285
+ // conversation (tool calls and native approval prompts) in the Sidebar.
286
+ return { kind: 'success', text: `${result.text}\n\n[[${CHILD_MARKER}${result.childId}]]` }
287
+ } catch (error) {
288
+ if (invocation.signal !== undefined && invocation.signal !== null && invocation.signal.aborted === true) {
289
+ return { kind: 'error', text: '侧问已取消。' }
290
+ }
291
+ const message = error instanceof Error ? error.message : String(error)
292
+ return { kind: 'error', text: message }
293
+ } finally {
294
+ inFlight.delete(sessionId)
295
+ }
296
+ }
297
+
298
+ ctx.effect(function* registerCommand() {
299
+ yield () => {
300
+ inFlight.clear()
301
+ }
302
+ yield ctx.commands.register({
303
+ definitionId: DEFINITION_ID,
304
+ name: COMMAND_NAME,
305
+ description: '侧问:起一个继承上下文、能用工具的临时子 agent,答案不进主干上下文',
306
+ input: { hint: '<问题>' },
307
+ handler,
308
+ })
309
+ }, 'dsh-btw command')
310
+ }
311
+
312
+ export const inject = ['commands']
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Side question (/btw)",
4
+ "description": "Ask one contextual question mid-task with no tools; the answer opens in a floating panel and never enters the main session's model context."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "侧问 (/btw)",
4
+ "description": "开发中途问一句:继承当前上下文、不带工具,答案浮在输入框上方,且不进入主干会话的模型上下文。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
- {
1
+ {
2
2
  "name": "@aspen138/dsh-btw",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Antigravity-style /btw side questions for DeepSeek Harness: ask one question mid-task, answered by a disposable forked child agent with the full tool set in its own right-Sidebar tab, without adding anything to the main session's model context.",
5
+ "keywords": [
6
+ "deepseek-harness",
7
+ "dsh-plugin",
8
+ "dsh",
9
+ "btw",
10
+ "side-question",
11
+ "side-query",
12
+ "subagent",
13
+ "context"
14
+ ],
15
+ "license": "MIT",
16
+ "author": "yhm138",
17
+ "type": "module",
18
+ "main": "index.js",
19
+ "exports": {
20
+ ".": "./index.js",
21
+ "./client": "./client.js",
22
+ "./locale/*.json": "./locale/*.json",
23
+ "./icon": "./icon.svg"
24
+ },
25
+ "files": [
26
+ "index.js",
27
+ "client.js",
28
+ "cordis.patch.yml",
29
+ "locale/*.json",
30
+ "icon.svg",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/yhm138/dsh-btw.git"
37
+ },
38
+ "homepage": "https://github.com/yhm138/dsh-btw#readme",
39
+ "bugs": {
40
+ "url": "https://github.com/yhm138/dsh-btw/issues"
41
+ },
42
+ "engines": {
43
+ "dsh": ">=0.2.1-rc.2 <0.3.0-0"
44
+ },
45
+ "dsh": {
46
+ "bundle": {
47
+ "patch": "./cordis.patch.yml"
48
+ },
49
+ "client": {
50
+ "platform": "web",
51
+ "immediately": true,
52
+ "inject": [
53
+ "@deepseek-ai/dsh-client-ui-conversation",
54
+ "@deepseek-ai/dsh-client-ui-sidebar-right"
55
+ ]
56
+ }
57
+ }
58
+ }