@starsharryzhu/complete-subagent 0.1.1 → 0.2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@starsharryzhu/complete-subagent",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Complete subagents for DeepSeek Harness: delegate and delegate_fork tools beside the official ones, where the cwd a parent gives a child is the only place the child may modify, writable_paths grants more up front, anything else needs the parent agent's permission, and the parent can choose the child's model and reasoning effort from the models listed in the settings.",
5
5
  "keywords": [
6
6
  "dsh-plugin",
package/src/AGENTS.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  ## 1. Role
4
4
 
5
- The plugin source. `index.ts` is the host entry the bundle row loads: it declares the injected services and the live settings, wraps the sandbox policy, registers the two delegation tools (rebuilt when the model settings change or a bundle sets the list through the `completeSubagent` service) and the four write-access tools, confines children that confined agents start by other means, and adds the child and open-request contexts to the prompt, all of it only for the agents of the configured `presets` when any are listed. On a host that ignores `when`, it applies the same visibility conditions as per-agent filters. Everything with logic lives in `host/`, so the entry stays a readable wiring diagram. `client/` is the browser half, the settings page, and `shared/` holds the settings shape both halves read.
5
+ The plugin source. `index.ts` is the host entry the bundle row loads: it declares the injected services and the live settings, wraps the sandbox policy, registers the two delegation tools (rebuilt when the model settings change or a bundle sets the list through the `completeSubagent` service) the four write-access tools, `model_notes_set`, and `switch_child_model`, confines children that confined agents start by other means, follows its children's turns for one their model stopped, and adds the child, open-request, and stopped-children contexts to the prompt, all of it only for the agents of the configured `presets` when any are listed. On a host that ignores `when`, it applies the same visibility conditions as per-agent filters. Everything with logic lives in `host/`, so the entry stays a readable wiring diagram. `client/` is the browser half, the settings page, and `shared/` holds the settings shape both halves read.
6
6
 
7
7
  ## 2. Constraints
8
8
 
9
- - The host entry exports only `name`, `inject`, `Config`, and `apply`, plus types: no default export and no top-level `await`, as the host loader requires.
9
+ - The host entry exports only `name`, `inject`, `Config`, `apply`, and `embed` (for a package that carries its own copy), plus types: no default export and no top-level `await`, as the host loader requires.
10
10
  - Every host registration goes through `ctx.effect` or `ctx.on`, or is disposed by an effect, so unloading the plugin removes all of it and restores the sandbox policy.
11
11
  - A callback the host runs for every session (an event listener, a visibility check, a prompt text) logs a warning and falls back rather than throwing, so a plugin failure cannot stop a step or an agent start.
12
12
  - `host/` never imports from `client/`, and `client/` never imports from `host/`; both may import `shared/`.
@@ -14,13 +14,16 @@ The plugin source. `index.ts` is the host entry the bundle row loads: it declare
14
14
 
15
15
  ## 3. Contents
16
16
 
17
- - `index.ts` — the host entry: services, live settings, the `completeSubagent` service, and wiring.
17
+ - `index.ts` — the host entry: services, live settings, the `completeSubagent` service, `embed`, the contexts the tools and texts are registered in, and wiring.
18
18
  - `host` — the fence, delegation, access, model choice, grants, requests, tools, prompts, storage, and path helpers.
19
19
  - `client` — the settings page on the Plugins screen.
20
20
  - `shared` — the settings shape and readers used by both halves.
21
21
 
22
22
  ## 4. Progress
23
23
 
24
+ - Done (2026-11-30, user request): the entry wires the model notes table and the switch of a child stopped by its model.
25
+
24
26
  - Done: entry wiring for every module and both halves, including the `presets` scope on every tool, both contexts, and inherited bindings, one table of visibility conditions for both kinds of host, and failure guards on every host callback; the `completeSubagent` service.
27
+ - Done (2026-12-03): the entry starts a copy first and registers its tools and prompt texts per context after it, so an embedded copy can do so in presets.
25
28
  - Open: nothing.
26
29
  - Goal later: nothing planned.
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## 1. Role
4
4
 
5
- The host modules. A delegation call decides the child's sub-workspace and `writable_paths` grants (`access.ts`) and its model and reasoning effort (`models.ts`), stores the binding under a reserved child id, and only then starts the child on the host's subagent runtime (`delegate.ts`); bindings and grants are stored per child session (`store.ts`); every sandbox policy the host resolves for a bound child, or for a child a confined agent started by other means, is narrowed to its access (`policy.ts`, with `call-scope.ts` for single-file grants); grants are issued under one authority rule (`grants.ts`); the child asks and the parent answers, grants, and revokes through four tools (`tools.ts`, with open requests in `requests.ts`); and the prompt texts explain all of it (`prompt.ts`). When the settings list agent presets, only the agents of those presets are served (`scope.ts`). What differs on a host older than 0.2.2-alpha.2 lives in `legacy.ts`.
5
+ The host modules. A delegation call decides the child's sub-workspace and `writable_paths` grants (`access.ts`) and its model and reasoning effort (`models.ts`), stores the binding under a reserved child id, and only then starts the child on the host's subagent runtime (`delegate.ts`); bindings and grants are stored per child session (`store.ts`); every sandbox policy the host resolves for a bound child, or for a child a confined agent started by other means, is narrowed to its access (`policy.ts`, with `call-scope.ts` for single-file grants); grants are issued under one authority rule (`grants.ts`); the child asks and the parent answers, grants, and revokes through four tools (`tools.ts`, with open requests in `requests.ts`); the prompt texts explain all of it (`prompt.ts`); and a parent records what it found out about each listed model in a table every parent shares (`notes.ts`, through `notes-tool.ts`), which the delegation descriptions show under each model; a child whose model is out of quota or rate-limited is recorded when its turn ends, its parent's context says so (`outages.ts`), and the parent moves it to another listed model, where it continues its own conversation (`switch-tool.ts`); the words of any other error a child's turn ended in reach its parent the same way. When the settings list agent presets, only the agents of those presets are served (`scope.ts`). What differs on a host older than 0.2.2-alpha.2 lives in `legacy.ts`.
6
6
 
7
7
  ## 2. Constraints
8
8
 
@@ -14,12 +14,21 @@ The host modules. A delegation call decides the child's sub-workspace and `writa
14
14
  - An inherited binding holds no access of its own; the fence resolves it to the nearest ancestor's current access, and a broken chain leaves none.
15
15
  - The delegation result text is `started subagent <id>`, as the official tools write it.
16
16
  - Only a `spawn` start carries the configured `childPreset` as `agentPreset`; a `fork` start never selects a preset.
17
+ - A configured `maxDepth` replaces the host's `resolveMaxDepth()` in `canStart` and in the start request; without one both read the host's setting.
17
18
  - A start's task (`cwd`, `prompt`, `parent`, `agentPreset`, `agentOptions`, `maxDepth`) goes both at the top level of the spec, for hosts from 0.2.2-rc.2, and under `request`, for older ones; `delegate.ts` builds it once and `types.ts` mirrors both shapes.
18
19
  - A child's route goes only through the start's `agentOptions`, which both 0.2.1-rc.5 and 0.2.2-alpha.2 use for its first request; nothing selects a model afterwards.
19
20
  - `ownModel` off applies to `delegate` only. On the parent's own route the host hands down the parent's effort unless one is named, so `models.ts` names the effort there.
20
21
  - A model outside the list fails first in the tool's own `enum` check, with the host's "must be one of" message; the message in `models.ts` covers a call that gets past it.
21
- - Requests live in memory only; bindings and grants are the only durable state.
22
+ - Requests live in memory only; bindings, grants, and the model notes are the only durable state.
23
+ - The model notes reach the parent only through the delegation descriptions, which change only when a note or the list does: the host re-sends every runtime context in full whenever any of them changes, so a table there would be paid for again and again. A description reads the notes whenever the host projects the schema; a note never rebuilds the tools, because a step admits a tool only while its registered definition is unchanged, and a swapped one would fail a call still running on the old definition (checked in the 0.2.1-rc.5 and 0.2.2-rc.5 sources).
24
+ - A note is for a listed model only, and its efforts must be ones that model allows, checked the same way as a delegation's effort. Its sources are kept in the file but left out of the description.
25
+ - A model is switched for a child's next step, never inside a step: every supported host fixes a step's model before its request (`agent-loop` `prepareRequest`), so a retry from `agent/request-error` would hit the same model. The child's turn ends with the host's own failure notice, and the switch then records the new model (`agent.model.select`, or on 0.2.1-rc.5 the session controller's internal `agents.selectForNextRequest`) and wakes the child with a message from its parent. A child the host has put away gets its new model in `agent/created`, before its first step.
26
+ - A model "cannot serve" a child when its request fails with `QUOTA`, `ACCOUNT_QUOTA`, or `RATE_LIMIT`, or HTTP 402; the same failure codes and turn ending exist from 0.2.1-rc.5 on. A model that refused a child cannot be chosen for it again until the child finishes a turn. Outages are in memory only; after a restart the parent still has the host's notice.
27
+ - Every error a child's turn ends in reaches its parent word for word (at most `MESSAGE_CHARS`), because the host says only that the child failed and a parent left to guess guesses wrong. Only the codes above count as a refusal; what a provider says under a code of its own is the parent's to read, and to have looked up when it does not know it, so no wording rules belong here. Such an error is shown until the child runs again, and for a day at most. A stopped turn is no error.
28
+ - The texts never let a parent force a task onto a model whose notes do not fit it: they say to ask the user first and try one only with their permission (the user's rule, 2026-11-30).
29
+ - The notes file is shared by every host process on this machine: a write rereads it first and replaces it atomically, and a damaged file reads as empty.
22
30
  - With presets listed, an agent whose preset cannot be read (no service, none recorded, a failure) is not served; an empty list serves every agent without reading a preset.
31
+ - A copy that serves every preset leaves the agents of claimed presets alone in both ways: it does not serve them, and on a host without `when` it adds no filter to them, since a filter goes by name and would hide the claiming copy's tools. An embedded copy filters only the agents it serves, because its tools do not exist for others.
23
32
  - A session's preset comes from `agentPresets.presetForSession` when the host has that method, since newer hosts deprecate the alternative, and otherwise from the `agentPreset` session projection.
24
33
  - A `tools.restrict` filter belongs to the agent's own context, not the plugin's, so the plugin lifts it on dispose. It never reaches the agent's children, because an agent's scope chain leads to its preset, not its parent.
25
34
  - A failure in the fence stays in the session it hit: a subagent falls back to read-only, a top-level session keeps the host's policy, and other sessions are not touched.
@@ -28,7 +37,7 @@ The host modules. A delegation call decides the child's sub-workspace and `writa
28
37
  ## 3. Contents
29
38
 
30
39
  - `types.ts` — structural mirrors of the host services, the delegation tools and their backends, and the write-access tool names.
31
- - `scope.ts` — reading a session's preset on any host, and which agents the plugin serves under the `presets` setting.
40
+ - `scope.ts` — reading a session's preset on any host, which agents the plugin serves under the `presets` setting, and the presets embedded copies have claimed.
32
41
  - `legacy.ts` — detecting a host older than 0.2.2-alpha.2, and the per-agent tool filters that replace `when` there.
33
42
  - `paths.ts` — resolving, canonicalizing, and comparing paths.
34
43
  - `store.ts` — per-child bindings and grants as JSON files under the DSH home.
@@ -40,6 +49,10 @@ The host modules. A delegation call decides the child's sub-workspace and `writa
40
49
  - `grants.ts` — resolving requested paths and issuing grants within the grantor's reach.
41
50
  - `requests.ts` — open write-access requests, answers, timeouts, and cancellation.
42
51
  - `tools.ts` — `request_write_access`, `answer_write_request`, `grant_write_access`, and `revoke_write_access`.
52
+ - `notes.ts` — the model notes table: one JSON file under the DSH home, one note per model.
53
+ - `notes-tool.ts` — `model_notes_set`, which checks and stores a note.
54
+ - `outages.ts` — the errors children's turns ended in, which of them mean a model cannot serve the child, the models that refused each child, and the parent's context.
55
+ - `switch-tool.ts` — `switch_child_model`, and recording a model for an agent's next step on every supported host.
43
56
  - `prompt.ts` — the delegation descriptions and parameter texts, the child context, which says what reaches its grants on this host, and the open-requests context.
44
57
 
45
58
  ## 4. Progress
@@ -49,5 +62,8 @@ The host modules. A delegation call decides the child's sub-workspace and `writa
49
62
  - Checked on the real rc.5 tool, prompt, projection, and sandbox-policy services (2026-11-02): `legacy.ts`, `scope.ts`, and the single-root grant, with stand-ins for agents and the subagent start.
50
63
  - Checked on real 0.2.1-rc.5 and 0.2.2-alpha.2 hosts with a mock model (2026-11-02): `delegate.ts` and `models.ts`, from the tool call to the child's first recorded request.
51
64
  - Fixed and checked on real 0.2.1-rc.5, 0.2.2-rc.1, 0.2.2-rc.2, and 0.2.2-rc.3 hosts with a mock model (2026-11-17): `delegate.ts` starts a child on each, where before it failed from 0.2.2-rc.2 on; the fence, a write-access request, its answer, and the grant worked on all four.
65
+ - Done (2026-11-30, user request): the model notes table and `model_notes_set`; the delegation descriptions show each listed model's note and ask for research on the models without one or with an old one.
66
+ - Done (2026-11-30, user request): a child stopped because its model is out of quota is reported to its parent with the reason, and `switch_child_model` moves it to another listed model, where it continues its own conversation; no text lets a parent force a task onto a model that does not fit it without asking the user.
67
+ - Done (2026-12-03): claimed presets, and a wrapper of `sandboxPolicy.resolve` that does nothing after its copy ended.
52
68
  - Open: `delegate.ts`, `models.ts`, `scope.ts`, `legacy.ts`, and inherited confinement are not yet verified in a real web app.
53
69
  - Goal later: nothing planned.
@@ -19,6 +19,7 @@ import type { ChildModel } from '../shared/settings.ts'
19
19
  import { decideAccess } from './access.ts'
20
20
  import type { AccessDeps } from './access.ts'
21
21
  import { chooseRoute, describeModels } from './models.ts'
22
+ import type { ModelNotes } from './notes.ts'
22
23
  import {
23
24
  CWD_DESCRIPTION,
24
25
  EFFORT_DESCRIPTION,
@@ -42,6 +43,10 @@ export interface DelegateDeps extends AccessDeps {
42
43
  readonly childPreset?: string
43
44
  /** False keeps a `delegate` child off the parent's own model when models are listed. */
44
45
  readonly ownModel?: boolean
46
+ /** The model notes table, shown under each listed model. */
47
+ readonly notes?: ModelNotes
48
+ /** Depth limit of this copy; undefined uses the host's setting. */
49
+ readonly maxDepth?: number
45
50
  }
46
51
 
47
52
  /** The arguments of one delegation call. */
@@ -57,6 +62,8 @@ interface DelegateArgs {
57
62
  /**
58
63
  * Build one delegation tool for the current settings. The model list is fixed
59
64
  * into the schema, so the entry rebuilds the tools when the settings change.
65
+ * The model notes are not: the description reads them whenever the host
66
+ * projects the schema, so a note shows from the parent's next step.
60
67
  * @param tool - which tool.
61
68
  * @param models - the settings' model list.
62
69
  * @param deps - shared state and services.
@@ -66,9 +73,10 @@ export function createDelegateTool(tool: DelegateTool, models: readonly ChildMod
66
73
  const provider = DELEGATE_TOOLS[tool]
67
74
  // A fork continues the parent's conversation, so its own model stays the default there.
68
75
  const ownModel = provider === 'spawn' ? deps.ownModel !== false : true
69
- return defineTool({
76
+ const describe = (): string => delegateDescription(tool, describeModels(models, ownModel, model => deps.notes?.get(model)))
77
+ const definition = defineTool({
70
78
  name: tool,
71
- description: delegateDescription(tool, describeModels(models, ownModel)),
79
+ description: describe(),
72
80
  parameters: {
73
81
  description: {
74
82
  type: 'string',
@@ -109,7 +117,7 @@ export function createDelegateTool(tool: DelegateTool, models: readonly ChildMod
109
117
  ownModel,
110
118
  })
111
119
  exec.signal.throwIfAborted()
112
- const maxDepth = deps.subagents.resolveMaxDepth()
120
+ const maxDepth = deps.maxDepth ?? deps.subagents.resolveMaxDepth()
113
121
  // The fork backend inherits the parent's context, so only spawn may select a preset.
114
122
  const agentPreset = provider === 'spawn' ? deps.childPreset : undefined
115
123
  const childId = deps.newId?.() ?? randomUUID()
@@ -141,22 +149,28 @@ export function createDelegateTool(tool: DelegateTool, models: readonly ChildMod
141
149
  }
142
150
  },
143
151
  })
152
+ // A note changes while the tool stays registered: the host's step admits a tool only while its registered
153
+ // definition is unchanged, so swapping the definition would fail a call still running on the old one.
154
+ Object.defineProperty(definition, 'description', { enumerable: true, configurable: true, get: describe })
155
+ return definition
144
156
  }
145
157
 
146
158
  /**
147
159
  * Whether an agent may delegate on a backend now: the backend is registered
148
- * and the agent is below the user's depth limit. A limit that cannot be read
149
- * leaves the tool visible; the runtime then rejects the start.
160
+ * and the agent is below the depth limit, this copy's own or else the user's.
161
+ * A limit that cannot be read leaves the tool visible; the runtime then
162
+ * rejects the start.
150
163
  * @param subagents - the subagent runtime.
151
164
  * @param tool - which tool.
152
165
  * @param agent - the would-be parent.
166
+ * @param configured - this copy's depth limit; undefined uses the host's setting.
153
167
  * @returns true when the tool should be offered.
154
168
  */
155
- export function canStart(subagents: SubagentsLike, tool: DelegateTool, agent: AgentLike): boolean {
169
+ export function canStart(subagents: SubagentsLike, tool: DelegateTool, agent: AgentLike, configured?: number): boolean {
156
170
  if (subagents.getProvider(DELEGATE_TOOLS[tool]) === undefined) return false
157
- let maxDepth: number | undefined
171
+ let maxDepth: number | undefined = configured
158
172
  try {
159
- maxDepth = subagents.resolveMaxDepth()
173
+ maxDepth ??= subagents.resolveMaxDepth()
160
174
  } catch {
161
175
  return true
162
176
  }
@@ -12,12 +12,19 @@
12
12
  * model is the first one, an effort-only call sets that model's effort, and an
13
13
  * omitted effort never comes from the parent, even when the parent runs the
14
14
  * same model. An empty list leaves the rules above.
15
+ *
16
+ * The description lists each model with its note from the model notes table
17
+ * (`notes.ts`), names the models without one, and tells the parent to have
18
+ * those researched by a child with web search and to record what it finds.
15
19
  * @module complete-subagent/host/models
16
20
  */
17
21
 
18
22
  import { modelKey } from '../shared/settings.ts'
19
23
  import type { ChildModel } from '../shared/settings.ts'
24
+ import { STALE_DAYS, WORK_KINDS } from './notes.ts'
25
+ import type { ModelNote } from './notes.ts'
20
26
  import type { AgentLike, LlmLike, RouteLike } from './types.ts'
27
+ import { NOTES_TOOL } from './types.ts'
21
28
 
22
29
  /** A route with its provider and model known. */
23
30
  export interface Route {
@@ -49,6 +56,19 @@ export function routeOf(agent: AgentLike): Route | undefined {
49
56
  }
50
57
  }
51
58
 
59
+ /**
60
+ * The efforts a child on one model may run: the listed ones, else every one the model advertises.
61
+ * @param route - the model.
62
+ * @param listed - the efforts the settings list for it.
63
+ * @param llm - the LLM runtime.
64
+ * @param signal - aborts the lookup.
65
+ * @returns the effort ids, empty for a model without selectable efforts.
66
+ */
67
+ export async function offeredEfforts(route: { readonly provider: string; readonly model: string }, listed: readonly string[], llm: LlmLike, signal?: AbortSignal): Promise<readonly string[]> {
68
+ if (listed.length > 0) return listed
69
+ return (await llm.resolveModelInfo(route.provider, route.model, signal)).reasoning?.efforts.map(item => item.id) ?? []
70
+ }
71
+
52
72
  /** The choices as one line for an error message. */
53
73
  function choicesLine(models: readonly ChildModel[]): string {
54
74
  return models.length === 0 ? 'none are listed in the settings' : models.map(modelKey).join(', ')
@@ -102,9 +122,7 @@ export async function chooseRoute(options: {
102
122
  if (llm === undefined) throw new Error('The child model cannot be checked because the `llm` service is unavailable.')
103
123
  let chosen = effort
104
124
  if (effort !== undefined) {
105
- const offered = allowed.length > 0
106
- ? allowed
107
- : (await llm.resolveModelInfo(route.provider, route.model, options.signal)).reasoning?.efforts.map(item => item.id) ?? []
125
+ const offered = await offeredEfforts(route, allowed, llm, options.signal)
108
126
  if (!offered.includes(effort)) {
109
127
  throw new Error(offered.length === 0
110
128
  ? `${key} has no selectable reasoning effort; omit \`reasoning_effort\`.`
@@ -125,31 +143,81 @@ export async function chooseRoute(options: {
125
143
  return { provider: route.provider, model: route.model, ...chosen === undefined ? {} : { reasoningEffort: chosen } }
126
144
  }
127
145
 
146
+ /** Text as a sentence: trimmed, with a closing full stop when it has no closing mark. */
147
+ function sentence(text: string): string {
148
+ const trimmed = text.trim()
149
+ return /[.!?。!?]$/u.test(trimmed) ? trimmed : `${trimmed}.`
150
+ }
151
+
152
+ /**
153
+ * One model's note as the line under its entry.
154
+ * @param note - the stored note.
155
+ * @returns the indented line.
156
+ */
157
+ export function noteLine(note: ModelNote): string {
158
+ const efforts = WORK_KINDS.flatMap(kind => note.efforts[kind] === undefined ? [] : [`${kind} work ${note.efforts[kind]}`])
159
+ return [
160
+ ` Notes (checked ${note.checked}). Strong at: ${sentence(note.strengths)} Weak at: ${sentence(note.weaknesses)}`,
161
+ ...efforts.length === 0 ? [] : [`Effort: ${efforts.join(', ')}.`],
162
+ ].join(' ')
163
+ }
164
+
165
+ /**
166
+ * What the parent does with the notes: research the models without one, and
167
+ * choose from them.
168
+ * @param models - the settings list, not empty.
169
+ * @param noteOf - the stored note on a model.
170
+ * @returns the paragraph.
171
+ */
172
+ function notesParagraph(models: readonly ChildModel[], noteOf: (model: string) => ModelNote | undefined): string {
173
+ const missing = models.map(modelKey).filter(key => noteOf(key) === undefined)
174
+ const research = 'start one research child that can search the web, beside the real work, and ask it to look up each of these models '
175
+ + 'in its provider\'s documentation, model card, and pricing and in independent evaluations, and to report its strengths, weaknesses, '
176
+ + 'speed, and price, and which reasoning effort suits light, normal, and hard work'
177
+ return [
178
+ ...missing.length === 0 ? [] : [
179
+ `No notes yet on ${missing.join(', ')}. The next time you delegate, also ${research}; then record each with \`${NOTES_TOOL}\`. `
180
+ + 'Until a model has a note, choose by its name.',
181
+ ],
182
+ `Choose each child's model and effort from these notes. When no listed model's notes fit a task, do not force the task onto one anyway: `
183
+ + 'ask your user first, and try a model only with their permission. '
184
+ + `A note checked more than ${STALE_DAYS} days ago may be out of date: `
185
+ + `have that model researched again the same way. Record what you learn later, such as a model doing poorly at some kind of work, with \`${NOTES_TOOL}\`.`,
186
+ ].join('\n')
187
+ }
188
+
128
189
  /**
129
190
  * The model-selection paragraph of a delegation tool's description.
130
191
  * @param models - the settings list.
131
192
  * @param ownModel - false keeps the child off the parent's own model when models are listed.
193
+ * @param noteOf - the stored note on a model, shown under its entry.
132
194
  * @returns the text the parent reads.
133
195
  */
134
- export function describeModels(models: readonly ChildModel[], ownModel = true): string {
196
+ export function describeModels(models: readonly ChildModel[], ownModel = true, noteOf: (model: string) => ModelNote | undefined = () => undefined): string {
135
197
  const efforts = (entry: ChildModel): string => entry.reasoningEfforts.length === 0
136
198
  ? 'any effort it supports'
137
199
  : `efforts ${entry.reasoningEfforts.join(', ')}`
200
+ const entries = models.flatMap(entry => {
201
+ const note = noteOf(modelKey(entry))
202
+ return [`- ${modelKey(entry)}: ${efforts(entry)}`, ...note === undefined ? [] : [noteLine(note)]]
203
+ })
138
204
  if (models.length === 0) {
139
205
  return 'Model: the child uses your own model. `reasoning_effort` may be any effort your model supports; omitted, the child keeps your current effort.'
140
206
  }
141
207
  if (!ownModel) {
142
208
  return [
143
209
  'Model: the child runs one of these models, never your own. Omit `model` to use the first; `reasoning_effort` applies to the model the child runs.',
144
- ...models.map(entry => `- ${modelKey(entry)}: ${efforts(entry)}`),
210
+ ...entries,
145
211
  'An omitted effort uses the model\'s default, or its first listed effort when the default is not listed.',
212
+ notesParagraph(models, noteOf),
146
213
  ].join('\n')
147
214
  }
148
215
  return [
149
216
  'Model: omit `model` to give the child your own model; `reasoning_effort` may then be any effort your model supports '
150
217
  + '(only the listed ones if your model is listed below), and an omitted effort keeps your current one.',
151
218
  'Other models you may choose with `model`:',
152
- ...models.map(entry => `- ${modelKey(entry)}: ${efforts(entry)}`),
219
+ ...entries,
153
220
  'On another model, an omitted effort uses that model\'s default, or its first listed effort when the default is not listed.',
221
+ notesParagraph(models, noteOf),
154
222
  ].join('\n')
155
223
  }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * `model_notes_set`: a parent records what it found out about a model its
3
+ * children may run, usually from a research child with web search, so the
4
+ * delegation tools show it from then on, in this and every later conversation.
5
+ * @module complete-subagent/host/notes-tool
6
+ */
7
+
8
+ import { defineTool } from '@deepseek-ai/dsh-tools'
9
+ import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
10
+ import { modelKey } from '../shared/settings.ts'
11
+ import type { ChildModel } from '../shared/settings.ts'
12
+ import { offeredEfforts } from './models.ts'
13
+ import { NOTE_MAX_CHARS, NOTE_MAX_SOURCES, WORK_KINDS, dayOf } from './notes.ts'
14
+ import type { ModelNote, ModelNotes, WorkKind } from './notes.ts'
15
+ import { NOTES_TOOL } from './types.ts'
16
+ import type { LlmLike } from './types.ts'
17
+
18
+ /** What the tool reads. */
19
+ export interface NotesToolDeps {
20
+ readonly notes: ModelNotes
21
+ /** The LLM runtime, read at call time because it is optional. */
22
+ readonly llm: () => LlmLike | undefined
23
+ /** The current time; replaceable in tests. */
24
+ readonly now?: () => Date
25
+ }
26
+
27
+ /** The arguments of one call. */
28
+ interface NotesArgs {
29
+ readonly model: string
30
+ readonly strengths: string
31
+ readonly weaknesses: string
32
+ readonly effort_light?: string
33
+ readonly effort_normal?: string
34
+ readonly effort_hard?: string
35
+ readonly sources?: string[]
36
+ }
37
+
38
+ /** What each effort parameter is for. */
39
+ const EFFORT_USE: Readonly<Record<WorkKind, string>> = {
40
+ light: 'light, mechanical work (copying, renaming, short lookups)',
41
+ normal: 'ordinary work (most research, writing, and edits)',
42
+ hard: 'hard work (deep reasoning, tricky code, careful analysis)',
43
+ }
44
+
45
+ /** Read one required text field. */
46
+ function text(value: unknown, field: string): string {
47
+ if (typeof value !== 'string' || value.trim() === '') throw new Error(`\`${field}\` must be a non-empty text`)
48
+ const trimmed = value.trim()
49
+ if (trimmed.length > NOTE_MAX_CHARS) throw new Error(`\`${field}\` is ${trimmed.length} characters; keep it under ${NOTE_MAX_CHARS}.`)
50
+ return trimmed
51
+ }
52
+
53
+ /** Read the sources: http(s) URLs, repeats dropped. */
54
+ function sourcesOf(value: unknown): string[] {
55
+ if (value === undefined) return []
56
+ if (!Array.isArray(value)) throw new Error('`sources` must be a list of URLs')
57
+ const urls = [...new Set((value as unknown[]).map(item => typeof item === 'string' ? item.trim() : ''))]
58
+ for (const url of urls) {
59
+ if (!/^https?:\/\/\S+$/u.test(url)) throw new Error(`Source "${url}" is not an http(s) URL.`)
60
+ }
61
+ if (urls.length > NOTE_MAX_SOURCES) throw new Error(`Give at most ${NOTE_MAX_SOURCES} sources.`)
62
+ return urls
63
+ }
64
+
65
+ /**
66
+ * Build the tool for the current model list, which its `model` parameter names.
67
+ * @param models - the settings' model list.
68
+ * @param deps - the table and services.
69
+ * @returns a registry-ready definition.
70
+ */
71
+ export function createNotesTool(models: readonly ChildModel[], deps: NotesToolDeps): ToolDefinition {
72
+ return defineTool({
73
+ name: NOTES_TOOL,
74
+ description: 'Record what you found out about one model your children may run, so the delegation tools show it from now on, '
75
+ + 'in this and every later conversation: what it does well and poorly (speed and price included), and which reasoning effort '
76
+ + 'suits light, normal, and hard work. Base it on research, usually a child\'s web search of the provider\'s documentation, '
77
+ + 'model card, pricing, and independent evaluations, or on how the model did on your own tasks. It replaces the model\'s earlier note.',
78
+ parameters: {
79
+ model: {
80
+ type: 'string',
81
+ required: true,
82
+ ...models.length === 0 ? {} : { enum: models.map(modelKey) },
83
+ description: 'The model as "provider/model", one of those the delegation tools list.',
84
+ },
85
+ strengths: { type: 'string', required: true, description: `What it does well, in a few phrases (at most ${NOTE_MAX_CHARS} characters).` },
86
+ weaknesses: { type: 'string', required: true, description: `What it does poorly, how slow or costly it is, in a few phrases (at most ${NOTE_MAX_CHARS} characters).` },
87
+ ...Object.fromEntries(WORK_KINDS.map(kind => [`effort_${kind}`, {
88
+ type: 'string' as const,
89
+ description: `The reasoning effort id for ${EFFORT_USE[kind]}, among those the model allows. Omit for a model without selectable efforts.`,
90
+ }])),
91
+ sources: { type: 'array', items: { type: 'string' }, description: `Up to ${NOTE_MAX_SOURCES} http(s) URLs the note rests on.` },
92
+ },
93
+ output: {
94
+ schema: {
95
+ type: 'object',
96
+ additionalProperties: false,
97
+ properties: {
98
+ model: { type: 'string', required: true },
99
+ checked: { type: 'string', required: true },
100
+ },
101
+ },
102
+ render: (_args, value) => [{ type: 'text', text: `Recorded the note on ${value.model} (checked ${value.checked}). The delegation tools show it from your next step.` }],
103
+ },
104
+ isConcurrencySafe: () => true,
105
+ async execute(raw, exec) {
106
+ const args = raw as NotesArgs
107
+ const model = typeof args.model === 'string' ? args.model.trim() : ''
108
+ const entry = models.find(item => modelKey(item) === model)
109
+ if (entry === undefined) {
110
+ throw new Error(`Model "${model}" is not offered for subagents, so it needs no note. Note one of: ${models.map(modelKey).join(', ') || 'none are listed'}.`)
111
+ }
112
+ const strengths = text(args.strengths, 'strengths')
113
+ const weaknesses = text(args.weaknesses, 'weaknesses')
114
+ const sources = sourcesOf(args.sources)
115
+ const named = WORK_KINDS.flatMap(kind => {
116
+ const value = args[`effort_${kind}`]
117
+ if (value === undefined) return []
118
+ if (typeof value !== 'string' || value.trim() === '') throw new Error(`\`effort_${kind}\` must be an effort id`)
119
+ return [[kind, value.trim()] as const]
120
+ })
121
+ const efforts: Partial<Record<WorkKind, string>> = {}
122
+ if (named.length > 0) {
123
+ const llm = deps.llm()
124
+ if (llm === undefined && entry.reasoningEfforts.length === 0) {
125
+ throw new Error('The model\'s efforts cannot be checked because the `llm` service is unavailable; omit the effort fields.')
126
+ }
127
+ const offered = await offeredEfforts(entry, entry.reasoningEfforts, llm as LlmLike, exec.signal)
128
+ for (const [kind, effort] of named) {
129
+ if (!offered.includes(effort)) {
130
+ throw new Error(offered.length === 0
131
+ ? `${model} has no selectable reasoning effort; omit the effort fields.`
132
+ : `Effort "${effort}" is not offered for ${model}. Choose among: ${offered.join(', ')}.`)
133
+ }
134
+ efforts[kind] = effort
135
+ }
136
+ }
137
+ exec.signal.throwIfAborted()
138
+ const note: ModelNote = { model, strengths, weaknesses, efforts, sources, checked: dayOf(deps.now?.() ?? new Date()) }
139
+ deps.notes.set(note)
140
+ return { model, checked: note.checked }
141
+ },
142
+ })
143
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The model notes table: what parents found out about the models a child may
3
+ * run (strengths, weaknesses, and the reasoning effort that suits light,
4
+ * normal, and hard work), so the choice of a child's model and effort can rest
5
+ * on it now and in later conversations.
6
+ *
7
+ * One JSON file for every parent on this machine, under
8
+ * `$DSH_HOME/plugin-data/complete-subagent/model-notes.json`: a model is the
9
+ * same model in every conversation. A parent fills it with `model_notes_set`,
10
+ * usually from what a child with web search found; the delegation tools show
11
+ * each listed model's note. Reads are cached; a write first rereads the file,
12
+ * so a row another host process stored in between survives, and replaces it
13
+ * atomically.
14
+ * @module complete-subagent/host/notes
15
+ */
16
+
17
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
18
+ import { homedir } from 'node:os'
19
+ import { dirname, join } from 'node:path'
20
+
21
+ /** Kinds of work a note gives an effort for. */
22
+ export const WORK_KINDS = ['light', 'normal', 'hard'] as const
23
+
24
+ /** One kind of work. */
25
+ export type WorkKind = typeof WORK_KINDS[number]
26
+
27
+ /** What is known about one model. */
28
+ export interface ModelNote {
29
+ /** `provider/model`, as a parent passes it to `delegate`. */
30
+ readonly model: string
31
+ /** What it does well, in a few phrases. */
32
+ readonly strengths: string
33
+ /** What it does poorly or costs, in a few phrases. */
34
+ readonly weaknesses: string
35
+ /** The effort id that suits each kind of work, for a model with selectable efforts. */
36
+ readonly efforts: Readonly<Partial<Record<WorkKind, string>>>
37
+ /** Where it came from: http(s) URLs. */
38
+ readonly sources: readonly string[]
39
+ /** The day it was recorded, `YYYY-MM-DD` in this computer's zone. */
40
+ readonly checked: string
41
+ }
42
+
43
+ /** The longest strengths or weaknesses text a note keeps. */
44
+ export const NOTE_MAX_CHARS = 600
45
+
46
+ /** The most sources a note keeps. */
47
+ export const NOTE_MAX_SOURCES = 8
48
+
49
+ /** Days after which a note may be out of date. */
50
+ export const STALE_DAYS = 90
51
+
52
+ /**
53
+ * The default notes file, following the host's home rule: `DSH_HOME`, then `~/.dsh`.
54
+ * @param env - environment to read.
55
+ * @returns the absolute path of the JSON file.
56
+ */
57
+ export function defaultNotesFile(env: NodeJS.ProcessEnv = process.env): string {
58
+ const home = env.DSH_HOME !== undefined && env.DSH_HOME !== '' ? env.DSH_HOME : join(homedir(), '.dsh')
59
+ return join(home, 'plugin-data', 'complete-subagent', 'model-notes.json')
60
+ }
61
+
62
+ /**
63
+ * A day as `YYYY-MM-DD` in this computer's zone.
64
+ * @param at - the moment.
65
+ * @returns the date text.
66
+ */
67
+ export function dayOf(at: Date): string {
68
+ const pad = (value: number): string => String(value).padStart(2, '0')
69
+ return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}`
70
+ }
71
+
72
+ /** Read one stored note, or undefined when it is malformed. */
73
+ function readNote(value: unknown): ModelNote | undefined {
74
+ if (typeof value !== 'object' || value === null) return undefined
75
+ const { model, strengths, weaknesses, efforts, sources, checked } = value as Record<string, unknown>
76
+ if (typeof model !== 'string' || !model.includes('/')) return undefined
77
+ if (typeof strengths !== 'string' || typeof weaknesses !== 'string') return undefined
78
+ if (typeof checked !== 'string' || !/^\d{4}-\d{2}-\d{2}$/u.test(checked)) return undefined
79
+ const stored = typeof efforts === 'object' && efforts !== null ? efforts as Record<string, unknown> : {}
80
+ const kept: Partial<Record<WorkKind, string>> = {}
81
+ for (const kind of WORK_KINDS) {
82
+ const effort = stored[kind]
83
+ if (typeof effort === 'string' && effort !== '') kept[kind] = effort
84
+ }
85
+ return {
86
+ model,
87
+ strengths,
88
+ weaknesses,
89
+ efforts: kept,
90
+ sources: Array.isArray(sources) ? sources.filter((source): source is string => typeof source === 'string') : [],
91
+ checked,
92
+ }
93
+ }
94
+
95
+ /** File-backed notes, one per model. */
96
+ export class ModelNotes {
97
+ private cache: Map<string, ModelNote> | undefined
98
+
99
+ /** @param file - the JSON file; created with its folder on first write. */
100
+ constructor(readonly file: string) {}
101
+
102
+ /**
103
+ * The note on one model.
104
+ * @param model - `provider/model`.
105
+ * @returns the stored note, if any.
106
+ */
107
+ get(model: string): ModelNote | undefined {
108
+ this.cache ??= this.load()
109
+ return this.cache.get(model)
110
+ }
111
+
112
+ /**
113
+ * Store a note, replacing any earlier one on the same model. The cache is
114
+ * updated first, so a failed write still shows the note for the life of
115
+ * this process; the failure is rethrown for the caller to report.
116
+ * @param note - the complete note.
117
+ */
118
+ set(note: ModelNote): void {
119
+ const notes = this.load()
120
+ notes.set(note.model, note)
121
+ this.cache = notes
122
+ mkdirSync(dirname(this.file), { recursive: true })
123
+ const temp = `${this.file}.${process.pid}.tmp`
124
+ writeFileSync(temp, `${JSON.stringify({ version: 1, notes: [...notes.values()] }, null, 2)}\n`)
125
+ renameSync(temp, this.file)
126
+ }
127
+
128
+ private load(): Map<string, ModelNote> {
129
+ const notes = new Map<string, ModelNote>()
130
+ let text: string
131
+ try {
132
+ text = readFileSync(this.file, 'utf8')
133
+ } catch {
134
+ return notes
135
+ }
136
+ try {
137
+ const value = JSON.parse(text) as { version?: unknown; notes?: unknown }
138
+ if (value.version !== 1 || !Array.isArray(value.notes)) return notes
139
+ for (const item of value.notes as unknown[]) {
140
+ const note = readNote(item)
141
+ if (note !== undefined) notes.set(note.model, note)
142
+ }
143
+ } catch {
144
+ // A damaged file reads as empty; the next write replaces it.
145
+ }
146
+ return notes
147
+ }
148
+ }