@starsharryzhu/complete-subagent 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.
Files changed (68) hide show
  1. package/AGENTS.md +58 -0
  2. package/LICENSE +21 -0
  3. package/README.md +168 -2
  4. package/cordis.patch.yml +11 -0
  5. package/lib/client.js +439 -0
  6. package/lib/client.modules.txt +8 -0
  7. package/lib/host/access.d.ts +46 -0
  8. package/lib/host/access.js +54 -0
  9. package/lib/host/call-scope.d.ts +21 -0
  10. package/lib/host/call-scope.js +26 -0
  11. package/lib/host/delegate.d.ts +47 -0
  12. package/lib/host/delegate.js +133 -0
  13. package/lib/host/grants.d.ts +51 -0
  14. package/lib/host/grants.js +62 -0
  15. package/lib/host/legacy.d.ts +57 -0
  16. package/lib/host/legacy.js +85 -0
  17. package/lib/host/models.d.ts +59 -0
  18. package/lib/host/models.js +139 -0
  19. package/lib/host/paths.d.ts +51 -0
  20. package/lib/host/paths.js +100 -0
  21. package/lib/host/policy.d.ts +72 -0
  22. package/lib/host/policy.js +169 -0
  23. package/lib/host/prompt.d.ts +41 -0
  24. package/lib/host/prompt.js +100 -0
  25. package/lib/host/requests.d.ts +82 -0
  26. package/lib/host/requests.js +109 -0
  27. package/lib/host/scope.d.ts +33 -0
  28. package/lib/host/scope.js +46 -0
  29. package/lib/host/store.d.ts +89 -0
  30. package/lib/host/store.js +128 -0
  31. package/lib/host/tools.d.ts +58 -0
  32. package/lib/host/tools.js +298 -0
  33. package/lib/host/types.d.ts +184 -0
  34. package/lib/host/types.js +26 -0
  35. package/lib/index.d.ts +55 -0
  36. package/lib/index.js +245 -0
  37. package/lib/shared/settings.d.ts +69 -0
  38. package/lib/shared/settings.js +86 -0
  39. package/locale/AGENTS.md +22 -0
  40. package/locale/en.json +6 -0
  41. package/locale/zh.json +6 -0
  42. package/package.json +95 -4
  43. package/src/AGENTS.md +26 -0
  44. package/src/client/AGENTS.md +28 -0
  45. package/src/client/css.d.ts +5 -0
  46. package/src/client/host.ts +82 -0
  47. package/src/client/index.ts +81 -0
  48. package/src/client/locales.ts +61 -0
  49. package/src/client/settings.tsx +222 -0
  50. package/src/client/styles.css +44 -0
  51. package/src/host/AGENTS.md +53 -0
  52. package/src/host/access.ts +82 -0
  53. package/src/host/call-scope.ts +31 -0
  54. package/src/host/delegate.ts +166 -0
  55. package/src/host/grants.ts +82 -0
  56. package/src/host/legacy.ts +86 -0
  57. package/src/host/models.ts +155 -0
  58. package/src/host/paths.ts +100 -0
  59. package/src/host/policy.ts +169 -0
  60. package/src/host/prompt.ts +113 -0
  61. package/src/host/requests.ts +149 -0
  62. package/src/host/scope.ts +54 -0
  63. package/src/host/store.ts +159 -0
  64. package/src/host/tools.ts +318 -0
  65. package/src/host/types.ts +192 -0
  66. package/src/index.ts +316 -0
  67. package/src/shared/AGENTS.md +20 -0
  68. package/src/shared/settings.ts +104 -0
@@ -0,0 +1,22 @@
1
+ # AGENTS.md
2
+
3
+ ## 1. Role
4
+
5
+ Plugin metadata the host's Plugins page reads through the package export `./locale/*.json`: the title and one-sentence description of the plugin in each supported language. The settings page's own copy is not here; it ships inside the browser half (`src/client/locales.ts`) and is registered with the page's locale service when the browser half loads.
6
+
7
+ ## 2. Constraints
8
+
9
+ - Each file holds only `meta.title` and `meta.description`.
10
+ - The titles are pinned by `tests/manifest.test.ts`: "Complete Subagent" in English and its Chinese name in Chinese.
11
+ - English and Chinese say the same thing.
12
+
13
+ ## 3. Contents
14
+
15
+ - `en.json` — English title and description.
16
+ - `zh.json` — Chinese title and description.
17
+
18
+ ## 4. Progress
19
+
20
+ - Done: both languages.
21
+ - Open: nothing.
22
+ - Goal later: nothing planned.
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Complete Subagent",
4
+ "description": "Standalone delegation tools delegate and delegate_fork: the cwd a parent passes is the only place the child may modify, writable_paths grants more up front, and anything else the child must ask its parent for. The parent can also choose the child's model and reasoning effort from those listed in the settings."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "完全子代理",
4
+ "description": "独立的子代理工具 delegate / delegate_fork:父代理传的 cwd 是子代理唯一能改的子工作区,writable_paths 可预先授权更多路径,其他地方要先向父代理申请;父代理还能从设置里列出的模型和推理强度中给子代理选。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,97 @@
1
1
  {
2
2
  "name": "@starsharryzhu/complete-subagent",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
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
+ "keywords": [
6
+ "dsh-plugin",
7
+ "deepseek-harness",
8
+ "subagent",
9
+ "sandbox",
10
+ "permissions",
11
+ "reasoning-effort"
12
+ ],
13
+ "author": "Starfield (https://github.com/StarsHarryZhu)",
14
+ "type": "module",
15
+ "main": "lib/index.js",
16
+ "types": "lib/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./lib/index.d.ts",
20
+ "default": "./lib/index.js"
21
+ },
22
+ "./client": {
23
+ "default": "./lib/client.js"
24
+ },
25
+ "./locale/*.json": "./locale/*.json",
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "lib",
30
+ "src",
31
+ "cordis.patch.yml",
32
+ "locale/*.json",
33
+ "README.md",
34
+ "AGENTS.md",
35
+ "LICENSE"
36
+ ],
37
+ "scripts": {
38
+ "link-dev": "node scripts/link-dev.mjs",
39
+ "build": "node build.js",
40
+ "typecheck": "node node_modules/typescript/bin/tsc --noEmit -p tsconfig.json && node node_modules/typescript/bin/tsc --noEmit -p tsconfig.client.json",
41
+ "test": "node build.js && node node_modules/vitest/vitest.mjs run"
42
+ },
43
+ "dependencies": {},
44
+ "devDependencies": {
45
+ "@deepseek-ai/cordis": "^4.0.2",
46
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.5 <0.3.0-0",
47
+ "@deepseek-ai/schemastery": "^3.18.5",
48
+ "@testing-library/dom": "^10.4.2",
49
+ "@testing-library/react": "^16.3.3",
50
+ "@types/node": "^22.20.1",
51
+ "@types/react": "~18.3.31",
52
+ "@types/react-dom": "~18.3.7",
53
+ "jsdom": "^29.1.1",
54
+ "react": "^18.3.1",
55
+ "react-dom": "^18.3.1",
56
+ "typescript": "^6.0.3",
57
+ "vitest": "^4.1.11"
58
+ },
59
+ "peerDependencies": {
60
+ "@deepseek-ai/cordis": "^4.0.2",
61
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.5 <0.3.0-0",
62
+ "@deepseek-ai/schemastery": "^3.18.5"
63
+ },
64
+ "dsh": {
65
+ "manifestVersion": 1,
66
+ "bundle": {
67
+ "patch": "./cordis.patch.yml"
68
+ },
69
+ "client": {
70
+ "platform": "web",
71
+ "inject": [
72
+ "@deepseek-ai/dsh-client-ui-slots",
73
+ "@deepseek-ai/dsh-client-locale",
74
+ "@deepseek-ai/dsh-client-ui-plugin-manager",
75
+ "@deepseek-ai/dsh-client-ui-settings",
76
+ "@deepseek-ai/dsh-api-remotes"
77
+ ]
78
+ }
79
+ },
80
+ "engines": {
81
+ "node": "^22.19.0 || >=24.0.0",
82
+ "dsh": ">=0.2.1-rc.5 <0.3.0-0"
83
+ },
84
+ "publishConfig": {
85
+ "access": "public",
86
+ "tag": "latest"
87
+ },
88
+ "repository": {
89
+ "type": "git",
90
+ "url": "git+https://github.com/StarsHarryZhu/complete-subagent.git"
91
+ },
92
+ "homepage": "https://github.com/StarsHarryZhu/complete-subagent#readme",
93
+ "bugs": {
94
+ "url": "https://github.com/StarsHarryZhu/complete-subagent/issues"
95
+ },
96
+ "license": "MIT"
97
+ }
package/src/AGENTS.md ADDED
@@ -0,0 +1,26 @@
1
+ # AGENTS.md
2
+
3
+ ## 1. Role
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.
6
+
7
+ ## 2. Constraints
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.
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
+ - 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
+ - `host/` never imports from `client/`, and `client/` never imports from `host/`; both may import `shared/`.
13
+ - Source files import siblings with `.ts` specifiers; the build rewrites them.
14
+
15
+ ## 3. Contents
16
+
17
+ - `index.ts` — the host entry: services, live settings, the `completeSubagent` service, and wiring.
18
+ - `host` — the fence, delegation, access, model choice, grants, requests, tools, prompts, storage, and path helpers.
19
+ - `client` — the settings page on the Plugins screen.
20
+ - `shared` — the settings shape and readers used by both halves.
21
+
22
+ ## 4. Progress
23
+
24
+ - 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.
25
+ - Open: nothing.
26
+ - Goal later: nothing planned.
@@ -0,0 +1,28 @@
1
+ # AGENTS.md
2
+
3
+ ## 1. Role
4
+
5
+ The browser half: one settings page on the Plugins screen, registered as the `plugins.bundle.config` entry for this package. It edits the host half's live settings, the models a parent may choose for a child with the reasoning efforts each allows and the write-access answer time, through the host's settings form for the `complete-subagent` profile entry. Models are added from the same catalog the model picker reads, and each model's efforts are checkboxes over what the catalog advertises.
6
+
7
+ ## 2. Constraints
8
+
9
+ - Import no harness package, not even for types: every host shape is a structural mirror in `host.ts`, with every field optional so an older host degrades instead of throwing.
10
+ - Runtime imports are only `react` and `react/jsx-runtime`; the build fails on anything else from outside the bundle.
11
+ - Saving writes only the changed fields, fenced by the revision the draft was read at, so `presets` and `childPreset`, which the page never shows, survive a save.
12
+ - A saved model the catalog no longer lists stays, marked unavailable, until the user removes it.
13
+ - Copy lives in `locales.ts` in Chinese and English; class names start with `complete-subagent-`.
14
+
15
+ ## 3. Contents
16
+
17
+ - `index.ts` — the browser entry: dictionaries, stylesheet, model catalog access, and the settings page registration.
18
+ - `host.ts` — structural mirrors of the slot, locale, settings form, and catalog services.
19
+ - `settings.tsx` — the settings page and its summary line.
20
+ - `locales.ts` — the page copy in Chinese and English.
21
+ - `styles.css` — the page stylesheet over the host's design tokens.
22
+ - `css.d.ts` — the type of the inlined stylesheet module.
23
+
24
+ ## 4. Progress
25
+
26
+ - Done: the page renders, adds and removes models, limits efforts, edits the answer time, and saves; covered by `tests/client.test.tsx` against the built bundle.
27
+ - Open: not yet checked in the real web app.
28
+ - Goal later: nothing planned.
@@ -0,0 +1,5 @@
1
+ /** The build inlines `styles.css` as one string module; this is its type. */
2
+ declare module '*.css' {
3
+ const text: string
4
+ export default text
5
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The slice of host slot props and services the browser half reads, as
3
+ * structural types. The browser half imports no harness package, not even for
4
+ * types; every field is optional because an older host or another composition
5
+ * may leave any of them out, and the page must degrade, not throw.
6
+ * @module complete-subagent/client/host
7
+ */
8
+
9
+ /** Bound translator for this plugin's namespace. */
10
+ export type Translate = (key: string, params?: Record<string, unknown>) => string
11
+
12
+ /** Props of a `plugins.bundle.config` entry. */
13
+ export interface ConfigViewProps {
14
+ view?: 'summary' | 'page'
15
+ t?: Translate
16
+ }
17
+
18
+ /** A settings path edit (`SettingsPathOpView`). */
19
+ export type PathOp = { op: 'set'; path: string[]; value: unknown } | { op: 'unset'; path: string[] }
20
+
21
+ /** One snapshot of a settings form (`ConfigFormSnapshot`). */
22
+ export interface FormSnapshotLike {
23
+ readonly status?: 'loading' | 'ready' | 'unavailable'
24
+ readonly value?: Record<string, unknown>
25
+ readonly revision?: number
26
+ readonly writable?: boolean
27
+ }
28
+
29
+ /** One settings form (`ConfigForm`). */
30
+ export interface ConfigFormLike {
31
+ getSnapshot(): FormSnapshotLike
32
+ subscribe(listener: () => void): () => void
33
+ mutate(ops: readonly PathOp[], expectedRevision?: number): Promise<boolean>
34
+ }
35
+
36
+ /** A remote call result (`RemoteResult`). */
37
+ export interface RemoteResultLike<T> {
38
+ readonly ok: boolean
39
+ readonly value?: T
40
+ }
41
+
42
+ /** One model of the catalog (`ModelCatalogModel`). */
43
+ export interface CatalogModel {
44
+ readonly id: string
45
+ readonly name?: string
46
+ readonly reasoning?: { readonly efforts?: readonly { id: string; name?: string }[]; readonly defaultEffort?: string }
47
+ }
48
+
49
+ /** One provider group of the catalog. */
50
+ export interface CatalogGroup {
51
+ readonly id: string
52
+ readonly name?: string
53
+ readonly models: readonly CatalogModel[]
54
+ }
55
+
56
+ /** `ctx.remote.session`, reduced to the model catalog the model picker also reads. */
57
+ export interface RemoteSessionLike {
58
+ modelCatalog(): Promise<RemoteResultLike<{ groups: readonly CatalogGroup[] }>>
59
+ }
60
+
61
+ /** The client context services the browser half uses. */
62
+ export interface ClientContextLike {
63
+ get?(name: string): unknown
64
+ effect?(execute: () => (() => void) | void, label?: string): unknown
65
+ inject?(deps: string[], callback: (scope: ClientContextLike) => void): unknown
66
+ }
67
+
68
+ /** The slot registry service. */
69
+ export interface SlotsLike {
70
+ inject(name: string, callback: () => (() => void) | void): unknown
71
+ register(options: Record<string, unknown>, component: unknown): () => void
72
+ }
73
+
74
+ /** The locale service. */
75
+ export interface LocaleLike {
76
+ register(namespace: string, dictionaries: Record<string, Record<string, string>>): () => void
77
+ }
78
+
79
+ /** The settings forms service. */
80
+ export interface ConfigFormsLike {
81
+ get(entryId: string): ConfigFormLike
82
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * complete-subagent browser half: the settings page on the Plugins screen, its
3
+ * copy, and one stylesheet. Each is an effect of this plugin's context and is
4
+ * skipped (logged) if its host seat is missing.
5
+ * @module complete-subagent/client
6
+ */
7
+
8
+ import { PACKAGE_NAME, PLUGIN_ID } from '../shared/settings.ts'
9
+ import type { ClientContextLike, ConfigFormsLike, LocaleLike, RemoteSessionLike, SlotsLike } from './host.ts'
10
+ import { en, zh } from './locales.ts'
11
+ import { createSettings } from './settings.tsx'
12
+ import css from './styles.css'
13
+
14
+ export const name = PACKAGE_NAME
15
+ export const inject = ['slots', 'locale']
16
+
17
+ /**
18
+ * Register the browser contributions.
19
+ * @param ctx - the plugin's client context.
20
+ */
21
+ export function apply(ctx: ClientContextLike): void {
22
+ const slots = ctx.get?.('slots') as SlotsLike | undefined
23
+ const locale = ctx.get?.('locale') as LocaleLike | undefined
24
+ if (slots === undefined) {
25
+ console.error(`${PLUGIN_ID}: the slots service is missing, so the settings page cannot render`)
26
+ return
27
+ }
28
+ // The remote session namespace is its own service and must be injected before use.
29
+ let session: RemoteSessionLike | undefined
30
+ const getSession = (): RemoteSessionLike | undefined => session
31
+
32
+ guard('dictionaries', () => {
33
+ if (locale !== undefined) ctx.effect?.(() => locale.register(PACKAGE_NAME, { zh, en }), `${PLUGIN_ID}: dictionaries`)
34
+ })
35
+ guard('styles', () => {
36
+ ctx.effect?.(() => mountStyles(css), `${PLUGIN_ID}: styles`)
37
+ })
38
+ guard('remote', () => {
39
+ ctx.inject?.(['remote', 'remote.session'], (scope) => {
40
+ const service = (scope.get?.('remote') as { session?: RemoteSessionLike } | undefined)?.session
41
+ session = service
42
+ scope.effect?.(() => () => { if (session === service) session = undefined }, `${PLUGIN_ID}: remote session`)
43
+ })
44
+ })
45
+ guard('settings', () => {
46
+ ctx.inject?.(['configForms'], (scope) => {
47
+ const forms = scope.get?.('configForms') as ConfigFormsLike | undefined
48
+ const scopedSlots = (scope.get?.('slots') as SlotsLike | undefined) ?? slots
49
+ if (forms === undefined) return
50
+ const Settings = createSettings(forms.get(PLUGIN_ID), getSession)
51
+ scopedSlots.inject('plugins.bundle.config', () => scopedSlots.register(
52
+ { name: 'plugins.bundle.config', key: PACKAGE_NAME, locale: PACKAGE_NAME },
53
+ Settings,
54
+ ))
55
+ })
56
+ })
57
+ }
58
+
59
+ /** Run one contribution, logging instead of throwing: a throw here fails the page's boot. */
60
+ function guard(label: string, run: () => void): void {
61
+ try {
62
+ run()
63
+ } catch (error) {
64
+ console.error(`${PLUGIN_ID}: the ${label} could not be registered`, error)
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Add the plugin's stylesheet, tagged with the plugin id.
70
+ * @param text - the stylesheet.
71
+ * @returns the cleanup that removes it.
72
+ */
73
+ function mountStyles(text: string): () => void {
74
+ if (typeof document === 'undefined') return () => undefined
75
+ const style = document.createElement('style')
76
+ style.setAttribute('data-plugin', PACKAGE_NAME)
77
+ style.setAttribute('data-plugin-css', `${PACKAGE_NAME}/styles.css`)
78
+ style.textContent = text
79
+ document.head.appendChild(style)
80
+ return () => { style.remove() }
81
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Settings page copy.
3
+ * @module complete-subagent/client/locales
4
+ */
5
+
6
+ export const zh: Record<string, string> = {
7
+ 'settings.summary.none': '子代理只用父代理自己的模型',
8
+ 'settings.summary.some': '可为子代理选择 {count} 个模型',
9
+ 'settings.models': '可选的子代理模型',
10
+ 'settings.models.hint': '父代理派生子代理时,只能从这里选模型。父代理自己的模型总能用:不在列表里时可选它支持的全部推理强度,在列表里就只能选勾选的强度。',
11
+ 'settings.models.empty': '还没有添加模型,子代理只用父代理自己的模型,推理强度可以调。',
12
+ 'settings.efforts': '允许的推理强度',
13
+ 'settings.efforts.all': '不勾选就是全部',
14
+ 'settings.efforts.none': '这个模型没有可选的推理强度',
15
+ 'settings.unavailable': '当前不可用',
16
+ 'settings.remove': '移除',
17
+ 'settings.add': '添加',
18
+ 'settings.add.placeholder': '选择要添加的模型',
19
+ 'settings.timeout': '写入申请的等待时间(秒)',
20
+ 'settings.timeout.hint': '子代理申请写入后,父代理超过这个时间没回复就按拒绝处理。最少 {min} 秒。',
21
+ 'settings.save': '保存',
22
+ 'settings.saved': '已保存,AI 的下一步起生效',
23
+ 'settings.failed': '保存失败,请重试。',
24
+ 'settings.readonly': '当前配置文件不可写。',
25
+ 'settings.loading': '正在读取…',
26
+ 'settings.catalogFailed': '读取模型列表失败,已保存的模型仍会保留。',
27
+ }
28
+
29
+ export const en: Record<string, string> = {
30
+ 'settings.summary.none': 'Children use their parent\'s model',
31
+ 'settings.summary.some': '{count} models to choose for children',
32
+ 'settings.models': 'Models for subagents',
33
+ 'settings.models.hint': 'A parent can choose a child\'s model only from this list. Its own model is always available: with every effort it supports when it is not listed, with the checked efforts when it is.',
34
+ 'settings.models.empty': 'No models yet: children use their parent\'s model, and the parent can still set the reasoning effort.',
35
+ 'settings.efforts': 'Allowed reasoning efforts',
36
+ 'settings.efforts.all': 'None checked means all',
37
+ 'settings.efforts.none': 'This model has no selectable reasoning effort',
38
+ 'settings.unavailable': 'Unavailable',
39
+ 'settings.remove': 'Remove',
40
+ 'settings.add': 'Add',
41
+ 'settings.add.placeholder': 'Choose a model to add',
42
+ 'settings.timeout': 'Write-access answer time (seconds)',
43
+ 'settings.timeout.hint': 'A request the parent does not answer within this time counts as denied. At least {min} seconds.',
44
+ 'settings.save': 'Save',
45
+ 'settings.saved': 'Saved; it applies from the next step',
46
+ 'settings.failed': 'Saving failed. Try again.',
47
+ 'settings.readonly': 'The profile is read-only.',
48
+ 'settings.loading': 'Loading…',
49
+ 'settings.catalogFailed': 'The model list could not be loaded; saved models are kept.',
50
+ }
51
+
52
+ /**
53
+ * Translator used when the locale service is missing.
54
+ * @param key - message key.
55
+ * @param params - interpolation values.
56
+ * @returns the English text.
57
+ */
58
+ export function fallbackT(key: string, params?: Record<string, unknown>): string {
59
+ const text = en[key] ?? key
60
+ return params === undefined ? text : text.replace(/\{(\w+)\}/gu, (match, name: string) => (name in params ? String(params[name]) : match))
61
+ }
@@ -0,0 +1,222 @@
1
+ /**
2
+ * The plugin's settings page on the Plugins screen.
3
+ *
4
+ * Edits the host half's live config (`models`, `requestTimeoutSeconds`)
5
+ * through the host's settings form for the `complete-subagent` profile entry.
6
+ * Models are added from the same catalog the model picker uses; each one's
7
+ * efforts are checkboxes over what the catalog advertises. A saved model the
8
+ * catalog no longer lists stays, marked unavailable, until it is removed.
9
+ * @module complete-subagent/client/settings
10
+ */
11
+
12
+ import { useEffect, useState, useSyncExternalStore, type ReactNode } from 'react'
13
+ import { MIN_TIMEOUT_SECONDS, modelKey, readModels, readTimeout } from '../shared/settings.ts'
14
+ import type { ChildModel } from '../shared/settings.ts'
15
+ import type { CatalogGroup, CatalogModel, ConfigFormLike, ConfigViewProps, PathOp, RemoteSessionLike, Translate } from './host.ts'
16
+ import { fallbackT } from './locales.ts'
17
+
18
+ /** The edited values. */
19
+ interface Values {
20
+ readonly models: readonly ChildModel[]
21
+ readonly requestTimeoutSeconds: number
22
+ }
23
+
24
+ /**
25
+ * Read form values with defaults.
26
+ * @param value - the form's accepted section.
27
+ * @returns complete values.
28
+ */
29
+ export function readValues(value: Record<string, unknown> | undefined): Values {
30
+ return { models: readModels(value?.models), requestTimeoutSeconds: readTimeout(value?.requestTimeoutSeconds) }
31
+ }
32
+
33
+ /**
34
+ * The edits that turn the stored values into the draft.
35
+ * @param stored - the saved values.
36
+ * @param draft - the edited values.
37
+ * @returns one `set` per changed field.
38
+ */
39
+ export function changes(stored: Values, draft: Values): PathOp[] {
40
+ const ops: PathOp[] = []
41
+ if (JSON.stringify(draft.models) !== JSON.stringify(stored.models)) {
42
+ ops.push({ op: 'set', path: ['models'], value: draft.models.map(entry => ({ ...entry, reasoningEfforts: [...entry.reasoningEfforts] })) })
43
+ }
44
+ if (draft.requestTimeoutSeconds !== stored.requestTimeoutSeconds) {
45
+ ops.push({ op: 'set', path: ['requestTimeoutSeconds'], value: draft.requestTimeoutSeconds })
46
+ }
47
+ return ops
48
+ }
49
+
50
+ /** One catalog model with its provider. */
51
+ interface Listed {
52
+ readonly group: CatalogGroup
53
+ readonly model: CatalogModel
54
+ }
55
+
56
+ /**
57
+ * Build the settings component over the form and the catalog.
58
+ * @param form - the `complete-subagent` settings form.
59
+ * @param getSession - the live `ctx.remote.session`, for the model catalog.
60
+ * @returns the `plugins.bundle.config` entry.
61
+ */
62
+ export function createSettings(form: ConfigFormLike, getSession: () => RemoteSessionLike | undefined) {
63
+ // The host form is a class instance: keep its methods bound.
64
+ const subscribe = (listener: () => void) => form.subscribe(listener)
65
+ const getSnapshot = () => form.getSnapshot()
66
+ return function CompleteSubagentSettings(props: ConfigViewProps): ReactNode {
67
+ const t = props.t ?? fallbackT
68
+ const snapshot = useSyncExternalStore(subscribe, getSnapshot)
69
+ const stored = readValues(snapshot.value)
70
+ if (props.view === 'summary') {
71
+ return stored.models.length === 0 ? t('settings.summary.none') : t('settings.summary.some', { count: stored.models.length })
72
+ }
73
+ return <SettingsPage form={form} stored={stored} ready={snapshot.status === 'ready'} writable={snapshot.writable !== false}
74
+ revision={snapshot.revision} getSession={getSession} t={t} />
75
+ }
76
+ }
77
+
78
+ function SettingsPage(props: {
79
+ form: ConfigFormLike
80
+ stored: Values
81
+ ready: boolean
82
+ writable: boolean
83
+ revision: number | undefined
84
+ getSession: () => RemoteSessionLike | undefined
85
+ t: Translate
86
+ }): ReactNode {
87
+ const { t, stored } = props
88
+ const [draft, setDraft] = useState<Values>(stored)
89
+ const [status, setStatus] = useState<'idle' | 'saving' | 'saved' | 'failed'>('idle')
90
+ const [groups, setGroups] = useState<readonly CatalogGroup[]>()
91
+ const [catalogFailed, setCatalogFailed] = useState(false)
92
+ const [adding, setAdding] = useState('')
93
+ const storedKey = JSON.stringify(stored)
94
+ // Re-seed the draft only when the stored values change, not on every render.
95
+ useEffect(() => { setDraft(stored) }, [storedKey])
96
+
97
+ useEffect(() => {
98
+ let live = true
99
+ const catalog = props.getSession()?.modelCatalog()
100
+ if (catalog === undefined) {
101
+ setCatalogFailed(true)
102
+ return
103
+ }
104
+ catalog.then((response) => {
105
+ if (!live) return
106
+ if (response.ok && response.value) setGroups(response.value.groups)
107
+ else setCatalogFailed(true)
108
+ }, () => { if (live) setCatalogFailed(true) })
109
+ return () => { live = false }
110
+ }, [props.getSession])
111
+
112
+ if (!props.ready) return <p className="complete-subagent-note">{t('settings.loading')}</p>
113
+ const listed: Listed[] = (groups ?? []).flatMap(group => group.models.map(model => ({ group, model })))
114
+ const find = (entry: { provider: string; model: string }) => listed.find(item => item.group.id === entry.provider && item.model.id === entry.model)
115
+ const chosen = new Set(draft.models.map(modelKey))
116
+ const addable = listed.filter(item => !chosen.has(modelKey({ provider: item.group.id, model: item.model.id })))
117
+ const ops = changes(stored, draft)
118
+ const disabled = !props.writable || status === 'saving'
119
+ const update = (patch: Partial<Values>) => {
120
+ setDraft(value => ({ ...value, ...patch }))
121
+ setStatus('idle')
122
+ }
123
+ const setModels = (models: readonly ChildModel[]) => update({ models })
124
+ const save = async () => {
125
+ setStatus('saving')
126
+ try {
127
+ setStatus(await props.form.mutate(ops, props.revision) ? 'saved' : 'failed')
128
+ } catch {
129
+ setStatus('failed')
130
+ }
131
+ }
132
+ const add = () => {
133
+ const item = addable.find(candidate => modelKey({ provider: candidate.group.id, model: candidate.model.id }) === adding)
134
+ if (item === undefined) return
135
+ setModels([...draft.models, { provider: item.group.id, model: item.model.id, reasoningEfforts: [] }])
136
+ setAdding('')
137
+ }
138
+ return (
139
+ <div className="complete-subagent-settings">
140
+ <section className="complete-subagent-section">
141
+ <h3>{t('settings.models')}</h3>
142
+ <p className="complete-subagent-note">{t('settings.models.hint')}</p>
143
+ {draft.models.length === 0 && <p className="complete-subagent-note">{t('settings.models.empty')}</p>}
144
+ <ul className="complete-subagent-models">
145
+ {draft.models.map((entry, index) => {
146
+ const item = find(entry)
147
+ const advertised = item?.model.reasoning?.efforts ?? []
148
+ const extra = entry.reasoningEfforts.filter(effort => !advertised.some(option => option.id === effort)).map(id => ({ id, name: id }))
149
+ const options = [...advertised, ...extra]
150
+ const toggle = (effort: string) => {
151
+ const next = entry.reasoningEfforts.includes(effort)
152
+ ? entry.reasoningEfforts.filter(value => value !== effort)
153
+ : options.map(option => option.id).filter(id => id === effort || entry.reasoningEfforts.includes(id))
154
+ setModels(draft.models.map((value, at) => (at === index ? { ...value, reasoningEfforts: next } : value)))
155
+ }
156
+ return (
157
+ <li key={modelKey(entry)} className="complete-subagent-model">
158
+ <div className="complete-subagent-model-head">
159
+ <span className="complete-subagent-model-name">{item?.model.name ?? entry.model}</span>
160
+ <code>{modelKey(entry)}</code>
161
+ {item === undefined && groups !== undefined && <span className="complete-subagent-tag">{t('settings.unavailable')}</span>}
162
+ <button type="button" className="complete-subagent-button" disabled={disabled}
163
+ onClick={() => setModels(draft.models.filter((_, at) => at !== index))}>
164
+ {t('settings.remove')}
165
+ </button>
166
+ </div>
167
+ {options.length === 0
168
+ ? <p className="complete-subagent-note">{t('settings.efforts.none')}</p>
169
+ : (
170
+ <fieldset className="complete-subagent-efforts" disabled={disabled}>
171
+ <legend>{t('settings.efforts')}<span className="complete-subagent-note">{t('settings.efforts.all')}</span></legend>
172
+ {options.map(option => (
173
+ <label key={option.id} className="complete-subagent-check">
174
+ <input type="checkbox" checked={entry.reasoningEfforts.includes(option.id)} onChange={() => toggle(option.id)} />
175
+ {option.name ?? option.id}
176
+ </label>
177
+ ))}
178
+ </fieldset>
179
+ )}
180
+ </li>
181
+ )
182
+ })}
183
+ </ul>
184
+ <div className="complete-subagent-add">
185
+ <select value={adding} disabled={disabled || addable.length === 0} onChange={event => setAdding(event.target.value)}
186
+ aria-label={t('settings.add.placeholder')}>
187
+ <option value="">{t('settings.add.placeholder')}</option>
188
+ {(groups ?? []).map(group => {
189
+ const models = addable.filter(item => item.group === group)
190
+ if (models.length === 0) return null
191
+ return (
192
+ <optgroup key={group.id} label={group.name ?? group.id}>
193
+ {models.map(item => (
194
+ <option key={item.model.id} value={modelKey({ provider: group.id, model: item.model.id })}>{item.model.name ?? item.model.id}</option>
195
+ ))}
196
+ </optgroup>
197
+ )
198
+ })}
199
+ </select>
200
+ <button type="button" className="complete-subagent-button" disabled={disabled || adding === ''} onClick={add}>{t('settings.add')}</button>
201
+ </div>
202
+ {catalogFailed && <p className="complete-subagent-note">{t('settings.catalogFailed')}</p>}
203
+ </section>
204
+ <section className="complete-subagent-section">
205
+ <label className="complete-subagent-field">
206
+ <span>{t('settings.timeout')}</span>
207
+ <input type="number" min={MIN_TIMEOUT_SECONDS} step={1} value={draft.requestTimeoutSeconds} disabled={disabled}
208
+ onChange={event => update({ requestTimeoutSeconds: Math.max(MIN_TIMEOUT_SECONDS, Math.round(Number(event.target.value) || MIN_TIMEOUT_SECONDS)) })} />
209
+ </label>
210
+ <p className="complete-subagent-note">{t('settings.timeout.hint', { min: MIN_TIMEOUT_SECONDS })}</p>
211
+ </section>
212
+ {!props.writable && <p className="complete-subagent-note">{t('settings.readonly')}</p>}
213
+ <div className="complete-subagent-actions">
214
+ <button type="button" className="complete-subagent-button" data-primary disabled={disabled || ops.length === 0} onClick={() => void save()}>
215
+ {t('settings.save')}
216
+ </button>
217
+ {status === 'saved' && <span className="complete-subagent-note">{t('settings.saved')}</span>}
218
+ {status === 'failed' && <span className="complete-subagent-error">{t('settings.failed')}</span>}
219
+ </div>
220
+ </div>
221
+ )
222
+ }