@starsharryzhu/complete-subagent 0.1.0 → 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.
@@ -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,
@@ -29,7 +30,7 @@ import {
29
30
  delegateDescription,
30
31
  } from './prompt.ts'
31
32
  import { DELEGATE_TOOLS } from './types.ts'
32
- import type { AgentLike, DelegateTool, LlmLike, SubagentsLike } from './types.ts'
33
+ import type { AgentLike, DelegateTool, LlmLike, StartRequestLike, SubagentsLike } from './types.ts'
33
34
 
34
35
  /** What the delegation tools read. */
35
36
  export interface DelegateDeps extends AccessDeps {
@@ -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,24 +117,28 @@ 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()
116
124
  deps.store.set({ version: 1, child: childId, parent: parent.session.id, workspace: access.workspace, grants: access.grants })
125
+ const task: StartRequestLike = {
126
+ ...access.cwd === undefined ? {} : { cwd: access.cwd },
127
+ prompt: [{ type: 'text', text: args.prompt }],
128
+ parent,
129
+ ...agentPreset === undefined ? {} : { agentPreset },
130
+ ...route === undefined ? {} : { agentOptions: route },
131
+ ...maxDepth === undefined ? {} : { maxDepth },
132
+ }
117
133
  try {
134
+ // The task goes both ways: hosts from 0.2.2-rc.2 read it at the top level and those before under
135
+ // `request`, and neither reads the other's fields, so one call starts the child on every host.
118
136
  const started = await deps.subagents.startActivation({
119
137
  provider,
120
138
  label: args.description,
121
139
  childId,
122
- request: {
123
- ...access.cwd === undefined ? {} : { cwd: access.cwd },
124
- prompt: [{ type: 'text', text: args.prompt }],
125
- parent,
126
- ...agentPreset === undefined ? {} : { agentPreset },
127
- ...route === undefined ? {} : { agentOptions: route },
128
- ...maxDepth === undefined ? {} : { maxDepth },
129
- },
140
+ ...task,
141
+ request: task,
130
142
  signal: exec.signal,
131
143
  delivery: 'parent',
132
144
  })
@@ -137,22 +149,28 @@ export function createDelegateTool(tool: DelegateTool, models: readonly ChildMod
137
149
  }
138
150
  },
139
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
140
156
  }
141
157
 
142
158
  /**
143
159
  * Whether an agent may delegate on a backend now: the backend is registered
144
- * and the agent is below the user's depth limit. A limit that cannot be read
145
- * 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.
146
163
  * @param subagents - the subagent runtime.
147
164
  * @param tool - which tool.
148
165
  * @param agent - the would-be parent.
166
+ * @param configured - this copy's depth limit; undefined uses the host's setting.
149
167
  * @returns true when the tool should be offered.
150
168
  */
151
- export function canStart(subagents: SubagentsLike, tool: DelegateTool, agent: AgentLike): boolean {
169
+ export function canStart(subagents: SubagentsLike, tool: DelegateTool, agent: AgentLike, configured?: number): boolean {
152
170
  if (subagents.getProvider(DELEGATE_TOOLS[tool]) === undefined) return false
153
- let maxDepth: number | undefined
171
+ let maxDepth: number | undefined = configured
154
172
  try {
155
- maxDepth = subagents.resolveMaxDepth()
173
+ maxDepth ??= subagents.resolveMaxDepth()
156
174
  } catch {
157
175
  return true
158
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
+ }