@user-mrz/dsh-system-prompt-studio 0.2.1 → 0.3.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 CHANGED
@@ -12,6 +12,73 @@ integration still targets the same DSH shapes, a major bump means it may not.
12
12
 
13
13
  Nothing yet.
14
14
 
15
+ ## [0.3.0] — 2026-11-13
16
+
17
+ ### Added
18
+
19
+ - **Workspace-level overrides.** There were two scopes — this conversation, and the global default —
20
+ with nothing in between, which is the wrong shape for the most common need: rules that belong to a
21
+ project. "Be terse, this repo has no test suite" had to be re-typed into every conversation opened in
22
+ that directory, or pushed into the global default where it leaks into unrelated work. The panel now has
23
+ a third scope, **This workspace**, keyed on the conversation's current working directory.
24
+
25
+ The precedence chain is, from most to least specific: this conversation → inherited from a fork →
26
+ **this workspace** → global default. Workspace sits above the global default because it is narrower;
27
+ below a fork's inherited rules because a fork carries the context of the work it branched from, and a
28
+ rule the user wrote for that specific branch is a more specific statement than the directory's default.
29
+
30
+ Two deliberate asymmetries:
31
+
32
+ - `workspaceScope` defaults to `all` (subagents included) while `globalDefaultScope` defaults to
33
+ `roots`. A global persona leaking into a tool-shaped subagent pollutes it; a project's rules
34
+ *should* reach the subagents doing that project's work, or the actual workers are the ones not
35
+ following them.
36
+ - `resetAll` clears per-conversation entries and leaves workspace entries alone. Workspace rules are
37
+ accumulated project configuration, not per-conversation scratch state; destroying them behind a
38
+ button labelled "clear all conversation overrides" would be unrecoverable and unexpected.
39
+
40
+ - **Directory changes are reconciled at assembly time.** `workingDirectory.set` (a user switching a
41
+ conversation to another project) emits no event, so a signature computed at install time would leave
42
+ the old directory's rules in force with nothing to explain it. The assembly listener now recomputes
43
+ each live agent's signature and reinstalls on a mismatch. It runs after the sections are already
44
+ collected, so the current request is unaffected and the change lands on the next one.
45
+
46
+ ### Fixed
47
+
48
+ - **The workspace key is not `workingDirectory.get()`.** That call returns
49
+ `stateOf(session) ?? defaultDirectory`, so a conversation that never changed directory reports the
50
+ *deployment default* directory rather than its own project. Keying on it directly would have collapsed
51
+ every conversation onto one workspace entry — rules saved in one project applying in another, with
52
+ nothing on screen to explain it. The key now comes from `workspaceRegistry` first (the workspace the
53
+ sidebar shows), then `workingDirectory.get()` **only when it differs from `defaultDirectory`** (i.e. a
54
+ change was really committed), then the session's recorded `header.cwd`.
55
+
56
+ - **Cold conversations could not use the workspace scope at all.** Resolving the workspace required a
57
+ `Session` object, and a cold conversation is neither a live agent nor in the in-memory session store,
58
+ so the lookup returned nothing: the panel showed "no usable workspace" and a conversation that had not
59
+ been resumed yet could not be given its project's rules. The registry is durable, so its ownership
60
+ lookup now runs on the bare session id alone, and the `Session`-dependent fallbacks are only tried when
61
+ one is actually available. A rule saved from a cold conversation applies to its live siblings
62
+ immediately.
63
+
64
+ ### Security
65
+
66
+ - **The workspace path is derived on the host, never supplied by the panel.** A workspace save sends a
67
+ `sessionId`; the host resolves that conversation's current directory itself. Accepting an arbitrary
68
+ path from the client would let any same-origin script write rules for directories the user never
69
+ opened — the loopback fence stops remote callers but not injected script. An explicit `workspaceKey`
70
+ field is still accepted when no `sessionId` is given, for scripts and tests, and passes the same
71
+ normalisation.
72
+
73
+ ### Changed
74
+
75
+ - Workspace keys are normalised paths, not `workspaceRegistry` ids: separators unified, trailing and
76
+ duplicate separators collapsed, `.` segments dropped, case folded on Windows. Re-registering a deleted
77
+ workspace would mint a new id, and a user's project rules should not evaporate because of that. The
78
+ *path* is read from the registry entry; the *id* is deliberately not used as the key.
79
+ - An unknown `scope` value still falls back to `session` rather than to `global`. Falling back to
80
+ `global` on a typo would silently rewrite every conversation while the user believes they edited one.
81
+
15
82
  ## [0.2.1] — 2026-11-12
16
83
 
17
84
  ### Fixed
@@ -231,7 +298,8 @@ scoped name unambiguous for anyone who arrives from GitHub.
231
298
  - Read-only assembly observer listing the real section names, order and size.
232
299
  - Loopback-only HTTP route for the panel; forged `Host` headers are refused.
233
300
 
234
- [Unreleased]: https://github.com/user-Mrz/dsh-system-prompt-studio/compare/v0.2.1...HEAD
301
+ [Unreleased]: https://github.com/user-Mrz/dsh-system-prompt-studio/compare/v0.3.0...HEAD
302
+ [0.3.0]: https://github.com/user-Mrz/dsh-system-prompt-studio/compare/v0.2.1...v0.3.0
235
303
  [0.2.1]: https://github.com/user-Mrz/dsh-system-prompt-studio/compare/v0.2.0...v0.2.1
236
304
  [0.2.0]: https://github.com/user-Mrz/dsh-system-prompt-studio/compare/v0.1.9...v0.2.0
237
305
  [0.1.9]: https://github.com/user-Mrz/dsh-system-prompt-studio/compare/v0.1.8...v0.1.9
package/README.md CHANGED
@@ -34,7 +34,8 @@ session, effective immediately.
34
34
  | **Replace everything** | Your text becomes the entire system prompt. Highest risk: drops first-party guidance **and every other plugin's sections** — see below. |
35
35
 
36
36
  - **Applies on the next model request.** No restart, no reload.
37
- - **Persists per session**, and a **global default** applies to new conversations automatically.
37
+ - **Three scopes**: this conversation, **this workspace** (a directory), or the global default. Rules
38
+ persist per session *and* per working directory.
38
39
  - **Inherits across forks.** A forked conversation picks up its parent's rules along the `parentSession`
39
40
  chain, with a **Pin** action to freeze the inherited result locally.
40
41
  - **Guards unsaved edits.** Esc, backdrop click and the close button all ask before discarding.
@@ -89,7 +90,7 @@ dsh plugin --profile <profile> add @user-mrz/dsh-system-prompt-studio
89
90
  From GitHub, which tracks the default branch and therefore needs a ref if you want a fixed version:
90
91
 
91
92
  ```bash
92
- dsh plugin --profile <profile> add github:user-Mrz/dsh-system-prompt-studio#v0.2.1
93
+ dsh plugin --profile <profile> add github:user-Mrz/dsh-system-prompt-studio#v0.3.0
93
94
  ```
94
95
 
95
96
  Replace `<profile>` with your profile name — for the Web build that is usually `web`.
@@ -98,7 +99,7 @@ Replace `<profile>` with your profile name — for the Web build that is usually
98
99
  changes what you install next time:
99
100
 
100
101
  ```bash
101
- dsh plugin --profile <profile> add @user-mrz/dsh-system-prompt-studio@0.2.1
102
+ dsh plugin --profile <profile> add @user-mrz/dsh-system-prompt-studio@0.3.0
102
103
  ```
103
104
 
104
105
  <details>
@@ -157,30 +158,68 @@ Your saved overrides are **not** deleted.
157
158
  conversation already has its own override). On a **brand-new conversation** the title bar is
158
159
  hidden by the harness, so the button lives in the welcome area instead, labeled
159
160
  **Set system prompt**.
160
- 2. Pick a scope: **this conversation** or **global default**. The global default applies to top-level
161
- conversations only — not to subagents.
161
+ 2. Pick a scope — **this conversation**, **this workspace**, or **global default**. The global default
162
+ applies to top-level conversations only (not subagents); the workspace scope applies to every
163
+ conversation whose working directory is that directory, subagents included.
162
164
  3. Choose a mode, write your text, save. It takes effect on your next message.
163
165
  4. Expand the two read-only blocks at the bottom to check reality:
164
166
  - *System prompt of the latest request* — what was actually sent;
165
167
  - *Sections assembled for this conversation* — real section names, order and size.
166
168
 
169
+ ### Scopes and precedence
170
+
171
+ From most specific to least, the first one that exists wins:
172
+
173
+ | # | Scope | Applies to | Survives a new conversation? |
174
+ | --- | --- | --- | --- |
175
+ | 1 | **This conversation** | exactly one conversation | no |
176
+ | 2 | **Inherited from a fork** | that fork and its descendants | n/a (lineage) |
177
+ | 3 | **This workspace** | every conversation in that directory | **yes** |
178
+ | 4 | **Global default** | every top-level conversation | yes |
179
+
180
+ The workspace scope sits above the global default because it is narrower — a project's rules should not
181
+ be overridden by a blanket persona. It sits *below* a fork's inherited rules because a fork carries the
182
+ context of the work it branched from, and a rule written for that specific branch is a more specific
183
+ statement than the directory's default.
184
+
185
+ **The directory is resolved from the workspace registry first.** The panel shows the resolved path next to
186
+ the tabs. Priority: the workspace this conversation belongs to in `workspaceRegistry` (the one you see in
187
+ the sidebar), then — only when no workspace owns it — the conversation's current directory, then the
188
+ directory recorded when the conversation was created.
189
+
190
+ That ordering matters more than it looks. `workingDirectory.get()` returns the **deployment default
191
+ directory** for a conversation that never changed directory, not its own project; keying on it directly
192
+ would make every conversation share one workspace entry, so rules saved in one project would apply in
193
+ another. It is therefore only trusted when it differs from that default, i.e. when a change was really
194
+ committed.
195
+
196
+ The panel displays the **original path spelling**, not the normalised key: normalisation lowercases the
197
+ Windows drive and directory names, which is right for matching and wrong for a path a user is meant to
198
+ recognise.
199
+
200
+ The path is resolved on the host — the panel never sends one, so a same-origin script cannot write rules
201
+ for directories you never opened.
202
+
203
+ `resetAll` (the API action that clears every per-conversation override) **does not** touch workspace
204
+ entries: those are accumulated project configuration, not per-conversation scratch state.
205
+
167
206
  ### Can I set the prompt of a conversation that hasn't started yet?
168
207
 
169
208
  Yes, and it applies from the **first** message, not the second. The harness creates the agent the
170
209
  moment the conversation exists — before you type anything — so the override is already registered by
171
210
  the time your first prompt is assembled. Open the welcome-area button and save.
172
211
 
173
- Two ways to cover a new conversation:
212
+ Three ways to cover a new conversation:
174
213
 
175
214
  | Want | Do this |
176
215
  | --- | --- |
177
216
  | Just this one new conversation | Open its welcome-area button → **this conversation** → save |
217
+ | Every conversation in this project | Open the button in any conversation in that directory → **this workspace** → save |
178
218
  | Every top-level conversation that has no override of its own | Open the button in any conversation → **global default** → save |
179
219
 
180
- The global default is **not** limited to conversations created after you save it: it is re-evaluated
181
- for every live conversation on each save, so existing top-level conversations without an override of
182
- their own pick it up immediately too. A conversation that has its own override keeps it — the global
183
- default only fills in where nothing more specific exists.
220
+ The global default and the workspace rules are **not** limited to conversations created after you save
221
+ them: both are re-evaluated for every live conversation on each save, so existing conversations without
222
+ something more specific pick them up immediately too. A conversation that has its own override keeps it.
184
223
 
185
224
  ### Choosing a section to replace
186
225
 
@@ -239,6 +278,7 @@ Edit the row in `cordis.patch.yml` or override it in your profile patch. The mos
239
278
  | `globalDefaultScope` | `roots` | Whether the global default also applies to subagents (`all` to include) |
240
279
  | `inheritOnFork` | `true` | Whether forked conversations inherit upstream rules |
241
280
  | `maxInheritDepth` | `3` | How many levels to walk up (1–8); `0` behaves like off |
281
+ | `workspaceScope` | `all` | Whether workspace rules also apply to subagents (`roots` for top-level only) |
242
282
  | `observeAssemblies` | `true` | Read-only assembly observer; required for the section list |
243
283
  | `visible` | `true` | Whether the panel button is shown (client-side) |
244
284
  | `showOnNewConversation` | `true` | Whether the welcome area of a brand-new conversation also gets a button (client-side) |
@@ -254,10 +294,18 @@ Every key is documented in [`cordis.patch.yml`](cordis.patch.yml).
254
294
  {
255
295
  "version": 1,
256
296
  "global": { "enabled": false, "mode": "append", "text": "", "target": "", "updatedAt": 0 },
257
- "sessions": { "<sessionId>": { "enabled": true, "mode": "append", "text": "…", "target": "", "updatedAt": 0 } }
297
+ "sessions": { "<sessionId>": { "enabled": true, "mode": "append", "text": "…", "target": "", "updatedAt": 0 } },
298
+ "workspaces": { "C:/work/alpha": { "enabled": true, "mode": "append", "text": "…", "target": "", "updatedAt": 0 } }
258
299
  }
259
300
  ```
260
301
 
302
+ Workspace keys are **normalised directory paths**, not `workspaceRegistry` ids. Separators are unified
303
+ to `/`, trailing and duplicate separators and `.` segments are dropped, and case is folded on Windows —
304
+ so `C:\work\alpha\`, `C:/work/alpha` and `c:/Work/Alpha` are one key. Ids were rejected on purpose:
305
+ deleting and re-registering a workspace mints a new id, and a project's rules should not evaporate
306
+ because of that. Keys that do not normalise cleanly (empty, or a bare drive like `C:`) are treated as
307
+ "no usable directory" rather than as a shared bucket.
308
+
261
309
  - Writes go through a temp file plus atomic `rename`, serialized on one queue.
262
310
  - If a write fails, the panel says so explicitly (*in memory only, lost on restart*) rather than
263
311
  pretending the save worked.
@@ -269,26 +317,34 @@ Every key is documented in [`cordis.patch.yml`](cordis.patch.yml).
269
317
  ```
270
318
  GET /api/system-prompt-studio?session=<sessionId>
271
319
  POST /api/system-prompt-studio
272
- { "action": "set", "scope": "session"|"global", "sessionId"?: "…", "patch": { "enabled": true, "mode": "append"|"replace"|"complete", "text": "…", "target": "…" } }
273
- { "action": "clear", "scope": "session"|"global", "sessionId"?: "…" }
320
+ { "action": "set", "scope": "session"|"workspace"|"global", "sessionId"?: "…", "patch": { "enabled": true, "mode": "append"|"replace"|"complete", "text": "…", "target": "…" } }
321
+ { "action": "clear", "scope": "session"|"workspace"|"global", "sessionId"?: "…" }
274
322
  { "action": "pin", "scope": "session", "sessionId": "…" }
275
323
  { "action": "resetAll", "confirm": true }
276
324
  ```
277
325
 
278
326
  - Loopback-only: both the socket and the `Host` header must be loopback; cross-site origins get 403.
279
327
  - POST bodies over `maxChars * 4` bytes are rejected with 413 (never truncated).
328
+ - `scope: "workspace"` resolves the directory **from `sessionId`** on the host. An explicit
329
+ `"workspaceKey": "C:/path"` is honoured only when no `sessionId` is given (scripts and tests) and goes
330
+ through the same normalisation. Sending a path is not how the panel works, by design: accepting one
331
+ would let same-origin script write rules for directories the user never opened.
332
+ - An unrecognised `scope` value falls back to `session`, never to `global`.
280
333
  - Stable error codes: `TEXT_TOO_LONG`, `EMPTY_TEXT`, `TARGET_REQUIRED`, `COMPLETE_BLOCKED`,
281
- `UNKNOWN_ACTION`, `MISSING_SESSION`, `NOTHING_TO_PIN`, `PIN_SESSION_ONLY`, `CONFIRM_REQUIRED`,
282
- `INVALID_JSON`, `BODY_TOO_LARGE`, `method-not-allowed`, `forbidden: loopback-only`.
334
+ `UNKNOWN_ACTION`, `MISSING_SESSION`, `MISSING_WORKSPACE`, `NOTHING_TO_PIN`, `PIN_SESSION_ONLY`,
335
+ `CONFIRM_REQUIRED`, `INVALID_JSON`, `BODY_TOO_LARGE`, `method-not-allowed`, `forbidden: loopback-only`.
283
336
 
284
337
  ## Known limitations
285
338
 
286
339
  1. **Overrides are keyed by session id, but forks inherit.** A forked conversation picks up the nearest
287
340
  ancestor's rules (disable with `inheritOnFork`). Subagents do not take the global default and do not
288
- participate in the chain. Resuming a session under the same id re-applies its rules.
289
- 2. **Cold sessions** (no live agent) can be saved for, but take effect once resumed. Inheritance
341
+ participate in the fork chain; they *do* take workspace rules unless `workspaceScope: roots`.
342
+ Resuming a session under the same id re-applies its rules.
343
+ 2. **Cold sessions** (no live agent) can be saved for, but take effect once resumed. Fork inheritance
290
344
  specifically requires a live agent, because the parent chain is read from the session header — a cold
291
- session has none until it is running again.
345
+ session has none until it is running again. Workspace rules work for cold sessions too: the registry
346
+ lookup only needs the session id, so a conversation that has not been resumed yet can still be given
347
+ its project's rules, and its live siblings pick them up immediately.
292
348
  3. **`{{…}}` is not interpolated.** Bodies are registered with `interpolate: false`, so braces stay
293
349
  literal. This is deliberate: otherwise any `{{x}}` in your text would fail assembly with
294
350
  *unknown prompt variable*.
@@ -299,6 +355,10 @@ POST /api/system-prompt-studio
299
355
  6. **Section attribution is approximate.** The list is attributed via the assembly context's scope (the
300
356
  agent); if that is unavailable it falls back to the most recent assembly. Overrides themselves are
301
357
  unaffected.
358
+ 7. **Workspace matching is textual, not filesystem-resolved.** Keys are normalised path spellings; `..`
359
+ is not resolved (that needs filesystem semantics this plugin does not touch) and symlinks are not
360
+ followed. The host prefers the `workspaceRegistry` entry, whose path is canonicalised by DSH itself,
361
+ so the normal case is exact.
302
362
 
303
363
  ## Development
304
364
 
@@ -377,13 +437,13 @@ dsh plugin --profile <profile> add @user-mrz/dsh-system-prompt-studio
377
437
  或从 GitHub(跟随默认分支,建议锁 tag):
378
438
 
379
439
  ```bash
380
- dsh plugin --profile <profile> add github:user-Mrz/dsh-system-prompt-studio#v0.2.1
440
+ dsh plugin --profile <profile> add github:user-Mrz/dsh-system-prompt-studio#v0.3.0
381
441
  ```
382
442
 
383
443
  锁定版本,保证装到的是一份确定的代码:
384
444
 
385
445
  ```bash
386
- dsh plugin --profile <profile> add @user-mrz/dsh-system-prompt-studio@0.2.1
446
+ dsh plugin --profile <profile> add @user-mrz/dsh-system-prompt-studio@0.3.0
387
447
  ```
388
448
 
389
449
  `prepare` 脚本只校验入口文件存在,不做编译。若被 pnpm 拦下,把 `pnpm-workspace.yaml` 里
@@ -392,7 +452,8 @@ dsh plugin --profile <profile> add @user-mrz/dsh-system-prompt-studio@0.2.1
392
452
 
393
453
  **安装后**:Host 半即时生效;客户端是新的 JS,需要刷新一次页面才会出现标题栏按钮。
394
454
 
395
- **使用**:打开对话 → 标题栏「系统提示词」按钮 → 选作用域、模式、写正文 → 保存,下一次发消息生效。
455
+ **使用**:打开对话 → 标题栏「系统提示词」按钮 → 选作用域(本对话 / 本工作区 / 全局默认)、模式、
456
+ 写正文 → 保存,下一次发消息生效。
396
457
  **新开的空对话**标题栏是隐藏的,入口改在欢迎区(文字为「设置系统提示词」)—— 会话一创建 agent
397
458
  就已经在了,所以这里保存的覆盖**从第一句话**就生效,不是等到第二句。
398
459
  面板底部两个只读区块分别显示「最近一次请求真正发出的系统提示词」与「本次装配到的段清单」。
@@ -405,8 +466,24 @@ dsh plugin --profile <profile> add @user-mrz/dsh-system-prompt-studio@0.2.1
405
466
  整体换成 `[completeSection]`,所以任何观察者(包括本插件)必然先看到全量。面板会把这种情况标出来,
406
467
  而不是让你对着几十个段怀疑替换没生效。
407
468
 
408
- **新对话怎么生效**:「本对话」只作用于这一个新对话;「全局默认」作用于**所有没有自身覆盖的顶层
409
- 对话**——包括保存时就已经存在的那些,它是「兜底」而不是「只对新对话」。
469
+ **新对话怎么生效**:「本对话」只作用于这一个新对话;「本工作区」作用于**这个目录下的所有对话**
470
+ (含子代理);「全局默认」作用于**所有没有自身覆盖的顶层对话**——后两者都包括保存时就已经存在的
471
+ 那些,它们是「兜底」而不是「只对新对话」。
472
+
473
+ **三档作用域的优先级**(从具体到宽泛,命中第一个就停):本对话 → fork 继承 → 本工作区 → 全局默认。
474
+ 工作区排在全局之上是因为它更窄;排在 fork 继承之下是因为 fork 带着它分叉出来的那段工作的上下文,
475
+ 用户为那个分支单独调过的规则比目录默认更具体。
476
+
477
+ **工作区按你侧边栏看到的那个工作区算**:优先用 `workspaceRegistry` 里的归属(会话在注册表里属于哪个
478
+ 工作区),所以它不会因为你在对话里 `cd` 而漂移;注册表里没有归属时,才退回这个对话的当前目录,再退回
479
+ 会话创建时记下的原始目录。面板会显示解析出来的**原始路径**(不是归一化后的小写键),供你核对。
480
+
481
+ > 这里有个坑值得说明:`workingDirectory.get()` 对**没换过目录**的会话返回的是部署默认目录,不是会话
482
+ > 自己的项目目录。直接拿它当工作区键,所有会话会共用同一个键——在这个项目里设的规则会莫名其妙地对
483
+ > 别处生效。所以它只在「确实换过目录」时才被采用。
484
+
485
+ 路径由宿主自己解析——面板从不传路径,否则同源脚本就能给用户从没打开过的目录写规则。`resetAll`
486
+ (清空所有会话覆盖的 API 动作)**不动**工作区条目:那是攒下来的项目配置,不是逐对话的临时状态。
410
487
 
411
488
  **fork 继承**:fork 出的对话是新 session id,会沿 `parentSession` 链继承最近的祖先规则;面板显示
412
489
  「继承自 …」并提供「在此固定」把继承结果固化成本地规则。子对话自己一改就停止继承。默认上溯 3 层,
@@ -418,5 +495,6 @@ dsh plugin --profile <profile> add @user-mrz/dsh-system-prompt-studio@0.2.1
418
495
  **数据位置**:`$DSH_HOME/dsh-system-prompt-studio/state.json`,原子写入;写失败会明说「只在内存」,
419
496
  文件损坏会先备份成 `.corrupt-<时间戳>` 再空态起步。
420
497
 
421
- **已知限制**:冷会话(没有活 agent)可以保存,但要等它恢复后才生效,且继承需要活会话才能读到父链;
422
- `{{…}}` 不插值(刻意为之);系统提示词一变,该对话的缓存前缀从首个变化的 token 起失效。
498
+ **已知限制**:冷会话(没有活 agent)可以保存,但要等它恢复后才生效,且 fork 继承需要活会话才能读到
499
+ 父链(工作区规则对冷会话也有效,目录从已存的会话里读);`{{…}}` 不插值(刻意为之);系统提示词一变,
500
+ 该对话的缓存前缀从首个变化的 token 起失效;工作区匹配是文本归一化,不解析 `..`、不跟随符号链接。
package/cordis.patch.yml CHANGED
@@ -27,6 +27,11 @@
27
27
  # maxObservedScopes 观察缓存的作用域上限(FIFO 淘汰),防止长期运行堆积。
28
28
  # globalDefaultScope 「全局默认」套用到哪些会话:roots(默认,只套用到顶层会话,
29
29
  # 不碰子代理)| all(含子代理)。
30
+ # workspaceScope 「工作区级」规则套用到哪些会话:all(默认,含子代理)|
31
+ # roots(只套用到顶层会话)。
32
+ # 默认值与 globalDefaultScope 不同是有意的:全局默认是「所有
33
+ # 对话的人格」,漏进子代理会污染工具型子任务;工作区级是
34
+ # 「这个项目的规矩」,子代理正是替这个项目干活的那批。
30
35
  # inheritOnFork fork 继承:子会话没有自身覆盖时,沿 parentSession 链向上找。
31
36
  # true(默认)| false(各会话独立,退回旧行为)。
32
37
  # maxInheritDepth 继承最多上溯几层(1–8,默认 3)。0 等同于关闭继承。
@@ -57,6 +62,7 @@
57
62
  observeAssemblies: true
58
63
  maxObservedScopes: 64
59
64
  globalDefaultScope: roots
65
+ workspaceScope: all
60
66
  inheritOnFork: true
61
67
  maxInheritDepth: 3
62
68
  visible: true
package/lib/client.js CHANGED
@@ -46,7 +46,15 @@ window.__ModuleLoader__.load({
46
46
  subtitle: '按对话覆盖模型实际收到的系统提示词',
47
47
  close: '关闭',
48
48
  scopeSession: '本对话',
49
+ scopeWorkspace: '本工作区',
49
50
  scopeGlobal: '全局默认',
51
+ scopeWorkspaceHint: '这个工作区下所有对话都套用(含子代理);按侧边栏里的工作区归属算。',
52
+ scopeWorkspaceNoDir: '这个对话没有可用的工作区,无法按工作区保存。',
53
+ scopeWorkspacePath: '工作区:',
54
+ workspaceEmpty: '这个工作区还没有规则',
55
+ workspaceSaved: '已保存为这个工作区的规则,它下面的对话下一次请求生效。',
56
+ workspaceCleared: '已清除这个工作区的规则。',
57
+ workspaceFrom: '当前规则来自这个工作区:',
50
58
  scopeGlobalHint: '所有没有自身覆盖的顶层对话都套用(不含子代理)。',
51
59
  modeAppend: '追加到末尾',
52
60
  modeAppendHint: '保留第一方全部提示词,只在末尾追加你的段落。',
@@ -67,6 +75,8 @@ window.__ModuleLoader__.load({
67
75
  bodyHint: '{{…}} 会原样保留,不会被当作变量插值。',
68
76
  chars: '字符',
69
77
  enable: '在本对话启用覆盖',
78
+ enableWorkspace: '在本工作区启用覆盖',
79
+ enableGlobal: '在全局默认启用覆盖',
70
80
  save: '保存',
71
81
  clear: '清除覆盖',
72
82
  saving: '保存中…',
@@ -113,7 +123,15 @@ window.__ModuleLoader__.load({
113
123
  subtitle: 'Override the system prompt this conversation actually sends',
114
124
  close: 'Close',
115
125
  scopeSession: 'This conversation',
126
+ scopeWorkspace: 'This workspace',
116
127
  scopeGlobal: 'Global default',
128
+ scopeWorkspaceHint: 'Applied to every conversation in this workspace (subagents included); keyed on the workspace the sidebar shows.',
129
+ scopeWorkspaceNoDir: 'This conversation has no usable workspace, so a workspace override cannot be saved.',
130
+ scopeWorkspacePath: 'Workspace: ',
131
+ workspaceEmpty: 'no rules for this workspace yet',
132
+ workspaceSaved: 'Saved as this workspace\'s rules; applies to its conversations on their next request.',
133
+ workspaceCleared: 'Cleared this workspace\'s rules.',
134
+ workspaceFrom: 'Current rules come from this workspace: ',
117
135
  scopeGlobalHint: 'Applied to every top-level conversation without an override of its own (not subagents).',
118
136
  modeAppend: 'Append',
119
137
  modeAppendHint: 'Keep every first-party section and add yours at the end.',
@@ -134,6 +152,8 @@ window.__ModuleLoader__.load({
134
152
  bodyHint: '{{…}} is kept literally and is not interpolated.',
135
153
  chars: 'chars',
136
154
  enable: 'Enable override for this conversation',
155
+ enableWorkspace: 'Enable override for this workspace',
156
+ enableGlobal: 'Enable override in the global default',
137
157
  save: 'Save',
138
158
  clear: 'Clear override',
139
159
  saving: 'Saving…',
@@ -452,7 +472,8 @@ window.__ModuleLoader__.load({
452
472
  const backdropRef = React.useRef(null)
453
473
 
454
474
  const captureBaseline = React.useCallback((payload, which) => {
455
- const entry = which === 'global' ? payload?.global : payload?.session
475
+ const entry =
476
+ which === 'global' ? payload?.global : which === 'workspace' ? payload?.workspace?.entry : payload?.session
456
477
  return {
457
478
  mode: entry !== null && entry !== undefined && typeof entry.mode === 'string' ? entry.mode : 'append',
458
479
  text: entry !== null && entry !== undefined && typeof entry.text === 'string' ? entry.text : '',
@@ -586,7 +607,24 @@ window.__ModuleLoader__.load({
586
607
  const maxChars = typeof payload?.limits?.maxChars === 'number' ? payload.limits.maxChars : 200000
587
608
  const current = payload?.current ?? null
588
609
  const ownEntry = payload?.session ?? null
610
+ /**
611
+ * 工作区这一档在当前对话上是否可用。
612
+ *
613
+ * `workspace.key` 为空表示 host 算不出这个对话的目录(服务缺失、或会话
614
+ * 记录里没有 cwd)。这时必须把「本工作区」这个 tab 显式标成不可用,
615
+ * 而不是让它看起来能点、点下去再报错——那会让用户以为是自己填错了。
616
+ */
617
+ const workspaceKey = typeof payload?.workspace?.key === 'string' ? payload.workspace.key : ''
618
+ const workspacePath =
619
+ typeof payload?.workspace?.path === 'string' && payload.workspace.path !== ''
620
+ ? payload.workspace.path
621
+ : workspaceKey
622
+ const workspaceEntry = payload?.workspace?.entry ?? null
623
+ const workspaceAvailable = workspaceKey !== ''
589
624
  const inheritFrom = scope === 'session' ? payload?.effective?.inheritedFrom ?? '' : ''
625
+ // 只在「本对话」这一档提示工作区来源:站在工作区 tab 上说「规则来自工作区」
626
+ // 是废话,用户此刻正在编辑的就是那条规则。
627
+ const workspaceFrom = scope === 'session' ? payload?.effective?.workspaceKey ?? '' : ''
590
628
  const disabled = blocked.off || blocked.noService || blocked.noAgents || busy
591
629
  const completeOk = !blocked.complete && (mode !== 'complete' || ack)
592
630
 
@@ -671,13 +709,17 @@ window.__ModuleLoader__.load({
671
709
  return
672
710
  }
673
711
  if (mode === 'complete' && !ack) return
712
+ if (scope === 'workspace' && !workspaceAvailable) {
713
+ setNotice({ kind: 'error', text: t('scopeWorkspaceNoDir') })
714
+ return
715
+ }
674
716
  setBusy(true)
675
717
  setNotice({ kind: '', text: '' })
676
718
  try {
677
719
  const body = {
678
720
  action: 'set',
679
721
  scope,
680
- sessionId: scope === 'session' ? sessionId : '',
722
+ sessionId: sessionId,
681
723
  patch: { enabled, mode, text, target: mode === 'replace' ? target.trim() : '' },
682
724
  }
683
725
  const result = await api.save(body)
@@ -686,7 +728,12 @@ window.__ModuleLoader__.load({
686
728
  setBaseline({ mode, text, target, enabled })
687
729
  setNotice({
688
730
  kind: result?.persisted === false ? 'error' : 'ok',
689
- text: result?.persisted === false ? t('savedLocal') : t('saved'),
731
+ text:
732
+ result?.persisted === false
733
+ ? t('savedLocal')
734
+ : scope === 'workspace'
735
+ ? t('workspaceSaved')
736
+ : t('saved'),
690
737
  })
691
738
  } catch (error) {
692
739
  setNotice({ kind: 'error', text: `${t('saveFailed')}${String(error?.message ?? error)}` })
@@ -696,14 +743,18 @@ window.__ModuleLoader__.load({
696
743
  }
697
744
 
698
745
  const onClear = async () => {
746
+ if (scope === 'workspace' && !workspaceAvailable) {
747
+ setNotice({ kind: 'error', text: t('scopeWorkspaceNoDir') })
748
+ return
749
+ }
699
750
  setBusy(true)
700
751
  setNotice({ kind: '', text: '' })
701
752
  try {
702
- const body = { action: 'clear', scope, sessionId: scope === 'session' ? sessionId : '' }
753
+ const body = { action: 'clear', scope, sessionId }
703
754
  const result = await api.save(body)
704
755
  setStatus({ phase: 'ready', payload: result, error: '' })
705
756
  applyPayload(result, scope)
706
- setNotice({ kind: 'ok', text: t('cleared') })
757
+ setNotice({ kind: 'ok', text: scope === 'workspace' ? t('workspaceCleared') : t('cleared') })
707
758
  } catch (error) {
708
759
  setNotice({ kind: 'error', text: `${t('saveFailed')}${String(error?.message ?? error)}` })
709
760
  } finally {
@@ -813,7 +864,24 @@ window.__ModuleLoader__.load({
813
864
  ? h('div', { key: 'inherit-none', 'data-sps': 'muted' }, t('inheritedNone'))
814
865
  : null,
815
866
 
816
- // 作用域
867
+ /**
868
+ * 工作区来源提示。
869
+ *
870
+ * 只在「本对话没有自身条目、且当前生效的规则来自工作区」时显示:
871
+ * 用户打开一个对话,发现提示词变了,而他自己没在这个对话里设过任何
872
+ * 东西——必须能一眼看出是「这个目录的规矩」在起作用,而不是以为
873
+ * 插件抽风或上一个对话的规则漏过来了。
874
+ */
875
+ workspaceFrom !== '' && ownEntry === null && inheritFrom === ''
876
+ ? h(
877
+ 'div',
878
+ { key: 'wsfrom', 'data-sps': 'warn', style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' } },
879
+ h('span', { style: { flex: 1, minWidth: 200 } }, `${t('workspaceFrom')}${workspaceFrom}`),
880
+ )
881
+ : null,
882
+
883
+ // 作用域:三档,从具体到宽泛排列(本对话 → 本目录 → 全局默认)。
884
+ // 顺序刻意按「影响范围递增」排,用户从左往右点就是在逐级放宽。
817
885
  h(
818
886
  'div',
819
887
  { key: 'scope', 'data-sps': 'row' },
@@ -833,6 +901,23 @@ window.__ModuleLoader__.load({
833
901
  },
834
902
  t('scopeSession'),
835
903
  ),
904
+ h(
905
+ 'button',
906
+ {
907
+ type: 'button',
908
+ 'data-sps': 'tab',
909
+ 'data-on': scope === 'workspace' ? 'true' : 'false',
910
+ // 没有可用目录时禁用而不是隐藏:隐藏会让用户以为插件不支持
911
+ // 工作区,禁用加下面的说明才告诉他「为什么这里不行」。
912
+ disabled: !workspaceAvailable,
913
+ title: workspaceAvailable ? workspacePath : t('scopeWorkspaceNoDir'),
914
+ onClick: () => {
915
+ setScope('workspace')
916
+ applyPayload(status.payload, 'workspace')
917
+ },
918
+ },
919
+ t('scopeWorkspace'),
920
+ ),
836
921
  h(
837
922
  'button',
838
923
  {
@@ -848,8 +933,36 @@ window.__ModuleLoader__.load({
848
933
  ),
849
934
  ),
850
935
  scope === 'global' ? h('span', { 'data-sps': 'muted' }, t('scopeGlobalHint')) : null,
936
+ scope === 'workspace'
937
+ ? h(
938
+ 'span',
939
+ { 'data-sps': 'muted' },
940
+ workspaceAvailable ? t('scopeWorkspaceHint') : t('scopeWorkspaceNoDir'),
941
+ )
942
+ : null,
851
943
  ),
852
944
 
945
+ // 工作区路径:必须显示,否则用户无法核对「我改的是不是这个项目」。
946
+ scope === 'workspace' && workspaceAvailable
947
+ ? h(
948
+ 'div',
949
+ { key: 'wspath', 'data-sps': 'row' },
950
+ h('span', { 'data-sps': 'label' }, t('scopeWorkspacePath')),
951
+ h(
952
+ 'code',
953
+ {
954
+ 'data-sps': 'wspath',
955
+ title: workspacePath,
956
+ style: { fontSize: 12, wordBreak: 'break-all', flex: 1, minWidth: 200 },
957
+ },
958
+ workspacePath,
959
+ ),
960
+ workspaceEntry === null
961
+ ? h('span', { 'data-sps': 'muted' }, `· ${t('workspaceEmpty')}`)
962
+ : null,
963
+ )
964
+ : null,
965
+
853
966
  // 模式
854
967
  h(
855
968
  'div',
@@ -987,7 +1100,11 @@ window.__ModuleLoader__.load({
987
1100
  'label',
988
1101
  { key: 'enable', 'data-sps': 'row', style: { gap: 8 } },
989
1102
  h('input', { type: 'checkbox', checked: enabled, onChange: (event) => setEnabled(event.target.checked) }),
990
- h('span', { 'data-sps': 'muted' }, t('enable')),
1103
+ h(
1104
+ 'span',
1105
+ { 'data-sps': 'muted' },
1106
+ t(scope === 'global' ? 'enableGlobal' : scope === 'workspace' ? 'enableWorkspace' : 'enable'),
1107
+ ),
991
1108
  ),
992
1109
 
993
1110
  // 影响说明
package/lib/index.js CHANGED
@@ -104,6 +104,12 @@ const DEFAULTS = {
104
104
  maxObservedScopes: 64,
105
105
  // 全局默认值套用到哪些会话:roots = 只套用到顶层会话;all = 含子代理。
106
106
  globalDefaultScope: 'roots',
107
+ // 工作区级覆盖套用到哪些会话:all(默认)= 含子代理;roots = 只套用到顶层会话。
108
+ //
109
+ // 与 globalDefaultScope 默认值不同是有意的:全局默认是「所有对话的人格」,
110
+ // 漏进子代理会污染工具型子任务的提示词;而工作区级是「这个项目的规矩」,
111
+ // 子代理正是替这个项目干活的那批,不给它们就等于让实际执行者不守规矩。
112
+ workspaceScope: 'all',
107
113
  // fork 继承:子会话没有自身覆盖时,沿 parentSession 链向上找。
108
114
  // inheritOnFork=false 可退回「各会话独立」的旧行为。
109
115
  inheritOnFork: true,
@@ -136,6 +142,7 @@ function resolveConfig(raw) {
136
142
  observeAssemblies: cfg.observeAssemblies !== false,
137
143
  maxObservedScopes: number(cfg.maxObservedScopes, DEFAULTS.maxObservedScopes, 1, 4096),
138
144
  globalDefaultScope: cfg.globalDefaultScope === 'all' ? 'all' : 'roots',
145
+ workspaceScope: cfg.workspaceScope === 'roots' ? 'roots' : 'all',
139
146
  inheritOnFork: cfg.inheritOnFork !== false,
140
147
  maxInheritDepth: number(cfg.maxInheritDepth, DEFAULTS.maxInheritDepth, 0, MAX_INHERIT_DEPTH),
141
148
  visible: cfg.visible !== false,
@@ -167,7 +174,7 @@ function emptyEntry(mode) {
167
174
  }
168
175
 
169
176
  function emptyState() {
170
- return { version: 1, global: emptyEntry(), sessions: {} }
177
+ return { version: 1, global: emptyEntry(), sessions: {}, workspaces: {} }
171
178
  }
172
179
 
173
180
  /**
@@ -186,9 +193,51 @@ function highestWriteSeq(state) {
186
193
  }
187
194
  consider(state.global)
188
195
  for (const entry of Object.values(state.sessions ?? {})) consider(entry)
196
+ for (const entry of Object.values(state.workspaces ?? {})) consider(entry)
189
197
  return max
190
198
  }
191
199
 
200
+ /**
201
+ * 工作区键:把目录路径洗成一个稳定的、可比较的字符串。
202
+ *
203
+ * 为什么用路径而不是 workspaceRegistry 的 WorkspaceId:id 是注册表内部标识,
204
+ * 同一个目录被删除后重新注册会拿到新 id,而用户的「这个项目的规矩」不该因此
205
+ * 失效。路径是用户自己能理解、能核对的那个东西。
206
+ *
207
+ * 归一化规则(只做「同一个目录的不同写法」之间必须一致的变换):
208
+ * - 统一用 `/` 分隔,去掉末尾分隔符(`C:\a\b\` 与 `C:/a/b` 必须相等);
209
+ * - Windows 上折叠大小写(NTFS 默认不区分),其余平台保留原样;
210
+ * - 折叠 `.` 段与重复分隔符。不做 `..` 解析:那需要文件系统语义,插件不碰。
211
+ *
212
+ * 空输入返回空串——空串表示「这个会话没有可用目录」,绝不能当成一个合法的
213
+ * 工作区键,否则所有无目录会话会共享同一条覆盖。
214
+ */
215
+ function workspaceKeyOf(raw) {
216
+ if (typeof raw !== 'string') return ''
217
+ let text = raw.trim()
218
+ if (text === '') return ''
219
+ text = text.replace(/\\/gu, '/')
220
+ // 折叠重复分隔符与 `.` 段(保留开头的 `//` UNC 前缀)。
221
+ const unc = text.startsWith('//')
222
+ if (unc) text = text.slice(2)
223
+ const segments = []
224
+ for (const segment of text.split('/')) {
225
+ if (segment === '' || segment === '.') continue
226
+ segments.push(segment)
227
+ }
228
+ text = segments.join('/')
229
+ if (unc) text = `//${text}`
230
+ // Windows 盘符统一大写,其余折叠大小写。
231
+ if (process.platform === 'win32') {
232
+ text = text.toLowerCase()
233
+ text = text.replace(/^([a-z]):/u, (_match, drive) => `${drive.toUpperCase()}:`)
234
+ }
235
+ if (text === '') return ''
236
+ // 只有盘符没有后续段(`C:`)不是可用目录。
237
+ if (/^[A-Za-z]:$/u.test(text)) return ''
238
+ return text
239
+ }
240
+
192
241
  function defaultStateFile() {
193
242
  const home = process.env.DSH_HOME && process.env.DSH_HOME.trim() !== '' ? process.env.DSH_HOME : join(homedir(), '.dsh')
194
243
  return join(home, 'dsh-system-prompt-studio', 'state.json')
@@ -254,6 +303,16 @@ function loadState(file) {
254
303
  state.sessions[id] = normalizeEntry(entry)
255
304
  }
256
305
  }
306
+ // 工作区条目:键是归一化后的目录路径。老状态文件没有这一段,缺席即空表。
307
+ if (parsed.workspaces !== null && typeof parsed.workspaces === 'object') {
308
+ for (const [rawKey, entry] of Object.entries(parsed.workspaces)) {
309
+ // 老文件里可能存着未归一化的键(手工编辑、或换过归一化规则),
310
+ // 这里重新洗一遍,避免同一个目录出现两条互不可见的覆盖。
311
+ const key = workspaceKeyOf(rawKey)
312
+ if (key === '') continue
313
+ state.workspaces[key] = normalizeEntry(entry)
314
+ }
315
+ }
257
316
  }
258
317
  health.loaded = true
259
318
  return { state, health }
@@ -372,7 +431,10 @@ function buildSignature(effective) {
372
431
  if (effective === null || effective === undefined) return 'none|'
373
432
  if (effective.kind === 'none') return `none|${effective.reason ?? ''}`
374
433
  const origin = effective.inheritedFrom === undefined ? '' : `|from:${effective.inheritedFrom}`
375
- return `${effective.kind}|${effective.target}|${effective.order}${origin}`
434
+ // 工作区来源也要进签名:换目录(`workingDirectory.set`)后段必须重装到新键上,
435
+ // 否则用户会看到「工作区规则还生效着,但面板说这个目录没有规则」。
436
+ const workspace = typeof effective.workspaceKey === 'string' && effective.workspaceKey !== '' ? `|ws:${effective.workspaceKey}` : ''
437
+ return `${effective.kind}|${effective.target}|${effective.order}${origin}${workspace}`
376
438
  }
377
439
 
378
440
  /** 逐块取出一条消息的纯文本;非文本块跳过。 */
@@ -565,13 +627,27 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
565
627
  }
566
628
  }
567
629
 
568
- // ── 观察:只记录,绝不改写 ───────────────────────────────────────────
569
- if (config.observeAssemblies) {
630
+ // ── 观察 + 对齐:只记录、只重装,绝不改写本次装配 ─────────────────────
631
+ //
632
+ // 这个监听器**总是**注册,而不是只在 observeAssemblies 时注册:里面的
633
+ // {@link reconcile} 负责发现「会话工作目录变了」,而那个变化没有事件可听。
634
+ // 关掉段清单观察不该连带让工作区规则在换目录后失灵。
635
+ //
636
+ // 两件事都发生在 waterfall 里、装配已经取完 sections 之后,所以本次装配
637
+ // 完全不受影响;重装只对下一次请求生效。
638
+ {
570
639
  const off = ctx.on('system-prompt/assemble', (assembly, context, next) => {
640
+ if (config.observeAssemblies) {
641
+ try {
642
+ observeAssembly(ctx, assembly, context)
643
+ } catch {
644
+ /* 观察失败绝不能影响装配 */
645
+ }
646
+ }
571
647
  try {
572
- observeAssembly(ctx, assembly, context)
648
+ reconcile()
573
649
  } catch {
574
- /* 观察失败绝不能影响装配 */
650
+ /* 对齐失败也不能影响装配 */
575
651
  }
576
652
  return next()
577
653
  })
@@ -674,20 +750,217 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
674
750
  }
675
751
  }
676
752
 
753
+ /**
754
+ * 一个会话所属的工作区(`workspaceRegistry` 里那条),没有就 undefined。
755
+ *
756
+ * 这是「工作区」的唯一权威:DSH 把工作区做成一等概念,由注册表按规范化的
757
+ * 项目目录维护 session → workspace 的归属,侧边栏看到的就是它。本插件按
758
+ * 用户看得见的那个东西来分组,而不是另造一套。
759
+ */
760
+ function workspaceOf(sessionId) {
761
+ const registry = service('workspaceRegistry')
762
+ if (registry === undefined || typeof registry.list !== 'function' || sessionId === '') return undefined
763
+ try {
764
+ for (const workspace of registry.list()) {
765
+ const ids = workspace?.sessionIds
766
+ if (!Array.isArray(ids)) continue
767
+ if (ids.includes(sessionId)) return workspace
768
+ }
769
+ } catch {
770
+ return undefined
771
+ }
772
+ return undefined
773
+ }
774
+
775
+ /**
776
+ * 一次会话 → 工作区**原始路径**的索引,按需建立、单次 pass 内复用。
777
+ *
778
+ * 为什么需要缓存:`reconcile()` 在每次装配时对每个活 agent 重算签名,而签名
779
+ * 里含工作区键;如果每次都 `registry.list()` 再逐条 `sessionIds.includes`,
780
+ * 复杂度是 O(agent × workspace × session)。工作区一多就变成每次模型请求都在
781
+ * 做平方级的数组扫描。索引建一次是 O(workspace × session),之后每个 agent
782
+ * 是 O(1)。
783
+ *
784
+ * 存**原始路径**而不是归一化键:显示时要用原路径(归一化会把 Windows 盘符和
785
+ * 目录名小写化,用户核对时看着别扭),匹配时再洗一遍。
786
+ *
787
+ * 失效方式很简单:不跨 pass 复用。工作区归属会变(新建、删除、归档会话),
788
+ * 而注册表没有变更事件可订阅,所以只在单次 pass 内缓存,下一次重算。
789
+ */
790
+ function workspaceIndex() {
791
+ const registry = service('workspaceRegistry')
792
+ const index = new Map()
793
+ if (registry === undefined || typeof registry.list !== 'function') return index
794
+ let list = []
795
+ try {
796
+ list = registry.list()
797
+ } catch {
798
+ return index
799
+ }
800
+ for (const workspace of list) {
801
+ const path = typeof workspace?.path === 'string' ? workspace.path : ''
802
+ const ids = workspace?.sessionIds
803
+ if (path === '' || !Array.isArray(ids)) continue
804
+ for (const id of ids) {
805
+ if (typeof id === 'string' && id !== '' && !index.has(id)) index.set(id, path)
806
+ }
807
+ }
808
+ return index
809
+ }
810
+
811
+ /**
812
+ * 一个会话的工作区,返回 `{ key, path }`;拿不到就返回 null。
813
+ * `key` 用于匹配(归一化),`path` 用于显示(原样)。
814
+ *
815
+ * `owner` 可以是 agent、Session,**也可以只是一个 sessionId 字符串**。后者
816
+ * 是冷会话的唯一可用形态:冷会话既没有活 agent,也不在内存 store 里,
817
+ * 所以拿不到 Session 对象——但注册表是持久化的,光凭 id 就能查到归属。
818
+ * 早期版本要求必须有 Session 对象,结果是冷会话的工作区档整个不可用。
819
+ *
820
+ * 顺序刻意是这样,每一档都对应一个真实的失败模式:
821
+ *
822
+ * 1. **注册表里的工作区目录**。这是用户看得见的那个「工作区」,也是唯一
823
+ * 稳定的归属——会话在注册表里的归属不会因为它中途 `cd` 而改变。
824
+ * 这一档只依赖 sessionId,所以冷会话也走得通。
825
+ *
826
+ * 2. **`workingDirectory.get()`,但只在它不等于 `defaultDirectory` 时采用**。
827
+ * 这一条是踩出来的:`get()` 的实现是 `stateOf(session) ?? defaultDirectory`,
828
+ * 也就是「没换过目录」的会话拿到的是**部署默认目录**,不是它自己的项目。
829
+ * 直接采用会让所有会话共用同一个键——用户在这个项目里设的规则会落到
830
+ * 默认目录名下,然后莫名其妙地对别处生效。只有当 get() 给出别的东西时,
831
+ * 才说明确实提交过一次目录变更。需要 Session 对象,冷会话跳过。
832
+ *
833
+ * 3. **`session.header.cwd`**,会话创建时记下的原始项目目录。
834
+ *
835
+ * 4. 最后才退回 `get()` 的兜底值(此时 header 也没有 cwd,它至少是个真目录)。
836
+ *
837
+ * @param owner agent / Session / sessionId 字符串
838
+ * @param index 可选的预建索引(`reconcile` 的 pass 内传入,避免重复扫描)
839
+ */
840
+ function workspaceRefFor(owner, index) {
841
+ const asId = typeof owner === 'string' ? owner.trim() : ''
842
+ if (asId === '' && (owner === null || typeof owner !== 'object')) return null
843
+ // agent 有 `.session`;冷会话传进来的就是 Session 本身;也可能只是个 id。
844
+ const session =
845
+ asId !== ''
846
+ ? undefined
847
+ : owner.session !== null && typeof owner.session === 'object'
848
+ ? owner.session
849
+ : owner
850
+ const sessionId =
851
+ asId !== ''
852
+ ? asId
853
+ : typeof session?.id === 'string'
854
+ ? session.id
855
+ : typeof owner?.id === 'string'
856
+ ? owner.id
857
+ : ''
858
+
859
+ /** 把一个原始路径包装成 `{ key, path }`;洗不出键就返回 null。 */
860
+ const ref = (raw) => {
861
+ const key = workspaceKeyOf(raw)
862
+ if (key === '') return null
863
+ // 显示用原路径;归一化只影响匹配,不该让用户看到一个被小写化的路径。
864
+ return { key, path: typeof raw === 'string' ? raw.trim() : key }
865
+ }
866
+
867
+ // ── 1. 注册表归属:只依赖 sessionId,冷会话同样成立 ──────────────────
868
+ const fromIndex = index !== undefined && sessionId !== '' ? index.get(sessionId) : undefined
869
+ if (fromIndex !== undefined && fromIndex !== null) {
870
+ const indexed = ref(fromIndex)
871
+ if (indexed !== null) return indexed
872
+ } else if (index === undefined) {
873
+ const workspace = workspaceOf(sessionId)
874
+ if (workspace !== undefined) {
875
+ const owned = ref(workspace.path)
876
+ if (owned !== null) return owned
877
+ }
878
+ }
879
+
880
+ // 后面几档都需要 Session 对象;冷会话到此为止。
881
+ if (session === undefined) return null
882
+
883
+ // ── 2. 当前目录,但排除「没换过目录时的部署默认值」 ─────────────────
884
+ const directory = service('workingDirectory')
885
+ const readDirectory = () => {
886
+ if (directory === undefined || typeof directory.get !== 'function') return ''
887
+ try {
888
+ const value = directory.get(session)
889
+ return typeof value === 'string' ? value : ''
890
+ } catch {
891
+ return ''
892
+ }
893
+ }
894
+
895
+ const current = readDirectory()
896
+ const changed = ref(current)
897
+ if (changed !== null) {
898
+ const fallback = workspaceKeyOf(directory?.defaultDirectory)
899
+ if (fallback === '' || changed.key !== fallback) return changed
900
+ }
901
+
902
+ // ── 3. 会话创建时记下的原始项目目录 ─────────────────────────────────
903
+ try {
904
+ const original = ref(session.header?.cwd)
905
+ if (original !== null) return original
906
+ } catch {
907
+ /* header 读不到就继续往下 */
908
+ }
909
+ return changed
910
+ }
911
+
912
+ /** 只要键的简写;内部判定都用这个。 */
913
+ function workspaceKeyFor(owner, index) {
914
+ const found = workspaceRefFor(owner, index)
915
+ return found === null ? '' : found.key
916
+ }
917
+
918
+ /**
919
+ * 工作区条目:命中归一化键的那一条;没有就 undefined。
920
+ *
921
+ * 先精确命中,再按「同一目录不同写法」兜底——状态文件里可能留着未归一化的
922
+ * 老键(手工编辑过、或归一化规则改过),只做精确匹配会让那份规则静默失效。
923
+ */
924
+ function workspaceEntryFor(key) {
925
+ if (key === '') return undefined
926
+ const direct = runtime.state.workspaces[key]
927
+ if (direct !== undefined) return direct
928
+ for (const [storedKey, entry] of Object.entries(runtime.state.workspaces)) {
929
+ if (workspaceKeyOf(storedKey) === key) return entry
930
+ }
931
+ return undefined
932
+ }
933
+
934
+ /** 该 agent 的工作区条目是否允许套用(受 workspaceScope 限制)。 */
935
+ function workspaceApplies(agent) {
936
+ if (config.workspaceScope === 'roots' && !isRootAgent(agent)) return false
937
+ return true
938
+ }
939
+
677
940
  /**
678
941
  * 判一个 agent 当前该不该有覆盖、以及是什么形态。
679
942
  *
680
- * 优先级:
943
+ * 优先级(从具体到宽泛,谁更靠近「这一次对话」谁赢):
681
944
  * 1. 自身会话条目
682
945
  * 2. 沿 parentSession 链继承(最近的有覆盖的祖先)
683
- * 3. 全局默认(按 globalDefaultScope 决定是否碰子代理)
946
+ * 3. 工作区条目(该对话当前目录的那条)
947
+ * 4. 全局默认(按 globalDefaultScope 决定是否碰子代理)
948
+ *
949
+ * 为什么工作区排在 fork 继承之后:fork 出来的对话带着上一段工作的上下文,
950
+ * 用户为它单独调过规则就是最具体的意图;而工作区规则是「这个目录的默认」,
951
+ * 比「这一次对话的调整」更宽泛。
952
+ *
953
+ * 为什么工作区排在全局之前:全局是「所有对话」,工作区是「这个项目」。
954
+ * 项目规则显然更具体,反过来的话工作区就永远不可能生效——那等于没这个功能。
684
955
  */
685
- function effectiveFor(agent) {
956
+ function effectiveFor(agent, index) {
686
957
  const id = typeof agent?.id === 'string' ? agent.id : ''
687
958
  const own = id !== '' ? runtime.state.sessions[id] : undefined
688
959
  if (own !== undefined && own.enabled) return overrideFromEntry(own, 'session')
689
960
  const inherited = findInheritedOverride(agent)
690
961
  if (inherited !== null) return inherited
962
+ const workspace = workspaceOverrideFor(agent, index)
963
+ if (workspace !== null) return workspace
691
964
  if (runtime.state.global.enabled) {
692
965
  if (config.globalDefaultScope === 'roots' && !isRootAgent(agent)) {
693
966
  return { kind: 'none', source: 'global', reason: 'subagent' }
@@ -697,21 +970,78 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
697
970
  return { kind: 'none' }
698
971
  }
699
972
 
973
+ /**
974
+ * 工作区层的判定:命中且启用且形态有效才返回覆盖,否则 null。
975
+ *
976
+ * 返回 null 而不是 `{kind:'none'}` 是有意的:这一层「没话说」时必须让调用方
977
+ * 继续往全局走,而不是在这里截断优先级链。
978
+ */
979
+ function workspaceOverrideFor(agent, index) {
980
+ if (!workspaceApplies(agent)) return null
981
+ const key = workspaceKeyFor(agent, index)
982
+ if (key === '') return null
983
+ const entry = workspaceEntryFor(key)
984
+ if (entry === undefined || !entry.enabled) return null
985
+ const override = overrideFromEntry(entry, 'workspace')
986
+ if (override.kind === 'none') return null
987
+ return { ...override, workspaceKey: key }
988
+ }
989
+
700
990
  /**
701
991
  * 冷会话(没有活 agent)时的退化判定。
702
992
  *
703
- * 冷会话读不到 header,因此找不到父链——只能看自身条目与全局默认。
993
+ * 冷会话读不到 header,因此找不到父链——只能看自身条目、工作区与全局默认。
704
994
  * 这是本方案的已知边界:冷会话的继承要等它被恢复(有了 agent)之后才成立。
995
+ *
996
+ * 工作区这一层在冷会话下仍然可用:`sessions` 服务能拿到 Session 对象,
997
+ * `workingDirectory.get(session)` 对冷会话同样有效。所以「给某个目录设规则,
998
+ * 之后才打开的对话」这件事不需要会话活着。
705
999
  */
706
1000
  function effectiveForId(sessionId) {
707
1001
  const agent = resolveAgentById(sessionId)
708
1002
  if (agent !== undefined) return effectiveFor(agent)
709
1003
  const own = runtime.state.sessions[sessionId]
710
1004
  if (own !== undefined && own.enabled) return overrideFromEntry(own, 'session')
1005
+ const coldWorkspace = workspaceOverrideForSession(sessionId)
1006
+ if (coldWorkspace !== null) return coldWorkspace
711
1007
  if (runtime.state.global.enabled) return overrideFromEntry(runtime.state.global, 'global')
712
1008
  return { kind: 'none' }
713
1009
  }
714
1010
 
1011
+ /**
1012
+ * 冷会话的工作区判定。
1013
+ *
1014
+ * 关键点:**不要求 Session 对象**。注册表是持久化的,光凭 sessionId 就能查到
1015
+ * 归属;早期版本这里先要 `sessions.get(id)`,而冷会话不在内存 store 里,
1016
+ * 于是「工作区」这一档对冷会话整个不可用——面板显示没有工作区,用户也就
1017
+ * 没法给一个还没恢复的对话设项目规则。
1018
+ *
1019
+ * 子代理判定在冷会话下读不到 header.parentSession(没有 Session 对象),
1020
+ * 所以 `workspaceScope: roots` 时只能保守地按「不是子代理」处理——宁可多套用
1021
+ * 一次,也不要让用户明明设了规则却完全不生效。
1022
+ */
1023
+ function workspaceOverrideForSession(sessionId) {
1024
+ if (config.workspaceScope === 'roots') {
1025
+ const session = coldSessionOf(service('sessions'), sessionId)
1026
+ if (session !== undefined) {
1027
+ let parent = ''
1028
+ try {
1029
+ parent = typeof session.header?.parentSession === 'string' ? session.header.parentSession : ''
1030
+ } catch {
1031
+ parent = ''
1032
+ }
1033
+ if (parent !== '') return null
1034
+ }
1035
+ }
1036
+ const key = workspaceKeyFor(resolveAgentById(sessionId) ?? coldSessionOf(service('sessions'), sessionId) ?? sessionId)
1037
+ if (key === '') return null
1038
+ const entry = workspaceEntryFor(key)
1039
+ if (entry === undefined || !entry.enabled) return null
1040
+ const override = overrideFromEntry(entry, 'workspace')
1041
+ if (override.kind === 'none') return null
1042
+ return { ...override, workspaceKey: key }
1043
+ }
1044
+
715
1045
  function signatureOf(effective) {
716
1046
  return buildSignature(effective)
717
1047
  }
@@ -767,7 +1097,7 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
767
1097
  * 签名,只在形态变化时重装注册。文本变化不必重装——段的 text 是函数,
768
1098
  * 每次装配都会重新求值。
769
1099
  */
770
- function install(agent) {
1100
+ function install(agent, index) {
771
1101
  if (agent === null || typeof agent !== 'object') return
772
1102
  const sessionId = typeof agent.id === 'string' ? agent.id : ''
773
1103
  if (sessionId === '') return
@@ -779,7 +1109,7 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
779
1109
  entry.effective = { kind: 'none', reason: 'disabled' }
780
1110
  return
781
1111
  }
782
- const effective = effectiveFor(agent)
1112
+ const effective = effectiveFor(agent, index)
783
1113
  const signature = signatureOf(effective)
784
1114
  if (entry.signature === signature) return
785
1115
  disposeSections(entry)
@@ -909,6 +1239,59 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
909
1239
  }
910
1240
  }
911
1241
 
1242
+ /**
1243
+ * 按当前状态重新对齐所有活会话的注册。
1244
+ *
1245
+ * 为什么需要它:装段只在 `agent/created` 和「状态被写入」时发生,但有一类
1246
+ * 变化既没有事件、也不经过本插件的写入路径——**会话的工作目录变了**
1247
+ * (`workingDirectory.set`,例如用户在会话里切到另一个项目)。那时工作区层
1248
+ * 该命中另一条规则,可签名只在下次 install 时才会重算,段于是停在旧目录的
1249
+ * 规则上,且没有任何地方能解释这件事。
1250
+ *
1251
+ * 对齐点选在每次装配之后:那是模型请求真正发生、规则真正被读取的时刻,
1252
+ * 也是用户唯一会察觉不对的时刻。重装只改注册形态、不重算文本,代价可以忽略。
1253
+ */
1254
+ function reconcile() {
1255
+ if (!config.enabled) return
1256
+ const registry = agents()
1257
+ if (registry === undefined) return
1258
+ let list = []
1259
+ try {
1260
+ list = registry.list()
1261
+ } catch {
1262
+ return
1263
+ }
1264
+ // 索引按 pass 建一次:每个 agent 的签名都要工作区键,逐 agent 扫注册表会
1265
+ // 变成 O(agent × workspace × session) 的平方级开销。
1266
+ const index = workspaceIndex()
1267
+ for (const agent of list) {
1268
+ const id = typeof agent?.id === 'string' ? agent.id : ''
1269
+ if (id === '') continue
1270
+ const entry = runtime.installed.get(id)
1271
+ if (entry === undefined) {
1272
+ // 新出现的 agent(例如观察先于 agent/created 到达):补装。
1273
+ try {
1274
+ install(agent, index)
1275
+ } catch {
1276
+ /* 对齐失败不能影响装配 */
1277
+ }
1278
+ continue
1279
+ }
1280
+ let expected = ''
1281
+ try {
1282
+ expected = signatureOf(effectiveFor(agent, index))
1283
+ } catch {
1284
+ continue
1285
+ }
1286
+ if (entry.signature === expected) continue
1287
+ try {
1288
+ install(agent, index)
1289
+ } catch {
1290
+ /* 同上 */
1291
+ }
1292
+ }
1293
+ }
1294
+
912
1295
  // ── 状态快照(GET 与写入后都返回同一形状) ───────────────────────────
913
1296
  /** 最近一次请求真正发出去的系统提示词:取活会话里最后一个 system 消息。 */
914
1297
  function currentSystemPrompt(sessions, sessionId) {
@@ -938,6 +1321,17 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
938
1321
  return { text: null, note: '该对话还没有发出过带系统提示词的请求。' }
939
1322
  }
940
1323
 
1324
+ /** 冷会话的 Session 对象(活会话没有 agent 时用);拿不到就 undefined。 */
1325
+ function coldSessionOf(store, sessionId) {
1326
+ if (store === undefined || typeof store.get !== 'function' || sessionId === '') return undefined
1327
+ try {
1328
+ const session = store.get(sessionId)
1329
+ return session === null || session === undefined ? undefined : session
1330
+ } catch {
1331
+ return undefined
1332
+ }
1333
+ }
1334
+
941
1335
  function snapshot(sessionId) {
942
1336
  const registry = agents()
943
1337
  const sessions = service('sessions')
@@ -947,6 +1341,19 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
947
1341
  const record = sessionId !== '' ? runtime.installed.get(sessionId) : undefined
948
1342
  const watch = sessionId !== '' ? runtime.observed.get(sessionId) : undefined
949
1343
  const current = sessionId !== '' ? currentSystemPrompt(sessions, sessionId) : { text: null, note: '未指定会话。' }
1344
+ /**
1345
+ * 该会话所属的工作区与它那条覆盖。
1346
+ *
1347
+ * 面板要同时显示两件事:这条覆盖的正文(用户能编辑),以及它属于哪个工作区
1348
+ * (用户能核对)。只给正文不给路径,用户没法判断自己是不是改到了另一个项目。
1349
+ *
1350
+ * `key` 用于匹配(归一化),`path` 用于显示(原样)。两者分开是因为归一化会
1351
+ * 把 Windows 盘符和目录名小写化——匹配需要它,显示不需要。
1352
+ */
1353
+ const workspaceRef =
1354
+ sessionId !== '' ? workspaceRefFor(resolveAgentById(sessionId) ?? coldSessionOf(sessions, sessionId) ?? sessionId) : null
1355
+ const workspaceKey = workspaceRef === null ? '' : workspaceRef.key
1356
+ const workspaceEntry = workspaceKey !== '' ? workspaceEntryFor(workspaceKey) : undefined
950
1357
  let live = false
951
1358
  try {
952
1359
  live = sessionId !== '' && typeof registry?.get === 'function' ? registry.get(sessionId) !== undefined : false
@@ -963,11 +1370,27 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
963
1370
  sessions: sessions !== undefined,
964
1371
  observeAssemblies: config.observeAssemblies,
965
1372
  allowComplete: config.allowComplete,
1373
+ workspace: config.workspaceScope,
966
1374
  },
967
1375
  sessionId,
968
1376
  live,
969
1377
  global: { ...runtime.state.global },
970
1378
  session: entry !== undefined ? { ...entry } : null,
1379
+ /**
1380
+ * 工作区层:`key` 是归一化路径(用于匹配与核对),`path` 是原始路径
1381
+ * (面板显示用),`entry` 是这条覆盖。
1382
+ *
1383
+ * `key` 为空表示这个会话没有可用工作区(例如注册表里没有归属、且读不到
1384
+ * 目录),此时面板必须说明「工作区级不可用」而不是显示一个空路径让用户
1385
+ * 以为能存。
1386
+ */
1387
+ workspace: {
1388
+ key: workspaceKey,
1389
+ path: workspaceRef === null ? '' : workspaceRef.path,
1390
+ entry: workspaceEntry !== undefined ? { ...workspaceEntry } : null,
1391
+ },
1392
+ /** 已配置的工作区数量,面板用来提示「还有 N 个项目有自己的规则」。 */
1393
+ workspaceCount: Object.keys(runtime.state.workspaces).length,
971
1394
  effective: {
972
1395
  kind: effective.kind,
973
1396
  target: effective.target ?? '',
@@ -977,6 +1400,8 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
977
1400
  // 继承信息:面板据此显示「继承自 <父会话>」并提供「在此固定」。
978
1401
  inheritedFrom: effective.inheritedFrom ?? '',
979
1402
  inheritedDepth: typeof effective.inheritedDepth === 'number' ? effective.inheritedDepth : 0,
1403
+ // 工作区信息:面板据此显示「来自 <目录> 的项目规则」。
1404
+ workspaceKey: effective.workspaceKey ?? '',
980
1405
  },
981
1406
  /** 该会话自身的父会话 id(没有则为空串);面板用来解释继承关系。 */
982
1407
  parentSession: parentIdOf(resolveAgentById(sessionId)),
@@ -1070,14 +1495,49 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
1070
1495
  async function handlePost(payload) {
1071
1496
  const body = payload !== null && typeof payload === 'object' ? payload : {}
1072
1497
  const action = typeof body.action === 'string' ? body.action : ''
1073
- const scope = body.scope === 'global' ? 'global' : 'session'
1498
+ /**
1499
+ * 作用域三档:session(本对话)| workspace(本目录)| global(全局默认)。
1500
+ *
1501
+ * 未知值一律回落到 session 而不是静默当成 global:写错作用域却成功保存,
1502
+ * 用户会以为改的是这一个对话,实际改的是所有对话——这是本插件最危险的一种
1503
+ * 静默失败。回落 session 至少还会因为缺 sessionId 被下面那条检查拦住。
1504
+ */
1505
+ const scope = body.scope === 'global' ? 'global' : body.scope === 'workspace' ? 'workspace' : 'session'
1074
1506
  const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1507
+ /**
1508
+ * 工作区键的来源。
1509
+ *
1510
+ * 面板不直接传路径,而是传 sessionId,由 host 自己算出这个会话当前的目录。
1511
+ * 原因:路径是安全边界——如果接受客户端传任意路径,一个被 XSS 的面板就能
1512
+ * 给任意目录写入规则(含用户从没打开过的目录)。回环围栏挡得住远程,挡不住
1513
+ * 同源脚本。所以只允许「给这个会话所在目录」写规则。
1514
+ *
1515
+ * `workspaceKey` 字段仍然接受,但只在没有 sessionId 时用作显式指定(供脚本
1516
+ * 与测试使用),并且要过同一套归一化。
1517
+ */
1518
+ let workspaceKey = ''
1519
+ if (scope === 'workspace') {
1520
+ if (sessionId !== '') {
1521
+ // 传 agent / Session 而不是裸 id:注册表归属那一档光凭 id 就够,但
1522
+ // 「没进注册表的会话」只能靠 Session 的 header.cwd,裸 id 拿不到它。
1523
+ const found = workspaceRefFor(
1524
+ resolveAgentById(sessionId) ?? coldSessionOf(service('sessions'), sessionId) ?? sessionId,
1525
+ )
1526
+ if (found !== null) workspaceKey = found.key
1527
+ }
1528
+ if (workspaceKey === '' && typeof body.workspaceKey === 'string') {
1529
+ workspaceKey = workspaceKeyOf(body.workspaceKey)
1530
+ }
1531
+ }
1075
1532
 
1076
1533
  if (action === 'resetAll') {
1077
1534
  if (body.confirm !== true) {
1078
1535
  return { status: 400, body: { ok: false, error: 'CONFIRM_REQUIRED', message: '清空全部会话覆盖需要 confirm: true。' } }
1079
1536
  }
1080
1537
  runtime.state.sessions = {}
1538
+ // 工作区规则是「项目规矩」,不是「这一次对话的临时调整」。resetAll 的
1539
+ // 语义是清掉逐对话的临时状态,把工作区一起清掉会毁掉用户攒下来的项目
1540
+ // 配置——那不可恢复,且用户点这个按钮时并不预期它发生。
1081
1541
  const persisted = await applyState()
1082
1542
  return { status: 200, body: { ...snapshot(''), persisted } }
1083
1543
  }
@@ -1088,9 +1548,20 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
1088
1548
  if (scope === 'session' && sessionId === '') {
1089
1549
  return { status: 400, body: { ok: false, error: 'MISSING_SESSION', message: '作用域是 session 时必须给 sessionId。' } }
1090
1550
  }
1551
+ if (scope === 'workspace' && workspaceKey === '') {
1552
+ return {
1553
+ status: 400,
1554
+ body: {
1555
+ ok: false,
1556
+ error: 'MISSING_WORKSPACE',
1557
+ message: '这个对话没有可用的工作区,无法按工作区保存。请给 sessionId(由其工作区归属决定),或显式给 workspaceKey。',
1558
+ },
1559
+ }
1560
+ }
1091
1561
 
1092
1562
  if (action === 'clear') {
1093
1563
  if (scope === 'global') runtime.state.global = { ...emptyEntry(config.defaultMode), ...stampWrite() }
1564
+ else if (scope === 'workspace') delete runtime.state.workspaces[workspaceKey]
1094
1565
  else delete runtime.state.sessions[sessionId]
1095
1566
  const persisted = await applyState()
1096
1567
  return { status: 200, body: { ...snapshot(sessionId), persisted } }
@@ -1129,7 +1600,11 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
1129
1600
 
1130
1601
  const patch = body.patch !== null && typeof body.patch === 'object' ? body.patch : {}
1131
1602
  const current =
1132
- scope === 'global' ? runtime.state.global : runtime.state.sessions[sessionId] ?? emptyEntry(config.defaultMode)
1603
+ scope === 'global'
1604
+ ? runtime.state.global
1605
+ : scope === 'workspace'
1606
+ ? workspaceEntryFor(workspaceKey) ?? emptyEntry(config.defaultMode)
1607
+ : runtime.state.sessions[sessionId] ?? emptyEntry(config.defaultMode)
1133
1608
  // 逐字段合并:只写用户真正提交的键,避免面板把没传的键清掉。
1134
1609
  const next = {
1135
1610
  enabled: typeof patch.enabled === 'boolean' ? patch.enabled : current.enabled,
@@ -1148,6 +1623,7 @@ export const apply = mountOnce(name, function apply(ctx, rawConfig) {
1148
1623
  }
1149
1624
 
1150
1625
  if (scope === 'global') runtime.state.global = next
1626
+ else if (scope === 'workspace') runtime.state.workspaces[workspaceKey] = next
1151
1627
  else runtime.state.sessions[sessionId] = next
1152
1628
  const persisted = await applyState()
1153
1629
  return { status: 200, body: { ...snapshot(sessionId), persisted } }
@@ -1245,6 +1721,7 @@ export const __internals = {
1245
1721
  emptyEntry,
1246
1722
  textOfMessage,
1247
1723
  deriveOrders,
1724
+ workspaceKeyOf,
1248
1725
  isLoopbackRequest,
1249
1726
  isIPv4Loopback,
1250
1727
  isLoopbackHostname,
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@user-mrz/dsh-system-prompt-studio",
3
3
  "displayName": "System prompt studio",
4
- "description": "Per-conversation system prompt control for DeepSeek Harness: append a section, shadow-replace one named section, or replace the whole prompt. Applies on the next model request, persists per session, and inherits along fork lineage.",
5
- "version": "0.2.1",
4
+ "description": "Per-conversation and per-workspace system prompt control for DeepSeek Harness: append a section, shadow-replace one named section, or replace the whole prompt. Applies on the next model request, persists per session and per working directory, and inherits along fork lineage.",
5
+ "version": "0.3.0",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
8
8
  "exports": {