@oh-my-dsh/auto-team 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Plugin Authors
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,133 @@
1
- # Temporary Holding Version
1
+ # DSH Auto Team
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [中文](README.zh.md)
4
+
5
+ `@oh-my-dsh/auto-team` is a host-only DeepSeek Harness plugin (Cordis id `auto-team`). It gives long tasks a scored start and a team-shaped run, and it keeps the numeric score out of the model's context.
6
+
7
+ The plugin adds the first-round decision, the goal bridge, and the Lead and worker policy gates. The teammate, task-board, and worktree tools come from the host profile. It targets DSH 0.2.1-rc.2.
8
+
9
+ ## How a task runs
10
+
11
+ The Lead calls `auto_team_score` once in the first round. The call takes five factors from 1 to 5, covering scope, parallelism, ambiguity, risk, and expected_steps, plus the task goal in its ordinary meaning.
12
+
13
+ The plugin turns the factors into a weighted score from 0 to 1. The model gets only `team` or `solo`; the score and the effective threshold stay host-side. The default threshold is 0.55. If a user-created goal already exists at the first score, the threshold is multiplied by 0.6.
14
+
15
+ The first round must be scored. If the turn tries to close before the tool ran, an `agent/turn-stopping` listener steers the Lead back with a reminder.
16
+
17
+ The score is frozen for the task. Only a user-triggered `/auto-team-reset` clears it; the next score becomes the new frozen decision. It is written to the session log as a `plugin:auto-team/score` record and folded into the host-only `autoTeam` projection, so resuming a session keeps the decision and does not score again.
18
+
19
+ On a team decision the plugin:
20
+
21
+ - reuses the current goal, or starts one when none exists;
22
+ - ensures a user-facing reporting teammate named `reporter`, which is configurable; the Lead relays its updates to the user;
23
+ - tells the Lead to keep the main Git repository and the team, and not to write code;
24
+ - denies the Lead's `write` and `edit` calls by default;
25
+ - requires each execution teammate to complete `create_worktree` before its own `write` or `edit` is allowed, and checks that an edit path stays inside the registered worktree when the host returns one. The reporter is exempt.
26
+
27
+ Multi-round execution belongs to the goal runtime. The plugin starts or reuses the goal and does not run its own continuation loop.
28
+
29
+ On a solo decision the task runs as a normal single-agent task.
30
+
31
+ ## Requirements
32
+
33
+ The profile must compose these host services:
34
+
35
+ - `agents`, `tools`, `systemPrompt`, `sessionProjections`
36
+ - `agentTeams` from `@deepseek-ai/dsh-experimental-agent-team`
37
+ - `goals` from `@deepseek-ai/dsh-goal`
38
+ - `commands` (optional; enables `/auto-team-reset`)
39
+
40
+ The plugin loads without the required services but logs a warning and installs nothing. When a service arrives later, an `internal/service` listener retries the install. The `commands` service is optional: without it the score tool still works and `/auto-team-reset` is not registered.
41
+
42
+ ## Install
43
+
44
+ Build and pack the package:
45
+
46
+ ```sh
47
+ pnpm install
48
+ pnpm run lint
49
+ pnpm test
50
+ pnpm run build
51
+ pnpm pack
52
+ ```
53
+
54
+ Install from npm once the package is published:
55
+
56
+ ```sh
57
+ dsh plugin --profile <profile> add @oh-my-dsh/auto-team
58
+ ```
59
+
60
+ Or install a locally packed tarball:
61
+
62
+ ```sh
63
+ dsh plugin --profile <profile> add ./oh-my-dsh-auto-team-0.1.1.tgz
64
+ ```
65
+
66
+ The package name is `@oh-my-dsh/auto-team`, published under the `@oh-my-dsh` scope.
67
+
68
+ ## Configuration
69
+
70
+ Every field is optional. Schemastery checks the values at load; invalid values fail activation.
71
+
72
+ | Field | Default | Meaning |
73
+ | --- | --- | --- |
74
+ | `message` | `auto-team loaded` | Activation log line. |
75
+ | `threshold` | `0.55` | Base score needed for Team mode. |
76
+ | `manualGoalFactor` | `0.6` | Multiplier applied to the threshold when a user-created goal exists. |
77
+ | `weights` | scope 0.3, parallelism 0.25, ambiguity 0.15, risk 0.15, expectedSteps 0.15 | Relative weight of each difficulty factor. |
78
+ | `reportingAgentName` | `reporter` | Name of the reporting teammate. |
79
+ | `reportingProvider` | `spawn` | Subagent provider used for the reporter. |
80
+ | `goalMaxRounds` | `256` | Round cap used when the plugin starts a goal. |
81
+ | `enforceLeadNoCode` | `true` | Install the Lead write/edit gate. |
82
+ | `leadDeniedTools` | `['write', 'edit']` | Tool names denied to a Team-mode Lead. |
83
+
84
+ ## Tool
85
+
86
+ The package adds one model-facing tool.
87
+
88
+ `auto_team_score` takes:
89
+
90
+ | Parameter | Type | Meaning |
91
+ | --- | --- | --- |
92
+ | `scope` | integer 1 to 5 | Expected change scope. |
93
+ | `parallelism` | integer 1 to 5 | How much independent work can run at once. |
94
+ | `ambiguity` | integer 1 to 5 | How much requirement or design uncertainty remains. |
95
+ | `risk` | integer 1 to 5 | How costly a wrong change would be. |
96
+ | `expected_steps` | integer 1 to 5 | Expected task length. |
97
+ | `objective` | string | The task goal in its ordinary meaning. Used only when the plugin starts a goal. |
98
+
99
+ It returns `{ decision, goal, reporter? }`. The numeric score and threshold are not in the result. The host's Agent Teams tools handle spawning, messaging, and the shared task board. The host goal lifecycle handles completion and continuation.
100
+
101
+ ## Commands
102
+
103
+ When the profile provides the host `commands` service, the plugin registers `auto-team-reset`:
104
+
105
+ - `/auto-team-reset` clears the frozen score for the current session.
106
+ - It appends a `plugin:auto-team/reset` record, so resuming the session does not restore the cleared score.
107
+ - It steers the Lead to call `auto_team_score` again. The current goal and reporter stay in place.
108
+ - The command is user-triggered; the model cannot invoke it.
109
+
110
+ ## Guards and limits
111
+
112
+ - The Lead gate is a tool-name policy, not a sandbox. `pwsh`, `run_code`, and direct filesystem effects can bypass it. The policy tells the Lead not to use them as a workaround.
113
+ - The worker gate checks that a `create_worktree` call succeeded and, when the host returns the worktree path, that each `write` or `edit` uses an absolute `file_path` inside it. If the host result has no path, the gate falls back to checking only that the call succeeded.
114
+ - The reporter is spawned with the configured provider. If the spawn fails, the score stays frozen and a later call retries the reporter.
115
+ - A real DSH profile composition test has not been run in this repository. `tests/runtime.test.ts` mounts a real Cordis context and a real detached Session with fake host services, and covers the install path, the scoring tool, the stop guard, the Lead gate, and the worker gate.
116
+
117
+ ## Development
118
+
119
+ ```sh
120
+ pnpm install
121
+ pnpm run lint
122
+ pnpm test
123
+ pnpm run build
124
+ pnpm pack --dry-run --json
125
+ ```
126
+
127
+ The tests cover the scoring policy, configuration, goal and reporter orchestration, the durable score projection and reset, the reset command, the runtime install path, and the Loader export shape.
128
+
129
+ Read [the design note](docs/auto-team-design.md) for the behavior and the flow chart, and [the plugin contracts](docs/dsh-plugin-contracts.md) for the package rules.
130
+
131
+ ## Status
132
+
133
+ The core flow works and is covered by the repository tests. The release checks pass. Install the package in a profile that composes the required services, then run a long task to verify the behavior in your environment.
package/README.zh.md ADDED
@@ -0,0 +1,133 @@
1
+ # DSH Auto Team
2
+
3
+ [English](README.md) | 中文
4
+
5
+ `@oh-my-dsh/auto-team` 是一个只跑在宿主侧的 DeepSeek Harness 插件,Cordis id 为 `auto-team`。它给长任务一个带评分的起点和团队式的执行方式,同时把具体分数留在模型上下文之外。
6
+
7
+ 插件负责首轮判断、goal 桥接,以及 Lead 和执行 Agent 的策略闸门。队友、任务板和 worktree 工具由宿主 profile 提供。目标版本是 DSH 0.2.1-rc.2。
8
+
9
+ ## 任务怎么跑
10
+
11
+ 首轮由 Lead 调用一次 `auto_team_score`。参数是五个 1 到 5 的难度因子:scope、parallelism、ambiguity、risk、expected_steps,再加一句任务在通常语义上的目标。
12
+
13
+ 插件把因子折算成 0 到 1 的加权分数。模型只拿到 `team` 或 `solo`,分数和实际阈值都留在宿主侧。默认阈值是 0.55。如果第一次打分时已经存在用户触发的 goal,阈值乘以 0.6。
14
+
15
+ 首轮必须打分。如果这一轮想在没有调用工具时结束,`agent/turn-stopping` 监听器会把 Lead 拉回来,再发一次提醒。
16
+
17
+ 分数在任务内冻结。只有用户主动执行 `/auto-team-reset` 才能清空;下一次打分成为新的冻结决定。它以 `plugin:auto-team/score` 记录写进 session log,并折进宿主侧的 `autoTeam` 投影。resume 时恢复这个决定,不会重新打分。
18
+
19
+ 决定使用团队后,插件会:
20
+
21
+ - 复用当前 goal;没有 goal 就启动一个;
22
+ - 确保存在名为 `reporter` 的汇报 Agent,名字可配置;它面向用户写更新,Lead 负责转达;
23
+ - 提示 Lead 维护主 Git 仓库和团队,不写代码;
24
+ - 默认拒绝 Lead 的 `write` 和 `edit`;
25
+ - 要求每个执行 Agent 先成功调用 `create_worktree`,之后才允许自己的 `write` 或 `edit`;宿主返回 worktree 路径时,还会检查编辑路径是否在该 worktree 内。汇报 Agent 不受这条限制。
26
+
27
+ 多轮执行交给 goal 运行时。插件只负责启动或复用 goal,不自己维护续跑循环。
28
+
29
+ 决定不使用团队时,任务按普通单 Agent 流程执行。
30
+
31
+ ## 依赖
32
+
33
+ profile 需要组合这些宿主服务:
34
+
35
+ - `agents`、`tools`、`systemPrompt`、`sessionProjections`
36
+ - `agentTeams`,来自 `@deepseek-ai/dsh-experimental-agent-team`
37
+ - `goals`,来自 `@deepseek-ai/dsh-goal`
38
+ - `commands`(可选;启用 `/auto-team-reset`)
39
+
40
+ 必需服务缺失时插件仍会加载,但只打一条警告,不安装任何东西。之后某个服务到位,`internal/service` 监听器会重试安装。`commands` 服务是可选的:没有它,打分工具照常工作,但不会注册 `/auto-team-reset`。
41
+
42
+ ## 安装
43
+
44
+ 构建并打包:
45
+
46
+ ```sh
47
+ pnpm install
48
+ pnpm run lint
49
+ pnpm test
50
+ pnpm run build
51
+ pnpm pack
52
+ ```
53
+
54
+ 从 npm 安装已发布的包:
55
+
56
+ ```sh
57
+ dsh plugin --profile <profile> add @oh-my-dsh/auto-team
58
+ ```
59
+
60
+ 或者安装本地打包的 tarball:
61
+
62
+ ```sh
63
+ dsh plugin --profile <profile> add ./oh-my-dsh-auto-team-0.1.1.tgz
64
+ ```
65
+
66
+ 包名是 `@oh-my-dsh/auto-team`,发布在 `@oh-my-dsh` scope 下。
67
+
68
+ ## 配置
69
+
70
+ 所有字段都可选。Schemastery 在加载时校验,非法值会让激活失败。
71
+
72
+ | 字段 | 默认值 | 含义 |
73
+ | --- | --- | --- |
74
+ | `message` | `auto-team loaded` | 激活时的日志。 |
75
+ | `threshold` | `0.55` | 进入团队模式的基础分数。 |
76
+ | `manualGoalFactor` | `0.6` | 已有用户触发 goal 时,阈值的乘数。 |
77
+ | `weights` | scope 0.3、parallelism 0.25、ambiguity 0.15、risk 0.15、expectedSteps 0.15 | 各难度因子的相对权重。 |
78
+ | `reportingAgentName` | `reporter` | 汇报 Agent 的名字。 |
79
+ | `reportingProvider` | `spawn` | 创建汇报 Agent 时用的子 Agent provider。 |
80
+ | `goalMaxRounds` | `256` | 插件启动 goal 时使用的轮次上限。 |
81
+ | `enforceLeadNoCode` | `true` | 是否安装 Lead 的写文件闸门。 |
82
+ | `leadDeniedTools` | `['write', 'edit']` | 团队模式下拒绝给 Lead 的工具名。 |
83
+
84
+ ## 工具
85
+
86
+ 这个包只增加一个模型可见工具。
87
+
88
+ `auto_team_score` 的参数:
89
+
90
+ | 参数 | 类型 | 含义 |
91
+ | --- | --- | --- |
92
+ | `scope` | 1 到 5 的整数 | 预计改动范围。 |
93
+ | `parallelism` | 1 到 5 的整数 | 有多少独立工作可以同时做。 |
94
+ | `ambiguity` | 1 到 5 的整数 | 还剩多少需求或设计不确定。 |
95
+ | `risk` | 1 到 5 的整数 | 改错了代价多大。 |
96
+ | `expected_steps` | 1 到 5 的整数 | 预计任务有多长。 |
97
+ | `objective` | 字符串 | 任务在通常语义上的目标。只在插件启动 goal 时使用。 |
98
+
99
+ 返回 `{ decision, goal, reporter? }`。分数和阈值不在返回里。创建队友、发消息和共享任务板由宿主的 Agent Teams 工具负责;完成和续跑由宿主的 goal 生命周期负责。
100
+
101
+ ## 命令
102
+
103
+ profile 提供宿主 `commands` 服务时,插件注册 `auto-team-reset`:
104
+
105
+ - `/auto-team-reset` 清空当前 session 的冻结分数。
106
+ - 它写入 `plugin:auto-team/reset` 记录,resume 时不会恢复被清掉的分数。
107
+ - 它提示 Lead 重新调用 `auto_team_score`;当前 goal 和汇报 Agent 保留。
108
+ - 命令由用户触发,模型不能调用。
109
+
110
+ ## 闸门与限制
111
+
112
+ - Lead 的闸门是工具名策略,不是沙箱。`pwsh`、`run_code` 和直接的文件系统操作可以绕过。策略文本会明确要求 Lead 不要拿它们绕路。
113
+ - 执行 Agent 的闸门会检查 `create_worktree` 是否成功;宿主返回 worktree 路径时,还会要求每次 `write`/`edit` 的 `file_path` 是该路径内的绝对路径。宿主结果没有路径时,只检查成功。
114
+ - 汇报 Agent 用配置的 provider 创建。如果创建失败,分数仍保持冻结,后续调用会重试创建。
115
+ - 仓库里还没有跑过真实 DSH profile 的组合测试。`tests/runtime.test.ts` 用真实 Cordis Context、真实 detached Session 和假的宿主服务,覆盖安装路径、打分工具、首轮停止闸门、Lead 闸门和执行 Agent 闸门。
116
+
117
+ ## 开发
118
+
119
+ ```sh
120
+ pnpm install
121
+ pnpm run lint
122
+ pnpm test
123
+ pnpm run build
124
+ pnpm pack --dry-run --json
125
+ ```
126
+
127
+ 测试覆盖评分策略、配置、goal 与汇报 Agent 编排、持久化分数投影与重设、重设命令、运行时安装路径,以及 Loader 导出形状。
128
+
129
+ 行为说明和流程图见[设计文档](docs/auto-team-design.md),包规则见[插件契约](docs/dsh-plugin-contracts.md)。
130
+
131
+ ## 状态
132
+
133
+ 核心流程已经可用,并有仓库测试覆盖。发布检查已通过。把包装进已经组合好所需服务的 profile,跑一个长任务确认实际行为。
@@ -0,0 +1,10 @@
1
+ # Bundle patch applied over the selected DSH profile when this package is listed
2
+ # in `dsh.profile.bundles`. The row id is deployment-local; the package name
3
+ # must match package.json. Display metadata and the icon come from the exported
4
+ # `locale/*.json` files and `./icon` resource, not from this patch.
5
+
6
+ - insert:
7
+ - id: auto-team
8
+ name: '@oh-my-dsh/auto-team'
9
+ config:
10
+ message: auto-team loaded
package/lib/index.d.ts ADDED
@@ -0,0 +1,85 @@
1
+ import schema from "@deepseek-ai/schemastery";
2
+ import { Context } from "@deepseek-ai/cordis";
3
+ //#region src/policy.d.ts
4
+ /** Relative weight of each difficulty factor. */
5
+ interface ScoreWeights {
6
+ readonly scope: number;
7
+ readonly parallelism: number;
8
+ readonly ambiguity: number;
9
+ readonly risk: number;
10
+ readonly expectedSteps: number;
11
+ }
12
+ //#endregion
13
+ //#region src/config.d.ts
14
+ /** Plugin configuration supplied by the profile composition. */
15
+ interface PluginConfig {
16
+ /** Message written when this plugin loads. */
17
+ message?: string;
18
+ /** Base team-trigger threshold in the 0..1 range. */
19
+ threshold?: number;
20
+ /**
21
+ * Multiplier applied to the threshold when a user-triggered goal already
22
+ * exists.
23
+ */
24
+ manualGoalFactor?: number;
25
+ /** Relative weight of each difficulty factor. */
26
+ weights?: Partial<ScoreWeights>;
27
+ /** Name of the reporting teammate created for a team task. */
28
+ reportingAgentName?: string;
29
+ /** Continuable-subagent provider used for the reporting teammate. */
30
+ reportingProvider?: string;
31
+ /** Positive round cap used when auto-team creates a goal. */
32
+ goalMaxRounds?: number;
33
+ /** Block Lead writes after the team decision. Defaults to true. */
34
+ enforceLeadNoCode?: boolean;
35
+ /** Tool names denied to a Team-mode Lead. Defaults to write and edit. */
36
+ leadDeniedTools?: string[];
37
+ }
38
+ /** Loader-visible configuration schema and defaults. */
39
+ declare const Config: schema<PluginConfig>;
40
+ /** Configuration after defaults have been resolved. */
41
+ interface ResolvedConfig {
42
+ /** Message written when this plugin loads. */
43
+ message: string;
44
+ /** Base team-trigger threshold in the 0..1 range. */
45
+ threshold: number;
46
+ /**
47
+ * Multiplier applied to the threshold when a user-triggered goal already
48
+ * exists.
49
+ */
50
+ manualGoalFactor: number;
51
+ /** Relative weight of each difficulty factor. */
52
+ weights: ScoreWeights;
53
+ /** Name of the reporting teammate created for a team task. */
54
+ reportingAgentName: string;
55
+ /** Continuable-subagent provider used for the reporting teammate. */
56
+ reportingProvider: string;
57
+ /** Positive round cap used when auto-team creates a goal. */
58
+ goalMaxRounds: number;
59
+ /** Block Lead writes after the team decision. */
60
+ enforceLeadNoCode: boolean;
61
+ /** Tool names denied to a Team-mode Lead. */
62
+ leadDeniedTools: string[];
63
+ }
64
+ //#endregion
65
+ //#region src/runtime.d.ts
66
+ /** Fakeable host boundary used by the baseline load message. */
67
+ interface PluginRuntime {
68
+ info: (message: string) => void;
69
+ warn: (message: string) => void;
70
+ }
71
+ /** Apply auto-team to the host; unmanaged scopes stay untouched. */
72
+ declare function apply(ctx: Context, config: PluginConfig): void;
73
+ //#endregion
74
+ //#region src/index.d.ts
75
+ /**
76
+ * Standalone function plugin for DeepSeek Harness.
77
+ *
78
+ * @module @oh-my-dsh/auto-team
79
+ */
80
+ /** Cordis plugin name; keep this stable after publishing. */
81
+ declare const name = "auto-team";
82
+ /** Services that must exist before the plugin is applied. */
83
+ declare const inject: string[];
84
+ //#endregion
85
+ export { Config, type PluginConfig, type PluginRuntime, type ResolvedConfig, apply, inject, name };
package/lib/index.js ADDED
@@ -0,0 +1,780 @@
1
+ import schema from "@deepseek-ai/schemastery";
2
+ import { createMessage } from "@deepseek-ai/dsh-llm";
3
+ import { appendPluginRecord, pluginRecordOf } from "@deepseek-ai/dsh-session";
4
+ import { z } from "zod";
5
+ import { defineTool } from "@deepseek-ai/dsh-tools";
6
+ import path from "node:path";
7
+ //#region src/policy.ts
8
+ const MIN_FACTOR = 1;
9
+ const MAX_FACTOR = 5;
10
+ const FACTOR_RANGE = 4;
11
+ /** Clamp one finite factor to 1..5 and normalize it to 0..1. */
12
+ function normalizeFactor(name, value) {
13
+ if (!Number.isFinite(value)) throw new TypeError(`difficulty factor "${name}" must be a finite number`);
14
+ return (Math.min(MAX_FACTOR, Math.max(MIN_FACTOR, value)) - MIN_FACTOR) / FACTOR_RANGE;
15
+ }
16
+ /** Reject negative or non-finite weights and an all-zero set. */
17
+ function validateWeights(weights) {
18
+ let total = 0;
19
+ for (const value of Object.values(weights)) {
20
+ if (!Number.isFinite(value) || value < 0) throw new TypeError("score weights must be finite and non-negative");
21
+ total += value;
22
+ }
23
+ if (total <= 0) throw new TypeError("score weights must have a positive total");
24
+ }
25
+ /** Weighted 0..1 difficulty score. */
26
+ function scoreAssessment(assessment, weights) {
27
+ validateWeights(weights);
28
+ const total = weights.scope + weights.parallelism + weights.ambiguity + weights.risk + weights.expectedSteps;
29
+ return (normalizeFactor("scope", assessment.scope) * weights.scope + normalizeFactor("parallelism", assessment.parallelism) * weights.parallelism + normalizeFactor("ambiguity", assessment.ambiguity) * weights.ambiguity + normalizeFactor("risk", assessment.risk) * weights.risk + normalizeFactor("expectedSteps", assessment.expectedSteps) * weights.expectedSteps) / total;
30
+ }
31
+ /**
32
+ * Effective trigger threshold; a user-triggered goal lowers it by the
33
+ * configured factor.
34
+ */
35
+ function effectiveThreshold(baseThreshold, manualGoal, manualGoalFactor) {
36
+ if (!Number.isFinite(baseThreshold) || baseThreshold < 0 || baseThreshold > 1) throw new TypeError("threshold must be between 0 and 1");
37
+ if (!Number.isFinite(manualGoalFactor) || manualGoalFactor < 0 || manualGoalFactor > 1) throw new TypeError("manualGoalFactor must be between 0 and 1");
38
+ let threshold = baseThreshold;
39
+ if (manualGoal) threshold = baseThreshold * manualGoalFactor;
40
+ return Math.min(1, Math.max(0, threshold));
41
+ }
42
+ /** Compare a score with the effective threshold. */
43
+ function decideTeam(score, threshold) {
44
+ if (score >= threshold) return "team";
45
+ return "solo";
46
+ }
47
+ /** Score one assessment and freeze the decision. */
48
+ function createScoreDecision(assessment, options) {
49
+ const threshold = effectiveThreshold(options.threshold, options.manualGoal, options.manualGoalFactor);
50
+ const score = scoreAssessment(assessment, options.weights);
51
+ return {
52
+ score,
53
+ threshold,
54
+ manualGoal: options.manualGoal,
55
+ decision: decideTeam(score, threshold)
56
+ };
57
+ }
58
+ //#endregion
59
+ //#region src/config.ts
60
+ /**
61
+ * Serializable configuration, schema, and direct-call defaults for auto-team.
62
+ *
63
+ * @module @oh-my-dsh/auto-team/config
64
+ */
65
+ const DEFAULT_WEIGHTS = {
66
+ scope: .3,
67
+ parallelism: .25,
68
+ ambiguity: .15,
69
+ risk: .15,
70
+ expectedSteps: .15
71
+ };
72
+ const DEFAULT_THRESHOLD = .55;
73
+ const DEFAULT_MANUAL_GOAL_FACTOR = .6;
74
+ const DEFAULT_REPORTING_AGENT_NAME = "reporter";
75
+ const DEFAULT_REPORTING_PROVIDER = "spawn";
76
+ const DEFAULT_GOAL_MAX_ROUNDS = 256;
77
+ const DEFAULT_ENFORCE_LEAD_NO_CODE = true;
78
+ const DEFAULT_LEAD_DENIED_TOOLS = ["write", "edit"];
79
+ const REPORTER_NAME_PATTERN = /^[a-z][a-z0-9-]*$/u;
80
+ const UNIT_RANGE = {
81
+ min: 0,
82
+ max: 1
83
+ };
84
+ /** Loader-visible configuration schema and defaults. */
85
+ const Config = schema.object({
86
+ message: schema.string().default("auto-team loaded"),
87
+ threshold: schema.number().min(0).max(1).default(DEFAULT_THRESHOLD),
88
+ manualGoalFactor: schema.number().min(0).max(1).default(DEFAULT_MANUAL_GOAL_FACTOR),
89
+ weights: schema.object({
90
+ scope: schema.number().min(0).max(1).default(DEFAULT_WEIGHTS.scope),
91
+ parallelism: schema.number().min(0).max(1).default(DEFAULT_WEIGHTS.parallelism),
92
+ ambiguity: schema.number().min(0).max(1).default(DEFAULT_WEIGHTS.ambiguity),
93
+ risk: schema.number().min(0).max(1).default(DEFAULT_WEIGHTS.risk),
94
+ expectedSteps: schema.number().min(0).max(1).default(DEFAULT_WEIGHTS.expectedSteps)
95
+ }),
96
+ reportingAgentName: schema.string().pattern(REPORTER_NAME_PATTERN).default(DEFAULT_REPORTING_AGENT_NAME),
97
+ reportingProvider: schema.string().default(DEFAULT_REPORTING_PROVIDER),
98
+ goalMaxRounds: schema.natural().min(1).default(DEFAULT_GOAL_MAX_ROUNDS),
99
+ enforceLeadNoCode: schema.boolean().default(DEFAULT_ENFORCE_LEAD_NO_CODE),
100
+ leadDeniedTools: schema.array(schema.string()).default([...DEFAULT_LEAD_DENIED_TOOLS])
101
+ });
102
+ /** Validate one finite number against an inclusive range. */
103
+ function numberInRange(name, value, range) {
104
+ if (!Number.isFinite(value) || value < range.min || value > range.max) throw new TypeError(`${name} must be between ${range.min} and ${range.max}`);
105
+ return value;
106
+ }
107
+ /** Merge partial factor weights over the defaults and validate the total. */
108
+ function resolveWeights(config) {
109
+ const weights = {
110
+ scope: config.weights?.scope ?? DEFAULT_WEIGHTS.scope,
111
+ parallelism: config.weights?.parallelism ?? DEFAULT_WEIGHTS.parallelism,
112
+ ambiguity: config.weights?.ambiguity ?? DEFAULT_WEIGHTS.ambiguity,
113
+ risk: config.weights?.risk ?? DEFAULT_WEIGHTS.risk,
114
+ expectedSteps: config.weights?.expectedSteps ?? DEFAULT_WEIGHTS.expectedSteps
115
+ };
116
+ validateWeights(weights);
117
+ return weights;
118
+ }
119
+ /** Resolve and validate the reporting teammate name. */
120
+ function resolveReportingAgentName(config) {
121
+ const name = config.reportingAgentName ?? DEFAULT_REPORTING_AGENT_NAME;
122
+ if (!REPORTER_NAME_PATTERN.test(name) || name === "lead") throw new TypeError("reportingAgentName must be lower-kebab-case and must not be \"lead\"");
123
+ return name;
124
+ }
125
+ /** Resolve and validate the goal round cap. */
126
+ function resolveGoalMaxRounds(config) {
127
+ const rounds = config.goalMaxRounds ?? DEFAULT_GOAL_MAX_ROUNDS;
128
+ if (!Number.isSafeInteger(rounds) || rounds < 1) throw new TypeError("goalMaxRounds must be a positive safe integer");
129
+ return rounds;
130
+ }
131
+ /** Resolve and validate the two score thresholds. */
132
+ function resolveThresholds(config) {
133
+ return {
134
+ threshold: numberInRange("threshold", config.threshold ?? DEFAULT_THRESHOLD, UNIT_RANGE),
135
+ manualGoalFactor: numberInRange("manualGoalFactor", config.manualGoalFactor ?? DEFAULT_MANUAL_GOAL_FACTOR, UNIT_RANGE)
136
+ };
137
+ }
138
+ /** Resolve the same defaults for direct callers that bypass Cordis Loader. */
139
+ function resolveConfig(config = {}) {
140
+ return {
141
+ message: config.message ?? "auto-team loaded",
142
+ ...resolveThresholds(config),
143
+ weights: resolveWeights(config),
144
+ reportingAgentName: resolveReportingAgentName(config),
145
+ reportingProvider: config.reportingProvider ?? DEFAULT_REPORTING_PROVIDER,
146
+ goalMaxRounds: resolveGoalMaxRounds(config),
147
+ enforceLeadNoCode: config.enforceLeadNoCode ?? DEFAULT_ENFORCE_LEAD_NO_CODE,
148
+ leadDeniedTools: [...config.leadDeniedTools ?? DEFAULT_LEAD_DENIED_TOOLS]
149
+ };
150
+ }
151
+ //#endregion
152
+ //#region src/projection.ts
153
+ const SCORE_RECORD_TYPE = "plugin:auto-team/score";
154
+ const RESET_RECORD_TYPE = "plugin:auto-team/reset";
155
+ const scoreRecordSchema = z.object({
156
+ score: z.number().min(0).max(1),
157
+ threshold: z.number().min(0).max(1),
158
+ manualGoal: z.boolean(),
159
+ decision: z.enum(["team", "solo"]),
160
+ goal: z.enum([
161
+ "started",
162
+ "reused",
163
+ "none"
164
+ ])
165
+ });
166
+ const autoTeamProjectionStateSchema = z.object({
167
+ score: scoreRecordSchema.optional(),
168
+ failure: z.string().optional()
169
+ });
170
+ /** Fold the first score after the latest reset into one durable decision. */
171
+ function applyAutoTeamProjection(state, event) {
172
+ const record = pluginRecordOf(event);
173
+ if (record === void 0) return state;
174
+ if (record.type === RESET_RECORD_TYPE) {
175
+ if (state.score === void 0) return state;
176
+ return {
177
+ ...state,
178
+ score: void 0
179
+ };
180
+ }
181
+ if (record.type !== SCORE_RECORD_TYPE) return state;
182
+ if (state.score !== void 0) return state;
183
+ const parsed = scoreRecordSchema.safeParse(record.data);
184
+ if (!parsed.success) return {
185
+ ...state,
186
+ failure: parsed.error.message
187
+ };
188
+ return {
189
+ ...state,
190
+ score: parsed.data
191
+ };
192
+ }
193
+ /** Host-only projection definition for the auto-team score. */
194
+ const autoTeamProjectionDefinition = {
195
+ key: "autoTeam",
196
+ stateSchema: autoTeamProjectionStateSchema,
197
+ init: () => ({}),
198
+ apply: applyAutoTeamProjection,
199
+ stateVersion: 1
200
+ };
201
+ //#endregion
202
+ //#region src/prompt.ts
203
+ /**
204
+ * Model-facing policy and teammate prompts for auto-team.
205
+ *
206
+ * @module @oh-my-dsh/auto-team/prompt
207
+ */
208
+ /** First-round steering text used when the scoring tool has not run yet. */
209
+ const FIRST_ROUND_STEER_TEXT = `Auto Team: the first round has no score yet. Call auto_team_score now with the five difficulty factors and the task's universal-semantic objective; the turn stays open until the decision is recorded.`;
210
+ /** Steering text used after the user resets the frozen score. */
211
+ const RESET_STEER_TEXT = `Auto Team: the user reset the score. Call auto_team_score again with the current task's difficulty factors and objective before continuing.`;
212
+ /** System prompt section that states the Lead's auto-team obligations. */
213
+ function policyText(reportingAgentName, leadDeniedTools) {
214
+ return `Auto Team policy
215
+
216
+ You are the Team Lead for a long task. Call auto_team_score before anything else in the first round. The call takes:
217
+ - scope, parallelism, ambiguity, risk, expected_steps: integers from 1 (low) to 5 (high)
218
+ - objective: the task goal in its ordinary, universal meaning
219
+
220
+ The first turn stays open until the tool records a decision. The result carries the team or solo decision and the goal and reporter status. The numeric score and threshold stay host-side; treat them as unavailable and act on the returned decision.
221
+
222
+ If the decision is solo, continue as a normal single agent.
223
+
224
+ If the decision is team:
225
+ - Your role is the Main Git repository and the team. Code changes belong to execution agents. The Lead's ${leadDeniedTools.join(", ")} calls are denied in Team mode. Treat that gate as a policy check: use pwsh, run_code, and other tools for review, tests, and inspection only.
226
+ - The plugin starts or reuses the goal and ensures a reporting agent named "${reportingAgentName}".
227
+ - The reporter writes for the user. Relay each update to the user as a user-facing message, and keep execution moving while details are resolved.
228
+ - Create shared tasks with disjoint write scopes, then spawn execution agents. Each execution agent creates its own worktree for its task before editing; the Lead works in the main checkout.
229
+ - Let the goal runtime drive multi-round continuation; follow its rounds.
230
+ - After the workers finish, review the final diff and run the tests in the main checkout.`;
231
+ }
232
+ /** Initial prompt for the dedicated reporting teammate. */
233
+ function reporterPrompt() {
234
+ return `You are the reporting agent for an auto-team task. Your reader is the user. The Lead relays each update to the user, so write every message as a user-facing status update in the user's language.
235
+
236
+ Cover what changed, what is blocked, and what the user needs to decide. Address the user directly.
237
+
238
+ Observe the roster and task board with list_agents and team_task_list. Hand each update to the Lead for relay with send_message({ target: "lead", message: "..." }). The Lead is the transport; the user is the reader.
239
+
240
+ Handle user-facing detail questions sent through the Lead. Record unresolved details, report the open question to the user, and keep execution moving. Your work is status, questions, and coordination; code changes belong to execution agents.`;
241
+ }
242
+ //#endregion
243
+ //#region src/reset-command.ts
244
+ /** Build the user-facing score reset command. */
245
+ function createResetCommand(autoTeam) {
246
+ return {
247
+ name: "auto-team-reset",
248
+ description: "Clear the frozen Auto Team score for this session and ask the Lead to score again.",
249
+ handler: (invocation) => {
250
+ if (autoTeam.decisionOf(invocation.agent) === void 0) return {
251
+ kind: "error",
252
+ text: "No frozen Auto Team score exists in this session."
253
+ };
254
+ autoTeam.reset(invocation.agent);
255
+ invocation.agent.steer(createMessage({
256
+ role: "user",
257
+ content: [{
258
+ type: "text",
259
+ text: RESET_STEER_TEXT
260
+ }],
261
+ source: { kind: "user" }
262
+ }));
263
+ return {
264
+ kind: "success",
265
+ text: "Auto Team score reset. The Lead will score again."
266
+ };
267
+ }
268
+ };
269
+ }
270
+ /** Structural guard for the optional host commands service. */
271
+ function isCommandRuntime(value) {
272
+ if (typeof value !== "object" || value === null || !("register" in value)) return false;
273
+ return typeof value.register === "function";
274
+ }
275
+ //#endregion
276
+ //#region src/auto-team.ts
277
+ /** Host-side auto-team state and operations. */
278
+ var AutoTeam = class {
279
+ records = /* @__PURE__ */ new WeakMap();
280
+ resets = /* @__PURE__ */ new Set();
281
+ deps;
282
+ config;
283
+ constructor(deps, config) {
284
+ this.deps = deps;
285
+ this.config = config;
286
+ }
287
+ /** Whether this agent already has a frozen score. */
288
+ hasScore(agent) {
289
+ return !this.resets.has(agent) && this.records.has(agent);
290
+ }
291
+ /** Seed a record restored from durable storage without scoring again. */
292
+ restore(agent, record) {
293
+ if (!this.resets.has(agent) && !this.records.has(agent)) this.records.set(agent, record);
294
+ }
295
+ /** The frozen team decision, when this agent has one. */
296
+ decisionOf(agent) {
297
+ if (this.resets.has(agent)) return;
298
+ return (this.records.get(agent) ?? this.deps.store.read(agent))?.decision;
299
+ }
300
+ /** Clear the frozen score after a user-triggered reset. */
301
+ reset(agent) {
302
+ this.deps.store.reset(agent);
303
+ this.records.delete(agent);
304
+ this.resets.add(agent);
305
+ }
306
+ /**
307
+ * Score one task, freeze the decision, then start or reuse its goal and
308
+ * ensure the reporting teammate.
309
+ */
310
+ async score(agent, request) {
311
+ let existing = this.records.get(agent) ?? this.deps.store.read(agent);
312
+ if (this.resets.has(agent)) existing = void 0;
313
+ if (existing !== void 0) {
314
+ this.records.set(agent, existing);
315
+ return await this.finish(agent, existing, request.signal);
316
+ }
317
+ const existingGoal = this.deps.goals.get(agent);
318
+ const manualGoal = existingGoal !== void 0;
319
+ const decision = createScoreDecision(request.assessment, {
320
+ weights: this.config.weights,
321
+ threshold: this.config.threshold,
322
+ manualGoal,
323
+ manualGoalFactor: this.config.manualGoalFactor
324
+ });
325
+ let goal = "none";
326
+ if (decision.decision === "team" && existingGoal === void 0) goal = this.startGoal(agent, request.objective);
327
+ else if (existingGoal !== void 0) goal = "reused";
328
+ const record = {
329
+ score: decision.score,
330
+ threshold: decision.threshold,
331
+ manualGoal,
332
+ decision: decision.decision,
333
+ goal
334
+ };
335
+ this.deps.store.write(agent, record);
336
+ this.records.set(agent, record);
337
+ this.resets.delete(agent);
338
+ return await this.finish(agent, record, request.signal);
339
+ }
340
+ /** Create the auto-started goal and return the reported action. */
341
+ startGoal(agent, objective) {
342
+ const trimmed = objective.trim();
343
+ if (trimmed.length === 0) throw new TypeError("objective is required when auto-team starts a goal");
344
+ this.deps.goals.create(agent, {
345
+ objective: trimmed,
346
+ maxGoalRounds: this.config.goalMaxRounds
347
+ });
348
+ return "started";
349
+ }
350
+ /** Add the reporter result to a frozen record, provisioning it when needed. */
351
+ async finish(agent, record, signal) {
352
+ if (record.decision === "solo") return {
353
+ decision: "solo",
354
+ goal: record.goal
355
+ };
356
+ const reporter = await this.ensureReporter(agent, signal);
357
+ return {
358
+ decision: "team",
359
+ goal: record.goal,
360
+ reporter
361
+ };
362
+ }
363
+ /** Reuse an existing reporting teammate or spawn one. */
364
+ async ensureReporter(agent, signal) {
365
+ const name = this.config.reportingAgentName;
366
+ const existing = this.deps.team.listMembers(agent).find((member) => member.name === name);
367
+ if (existing !== void 0) return existing.name;
368
+ return (await this.deps.team.spawnReporter(agent, {
369
+ name,
370
+ description: "User-facing status reporter for the auto team",
371
+ prompt: reporterPrompt(),
372
+ provider: this.config.reportingProvider,
373
+ signal
374
+ })).name;
375
+ }
376
+ };
377
+ //#endregion
378
+ //#region src/services.ts
379
+ /** Read the goal service or fail with a plugin-specific message. */
380
+ function goalService(ctx) {
381
+ const service = ctx.get("goals");
382
+ if (service === void 0) throw new Error("auto-team: goals service is unavailable");
383
+ return service;
384
+ }
385
+ /** Read the Team service or fail with a plugin-specific message. */
386
+ function teamService(ctx) {
387
+ const service = ctx.get("agentTeams");
388
+ if (service === void 0) throw new Error("auto-team: agentTeams service is unavailable");
389
+ return service;
390
+ }
391
+ /** Build the goal, team, and durable score ports from Cordis services. */
392
+ function createAutoTeam(ctx, config) {
393
+ return new AutoTeam({
394
+ goals: {
395
+ get: (agent) => goalService(ctx).get(agent),
396
+ create: (agent, request) => goalService(ctx).create(agent, request)
397
+ },
398
+ team: {
399
+ listMembers: (agent) => teamService(ctx).listMembers(agent),
400
+ spawnReporter: async (agent, request) => {
401
+ return { name: (await teamService(ctx).spawnTeammate(agent, {
402
+ name: request.name,
403
+ description: request.description,
404
+ prompt: [{
405
+ type: "text",
406
+ text: request.prompt
407
+ }],
408
+ context: "fresh",
409
+ provider: request.provider,
410
+ signal: request.signal
411
+ })).member.name };
412
+ }
413
+ },
414
+ store: {
415
+ read: (agent) => ctx.get("sessionProjections")?.stateOf(agent.session, "autoTeam")?.score,
416
+ write: (agent, record) => {
417
+ appendPluginRecord(agent.session, "plugin:auto-team/score", record);
418
+ },
419
+ reset: (agent) => {
420
+ appendPluginRecord(agent.session, "plugin:auto-team/reset", { at: Date.now() });
421
+ }
422
+ }
423
+ }, config);
424
+ }
425
+ //#endregion
426
+ //#region src/tool.ts
427
+ /**
428
+ * Model-facing scoring tool. The numeric score and threshold are never part of
429
+ * the tool result.
430
+ *
431
+ * @module @oh-my-dsh/auto-team/tool
432
+ */
433
+ /** Build the one-shot scoring tool for a Lead agent scope. */
434
+ function createScoreTool(autoTeam) {
435
+ return defineTool({
436
+ name: "auto_team_score",
437
+ description: "Record the first-round difficulty assessment and return the team or solo decision. Call once before any other action; the decision is frozen for the task.",
438
+ parameters: {
439
+ scope: {
440
+ type: "integer",
441
+ required: true,
442
+ enum: [
443
+ 1,
444
+ 2,
445
+ 3,
446
+ 4,
447
+ 5
448
+ ],
449
+ description: "Expected change scope, from 1 low to 5 high."
450
+ },
451
+ parallelism: {
452
+ type: "integer",
453
+ required: true,
454
+ enum: [
455
+ 1,
456
+ 2,
457
+ 3,
458
+ 4,
459
+ 5
460
+ ],
461
+ description: "How much independent work can run in parallel, from 1 low to 5 high."
462
+ },
463
+ ambiguity: {
464
+ type: "integer",
465
+ required: true,
466
+ enum: [
467
+ 1,
468
+ 2,
469
+ 3,
470
+ 4,
471
+ 5
472
+ ],
473
+ description: "How much requirements or design uncertainty remains, from 1 low to 5 high."
474
+ },
475
+ risk: {
476
+ type: "integer",
477
+ required: true,
478
+ enum: [
479
+ 1,
480
+ 2,
481
+ 3,
482
+ 4,
483
+ 5
484
+ ],
485
+ description: "How costly a wrong change would be, from 1 low to 5 high."
486
+ },
487
+ expected_steps: {
488
+ type: "integer",
489
+ required: true,
490
+ enum: [
491
+ 1,
492
+ 2,
493
+ 3,
494
+ 4,
495
+ 5
496
+ ],
497
+ description: "Expected length of the task, from 1 short to 5 long."
498
+ },
499
+ objective: {
500
+ type: "string",
501
+ required: true,
502
+ description: "The task goal in its ordinary, universal meaning. Used only when auto-team starts a goal."
503
+ }
504
+ },
505
+ output: {
506
+ schema: {
507
+ type: "object",
508
+ additionalProperties: false,
509
+ properties: {
510
+ decision: {
511
+ type: "string",
512
+ required: true,
513
+ enum: ["team", "solo"]
514
+ },
515
+ goal: {
516
+ type: "string",
517
+ required: true,
518
+ enum: [
519
+ "started",
520
+ "reused",
521
+ "none"
522
+ ]
523
+ },
524
+ reporter: { type: "string" }
525
+ }
526
+ },
527
+ render: (_args, value) => [{
528
+ type: "text",
529
+ text: JSON.stringify(value)
530
+ }]
531
+ },
532
+ async execute(args, exec) {
533
+ const { agent } = exec;
534
+ if (agent === void 0) throw new Error("auto_team_score requires a calling Agent");
535
+ return await autoTeam.score(agent, {
536
+ assessment: {
537
+ scope: args.scope,
538
+ parallelism: args.parallelism,
539
+ ambiguity: args.ambiguity,
540
+ risk: args.risk,
541
+ expectedSteps: args.expected_steps
542
+ },
543
+ objective: args.objective,
544
+ signal: exec.signal
545
+ });
546
+ }
547
+ });
548
+ }
549
+ //#endregion
550
+ //#region src/worker-guard.ts
551
+ /**
552
+ * Worker write/edit gate: a successful worktree is required, and when the host
553
+ * returns its path, edits must stay inside it.
554
+ *
555
+ * @module @oh-my-dsh/auto-team/worker-guard
556
+ */
557
+ /** Read a write or edit file path from its tool arguments. */
558
+ function filePathOf(args) {
559
+ if (typeof args !== "object" || args === null || !("file_path" in args)) return;
560
+ const filePath = args.file_path;
561
+ if (typeof filePath === "string") return filePath;
562
+ }
563
+ /** Read the worktree path from a create_worktree canonical value. */
564
+ function worktreePathOf(value) {
565
+ if (typeof value !== "object" || value === null || !("path" in value)) return;
566
+ const worktreePath = value.path;
567
+ if (typeof worktreePath === "string") return worktreePath;
568
+ }
569
+ /** Whether target resolves inside root. */
570
+ function isInside(root, target) {
571
+ const relative = path.relative(path.resolve(root), path.resolve(target));
572
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
573
+ }
574
+ /** Require one execution teammate to work inside its own worktree. */
575
+ function installWorkerGuard(agent, root, autoTeam) {
576
+ let hasWorktree = false;
577
+ let worktreePath = void 0;
578
+ const disposers = [];
579
+ const register = (dispose) => {
580
+ disposers.push(dispose);
581
+ };
582
+ try {
583
+ const pre = agent.ctx.on("tools/pre-execute", async (exec, next) => {
584
+ if (exec.agent === agent && autoTeam.decisionOf(root) === "team" && (exec.name === "write" || exec.name === "edit")) {
585
+ if (!hasWorktree) return {
586
+ kind: "deny",
587
+ reason: "auto-team: create your own worktree with create_worktree before editing files"
588
+ };
589
+ if (worktreePath !== void 0) {
590
+ const filePath = filePathOf(exec.arguments);
591
+ if (filePath === void 0) return {
592
+ kind: "deny",
593
+ reason: "auto-team: write and edit require a file_path so the worktree guard can verify it"
594
+ };
595
+ if (!path.isAbsolute(filePath)) return {
596
+ kind: "deny",
597
+ reason: "auto-team: use an absolute file path inside your registered worktree"
598
+ };
599
+ if (!isInside(worktreePath, filePath)) return {
600
+ kind: "deny",
601
+ reason: `auto-team: edit path is outside your worktree: ${worktreePath}`
602
+ };
603
+ }
604
+ }
605
+ return await next();
606
+ });
607
+ register(() => {
608
+ pre();
609
+ });
610
+ const post = agent.ctx.on("tools/post-execute", async (exec, result, next) => {
611
+ if (exec.agent === agent && exec.name === "create_worktree" && !result.isError) {
612
+ hasWorktree = true;
613
+ const registered = worktreePathOf(result.value);
614
+ if (registered !== void 0) worktreePath = registered;
615
+ }
616
+ return await next();
617
+ });
618
+ register(() => {
619
+ post();
620
+ });
621
+ } catch (error) {
622
+ for (const dispose of disposers.toReversed()) dispose();
623
+ throw error;
624
+ }
625
+ return () => {
626
+ for (const dispose of disposers.toReversed()) dispose();
627
+ };
628
+ }
629
+ //#endregion
630
+ //#region src/runtime.ts
631
+ /** Create the production runtime adapter from a scoped Cordis context. */
632
+ function createPluginRuntime(ctx) {
633
+ return {
634
+ info: (message) => {
635
+ ctx.logger.info(message);
636
+ },
637
+ warn: (message) => {
638
+ ctx.logger.warn(message);
639
+ }
640
+ };
641
+ }
642
+ /** Install the prompt, scoring tool, and stop guard in one Lead scope. */
643
+ function installLead(options) {
644
+ const { agent, autoTeam, config, source } = options;
645
+ const systemPrompt = agent.ctx.systemPrompt;
646
+ const tools = agent.ctx.tools;
647
+ const disposers = [];
648
+ const register = (dispose) => {
649
+ disposers.push(dispose);
650
+ };
651
+ try {
652
+ register(systemPrompt.section({
653
+ name: "auto-team:policy",
654
+ order: systemPrompt.getSectionOrder("TEAM_POLICY"),
655
+ text: policyText(config.reportingAgentName, config.leadDeniedTools)
656
+ }));
657
+ register(tools.register(createScoreTool(autoTeam)));
658
+ if (source === "startup" || source === "clear") {
659
+ const stop = agent.ctx.on("agent/turn-stopping", (payload) => {
660
+ if (payload.agent !== agent || payload.turn !== 1 || autoTeam.hasScore(agent)) return;
661
+ agent.steer(createMessage({
662
+ role: "user",
663
+ content: [{
664
+ type: "text",
665
+ text: FIRST_ROUND_STEER_TEXT
666
+ }],
667
+ source: { kind: "user" }
668
+ }));
669
+ });
670
+ register(() => {
671
+ stop();
672
+ });
673
+ }
674
+ if (config.enforceLeadNoCode) {
675
+ const guard = agent.ctx.on("tools/pre-execute", async (exec, next) => {
676
+ if (exec.agent !== agent || autoTeam.decisionOf(agent) !== "team" || !config.leadDeniedTools.includes(exec.name)) return await next();
677
+ return {
678
+ kind: "deny",
679
+ reason: "auto-team: the Lead must delegate code changes to an execution agent"
680
+ };
681
+ });
682
+ register(() => {
683
+ guard();
684
+ });
685
+ }
686
+ } catch (error) {
687
+ for (const dispose of disposers.toReversed()) dispose();
688
+ throw error;
689
+ }
690
+ return () => {
691
+ for (const dispose of disposers.toReversed()) dispose();
692
+ };
693
+ }
694
+ /** Read the services needed by the install path without assuming load order. */
695
+ function servicesReady(ctx) {
696
+ return ctx.get("agentTeams") !== void 0 && ctx.get("goals") !== void 0 && ctx.get("tools") !== void 0 && ctx.get("systemPrompt") !== void 0;
697
+ }
698
+ /** Apply auto-team to the host; unmanaged scopes stay untouched. */
699
+ function apply(ctx, config) {
700
+ const resolved = resolveConfig(config);
701
+ const runtime = createPluginRuntime(ctx);
702
+ runtime.info(resolved.message);
703
+ const autoTeam = createAutoTeam(ctx, resolved);
704
+ const installed = /* @__PURE__ */ new Map();
705
+ let warned = false;
706
+ let projectionRegistered = false;
707
+ let resetCommandRegistered = false;
708
+ const ensureProjection = () => {
709
+ if (projectionRegistered) return;
710
+ const registry = ctx.get("sessionProjections");
711
+ if (registry === void 0) return;
712
+ ctx.effect(() => registry.register(autoTeamProjectionDefinition), "auto-team.projection()");
713
+ projectionRegistered = true;
714
+ };
715
+ ensureProjection();
716
+ const ensureResetCommand = () => {
717
+ if (resetCommandRegistered) return;
718
+ const commands = ctx.get("commands");
719
+ if (!isCommandRuntime(commands)) return;
720
+ ctx.effect(() => commands.register(createResetCommand(autoTeam)), "auto-team.reset-command()");
721
+ resetCommandRegistered = true;
722
+ };
723
+ ensureResetCommand();
724
+ const install = (agent, source) => {
725
+ if (installed.has(agent)) return;
726
+ ensureProjection();
727
+ if (!servicesReady(ctx)) {
728
+ if (!warned) {
729
+ runtime.warn("auto-team: host services are unavailable; waiting for agent and goal services");
730
+ warned = true;
731
+ }
732
+ return;
733
+ }
734
+ const membership = ctx.get("agentTeams")?.tryMembership(agent);
735
+ if (membership === void 0) return;
736
+ if (membership.role === "teammate") {
737
+ if (membership.name !== resolved.reportingAgentName) installed.set(agent, installWorkerGuard(agent, membership.root, autoTeam));
738
+ return;
739
+ }
740
+ const restored = ctx.get("sessionProjections")?.stateOf(agent.session, "autoTeam")?.score;
741
+ if (restored !== void 0 && restored !== null) autoTeam.restore(agent, restored);
742
+ installed.set(agent, installLead({
743
+ agent,
744
+ autoTeam,
745
+ config: resolved,
746
+ source
747
+ }));
748
+ };
749
+ for (const agent of ctx.get("agents")?.list() ?? []) install(agent);
750
+ ctx.on("agent/created", ({ agent, source }) => {
751
+ install(agent, source);
752
+ });
753
+ ctx.on("agent/disposed", ({ agent }) => {
754
+ installed.get(agent)?.();
755
+ installed.delete(agent);
756
+ });
757
+ ctx.on("internal/service", (name) => {
758
+ if (name !== "agentTeams" && name !== "goals" && name !== "tools" && name !== "systemPrompt" && name !== "sessionProjections" && name !== "commands") return;
759
+ ensureProjection();
760
+ ensureResetCommand();
761
+ for (const agent of ctx.get("agents")?.list() ?? []) install(agent);
762
+ });
763
+ ctx.effect(() => () => {
764
+ for (const dispose of installed.values()) dispose();
765
+ installed.clear();
766
+ }, "auto-team.install()");
767
+ }
768
+ //#endregion
769
+ //#region src/index.ts
770
+ /**
771
+ * Standalone function plugin for DeepSeek Harness.
772
+ *
773
+ * @module @oh-my-dsh/auto-team
774
+ */
775
+ /** Cordis plugin name; keep this stable after publishing. */
776
+ const name = "auto-team";
777
+ /** Services that must exist before the plugin is applied. */
778
+ const inject = [];
779
+ //#endregion
780
+ export { Config, apply, inject, name };
package/package.json CHANGED
@@ -1,6 +1,108 @@
1
1
  {
2
2
  "name": "@oh-my-dsh/auto-team",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Score-gated Agent Teams workflow for DeepSeek Harness",
4
+ "keywords": [
5
+ "cordis",
6
+ "cordis-plugin",
7
+ "deepseek-harness",
8
+ "dsh",
9
+ "dsh-plugin",
10
+ "auto-team",
11
+ "long-task",
12
+ "agent-team",
13
+ "goal"
14
+ ],
15
+ "license": "BSD-3-Clause",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/omdsh-dev/auto-team.git"
19
+ },
20
+ "homepage": "https://github.com/omdsh-dev/auto-team#readme",
21
+ "bugs": {
22
+ "url": "https://github.com/omdsh-dev/auto-team/issues"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "engines": {
28
+ "node": ">=24.0.0",
29
+ "dsh": ">=0.2.1-rc.2 <0.3.0"
30
+ },
31
+ "type": "module",
32
+ "version": "0.1.1",
33
+ "imports": {
34
+ "#src/*": "./src/*.ts"
35
+ },
36
+ "files": [
37
+ "lib",
38
+ "cordis.patch.yml",
39
+ "src/assets/locale/*.json",
40
+ "src/assets/icon.svg",
41
+ "README.md",
42
+ "README.zh.md"
43
+ ],
44
+ "exports": {
45
+ ".": {
46
+ "types": "./lib/index.d.ts",
47
+ "default": "./lib/index.js"
48
+ },
49
+ "./locale/*.json": "./src/assets/locale/*.json",
50
+ "./icon": "./src/assets/icon.svg",
51
+ "./package.json": "./package.json"
52
+ },
53
+ "main": "./lib/index.js",
54
+ "types": "./lib/index.d.ts",
55
+ "icon": "./src/assets/icon.svg",
56
+ "dsh": {
57
+ "manifestVersion": 1,
58
+ "bundle": {
59
+ "patch": "./cordis.patch.yml"
60
+ }
61
+ },
62
+ "dependencies": {
63
+ "zod": "4.4.3"
64
+ },
65
+ "peerDependencies": {
66
+ "@deepseek-ai/cordis": "~4.0.5",
67
+ "@deepseek-ai/schemastery": "~3.18.5",
68
+ "@deepseek-ai/dsh-agent": "0.2.1-rc.2",
69
+ "@deepseek-ai/dsh-experimental-agent-team": "0.2.1-rc.2",
70
+ "@deepseek-ai/dsh-goal": "0.2.1-rc.2",
71
+ "@deepseek-ai/dsh-llm": "0.2.1-rc.2",
72
+ "@deepseek-ai/dsh-session": "0.2.1-rc.2",
73
+ "@deepseek-ai/dsh-session-projection": "0.2.1-rc.2",
74
+ "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2",
75
+ "@deepseek-ai/dsh-tools": "0.2.1-rc.2"
76
+ },
77
+ "devDependencies": {
78
+ "@deepseek-ai/cordis": "~4.0.5",
79
+ "@deepseek-ai/cordis-plugin-loader": "~1.0.6",
80
+ "@deepseek-ai/schemastery": "~3.18.5",
81
+ "@deepseek-ai/dsh-agent": "0.2.1-rc.2",
82
+ "@deepseek-ai/dsh-experimental-agent-team": "0.2.1-rc.2",
83
+ "@deepseek-ai/dsh-goal": "0.2.1-rc.2",
84
+ "@deepseek-ai/dsh-llm": "0.2.1-rc.2",
85
+ "@deepseek-ai/dsh-session": "0.2.1-rc.2",
86
+ "@deepseek-ai/dsh-session-projection": "0.2.1-rc.2",
87
+ "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2",
88
+ "@deepseek-ai/dsh-tools": "0.2.1-rc.2",
89
+ "@tsconfig/node24": "^24.0.5",
90
+ "@types/node": "^24.0.0",
91
+ "oxfmt": "0.73.0",
92
+ "oxlint": "1.81.0",
93
+ "oxlint-tsgolint": "7.0.2001",
94
+ "tsdown": "^0.22.2",
95
+ "typescript": "^6.0.3",
96
+ "vitest": "^4.1.11"
97
+ },
98
+ "scripts": {
99
+ "build": "tsdown",
100
+ "fmt": "oxfmt src tests",
101
+ "fmt:check": "oxfmt --check src tests",
102
+ "lint": "oxlint src tests",
103
+ "lint:fix": "oxlint --fix src tests",
104
+ "test": "vitest run",
105
+ "extract:patch": "node scripts/extract-patch.mjs",
106
+ "patch:host": "bash scripts/patch.sh"
107
+ }
6
108
  }
@@ -0,0 +1,13 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="DSH Plugin Template">
2
+ <defs>
3
+ <linearGradient id="g" x1="8" y1="4" x2="56" y2="60" gradientUnits="userSpaceOnUse">
4
+ <stop offset="0" stop-color="#4f8cff"/>
5
+ <stop offset="1" stop-color="#7048e8"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <rect x="4" y="4" width="56" height="56" rx="14" fill="url(#g)"/>
9
+ <path d="M23 21v7M41 21v7" stroke="#fff" stroke-width="4" stroke-linecap="round"/>
10
+ <path d="M19 28h26v10a13 13 0 0 1-13 13 13 13 0 0 1-13-13V28Z" fill="#fff"/>
11
+ <path d="M32 36v8" stroke="#7048e8" stroke-width="4" stroke-linecap="round"/>
12
+ <circle cx="48" cy="16" r="4" fill="#ffd43b"/>
13
+ </svg>
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Auto Team",
4
+ "description": "Score-gated Agent Teams workflow for DeepSeek Harness."
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Auto Team",
4
+ "description": "按难度评分启用 Agent Team 的长任务协作流程。"
5
+ }
6
+ }