dsh-session-title-format 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,132 @@
1
+ # dsh-session-title-format
2
+
3
+ DeepSeek Harness 插件:为每个 Agent 注册 `set_session_title` 工具,把会话标题统一为「MMDD|类型|主题」。
4
+
5
+ ## 规则
6
+
7
+ - **MMDD**:会话实际创建日期(`session.header.createdAt`),按上海时区(`Asia/Shanghai`)计算,由工具自动生成,模型无需也不能提供。
8
+ - **类型**:功能 / 设计 / 开发 / 修复 / 优化 / 发布 / 探索 / 文档 / 研究(工具参数枚举强制)。
9
+ - **主题**:由模型根据对话实际内容简洁概括;工具拒绝空主题、超长主题、重复项目(工作区)名的主题。
10
+ - 无法确定时模型不应调用工具(保留原标题);用户手动命名过的会话,工具直接跳过,不覆盖。
11
+ - 只写 `session/title` 日志事件(标题投影),不触碰项目名称、内容、归属、排序、置顶、归档状态。
12
+
13
+ 已在 dsh 0.1.2-alpha.3(Windows)与 0.1.5-alpha.1(Linux)上验证:headless 独立进程与运行中的 web 服务器(RPC 建会话)两条路径,模型均于首轮主动命名(示例:`0910|研究|闭包概念解释`、`0910|开发|统计log文件总行数`)。
14
+
15
+ > **行为说明**:纯寒暄类对话(如「你好」)无法确定类型/主题,模型会按规则保留原标题——这是设计行为,不是插件失效。有实际内容的对话才会被命名。
16
+
17
+ > **无需手动配置 AGENTS.md**:插件在会话首个 step 通过 `agent/pre-step` 钩子自动注入命名规则(与 `dsh-agent-instructions` 注入全局指令同一机制、`<system-reminder>` 同一格式,作为 plugin 来源的持久 user 消息落盘、resume 不重复注入)。不想要注入可配 `injectInstruction: false`(见「配置」)。
18
+
19
+ ## 安装
20
+
21
+ ### 方式一:官方 CLI(推荐)
22
+
23
+ ```sh
24
+ dsh plugin --profile web add dsh-session-title-format # 从 npm(发布后)
25
+ dsh plugin --profile web add github:<owner>/dsh-session-title-format # 从 GitHub
26
+ dsh plugin --profile web add https://.../dsh-session-title-format-1.0.0.tgz # 从 tarball
27
+ dsh plugin --profile web add /path/to/dsh-session-title-format # 从本地目录(未发布前的等效方式)
28
+ ```
29
+
30
+ 一条命令完成:pnpm 安装到 profile(自动写入 `dependencies`)→ 依据包内 `dsh.bundle` 声明自动登记进 `dsh.profile.bundles`(reconcile 是 `dsh plugin` 自动做的,**无需手动编辑 profile 的 package.json**)。
31
+
32
+ **安装后重启该 profile 的 dsh 进程生效**(bundle 列表在启动时组合;运行中的进程只监视补丁文件,不监视 package.json)。
33
+
34
+ > 从 GitHub 安装带构建脚本的插件时,pnpm 会要求在 profile 的 `pnpm-workspace.yaml` 加 `allowBuilds`;本插件是纯 JS 无构建,无此问题。
35
+
36
+ ### 方式二:市场 GUI
37
+
38
+ 安装任一市场插件(如 `dshmarket`)后,在 Web 设置里搜索安装。市场数据来自社区注册表(见「发布 → 社区收录」)。
39
+
40
+ ### 方式三:手动挂载(无需 npm/pnpm,已在 Linux 实测)
41
+
42
+ 不装任何包,直接放置插件文件并写两个用户级配置文件。**第 1 步:放置插件文件**
43
+
44
+ ```
45
+ ~/.dsh/plugins/dsh-session-title-format/
46
+ ├── index.js # 插件本体
47
+ ├── package.json
48
+ ├── cordis.patch.yml
49
+ └── README.md
50
+ ```
51
+
52
+ **第 2 步:建立依赖解析链接**(让插件能解析宿主的 `@deepseek-ai/dsh-tools`、`@deepseek-ai/schemastery`)
53
+
54
+ ```sh
55
+ mkdir -p ~/.dsh/plugins/node_modules
56
+ ln -s ~/.dsh/profiles/node_modules/@deepseek-ai ~/.dsh/plugins/node_modules/@deepseek-ai
57
+ ```
58
+
59
+ > ⚠️ `@deepseek-ai` 链接的父目录 `node_modules` 先建好,但 **`@deepseek-ai` 本身必须不存在**(`ln -s` 直接在目标位置创建链接;若先 `mkdir` 了它,链接会被错误地嵌套创建在里面)。
60
+ >
61
+ > Windows 用 junction(管理员 PowerShell):
62
+ > ```powershell
63
+ > New-Item -ItemType Directory -Force "$HOME\.dsh\plugins\node_modules" | Out-Null
64
+ > New-Item -ItemType Junction -Path "$HOME\.dsh\plugins\node_modules\@deepseek-ai" -Target "$HOME\.dsh\profiles\node_modules\@deepseek-ai"
65
+ > ```
66
+
67
+ **第 3 步:写家级补丁 `~/.dsh/cordis.patch.yml`**(对所有 profile 生效)
68
+
69
+ ```yaml
70
+ - insert:
71
+ - id: session-title-format
72
+ name: file:///home/<user>/.dsh/plugins/dsh-session-title-format/index.js
73
+ ```
74
+
75
+ > `name` 必须是**绝对路径**的 file:// URL(`<user>` 换成实际用户名;root 用户为 `file:///root/...`,Windows 形如 `file:///C:/Users/<user>/.dsh/...`)。
76
+
77
+ **第 4 步:重启 dsh 进程**(家级补丁热重载在不同版本上行为不一致,重启是最可靠的生效方式)
78
+
79
+ ```sh
80
+ systemctl restart dsh-web.service # systemd 部署示例
81
+ # 手动前台运行的:重启 dsh web(或 dsh --profile <name>)
82
+ ```
83
+
84
+ > 命名规则由插件自动注入,**不需要**再手动配置 `~/.dsh/AGENTS.md`。若此前已配置过,可以删除该条目(保留也不冲突,只是模型会看到两份相同规则)。
85
+
86
+ ### 验证安装
87
+
88
+ 1. **模块自检**(应输出四个导出与插件名):
89
+
90
+ ```sh
91
+ node --input-type=module -e "import('file://$HOME/.dsh/plugins/dsh-session-title-format/index.js').then(m => console.log(Object.keys(m), m.name))"
92
+ ```
93
+
94
+ 2. **功能验证**:在 GUI(或 RPC)发一条**有实际内容**的新消息(如「用一句话说明 git rebase 和 git merge 的区别」),等待回复完成后查看会话标题——应变为 `MMDD|类型|主题` 格式(如 `0910|研究|git rebase 与 merge 区别`)。
95
+
96
+ 3. **日志级核验**(可选,最严谨):解压会话日志(`~/.dsh/sessions/<workspace>/<session-id>/session*.jsonl.zstd`),确认成对出现:
97
+
98
+ ```
99
+ tool/call name=set_session_title args={"type":"...","topic":"..."}
100
+ session/title title="MMDD|类型|主题" source={"kind":"user"}
101
+ tool/result isError=false
102
+ ```
103
+
104
+ 「你好」类寒暄不会被命名(模型按规则保留原标题),属正常现象——若怀疑未生效,请用有实际内容的对话测试。
105
+
106
+ ## 配置(可选)
107
+
108
+ 安装条目可加 `config`(均有默认值):
109
+
110
+ ```yaml
111
+ - insert:
112
+ - id: session-title-format
113
+ name: 'dsh-session-title-format' # 方式一安装时
114
+ # name: file:///home/<user>/.dsh/plugins/dsh-session-title-format/index.js # 方式三挂载时
115
+ config:
116
+ timezone: Asia/Shanghai # MMDD 计算所用 IANA 时区
117
+ maxTopicBytes: 48 # 主题 UTF-8 字节上限(约 16 个汉字)
118
+ injectInstruction: true # 首轮自动注入命名指令(默认 true;改 false 后需自行在 AGENTS.md 配置)
119
+ ```
120
+
121
+ ## 卸载
122
+
123
+ ```sh
124
+ dsh plugin --profile web remove dsh-session-title-format # 方式一:pnpm 移除 + bundles 自动剔除,然后重启进程
125
+ ```
126
+
127
+ 方式三则删除 `~/.dsh/cordis.patch.yml` 的对应条目及 `~/.dsh/plugins/dsh-session-title-format/` 目录,再重启 dsh 进程。已注入过指令的历史会话日志不受影响(指令只对新会话生效)。
128
+
129
+ ## 版本兼容性说明
130
+
131
+ - dsh 0.1.2-alpha.3 / 0.1.5-alpha.1 实测通过(headless + 运行中 web 服务器 RPC 两条路径)
132
+ - 家级补丁热重载在两版本上行为不一致(0.1.2 上条目变更触发重载实证有效;0.1.5 上新建/touch 未触发,需重启)——因此两种安装方式的最后一步都建议重启进程
@@ -0,0 +1,23 @@
1
+ # dsh-session-title-format bundle patch
2
+ #
3
+ # Installed through the official CLI:
4
+ # dsh plugin --profile <name> add dsh-session-title-format
5
+ # the command reconciles `dsh.profile.bundles` against installed packages and,
6
+ # seeing this package's `dsh.bundle` declaration, appends it to the bundle
7
+ # stack. The profile boot then merges THIS patch (a single `insert` of the
8
+ # plugin row) — no profile file edits needed.
9
+ #
10
+ # If the profile still carries an older manual mount line (for example a
11
+ # ~/.dsh/cordis.patch.yml entry pointing at a plugins/ directory), remove it
12
+ # before switching to this bundle channel to avoid double-mounting.
13
+ #
14
+ # Optional per-entry config:
15
+ # - insert:
16
+ # - id: session-title-format
17
+ # name: 'dsh-session-title-format'
18
+ # config:
19
+ # timezone: Asia/Shanghai # IANA timezone for the MMDD date part
20
+ # maxTopicBytes: 48 # topic UTF-8 byte ceiling (16 CJK chars)
21
+ - insert:
22
+ - id: session-title-format
23
+ name: 'dsh-session-title-format'
package/index.js ADDED
@@ -0,0 +1,342 @@
1
+ /**
2
+ * dsh-session-title-format — a DeepSeek Harness plugin that gives every agent a
3
+ * `set_session_title` tool renaming its own session to「MMDD|类型|主题」.
4
+ *
5
+ * - MMDD: the session's actual creation date in the configured timezone
6
+ * (default Asia/Shanghai), computed from `session.header.createdAt`.
7
+ * - 类型: one of a fixed vocabulary (功能/设计/开发/修复/优化/发布/探索/文档/研究),
8
+ * enforced by the tool's parameter enum.
9
+ * - 主题: a concise topic supplied by the agent; the tool cleans it, rejects
10
+ * empty/oversized topics and topics repeating the project (workspace) name,
11
+ * then delegates to `ctx.sessionTitle.rename()`, whose accepted revision is
12
+ * a log-only `session/title` event.
13
+ *
14
+ * Only the title changes: project (workspace) name, content, ownership,
15
+ * ordering, pinning and archive state are untouched by design.
16
+ *
17
+ * Self-contained instruction: at a session's first step the plugin injects
18
+ * the "name this conversation in round one" rule as a durable plugin-sourced
19
+ * user message (the dsh-agent-instructions pattern), so no manual
20
+ * ~/.dsh/AGENTS.md entry is needed. Disable with `injectInstruction: false`.
21
+ *
22
+ * Named exports only (name/inject/Config/apply) and no default export, per the
23
+ * loader's unwrapExports contract. Dependencies (`@deepseek-ai/dsh-tools`,
24
+ * `@deepseek-ai/schemastery`) resolve through the profile module fallback.
25
+ * @module dsh-session-title-format
26
+ */
27
+
28
+ import z from '@deepseek-ai/schemastery'
29
+ import { defineTool } from '@deepseek-ai/dsh-tools'
30
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
31
+
32
+ export const name = 'dsh-session-title-format'
33
+ export const inject = ['tools', 'sessionTitle']
34
+
35
+ /** The fixed type vocabulary of the title format. */
36
+ const TITLE_TYPES = ['功能', '设计', '开发', '修复', '优化', '发布', '探索', '文档', '研究']
37
+ const DEFAULT_TIMEZONE = 'Asia/Shanghai'
38
+ const DEFAULT_MAX_TOPIC_BYTES = 48
39
+ /** Minimum length for a workspace-name fragment that may trip the no-repeat check. */
40
+ const MIN_PROJECT_NAME_FRAGMENT = 4
41
+ /** Plugin-owned system-reminder frame for the injected first-round instruction. */
42
+ const REMINDER_OPEN = '<system-reminder>'
43
+ const REMINDER_CLOSE = '</system-reminder>'
44
+
45
+ /** Schemastery configuration for the plugin entry. */
46
+ export const Config = z.object({
47
+ timezone: z.string().default(DEFAULT_TIMEZONE),
48
+ maxTopicBytes: z.number().step(1).min(4).default(DEFAULT_MAX_TOPIC_BYTES),
49
+ injectInstruction: z.boolean().default(true),
50
+ })
51
+
52
+ /** Terminal control sequences, pipes, and other characters that would break the title format. */
53
+ const OSC_SEQUENCE = /(?:\u001B\]|\u009D)(?:(?!\u0007|\u001B\\)[\s\S])*(?:\u0007|\u001B\\|$)/gu
54
+ const CSI_SEQUENCE = /(?:\u001B\[|\u009B)[0-?]*[ -/]*[@-~]/gu
55
+ const ESC_SEQUENCE = /\u001B[@-_]/gu
56
+ const CONTROL_CHARACTER = /[\u0000-\u001F\u007F-\u009F]/gu
57
+ const DIRECTIONAL_CONTROL = /[\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF]/gu
58
+ /** The vertical bar would split the three-part format, so it never survives cleaning. */
59
+ const PIPE = /\|+/gu
60
+
61
+ /**
62
+ * Clean a topic the same way the session-title service cleans whole titles
63
+ * (so byte accounting matches what will be accepted), plus pipe removal.
64
+ * @param {string} input - raw topic text from the model.
65
+ * @returns {string} the cleaned one-line topic.
66
+ */
67
+ function cleanTopic(input) {
68
+ return String(input)
69
+ .replace(OSC_SEQUENCE, '')
70
+ .replace(CSI_SEQUENCE, '')
71
+ .replace(ESC_SEQUENCE, '')
72
+ .replace(CONTROL_CHARACTER, '')
73
+ .replace(DIRECTIONAL_CONTROL, '')
74
+ .replace(PIPE, ' ')
75
+ .replace(/\s+/gu, ' ')
76
+ .trim()
77
+ }
78
+
79
+ /**
80
+ * Format a Unix epoch millisecond timestamp as MMDD in an IANA timezone.
81
+ * @param {number} epochMs - creation time of the session.
82
+ * @param {string} timeZone - IANA timezone identifier, e.g. 'Asia/Shanghai'.
83
+ * @returns {string} zero-padded `MMDD`.
84
+ * @throws {RangeError} when the timezone identifier is invalid.
85
+ */
86
+ function mmddInTimeZone(epochMs, timeZone) {
87
+ const parts = new Intl.DateTimeFormat('en-US', {
88
+ timeZone,
89
+ month: '2-digit',
90
+ day: '2-digit',
91
+ }).formatToParts(new Date(epochMs))
92
+ let month = ''
93
+ let day = ''
94
+ for (const part of parts) {
95
+ if (part.type === 'month') month = part.value
96
+ else if (part.type === 'day') day = part.value
97
+ }
98
+ if (month.length === 0 || day.length === 0) throw new Error('failed to derive MMDD from the creation date')
99
+ return `${month}${day}`
100
+ }
101
+
102
+ /**
103
+ * Workspace-name fragments the topic must not repeat: the session cwd's own
104
+ * name and its parent directory name (both commonly shown as project names).
105
+ * @param {string|undefined} cwd - the session's working directory.
106
+ * @returns {string[]} significant, case-folded fragments.
107
+ */
108
+ function projectNameFragments(cwd) {
109
+ if (typeof cwd !== 'string' || cwd.length === 0) return []
110
+ const segments = cwd.split(/[\\/]+/).filter((segment) => segment.length >= MIN_PROJECT_NAME_FRAGMENT)
111
+ const last = segments.slice(-2)
112
+ return last.map((segment) => segment.toLowerCase())
113
+ }
114
+
115
+ /**
116
+ * Resolve the plugin config with defensive defaults (the entry may mount
117
+ * without a `config` block at all).
118
+ * @param {unknown} config - the raw entry config.
119
+ * @returns {{ timezone: string, maxTopicBytes: number }} effective config.
120
+ */
121
+ function effectiveConfig(config) {
122
+ const candidate = config === null || typeof config !== 'object' ? {} : config
123
+ const timezone = typeof candidate.timezone === 'string' && candidate.timezone.length > 0 ? candidate.timezone : DEFAULT_TIMEZONE
124
+ const maxTopicBytes = Number.isInteger(candidate.maxTopicBytes) && candidate.maxTopicBytes >= 4 ? candidate.maxTopicBytes : DEFAULT_MAX_TOPIC_BYTES
125
+ const injectInstruction = typeof candidate.injectInstruction === 'boolean' ? candidate.injectInstruction : true
126
+ return { timezone, maxTopicBytes, injectInstruction }
127
+ }
128
+
129
+ /**
130
+ * Compose the first-round instruction text injected as a plugin-sourced user
131
+ * message (the same rule a manual ~/.dsh/AGENTS.md entry would carry, framed
132
+ * as a plugin-owned system-reminder per the harness convention).
133
+ * @returns {string} the complete reminder text.
134
+ */
135
+ function firstRoundInstructionText() {
136
+ const body = [
137
+ '会话标题命名规则(dsh-session-title-format 插件注入,等效于全局指令,无需手动配置 AGENTS.md):',
138
+ '- 本对话首轮回复结束前,主动调用 set_session_title 工具,把本会话标题统一为「MMDD|类型|主题」:日期由工具按上海时区自动计算,你只需提供类型与主题。',
139
+ `- 类型从:${TITLE_TYPES.join('、')} 中选择一个;主题按对话实际内容简洁概括(约 16 字以内),不要重复项目名或工作区名。`,
140
+ '- 无法确定类型或主题时,不要调用该工具,保留原标题。用户手动命名过的会话不要改名(工具会自动跳过)。',
141
+ '- 只修改对话标题,其他一切状态保持不变。子代理会话同样适用本规则。',
142
+ ].join('\n')
143
+ return `${REMINDER_OPEN}\n${body}\n${REMINDER_CLOSE}`
144
+ }
145
+
146
+ /**
147
+ * Read a live session's full event log across dsh versions: 0.1.5-alpha.1
148
+ * removed the `events` getter in favor of `snapshotEvents()`; 0.1.2 has the
149
+ * getter. Returns a (possibly empty) read-only array either way.
150
+ * @param {import('@deepseek-ai/dsh-session').Session} session - the session.
151
+ * @returns {readonly import('@deepseek-ai/dsh-session').SessionEvent[]} events.
152
+ */
153
+ function sessionEventsOf(session) {
154
+ if (typeof session.snapshotEvents === 'function') return session.snapshotEvents()
155
+ if (Array.isArray(session.events)) return session.events
156
+ return []
157
+ }
158
+
159
+ /**
160
+ * Whether one session has already produced an assistant message (its first
161
+ * round is over) — the injection only targets a session's very first step.
162
+ * @param {import('@deepseek-ai/dsh-session').Session} session - the session.
163
+ * @returns {boolean} true when any assistant message is already logged.
164
+ */
165
+ function hasAssistantMessage(session) {
166
+ return sessionEventsOf(session).some((event) => event.type === 'assistant/message')
167
+ }
168
+
169
+ /**
170
+ * Whether the session already carries an instruction injected by this plugin
171
+ * (durable dedup: resume and replay never inject twice).
172
+ * @param {import('@deepseek-ai/dsh-session').Session} session - the session.
173
+ * @returns {boolean} true when this plugin already injected the reminder.
174
+ */
175
+ function hasOwnInstruction(session) {
176
+ return sessionEventsOf(session).some((event) => {
177
+ if (event.type !== 'user/message') return false
178
+ const source = event.data.source
179
+ return typeof source === 'object' && source !== null && source.kind === 'plugin' && source.plugin === name
180
+ })
181
+ }
182
+
183
+ /**
184
+ * Register the `set_session_title` tool on `ctx.tools`.
185
+ * @param {import('@deepseek-ai/cordis').Context} ctx - registrant context.
186
+ * @param {unknown} config - deployment config (timezone, maxTopicBytes).
187
+ */
188
+ export function apply(ctx, config) {
189
+ const { timezone, maxTopicBytes, injectInstruction } = effectiveConfig(config)
190
+
191
+ const description = [
192
+ "Set the current conversation's title in the unified「MMDD|类型|主题」format. The MMDD date part (this session's actual creation date in the Asia/Shanghai timezone) is computed automatically — supply only `type` and `topic`.",
193
+ 'Rules:',
194
+ `- type: exactly one of ${TITLE_TYPES.join(' / ')}, chosen from the conversation's actual purpose.`,
195
+ '- topic: a concise summary of the conversation content (about 16 CJK characters at most). Do NOT repeat the project or workspace name.',
196
+ '- Only the conversation title changes; project name, content, ownership, ordering, pinning and archive state stay untouched.',
197
+ '- When the type or topic cannot be determined confidently, do NOT call this tool — keep the current title.',
198
+ '- If the session was renamed manually by the user, the call is skipped.',
199
+ '- Call this before your first reply finishes in a new conversation; you may call it again later to correct the title.',
200
+ ].join('\n')
201
+
202
+ ctx.tools.register(
203
+ defineTool({
204
+ name: 'set_session_title',
205
+ description,
206
+ parameters: {
207
+ type: {
208
+ type: 'string',
209
+ required: true,
210
+ enum: [...TITLE_TYPES],
211
+ description: `The conversation type; one of ${TITLE_TYPES.join(' / ')}.`,
212
+ },
213
+ topic: {
214
+ type: 'string',
215
+ required: true,
216
+ description: 'Concise topic of this conversation (no project name, no date, no pipe characters).',
217
+ },
218
+ },
219
+ output: {
220
+ schema: {
221
+ type: 'object',
222
+ additionalProperties: false,
223
+ properties: {
224
+ renamed: {
225
+ type: 'boolean',
226
+ required: true,
227
+ },
228
+ title: {
229
+ type: 'string',
230
+ required: true,
231
+ },
232
+ previousTitle: {
233
+ type: 'string',
234
+ required: true,
235
+ },
236
+ reason: {
237
+ type: 'string',
238
+ required: true,
239
+ },
240
+ },
241
+ },
242
+ render: (_args, value) => [
243
+ {
244
+ type: 'text',
245
+ text: value.renamed
246
+ ? `Session title set to「${value.title}」(previous: ${value.previousTitle.length === 0 ? '(none)' : `「${value.previousTitle}」`}).`
247
+ : `Session title NOT changed: ${value.reason}`,
248
+ },
249
+ ],
250
+ },
251
+ isConcurrencySafe: () => false,
252
+ async execute(args, exec) {
253
+ if (!exec.agent) throw new Error('set_session_title requires an owning agent session')
254
+ const session = exec.agent.session
255
+ const sessionTitle = ctx.sessionTitle
256
+ if (typeof sessionTitle !== 'object' || sessionTitle === null) throw new Error('set_session_title requires the session-title service')
257
+
258
+ const type = args.type
259
+ if (!TITLE_TYPES.includes(type)) throw new Error(`invalid type ${JSON.stringify(type)}; must be one of ${TITLE_TYPES.join(' / ')}`)
260
+
261
+ const previous = sessionTitle.get(session)
262
+ if (previous !== undefined && previous.source.kind === 'user') {
263
+ return {
264
+ renamed: false,
265
+ title: previous.title,
266
+ previousTitle: previous.title,
267
+ reason: 'the current title was set manually by the user; not overriding it',
268
+ }
269
+ }
270
+ const topic = cleanTopic(args.topic)
271
+ if (topic.length === 0) throw new Error('topic must contain visible characters')
272
+ const topicBytes = Buffer.byteLength(topic, 'utf8')
273
+ if (topicBytes > maxTopicBytes) {
274
+ throw new Error(`topic is ${topicBytes} UTF-8 bytes; keep it within ${maxTopicBytes} bytes (about ${Math.floor(maxTopicBytes / 3)} CJK characters)`)
275
+ }
276
+ for (const fragment of projectNameFragments(session.header.cwd)) {
277
+ if (topic.toLowerCase().includes(fragment)) {
278
+ throw new Error(`topic must not repeat the project/workspace name (${JSON.stringify(fragment)} was found in it); summarize the content instead`)
279
+ }
280
+ }
281
+
282
+ const createdAt = session.header.createdAt
283
+ const events = sessionEventsOf(session)
284
+ const creationTime = typeof createdAt === 'number' && Number.isFinite(createdAt) ? createdAt : (events[0]?.time ?? Date.now())
285
+ const datePart = mmddInTimeZone(creationTime, timezone)
286
+ const title = `${datePart}|${type}|${topic}`
287
+
288
+ const maxTitleBytes = typeof sessionTitle.config?.maxTitleBytes === 'number' ? sessionTitle.config.maxTitleBytes : 120
289
+ const titleBytes = Buffer.byteLength(title, 'utf8')
290
+ if (titleBytes > maxTitleBytes) {
291
+ throw new Error(`composed title is ${titleBytes} UTF-8 bytes; the service accepts at most ${maxTitleBytes}. Shorten the topic.`)
292
+ }
293
+
294
+ if (previous !== undefined && previous.title === title) {
295
+ return {
296
+ renamed: false,
297
+ title,
298
+ previousTitle: previous.title,
299
+ reason: 'the session already carries this exact title',
300
+ }
301
+ }
302
+
303
+ sessionTitle.rename(session, title)
304
+ return {
305
+ renamed: true,
306
+ title,
307
+ previousTitle: previous === undefined ? '' : previous.title,
308
+ reason: 'title accepted as a user-sourced session/title event',
309
+ }
310
+ },
311
+ presentCall: (args) => ({
312
+ card: 'generic',
313
+ title: 'Set session title',
314
+ kind: 'other',
315
+ rawInput: { type: args.type, topic: args.topic },
316
+ }),
317
+ }),
318
+ )
319
+
320
+ // First-round instruction injection: fold the naming rule into the very
321
+ // first step of every session as a durable plugin-sourced user message,
322
+ // exactly the dsh-agent-instructions pattern. This replaces the manual
323
+ // ~/.dsh/AGENTS.md entry — the plugin is self-contained.
324
+ if (injectInstruction) {
325
+ ctx.on('agent/pre-step', async ({ agent, messages }, next) => {
326
+ const decision = await next()
327
+ if (decision.kind === 'reject') return decision
328
+ const session = agent.session
329
+ if (decision.messages.length === 0) return decision
330
+ if (hasAssistantMessage(session) || hasOwnInstruction(session)) return decision
331
+ const reminder = createUserMessage({
332
+ content: [{ type: 'text', text: firstRoundInstructionText() }],
333
+ source: { kind: 'plugin', plugin: name },
334
+ })
335
+ const lastClaimedIndex = decision.messages.findLastIndex((message) => messages.includes(message))
336
+ return {
337
+ ...decision,
338
+ messages: decision.messages.toSpliced(lastClaimedIndex + 1, 0, reminder),
339
+ }
340
+ })
341
+ }
342
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "dsh-session-title-format",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "DSH plugin: set_session_title tool renaming the calling agent's session to「MMDD|类型|主题」— Shanghai-timezone creation date, fixed type vocabulary, concise topic",
6
+ "keywords": [
7
+ "deepseek",
8
+ "harness",
9
+ "dsh",
10
+ "dsh-plugin",
11
+ "session",
12
+ "title"
13
+ ],
14
+ "license": "MIT",
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "main": "index.js",
19
+ "files": [
20
+ "index.js",
21
+ "cordis.patch.yml",
22
+ "README.md"
23
+ ],
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "peerDependencies": {
28
+ "@deepseek-ai/dsh-llm": ">=0.1.0-rc.8",
29
+ "@deepseek-ai/dsh-tools": ">=0.1.0-rc.8",
30
+ "@deepseek-ai/schemastery": "^3.18.2"
31
+ },
32
+ "dsh": {
33
+ "bundle": {
34
+ "patch": "./cordis.patch.yml"
35
+ }
36
+ }
37
+ }