dsh-agent-team-presets 0.2.0 → 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.
Files changed (52) hide show
  1. package/NOTICE +29 -0
  2. package/README.md +61 -12
  3. package/README.zh.md +60 -11
  4. package/assets/card-patches/dsh-better-sidebar-0.32.0.client.js.gz +0 -0
  5. package/assets/card-patches/dsh-context-0.84.0.client.js.gz +0 -0
  6. package/assets/card-patches/licenses/dsh-better-sidebar-LICENSE +21 -0
  7. package/assets/card-patches/licenses/dsh-context-LICENSE +201 -0
  8. package/lib/client.js +9068 -2097
  9. package/lib/index.js +3084 -1212
  10. package/lib/typert.host.js +7454 -1720
  11. package/lib/typert.remote-client.d.ts +16 -1
  12. package/lib/typert.remote-client.d.ts.map +1 -0
  13. package/lib/typert.remote-client.js +7383 -1649
  14. package/lib/types/application.d.ts +24 -1
  15. package/lib/types/application.js +77 -34
  16. package/lib/types/builtin-skill.js +7 -13
  17. package/lib/types/card-patches.d.ts +104 -0
  18. package/lib/types/card-patches.js +275 -0
  19. package/lib/types/client/CardPatchView.d.ts +27 -0
  20. package/lib/types/client/CardPatchView.js +80 -0
  21. package/lib/types/client/ComposerTeamSelect.d.ts +1 -1
  22. package/lib/types/client/ComposerTeamSelect.js +100 -7
  23. package/lib/types/client/TeamImportDialog.js +1 -1
  24. package/lib/types/client/TeamListView.js +8 -7
  25. package/lib/types/client/TeamPresetsSection.js +13 -5
  26. package/lib/types/client/TeamRosterAction.d.ts +15 -0
  27. package/lib/types/client/TeamRosterAction.js +205 -0
  28. package/lib/types/client/agent-card-badges.d.ts +47 -0
  29. package/lib/types/client/agent-card-badges.js +61 -0
  30. package/lib/types/client/card-patches-controller.d.ts +152 -0
  31. package/lib/types/client/card-patches-controller.js +211 -0
  32. package/lib/types/client/index.js +42 -5
  33. package/lib/types/client/locales.d.ts +1 -1
  34. package/lib/types/client/locales.js +118 -12
  35. package/lib/types/client/team-presets-controller.d.ts +20 -0
  36. package/lib/types/client/team-presets-controller.js +15 -0
  37. package/lib/types/execution.d.ts +2 -2
  38. package/lib/types/execution.js +13 -11
  39. package/lib/types/index.js +90 -22
  40. package/lib/types/member-runtime.d.ts +40 -2
  41. package/lib/types/member-runtime.js +70 -2
  42. package/lib/types/member-store.d.ts +9 -0
  43. package/lib/types/member-store.js +13 -1
  44. package/lib/types/presentation.d.ts +12 -5
  45. package/lib/types/presentation.js +63 -10
  46. package/lib/types/preset-tools.js +3 -9
  47. package/lib/types/team-runtime.d.ts +25 -0
  48. package/lib/types/team-runtime.js +50 -0
  49. package/lib/types/tool-catalog.d.ts +64 -1
  50. package/lib/types/tool-catalog.js +103 -0
  51. package/lib/types/types.d.ts +69 -0
  52. package/package.json +52 -49
@@ -19,7 +19,7 @@
19
19
  import type { Context } from '@deepseek-ai/cordis';
20
20
  import type { Agent } from '@deepseek-ai/dsh-agent';
21
21
  import { ReasoningEffortId } from '@deepseek-ai/dsh-llm';
22
- import type { SessionId } from '@deepseek-ai/dsh-session';
22
+ import { SessionId } from '@deepseek-ai/dsh-session';
23
23
  import type { ConfiguredMemberRoute } from './presets.ts';
24
24
  import type { TeamAgentPreset, TeamCaptainPreset, TeamPreset } from './types.ts';
25
25
  import type { MemberRuntime } from './member-runtime.ts';
@@ -168,6 +168,29 @@ export declare function assertTeamApplicable(agent: Agent, team: TeamPreset): vo
168
168
  * @returns the refusal text, or undefined when every named capability is reachable.
169
169
  */
170
170
  export declare function capabilityRefusal(agent: Agent, team: TeamPreset, target?: TeamApplicationTarget): string | undefined;
171
+ /**
172
+ * One roster line this refusal can act on.
173
+ *
174
+ * The roster is the only place that knows whether an occupied slot belongs to a
175
+ * member that still runs, or to a creation that never became usable. Without that
176
+ * split the captain cannot tell a busy Team from one that will never summon again.
177
+ */
178
+ export interface SpawnRosterEntry {
179
+ readonly name: string;
180
+ readonly status: string;
181
+ }
182
+ /**
183
+ * Explain one failed creation in terms the captain can act on.
184
+ *
185
+ * The two limits are different: an activity slot frees itself when a member
186
+ * finishes, while a used-up Team allowance never comes back. The official text
187
+ * is always preserved verbatim inside the explanation, because it carries the
188
+ * exact numbers the Host decided with.
189
+ * @param error - the failure `startActivation` reported.
190
+ * @param roster - current roster rows, used to name the slots that never became usable.
191
+ * @returns the model-facing explanation.
192
+ */
193
+ export declare function classifySpawnFailure(error: unknown, roster?: readonly SpawnRosterEntry[]): string;
171
194
  /**
172
195
  * Apply one Team preset to one live Session.
173
196
  *
@@ -18,6 +18,8 @@
18
18
  */
19
19
  import { defineTool } from '@deepseek-ai/dsh-tools';
20
20
  import { ReasoningEffortId } from '@deepseek-ai/dsh-llm';
21
+ import { SessionId } from '@deepseek-ai/dsh-session';
22
+ import { randomUUID } from 'node:crypto';
21
23
  import { PERSONA_PREFIX_SECTION } from '@deepseek-ai/dsh-system-prompt';
22
24
  import { IMPLICIT_TOOLS, captainBriefing, definitionFingerprint, findMember, memberBriefing, memberRouteOf, memberTargets, memberTeamDivision, soloMemberBriefing, toolMode } from "./presets.js";
23
25
  import { depthRefusal, routeRefusal } from "./delegation.js";
@@ -25,6 +27,7 @@ import { memberProviderFor } from "./member-identity.js";
25
27
  import { guardPolicy, inheritedFilter, isOwnLayerTool, policyOf } from "./tool-policy.js";
26
28
  import { SPAWN_TEAM_MEMBER_DESCRIPTION } from "./tool-descriptions.js";
27
29
  import { prepareNativePresentation } from "./presentation.js";
30
+ import { reserveMember, teamMembers } from "./team-runtime.js";
28
31
  /** The route this plugin actually installed on one created member. */
29
32
  const MEMBER_ROUTE_SCHEMA = {
30
33
  type: 'object',
@@ -163,6 +166,8 @@ export function capabilityRefusal(agent, team, target) {
163
166
  const CONCURRENT_CAPACITY = /active child limit/i;
164
167
  /** The Team's lifetime member allowance, which a finished member still occupies. */
165
168
  const LIFETIME_QUOTA = /team member limit/i;
169
+ /** The allowance the Host reported, when its refusal carries the number. */
170
+ const LIFETIME_LIMIT = /team member limit (\d+)/i;
166
171
  /**
167
172
  * Explain one failed creation in terms the captain can act on.
168
173
  *
@@ -170,18 +175,30 @@ const LIFETIME_QUOTA = /team member limit/i;
170
175
  * finishes, while a used-up Team allowance never comes back. The official text
171
176
  * is always preserved verbatim inside the explanation, because it carries the
172
177
  * exact numbers the Host decided with.
173
- * @param error - the failure `spawnTeammate` reported.
178
+ * @param error - the failure `startActivation` reported.
179
+ * @param roster - current roster rows, used to name the slots that never became usable.
174
180
  * @returns the model-facing explanation.
175
181
  */
176
- function classifySpawnFailure(error) {
182
+ export function classifySpawnFailure(error, roster = []) {
177
183
  const message = error instanceof Error ? error.message : String(error);
178
184
  if (CONCURRENT_CAPACITY.test(message)) {
179
185
  return 'No subagent slot is free right now: this deployment\'s concurrent subagent limit is reached. Wait for a '
180
186
  + `running member to finish, then summon again. (${message})`;
181
187
  }
182
188
  if (LIFETIME_QUOTA.test(message)) {
183
- return 'This Team has used up its lifetime member allowance. A member that already finished still occupies its '
184
- + `Team roster slot, so this Team cannot summon another instance; finish the task with the members it has. (${message})`;
189
+ const limit = LIFETIME_LIMIT.exec(message)?.[1];
190
+ const used = roster.length;
191
+ const failed = roster.filter(entry => entry.status === 'failed').map(entry => entry.name);
192
+ const occupancy = limit === undefined
193
+ ? `${used} roster slot${used === 1 ? '' : 's'} occupied`
194
+ : `${used} of ${limit} roster slots occupied`;
195
+ const spent = failed.length === 0
196
+ ? ''
197
+ : `, and ${failed.length} of them never became usable (${failed.join(', ')})`;
198
+ return 'This Team has used up its lifetime member allowance. A member that already finished, or a creation that '
199
+ + `never became usable, still occupies its Team roster slot (${occupancy}${spent}). The Host's roster is `
200
+ + 'append-only and exposes no removal API, so a slot spent by a failed creation cannot be reclaimed; start a new '
201
+ + `Session to summon more members. (${message})`;
185
202
  }
186
203
  return message;
187
204
  }
@@ -210,16 +227,38 @@ function routedMember(frozen, stored) {
210
227
  const matches = stored.members.filter(member => member.name.trim() === frozen.name.trim());
211
228
  return matches.length === 1 ? matches[0] : frozen;
212
229
  }
230
+ /**
231
+ * Reserve one child name the subagent runtime accepts.
232
+ *
233
+ * A name is a lower-case segment of at most 32 characters that starts with a
234
+ * letter and is never `lead`, so a display-derived target is adjusted rather
235
+ * than passed through.
236
+ * @param target - the configured teammate target.
237
+ * @param used - names already taken among the captain's children.
238
+ * @returns a free name for this creation.
239
+ */
240
+ function availableName(target, used) {
241
+ const prefixed = /^[a-z]/u.test(target) ? target : `m-${target}`;
242
+ const base = (prefixed === 'lead' ? 'lead-2' : prefixed).slice(0, 32).replace(/-+$/u, '');
243
+ let name = base;
244
+ let suffix = 2;
245
+ while (used.has(name)) {
246
+ const tail = `-${suffix++}`;
247
+ name = `${base.slice(0, 32 - tail.length).replace(/-+$/u, '')}${tail}`;
248
+ }
249
+ return name;
250
+ }
213
251
  /**
214
252
  * Register the model-facing member tool on one Session.
215
253
  *
216
- * Official rc.2's Team request accepts only `name`, `description`, `prompt`,
217
- * `context`, `provider`, and `signal`; the member's route, persona, and tool
218
- * scope therefore travel through the durable member snapshot this tool records
219
- * BEFORE `spawnTeammate` is called, and are installed by the serial
220
- * `agent/created` listener. A refused snapshot refuses the spawn: a member that
221
- * could not be recorded must not be created, because nothing would re-scope it.
222
- * @param ctx - the plugin context providing `agentTeams`.
254
+ * A subagent creation request carries no persona or tool filter, so the member's
255
+ * route, persona, and tool scope travel through the durable member snapshot this
256
+ * tool records BEFORE `startActivation` is called, and are installed by the
257
+ * serial `agent/created` listener. The snapshot also reserves the child
258
+ * identity, because the runtime publishes tree membership only after that
259
+ * callback returns. A refused snapshot refuses the spawn: a member that could
260
+ * not be recorded must not be created, because nothing would re-scope it.
261
+ * @param ctx - the plugin context providing `subagents`.
223
262
  * @param agent - the live Session agent that owns the tool.
224
263
  * @param team - the applied Team preset.
225
264
  * @param providers - continuable-subagent providers to spawn through.
@@ -282,15 +321,10 @@ function registerMemberTool(ctx, agent, team, providers, stored, members) {
282
321
  const alias = memberProviderFor(providers, context);
283
322
  if ('error' in alias)
284
323
  throw new Error(alias.error);
285
- const used = new Set(ctx.agentTeams.listMembers(caller).map(row => row.name));
324
+ const used = new Set(teamMembers(ctx, caller).map(row => row.name.split('/').pop() ?? row.name));
286
325
  for (const name of reserved)
287
326
  used.add(name);
288
- let instance = target;
289
- let suffix = 2;
290
- while (used.has(instance)) {
291
- const tail = `-${suffix++}`;
292
- instance = `${target.slice(0, 64 - tail.length).replace(/-+$/u, '')}${tail}`;
293
- }
327
+ const instance = availableName(target, used);
294
328
  reserved.add(instance);
295
329
  try {
296
330
  return await members.admit(async () => {
@@ -309,8 +343,15 @@ function registerMemberTool(ctx, agent, team, providers, stored, members) {
309
343
  if (recheck !== undefined)
310
344
  throw new Error(recheck);
311
345
  const policy = policyOf(team.id, member);
346
+ // The child identity is reserved here and recorded with the snapshot,
347
+ // so the creation callback can identify this member before the runtime
348
+ // publishes any membership for it.
349
+ const childId = SessionId(randomUUID());
350
+ const description = args.description
351
+ ?? (member.description.trim() === '' ? member.name.trim() || target : member.description.trim());
312
352
  const prepared = await members.prepare({
313
353
  root: caller,
354
+ childId,
314
355
  target: instance,
315
356
  teamId: team.id,
316
357
  roleId: member.id,
@@ -332,25 +373,24 @@ function registerMemberTool(ctx, agent, team, providers, stored, members) {
332
373
  });
333
374
  if (prepared.kind === 'refused')
334
375
  throw new Error(prepared.reason);
376
+ const release = reserveMember(caller, childId, instance);
335
377
  try {
336
- // Official fields only. The three extra properties earlier versions
337
- // passed here are not part of the Team request and were ignored.
338
- const result = await ctx.agentTeams.spawnTeammate(caller, {
339
- name: instance,
340
- description: args.description ?? (member.description.trim() === '' ? member.name.trim() || target : member.description.trim()),
341
- prompt: task,
342
- context,
378
+ // The alias is this member's durable identity: the Host writes it into
379
+ // the child's own descriptor, which is what tells this member apart
380
+ // from a native teammate after a restart.
381
+ const activation = members.track(await ctx.subagents.startActivation({
343
382
  provider: alias.name,
383
+ label: description,
384
+ prompt: task,
385
+ parent: caller,
344
386
  signal: exec.signal,
345
- });
346
- const failed = result.member.status === 'failed';
347
- // The Host can settle a member as failed while resolving the spawn;
348
- // record that on the snapshot so the durable record matches the action.
349
- if (failed)
350
- await members.markFailed(caller.id, instance);
387
+ delivery: 'parent',
388
+ name: instance,
389
+ childId,
390
+ }));
351
391
  return {
352
- target: result.member.name,
353
- status: failed ? 'failed' : 'active',
392
+ target: activation.name,
393
+ status: 'active',
354
394
  ...route === undefined ? {} : { configuredRoute: { ...route } },
355
395
  };
356
396
  }
@@ -362,11 +402,14 @@ function registerMemberTool(ctx, agent, team, providers, stored, members) {
362
402
  // and the Host then reports only its provisioning checkpoint. Name the
363
403
  // member's real cause so the fault is not mistaken for a Team fault.
364
404
  const cause = members.failureOf(caller.id, instance);
365
- const reported = classifySpawnFailure(error);
405
+ const reported = classifySpawnFailure(error, teamMembers(ctx, caller));
366
406
  if (cause === undefined)
367
407
  throw new Error(reported, { cause: error });
368
408
  throw new Error(`${reported} (the member's own first request failed: ${cause})`, { cause: error });
369
409
  }
410
+ finally {
411
+ release();
412
+ }
370
413
  });
371
414
  }
372
415
  finally {
@@ -40,7 +40,7 @@ export const BUILTIN_SKILL_CONTENT = `# Agent Team Presets 使用问题排查
40
40
  | 现象 | 先查 | 常见原因 | 处理 |
41
41
  |---|---|---|---|
42
42
  | 选中团队但不生效 | 当前会话 Team selection、应用状态、报错文本 | Team 无效、被 quarantine、任务运行中冻结、Agent preset 不兼容 | 修复预设或换 Team;等队长/成员 idle;必要时换 Agent preset |
43
- | 自定义工具策略被拒 | 报错是否提到 native Agent preset / PTC | DSH rc.1 无法在临时覆盖执行器后恢复继承执行器,插件主动拒绝 | 改用 all-tools,或先把 Agent preset 换成 standard/cordis |
43
+ | 自定义工具策略被拒 | 报错是否提到 native executor / run_code 仍暴露 | 挂载 native 执行器失败,或挂载后工具面仍含 PTC 传输 | 改用 all-tools,或在会话开始前换 standard/cordis 预设;两种情况都不会留下残留 |
44
44
  | 成员无法召唤 | 报错文本、成员快照、subagent provider、存储 | 无 member runtime、无存储、无 spawn/fork 后端、深度/配额、快照损坏、技能目录无法发布 | 按报错逐项修复;不要绕过标记或隔离 |
45
45
  | 成员模型与配置不符 | configuredRoute、model/selection、request/header、成员快照 route;list_agents 的 model 仅作展示 | 展示值 fallback(list_agents 可能返回错误/继承模型);预设未保存;provider 不支持该模型/effort;成员路由在召唤时读取 | 以运行证据为准;三处运行证据一致而 list_agents 不同时,判定为展示问题,实际路由正确 |
46
46
  | Team Skill 不可见 | 是否已分配给正确 roleId、skill 工具是否可见、库是否打开 | 分配错角色、成员创建早于目录发布、宿主隐藏 skill 工具、存储未打开 | 重新分配/重建成员;检查库与绑定 |
@@ -60,19 +60,13 @@ export const BUILTIN_SKILL_CONTENT = `# Agent Team Presets 使用问题排查
60
60
 
61
61
  ## 2. 自定义工具策略被拒 / PTC
62
62
 
63
- 典型报错:
63
+ PTC 预设 + 自定义白名单现在可以应用,但会改变该会话的工具面:
64
64
 
65
- ~~~text
66
- Custom Team tool policies require a native Agent preset (standard or cordis).
67
- This Session uses PTC, and this Harness version cannot restore an inherited
68
- executor after a temporary override.
69
- ~~~
70
-
71
- - 这是 **有意拒绝**,不是漏配。DSH 0.2.2-rc.1 的 setExecutor disposer 会在精确作用域留下不可用的选择,没有公开操作能恢复继承执行器;插件不再安装 native presentation 覆盖,因此 PTC 下不能安全执行自定义 allow-list。
72
- - 处理:
73
- 1. 在会话开始前把 Agent preset 切到 standard 或 cordis;或
74
- 2. 该 Team 改用 all-tools 模式(PTC 仍可用)。
75
- - 不要尝试 presentAs、强制 native、关闭 guard 或修改隔离来“让它先跑起来”;这会让策略与实际执行面不一致。
65
+ - 应用时插件把宿主自带的 native 工具执行器挂到**该会话的 Agent 作用域**(\`agent.ctx.tools.setExecutor\`),部署级 PTC 执行器和其他会话都不受影响。
66
+ - 该注册的 effect 归 Agent ctx 所有,插件**从不主动释放** —— 这正是 DSH 0.2.2-rc.1 单向释放(tombstone)不会咬到的原因;Agent 销毁时随上下文回收。
67
+ - 代价:这个会话此后不再使用 \`run_code\`,直到它的 Agent 结束。
68
+ - 报错时只有两种可能:挂载失败,或挂载后工具面仍暴露 PTC 传输;两种情况都不会留下残留(从未释放过执行器),处理方式是该 Team 改用 all-tools 模式,或在会话开始前选 native 预设。
69
+ - 不要绕过 guard、不要关闭隔离、也不要手工 \`presentAs\`:策略必须与实际执行面一致。
76
70
  - 检查点:会话当前 Agent preset、Team 队长/成员的 toolMode、报错是否来自应用阶段还是 spawn_team_member。
77
71
 
78
72
  ## 3. 成员无法召唤
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Optional card-badge patches for other plugins' Agent cards.
3
+ *
4
+ * Neither dsh-context nor dsh-better-sidebar publishes a card extension point,
5
+ * so marking the subagents a Team created on their cards requires replacing
6
+ * that plugin's browser bundle with one built from the pinned source plus a
7
+ * small registration service. This module owns that replacement: what a
8
+ * supported target is, whether the installed copy is still the published
9
+ * bundle or already ours, and how to swap it in and back out.
10
+ *
11
+ * Nothing here builds anything. Both replacements ship as prebuilt assets
12
+ * (`assets/card-patches`) produced from the exact upstream revision named in
13
+ * the catalog, so an install is an offline file swap. Every decision comes from
14
+ * a content hash: a bundle matching neither the published original nor this
15
+ * build's replacement is refused, because overwriting it would destroy an edit
16
+ * this plugin cannot reproduce.
17
+ *
18
+ * Each target is pinned to one version. A target running any other version
19
+ * reports `unsupported` rather than receiving a bundle built from different
20
+ * source.
21
+ * @module dsh-agent-team-presets/card-patches
22
+ */
23
+ import type { CardPatchFileState, CardPatchResult, CardPatchTargetView } from './types.ts';
24
+ export type { CardPatchFileState, CardPatchResult, CardPatchTargetView };
25
+ /** One target plugin this build can patch, pinned to the version it was built for. */
26
+ export interface CardPatchTarget {
27
+ /** Stable identity used by the settings page and the Remote methods. */
28
+ readonly id: string;
29
+ /** Package whose browser bundle is replaced. */
30
+ readonly packageName: string;
31
+ /** The one version this build's bundle was produced from. */
32
+ readonly version: string;
33
+ /** Upstream revision the bundle was built from, for the operator's audit. */
34
+ readonly source: string;
35
+ /** Prebuilt replacement, relative to `assets/card-patches`. */
36
+ readonly asset: string;
37
+ /**
38
+ * Service name the replacement registers. The settings page reads its
39
+ * presence in the live client to tell an installed patch from one that is on
40
+ * disk but not yet served.
41
+ */
42
+ readonly service: string;
43
+ /** sha256 of the bundle the package publishes; the only state one may overwrite. */
44
+ readonly pristineSha256: string;
45
+ /** sha256 of the prebuilt replacement; the only state one may restore from. */
46
+ readonly patchedSha256: string;
47
+ }
48
+ /**
49
+ * The supported targets.
50
+ *
51
+ * Each entry is fixed to one upstream version on purpose: the replacement is a
52
+ * whole-bundle build, so a different version's bundle would silently change
53
+ * behaviour that was never reviewed here.
54
+ */
55
+ export declare const CARD_PATCH_TARGETS: readonly CardPatchTarget[];
56
+ /**
57
+ * The file-system facts one patch operation depends on.
58
+ *
59
+ * Injected rather than read from ambient state so a test can point at a fixture
60
+ * package instead of the running profile.
61
+ */
62
+ export interface CardPatchEnvironment {
63
+ /** Resolve one package name to its directory, or undefined when it is absent. */
64
+ resolvePackage(packageName: string): string | undefined;
65
+ /** Absolute directory this plugin owns for backups. */
66
+ backupDirectory(): string;
67
+ /** Absolute directory holding the prebuilt replacements. */
68
+ assetDirectory(): string;
69
+ }
70
+ /** The real environment: the running profile's packages and this plugin's directories. */
71
+ export declare const realCardPatchEnvironment: CardPatchEnvironment;
72
+ /**
73
+ * Classify one installed target without changing anything.
74
+ * @param target - the catalog entry.
75
+ * @param env - the file-system facts to read through.
76
+ * @returns the row the settings page renders.
77
+ */
78
+ export declare function targetState(target: CardPatchTarget, env?: CardPatchEnvironment): CardPatchTargetView;
79
+ /**
80
+ * Replace one target's browser bundle with the prebuilt replacement.
81
+ *
82
+ * The installed bytes are copied into this plugin's backup directory before the
83
+ * replacement is written, and the write is a rename of a sibling file, so a
84
+ * failure leaves the original in place. A target whose bundle is not the exact
85
+ * published build is refused: restoring it later could not reproduce an edit
86
+ * this plugin never saw.
87
+ * @param target - the catalog entry.
88
+ * @param env - the file-system facts to act through.
89
+ * @returns the outcome and the resulting state.
90
+ */
91
+ export declare function installCardPatch(target: CardPatchTarget, env?: CardPatchEnvironment): CardPatchResult;
92
+ /**
93
+ * Restore one target's published browser bundle from this plugin's backup.
94
+ * @param target - the catalog entry.
95
+ * @param env - the file-system facts to act through.
96
+ * @returns the outcome and the resulting state.
97
+ */
98
+ export declare function uninstallCardPatch(target: CardPatchTarget, env?: CardPatchEnvironment): CardPatchResult;
99
+ /**
100
+ * Resolve one catalog entry by target id.
101
+ * @param id - the settings page's row identity.
102
+ * @returns the entry, or undefined for an id this build does not ship.
103
+ */
104
+ export declare function findCardPatchTarget(id: string): CardPatchTarget | undefined;
@@ -0,0 +1,275 @@
1
+ /**
2
+ * Optional card-badge patches for other plugins' Agent cards.
3
+ *
4
+ * Neither dsh-context nor dsh-better-sidebar publishes a card extension point,
5
+ * so marking the subagents a Team created on their cards requires replacing
6
+ * that plugin's browser bundle with one built from the pinned source plus a
7
+ * small registration service. This module owns that replacement: what a
8
+ * supported target is, whether the installed copy is still the published
9
+ * bundle or already ours, and how to swap it in and back out.
10
+ *
11
+ * Nothing here builds anything. Both replacements ship as prebuilt assets
12
+ * (`assets/card-patches`) produced from the exact upstream revision named in
13
+ * the catalog, so an install is an offline file swap. Every decision comes from
14
+ * a content hash: a bundle matching neither the published original nor this
15
+ * build's replacement is refused, because overwriting it would destroy an edit
16
+ * this plugin cannot reproduce.
17
+ *
18
+ * Each target is pinned to one version. A target running any other version
19
+ * reports `unsupported` rather than receiving a bundle built from different
20
+ * source.
21
+ * @module dsh-agent-team-presets/card-patches
22
+ */
23
+ import { createHash } from 'node:crypto';
24
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
25
+ import { createRequire } from 'node:module';
26
+ import { homedir } from 'node:os';
27
+ import { dirname, join } from 'node:path';
28
+ import { fileURLToPath } from 'node:url';
29
+ import { gunzipSync } from 'node:zlib';
30
+ /**
31
+ * The supported targets.
32
+ *
33
+ * Each entry is fixed to one upstream version on purpose: the replacement is a
34
+ * whole-bundle build, so a different version's bundle would silently change
35
+ * behaviour that was never reviewed here.
36
+ */
37
+ export const CARD_PATCH_TARGETS = [
38
+ {
39
+ id: 'dsh-context',
40
+ packageName: 'dsh-context',
41
+ version: '0.84.0',
42
+ source: 'bowenliang123/dsh-context@aa98b1231d5f0f8e833391f198e65e14e73b3323',
43
+ asset: 'dsh-context-0.84.0.client.js.gz',
44
+ service: 'contextAgentCardBadges',
45
+ pristineSha256: '686ce45c05394d5820697c402dc64de05ff83b0f2770fed32fb524b3dbdf8450',
46
+ patchedSha256: '4d4e0afe7b536ca5f32e8ed910e226afbbb81e1e3d9481d8e93e7a3e8b4ea461',
47
+ },
48
+ {
49
+ id: 'dsh-better-sidebar',
50
+ packageName: 'dsh-better-sidebar',
51
+ version: '0.32.0',
52
+ source: 'omdsh-dev/DSH-better-sidebar@v0.32.0',
53
+ asset: 'dsh-better-sidebar-0.32.0.client.js.gz',
54
+ service: 'betterSidebarAgentCardBadges',
55
+ pristineSha256: '30d0022f89c0bc4751fe6cf274cb7f3543389c27ad18ebf4e58fac4a40ad7cc4',
56
+ patchedSha256: 'd0a9f0257e80fb3fdf6eb06a587b5b5aa985e1cfbaaf7a187ee381da0a8ac7ba',
57
+ },
58
+ ];
59
+ /** Directory holding the prebuilt replacements shipped with this package. */
60
+ function shippedAssets() {
61
+ // Built output lives in `lib/`, one level below the package root.
62
+ return join(dirname(dirname(fileURLToPath(import.meta.url))), 'assets', 'card-patches');
63
+ }
64
+ /** Backups of replaced bundles, under the same `$DSH_HOME` this plugin already uses. */
65
+ function shippedBackups() {
66
+ const home = process.env['DSH_HOME'] !== undefined && process.env['DSH_HOME'] !== ''
67
+ ? process.env['DSH_HOME']
68
+ : join(homedir(), '.dsh');
69
+ return join(home, 'agent-team-presets', 'card-patches');
70
+ }
71
+ /**
72
+ * Resolve a package the way the running profile resolves it.
73
+ *
74
+ * This module is loaded from the profile's `node_modules`, so the package beside
75
+ * it is the one the browser is served. A resolution failure is "not installed"
76
+ * rather than an error: a profile without a target is the ordinary case.
77
+ * @param packageName - the target package name.
78
+ * @returns its directory, or undefined when it is absent.
79
+ */
80
+ function resolveProfilePackage(packageName) {
81
+ try {
82
+ const require = createRequire(import.meta.url);
83
+ return dirname(require.resolve(`${packageName}/package.json`));
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ }
89
+ /** The real environment: the running profile's packages and this plugin's directories. */
90
+ export const realCardPatchEnvironment = {
91
+ resolvePackage: resolveProfilePackage,
92
+ backupDirectory: shippedBackups,
93
+ assetDirectory: shippedAssets,
94
+ };
95
+ /**
96
+ * Read the installed package.json version.
97
+ * @param directory - target package directory.
98
+ * @returns its version, or undefined when the manifest is unreadable.
99
+ */
100
+ function installedVersion(directory) {
101
+ try {
102
+ const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'));
103
+ return typeof manifest.version === 'string' ? manifest.version : undefined;
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ }
109
+ /**
110
+ * Where the target's browser bundle lives.
111
+ * @param directory - target package directory.
112
+ * @returns the absolute path the client module system serves.
113
+ */
114
+ function bundlePath(directory) {
115
+ return join(directory, 'lib', 'client.js');
116
+ }
117
+ /**
118
+ * Hash one file's bytes.
119
+ * @param path - absolute file path.
120
+ * @returns the lowercase hex sha256.
121
+ */
122
+ function sha256Of(path) {
123
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
124
+ }
125
+ /**
126
+ * Classify one installed target without changing anything.
127
+ * @param target - the catalog entry.
128
+ * @param env - the file-system facts to read through.
129
+ * @returns the row the settings page renders.
130
+ */
131
+ export function targetState(target, env = realCardPatchEnvironment) {
132
+ const base = {
133
+ id: target.id,
134
+ packageName: target.packageName,
135
+ source: target.source,
136
+ supportedVersion: target.version,
137
+ };
138
+ const directory = env.resolvePackage(target.packageName);
139
+ if (directory === undefined) {
140
+ return { ...base, state: 'absent', detail: 'this plugin is not installed in the running profile' };
141
+ }
142
+ const version = installedVersion(directory);
143
+ if (version === undefined) {
144
+ return { ...base, state: 'absent', detail: 'its package.json could not be read' };
145
+ }
146
+ if (version !== target.version) {
147
+ return {
148
+ ...base,
149
+ installedVersion: version,
150
+ state: 'unsupported',
151
+ detail: `this build ships a replacement for ${target.version}, not ${version}`,
152
+ };
153
+ }
154
+ const bundle = bundlePath(directory);
155
+ if (!existsSync(bundle)) {
156
+ return { ...base, installedVersion: version, state: 'absent', detail: 'its browser bundle is missing' };
157
+ }
158
+ const digest = sha256Of(bundle);
159
+ if (digest === target.patchedSha256)
160
+ return { ...base, installedVersion: version, state: 'patched' };
161
+ if (digest === target.pristineSha256)
162
+ return { ...base, installedVersion: version, state: 'pristine' };
163
+ return {
164
+ ...base,
165
+ installedVersion: version,
166
+ state: 'foreign',
167
+ detail: 'its browser bundle matches neither the published build nor this plugin\'s replacement',
168
+ };
169
+ }
170
+ /**
171
+ * Replace one target's browser bundle with the prebuilt replacement.
172
+ *
173
+ * The installed bytes are copied into this plugin's backup directory before the
174
+ * replacement is written, and the write is a rename of a sibling file, so a
175
+ * failure leaves the original in place. A target whose bundle is not the exact
176
+ * published build is refused: restoring it later could not reproduce an edit
177
+ * this plugin never saw.
178
+ * @param target - the catalog entry.
179
+ * @param env - the file-system facts to act through.
180
+ * @returns the outcome and the resulting state.
181
+ */
182
+ export function installCardPatch(target, env = realCardPatchEnvironment) {
183
+ const before = targetState(target, env);
184
+ if (before.state === 'patched')
185
+ return { ok: true, id: target.id, state: 'patched' };
186
+ if (before.state !== 'pristine') {
187
+ return { ok: false, id: target.id, state: before.state, ...before.detail === undefined ? {} : { detail: before.detail } };
188
+ }
189
+ const directory = env.resolvePackage(target.packageName);
190
+ if (directory === undefined)
191
+ return { ok: false, id: target.id, state: 'absent', detail: 'the package disappeared' };
192
+ const asset = join(env.assetDirectory(), target.asset);
193
+ if (!existsSync(asset)) {
194
+ return {
195
+ ok: false,
196
+ id: target.id,
197
+ state: 'pristine',
198
+ detail: 'this installation ships no prebuilt replacement; reinstall the plugin so assets/card-patches is included',
199
+ };
200
+ }
201
+ const replacement = gunzipSync(readFileSync(asset));
202
+ if (createHash('sha256').update(replacement).digest('hex') !== target.patchedSha256) {
203
+ return { ok: false, id: target.id, state: 'pristine', detail: 'the prebuilt replacement does not match its recorded hash' };
204
+ }
205
+ const bundle = bundlePath(directory);
206
+ try {
207
+ const backups = env.backupDirectory();
208
+ mkdirSync(backups, { recursive: true });
209
+ copyFileSync(bundle, join(backups, `${target.id}-${target.version}.client.js`));
210
+ const staged = `${bundle}.card-patch.tmp`;
211
+ writeFileSync(staged, replacement);
212
+ renameSync(staged, bundle);
213
+ }
214
+ catch (error) {
215
+ return { ok: false, id: target.id, state: 'pristine', detail: `the replacement could not be written: ${String(error)}` };
216
+ }
217
+ const after = targetState(target, env);
218
+ // The running server publishes the new bundle itself: the Web composition's
219
+ // client-hmr transport stat-polls every client bundle and pushes a rebuild to
220
+ // the page, which reloads that plugin in place. No server restart is involved.
221
+ return after.state === 'patched'
222
+ ? { ok: true, id: target.id, state: 'patched', detail: 'the page loads the replacement within a second' }
223
+ : { ok: false, id: target.id, state: after.state, detail: 'the replaced bundle did not match its recorded hash' };
224
+ }
225
+ /**
226
+ * Restore one target's published browser bundle from this plugin's backup.
227
+ * @param target - the catalog entry.
228
+ * @param env - the file-system facts to act through.
229
+ * @returns the outcome and the resulting state.
230
+ */
231
+ export function uninstallCardPatch(target, env = realCardPatchEnvironment) {
232
+ const before = targetState(target, env);
233
+ if (before.state === 'pristine')
234
+ return { ok: true, id: target.id, state: 'pristine' };
235
+ if (before.state !== 'patched') {
236
+ return { ok: false, id: target.id, state: before.state, ...before.detail === undefined ? {} : { detail: before.detail } };
237
+ }
238
+ const directory = env.resolvePackage(target.packageName);
239
+ if (directory === undefined)
240
+ return { ok: false, id: target.id, state: 'absent', detail: 'the package disappeared' };
241
+ const backup = join(env.backupDirectory(), `${target.id}-${target.version}.client.js`);
242
+ if (!existsSync(backup)) {
243
+ return {
244
+ ok: false,
245
+ id: target.id,
246
+ state: 'patched',
247
+ detail: 'this plugin holds no backup of the published bundle; reinstall the target package to restore it',
248
+ };
249
+ }
250
+ if (sha256Of(backup) !== target.pristineSha256) {
251
+ return { ok: false, id: target.id, state: 'patched', detail: 'the stored backup does not match the published bundle' };
252
+ }
253
+ const bundle = bundlePath(directory);
254
+ try {
255
+ const staged = `${bundle}.card-unpatch.tmp`;
256
+ copyFileSync(backup, staged);
257
+ renameSync(staged, bundle);
258
+ rmSync(backup, { force: true });
259
+ }
260
+ catch (error) {
261
+ return { ok: false, id: target.id, state: 'patched', detail: `the published bundle could not be restored: ${String(error)}` };
262
+ }
263
+ const after = targetState(target, env);
264
+ return after.state === 'pristine'
265
+ ? { ok: true, id: target.id, state: 'pristine', detail: 'the page drops the replacement within a second' }
266
+ : { ok: false, id: target.id, state: after.state, detail: 'the restored bundle did not match its recorded hash' };
267
+ }
268
+ /**
269
+ * Resolve one catalog entry by target id.
270
+ * @param id - the settings page's row identity.
271
+ * @returns the entry, or undefined for an id this build does not ship.
272
+ */
273
+ export function findCardPatchTarget(id) {
274
+ return CARD_PATCH_TARGETS.find(target => target.id === id);
275
+ }