diff --git a/README.ja.md b/README.ja.md index d62ee95..108a688 100644 --- a/README.ja.md +++ b/README.ja.md @@ -97,7 +97,7 @@ DeepSeek Harness(DSH)で、プロンプトキャッシュが切れた古い ## 設定 -プロファイルの `cordis.patch.yml` で設定を変更できます。省略した項目には既定値が使われます。 +Web UI のプラグインのページ(サイドバーの「プラグイン」→「cache-sentinel」)か、プロファイルの `cordis.patch.yml` で設定を変更できます。省略した項目には既定値が使われます。 ```yaml - id: cache-sentinel @@ -114,7 +114,8 @@ DeepSeek Harness(DSH)で、プロンプトキャッシュが切れた古い # stateFile: /path/to/state.json # 永続状態ファイルのパス(既定: $DSH_HOME/cache-sentinel/profiles/<プロファイル名>/state.json) ``` -- `cordis.patch.yml` の設定変更は DSH の再起動なしで反映されます(プラグインが新しい設定で再適用され、メモリ上の `/unlock` の許可は消えます)。 +- プラグインのページには `stateFile` 以外の項目が並びます。「保存」でプロファイルの `cordis.patch.yml` に書き込まれます。範囲外や整数でない値は保存できません。 +- 設定の変更は DSH の再起動なしで反映されます。`stateFile` 以外は動いているプラグインにそのまま反映されます(メモリ上の `/unlock` の許可は残ります)。`stateFile` を変えるとプラグインが新しい設定で再適用され、メモリ上の `/unlock` の許可は消えます。 - 未知のキーや型・範囲が不正な値を指定した場合はエラーになります。 ## 仕組み diff --git a/README.md b/README.md index b367936..6dbbd85 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ The argument is optional. After you type `/sentinel ` in the input box, the choi ## Configuration -You can change the settings in your profile's `cordis.patch.yml`. Omitted keys use their default values. +You can change the settings on the plugin's page in the Web UI (sidebar **Plugins** → **cache-sentinel**), or in your profile's `cordis.patch.yml`. Omitted keys use their default values. ```yaml - id: cache-sentinel @@ -114,7 +114,8 @@ You can change the settings in your profile's `cordis.patch.yml`. Omitted keys u # stateFile: /path/to/state.json # path to persistent state file (default: $DSH_HOME/cache-sentinel/profiles//state.json) ``` -- Changes to `cordis.patch.yml` take effect without restarting DSH (the plugin is re-applied with the new settings, and in-memory `/unlock` permissions are cleared). +- The plugin page shows every key except `stateFile`. **Save** writes the values to the profile's `cordis.patch.yml`; values that are out of range or not integers cannot be saved. +- Changes take effect without restarting DSH. Keys other than `stateFile` are applied to the running plugin as they are (in-memory `/unlock` permissions are kept). Changing `stateFile` re-applies the plugin with the new settings, which clears in-memory `/unlock` permissions. - Specifying unknown keys or values with invalid types or ranges results in an error. ## How It Works diff --git a/README.zh-CN.md b/README.zh-CN.md index c6e80c6..bc02cc2 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -97,7 +97,7 @@ DeepSeek Harness(DSH)插件,用于防止误向提示缓存(Prompt Cache ## 设置 -可在配置文件的 `cordis.patch.yml` 中修改设置。省略的项将使用默认值。 +可在 Web UI 的插件页面(侧边栏「插件」→「cache-sentinel」)或配置文件的 `cordis.patch.yml` 中修改设置。省略的项将使用默认值。 ```yaml - id: cache-sentinel @@ -114,7 +114,8 @@ DeepSeek Harness(DSH)插件,用于防止误向提示缓存(Prompt Cache # stateFile: /path/to/state.json # 持久化状态文件路径(默认: $DSH_HOME/cache-sentinel/profiles/<配置文件>/state.json) ``` -- `cordis.patch.yml` 的设置修改无需重启 DSH 即可生效(插件会以新设置重新应用,内存中的 `/unlock` 许可会被清除)。 +- 插件页面列出除 `stateFile` 以外的所有项。点击「保存」会写入配置文件的 `cordis.patch.yml`;超出范围或不是整数的值无法保存。 +- 设置修改无需重启 DSH 即可生效。`stateFile` 以外的项会直接应用到正在运行的插件(内存中的 `/unlock` 许可会保留)。修改 `stateFile` 时插件会以新设置重新应用,内存中的 `/unlock` 许可会被清除。 - 指定未知键名或类型、范围无效的值时会报错。 ## 工作原理 diff --git a/docs/spike.md b/docs/spike.md index 71e67b4..28ce04e 100644 --- a/docs/spike.md +++ b/docs/spike.md @@ -1141,3 +1141,93 @@ spec.md §2 の lastResponseAt は、サブエージェントの fork の子に ホバー・キーボードフォーカス・disabled は CDP で操作して確かめた。DSH の実画面(認証付きの URL)では未確認。 入力カードの幅にそろえた後は、同じページで 1590px(明・暗)と 390px の両方について、警告・許可中・失敗の 3 状態とも、 バナーと入力カードの左右の端の差が 0px であることを `getBoundingClientRect` で確かめた。 + +--- + +# 設定スキーマ (`export const Config`) と設定ページ (2026-11-02, DSH 0.2.2-alpha.2) — #10 + +`$PK` = `/node_modules/@deepseek-ai`(0.2.2-alpha.2)。行番号は特記なければこの版のもの。 +古い版は `npm pack` で取り寄せて比べた(schemastery 3.18.4 / 3.18.5、cordis-plugin-loader 1.0.5 / 1.0.6、 +dsh-client-ui-primitives 0.2.0-rc.2 / 0.2.1-rc.5、dsh-client-ui-settings 0.2.0-rc.2 / 0.2.1-rc.5)。 +2026-10-23 の下調べ(依頼者の手元のブランチ `feat/issue-10-config-schema`、0.2.1-rc.2)の結論を今の版で確かめ直し、 +実装まで進めた。 + +結論: +- `@deepseek-ai/schemastery` は依存に足さず、DSH が実行時に提供するものを読み込む(S1)。 +- DSH の設定サービスが編集対象にするのは `.volatile()` のキーだけ(S2)。stateFile 以外を volatile にした。 +- volatile のキーは保存しても `apply` が呼び直されず、参照の中身が入れ替わって `loader/volatile-update` が届く(S3)。 + これを受けて実行中の設定を差し替え、`checkIntervalSeconds` が変わったら interval を張り直す(S4)。 +- **DSH の Web UI は、スキーマからフォームを自動では作らない**(S5)。プラグイン画面の自分のページ + (`plugins.bundle.config`)にフォームを出す部品をクライアント半分で登録した。部品は DSH 公式の設定ページと同じもの。 + +## S1: schemastery の読み込み — 確定(実機) +- `@deepseek-ai/schemastery` は `@deepseek-ai/dsh` 自身の依存で、プラグインからの import は DSH の解決層が + 宣言元(`@deepseek-ai/dsh`)の位置から解決し直す(下調べの Y3。`$PK/dsh-app-boot/lib/index.js` の `routeScoped`)。 + ビルドは既に `external: ['@deepseek-ai/*']`(`scripts/build.ts`)なので、バンドルには入らない。 +- `src/config-schema.ts` はトップレベル await の `import('@deepseek-ai/schemastery')` で読み、失敗したら `undefined` + (このリポジトリのテスト・CI、DSH の外)。静的 import にしないのは、読めない環境でモジュールごと読み込めなくなるため。 +- 実機(DSH 0.2.2-alpha.2、`DSH_HOME` を一時ディレクトリにした web プロファイルに `npm pack` の tarball を + `dsh plugin --profile web add` で入れた)で、`Config` が作られ、設定ページに項目が出ることを確かめた(S5)。 +- 判定は `isNativeConfigSchema`(`$PK/dsh-app-boot/lib/index.js:2501`)。`Symbol.for` を使うので、 + schemastery のコピーが複数あっても通る(下調べの Y1)。 + +## S2: 設定サービスが編集対象にするキー — 確定 +- `SettingsForms#describe()`(`$PK/dsh-settings/lib/index.js:413`)は `entry.fiber.runtime.Config`(`:538`)を読み、 + `volatileForm(schema)`(`:122`)が `undefined` の entry を飛ばす。`volatileForm` は `meta.volatile` のノードだけを集める。 + 書き込み(`write`、`:505` 付近)も volatile でないパスを `Config field "…" is not volatile` で拒否する。 +- README: 「Forms expose only volatile fields … Ordinary configuration remains editable through Cordis configuration files.」 + (`$PK/dsh-settings/README.md:33`)。 +- `stateFile` は volatile にしない。変えると状態ファイルを読み直す必要があり、実行中に差し替える作りにしていない。 + volatile でないキーが変わると loader は普通の再読み込み(`apply` のやり直し)をする(S3)ので、YAML で変えれば従来どおり効く。 +- 整数は `number().step(1).min(下限)`。schemastery の `natural()` も `number().step(1).min(0)`(`$PK/schemastery/lib/index.mjs:334`)。 + +## S3: 保存したときの流れ — 確定(コードと実機) +- 書き込みは `configEditor.edit` が候補を `fiber.resolveConfig(next)` で検証してからファイルに書く + (`$PK/dsh-config-editor/lib/index.js:82`。README「Writes validate the complete candidate before touching disk」)。 + 検証は cordis の `resolveConfig` が `Config["~standard"].validate` を呼ぶ(`$PK/cordis/lib/index.js:956`)。 + → **スキーマで不正な値はファイルに書かれない**。 +- loader は volatile のキーだけが変わったとき(`$PK/cordis-plugin-loader/lib/index.js:450`)、再読み込みせず + `_commitVolatile`(`:463`)で実行中の参照の中身を差し替え、自分の fiber にだけ `loader/volatile-update`(`:490`)を出す。 + 型は `$PK/cordis-plugin-loader/lib/types/index.d.ts:29`(`'loader/volatile-update'(paths: readonly (readonly string[])[]): void`)。 + README「Volatile configuration」(`$PK/cordis-plugin-loader/README.md:61`)。 +- volatile のノードは、値ではなく `get()` で今の値を返す参照(`createVolatile`)として `apply` に渡る + (`$PK/schemastery/lib/index.mjs:265`、型は `$PK/cosmokit/lib/types/volatile.d.ts` の `Volatile`)。 + なので `apply` は `plainConfig` で値に戻してから `parseConfig` を通す。 +- 同じ仕組み(`createVolatile`・`loader/volatile-update`)は schemastery 3.18.4 / 3.18.5、loader 1.0.5 / 1.0.6 にもある + (対応範囲の 0.2.0-rc.2〜0.2.1-rc.5 が使う版)。 +- schemastery の検証は未知のキーを通す(下調べの Y4)。未知キーの拒否と、エラー文面の表示言語は `parseConfig` に残した。 + 反映のときに `parseConfig` が失敗したら warn を出し、前の設定のまま動く。 + +## S4: 実行中の設定の差し替え — 実装 +- `createRuntime` は設定を変数に持ち、`reconfigure(next)` で差し替える。入力禁止の部品(`createSentinel`)には + 今の設定を読むビューを渡し、`unlockTtlMinutes` も呼ばれるたびに読むようにした。`/unlock` の許可・最終応答時刻など、 + 実行中に覚えている状態は持ち越す(再読み込みすると消える)。 +- モードがアーカイブしない → する、に変わったらすぐ 1 サイクル回す(`/sentinel` と同じ)。 +- `checkIntervalSeconds` が変わったら、`ctx.interval` が返す後始末で前の interval を止めてから張り直す。 +- 実機: 設定ページで `入力禁止までの分数` を 30、モードを both、dryRun を on にして保存すると、プロファイルの + `cordis.patch.yml` に `idleMinutes: 30` / `mode: both` / `dryRun: true` が書かれ、ログに + `[cache-sentinel] 設定を反映しました: 設定のモード both, 入力禁止 30 分, …, dryRun` が出た(再読み込みの「開始」は出ない)。 + +## S5: 設定ページ — 確定(コードと実機) +- DSH の Web UI には、スキーマからフォームを自動で作る画面は無い。`dsh-settings` の `describe()` は `autoGenerate` を返すが、 + 「no shipped client does so yet」(`$PK/dsh-settings/README.md:39`。0.2.1-rc.5 の README も同じ)。 +- プラグインの設定は、サイドバーの「プラグイン」画面に、プラグイン自身のクライアント半分が登録する + (`$PK/dsh-client-ui-plugin-manager/README.md`「Configuration pages」)。バンドル自身の設定は `plugins.bundle.config` + (キーはパッケージ名)で、バンドルのページの説明と行の間に出る(`$PK/dsh-client-ui-plugin-manager/lib/types/client/slot-contract.d.ts:153`)。 +- 公式の設定ページ(シェル・エージェントループ・Web 検索・サブエージェント)は、`configForms.get(エントリ id)` を + `@deepseek-ai/dsh-client-ui-primitives` の `SettingsFormModel` に渡し、`SettingsForm`・`SettingsValueField`・`Switch` で描く + (例: `$PK/dsh-client-ui-settings-shell/lib/client.js` の `ShellCardController`)。スロットの face の `hooks` に + `{ getSnapshot, subscribe }` を渡すと、部品側で `use<名前>` になる(`@deepseek-ai/dsh-client-ui-slots` の `InjectFace`)。 + cache-sentinel も同じ作りにした(`src/client/settings-page.ts`)。primitives はシェルが提供する共有モジュールで、 + 0.2.0-rc.2 / 0.2.1-rc.5 も `SettingsForm`・`SettingsFormModel`・`SettingsValueField`・`SegmentedControl` を export している。 +- `configForms` は `@deepseek-ai/dsh-client-ui-settings` のサービス。必須の inject にするとそれが無い構成でバナーまで止まるので、 + `ctx.inject(['configForms'], …)` の子で登録する。`whileServed`(0.2.0-rc.2 にもある)で、Host 側の entry が動いている間だけ出す。 +- 不正な入力(下限未満・整数以外)は、部品が欄を赤くして説明を出し、保存ボタンを押せなくする(実機で確認)。 + 部品を通さない書き込みも、Host がスキーマで拒否する(S3)。 +- 画面の確認は headless Chromium(1280×900、明るいテーマ、ja)で、一時の `DSH_HOME` の web プロファイルに入れて行った。 + ユーザーの実際のプロファイル・暗いテーマ・Desktop では見ていない。 + +## 未確認 +- `settings.configure({ auto: false }, fiber)`(自前のページを持つプラグインが、将来の自動フォームと二重にならないようにする口。 + `$PK/dsh-settings/README.md:39`)は呼んでいない。今は自動フォームを作るクライアントが無いため。 +- 0.2.0-rc.2〜0.2.1-rc.5 の実機では動かしていない(上の版比較はコードのみ)。 diff --git a/lib/client.js b/lib/client.js index 29a4b3c..d104df0 100644 --- a/lib/client.js +++ b/lib/client.js @@ -31,7 +31,7 @@ __export(index_exports, { name: () => name }); module.exports = __toCommonJS(index_exports); -var import_react = require("react"); +var import_react2 = require("react"); // src/i18n.ts var SKIPPED = /* @__PURE__ */ new Set(["", "c", "posix"]); @@ -91,7 +91,39 @@ var en = { configInvalidMode: (modes) => `Config key mode must be one of ${modes}`, commandUnlockDescription: "Allow the next send in a session where sending is blocked because the cache expired (cache-sentinel)", commandSentinelDescription: "Show cache-sentinel status and switch mode: /sentinel [block|archive|both|off|default]", - commandSentinelInputHint: "[block|archive|both|off|default]" + commandSentinelInputHint: "[block|archive|both|off|default]", + settingsLabels: { + mode: "Mode", + idleMinutes: "Minutes until sends are blocked", + archiveAfterMinutes: "Minutes until archiving (both mode)", + unlockTtlMinutes: "Minutes /unlock stays valid", + checkIntervalSeconds: "Archive check interval (seconds)", + skipPinned: "Do not archive pinned sessions", + archiveExisting: "Also archive sessions that were already idle", + maxPerCycle: "Sessions archived per check (max)", + dryRun: "Dry run (log only)" + }, + settingsHints: { + mode: "block: block sends; archive: archive sessions; both: block, then archive later; off: do nothing. A mode chosen with /sentinel takes precedence (/sentinel default returns to this one).", + idleMinutes: "Minutes since the last response. Also the archive threshold in archive mode. Integer, 1 or more.", + archiveAfterMinutes: "Archive threshold in both mode. Integer, 1 or more.", + unlockTtlMinutes: "How long an /unlock allowance lasts. Integer, 1 or more.", + checkIntervalSeconds: "How often to look for sessions to archive. Integer, 10 or more.", + skipPinned: "Pinned sessions are never archived.", + archiveExisting: "Include sessions that stopped before archiving was first enabled.", + maxPerCycle: "Upper limit per check. Integer, 1 or more.", + dryRun: "Neither block nor archive; only write what would happen to the log." + }, + settingsModeOptions: { block: "block", archive: "archive", both: "both", off: "off" }, + settingsInvalidInteger: (min) => `Enter an integer of ${min} or more, or leave blank to use the default.`, + settingsOverridden: "Changed", + settingsReset: "Reset to default", + settingsReadOnly: "This deployment stores settings read-only.", + settingsUnavailable: "cache-sentinel is not running, so it cannot be configured right now.", + settingsSave: "Save", + settingsSaving: "Saving\u2026", + settingsSaveFailed: "These values were not accepted; they are kept here for you to correct.", + settingsStateFileNote: "The state file location (stateFile) is set in the profile patch, not here." }; var ja = { noticeBlocked: (idleMinutes) => `\u9001\u4FE1\u3092\u6B62\u3081\u307E\u3057\u305F(\u6700\u7D42\u5FDC\u7B54\u304B\u3089 ${idleMinutes} \u5206\u3002\u30AD\u30E3\u30C3\u30B7\u30E5\u304C\u5207\u308C\u3066\u3044\u308B\u53EF\u80FD\u6027\u304C\u9AD8\u3044\u305F\u3081)\u3002`, @@ -131,7 +163,39 @@ var ja = { configInvalidMode: (modes) => `\u8A2D\u5B9A mode \u306F ${modes} \u306E\u3044\u305A\u308C\u304B\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`, commandUnlockDescription: "\u30AD\u30E3\u30C3\u30B7\u30E5\u5207\u308C\u3067\u5165\u529B\u7981\u6B62\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u3067\u3001\u6B21\u306E\u9001\u4FE1\u3092\u8A31\u53EF\u3059\u308B(cache-sentinel)", commandSentinelDescription: "cache-sentinel \u306E\u72B6\u614B\u8868\u793A\u3068\u30E2\u30FC\u30C9\u5207\u308A\u66FF\u3048: /sentinel [block|archive|both|off|default]", - commandSentinelInputHint: "[block|archive|both|off|default]" + commandSentinelInputHint: "[block|archive|both|off|default]", + settingsLabels: { + mode: "\u30E2\u30FC\u30C9", + idleMinutes: "\u5165\u529B\u7981\u6B62\u307E\u3067\u306E\u5206\u6570", + archiveAfterMinutes: "\u30A2\u30FC\u30AB\u30A4\u30D6\u307E\u3067\u306E\u5206\u6570(both \u30E2\u30FC\u30C9)", + unlockTtlMinutes: "/unlock \u306E\u6709\u52B9\u6642\u9593(\u5206)", + checkIntervalSeconds: "\u30A2\u30FC\u30AB\u30A4\u30D6\u306E\u78BA\u8A8D\u9593\u9694(\u79D2)", + skipPinned: "\u30D4\u30F3\u7559\u3081\u3057\u305F\u30BB\u30C3\u30B7\u30E7\u30F3\u306F\u30A2\u30FC\u30AB\u30A4\u30D6\u3057\u306A\u3044", + archiveExisting: "\u524D\u304B\u3089\u6B62\u307E\u3063\u3066\u3044\u305F\u30BB\u30C3\u30B7\u30E7\u30F3\u3082\u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B", + maxPerCycle: "1 \u56DE\u306B\u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B\u4E0A\u9650", + dryRun: "\u30ED\u30B0\u3060\u3051\u51FA\u3059(dryRun)" + }, + settingsHints: { + mode: "block: \u9001\u4FE1\u3092\u6B62\u3081\u308B / archive: \u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B / both: \u9001\u4FE1\u3092\u6B62\u3081\u3001\u3055\u3089\u306B\u5F8C\u3067\u30A2\u30FC\u30AB\u30A4\u30D6 / off: \u4F55\u3082\u3057\u306A\u3044\u3002/sentinel \u3067\u9078\u3093\u3060\u30E2\u30FC\u30C9\u304C\u3042\u308C\u3070\u305D\u3061\u3089\u304C\u512A\u5148\u3055\u308C\u307E\u3059(/sentinel default \u3067\u3053\u3053\u306E\u5024\u306B\u623B\u308A\u307E\u3059)\u3002", + idleMinutes: "\u6700\u7D42\u5FDC\u7B54\u304B\u3089\u306E\u5206\u6570\u3002archive \u30E2\u30FC\u30C9\u3067\u306F\u30A2\u30FC\u30AB\u30A4\u30D6\u306E\u3057\u304D\u3044\u5024\u306B\u3082\u306A\u308A\u307E\u3059\u30021 \u4EE5\u4E0A\u306E\u6574\u6570\u3002", + archiveAfterMinutes: "both \u30E2\u30FC\u30C9\u306E\u30A2\u30FC\u30AB\u30A4\u30D6\u306E\u3057\u304D\u3044\u5024\u30021 \u4EE5\u4E0A\u306E\u6574\u6570\u3002", + unlockTtlMinutes: "/unlock \u3067\u8A31\u53EF\u3057\u305F\u9001\u4FE1\u306E\u6709\u52B9\u6642\u9593\u30021 \u4EE5\u4E0A\u306E\u6574\u6570\u3002", + checkIntervalSeconds: "\u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B\u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u63A2\u3059\u9593\u9694\u300210 \u4EE5\u4E0A\u306E\u6574\u6570\u3002", + skipPinned: "\u30D4\u30F3\u7559\u3081\u3057\u305F\u30BB\u30C3\u30B7\u30E7\u30F3\u306F\u30A2\u30FC\u30AB\u30A4\u30D6\u3057\u307E\u305B\u3093\u3002", + archiveExisting: "\u30A2\u30FC\u30AB\u30A4\u30D6\u3092\u521D\u3081\u3066\u6709\u52B9\u306B\u3059\u308B\u524D\u306B\u6B62\u307E\u3063\u3066\u3044\u305F\u30BB\u30C3\u30B7\u30E7\u30F3\u3082\u5BFE\u8C61\u306B\u3057\u307E\u3059\u3002", + maxPerCycle: "1 \u56DE\u306E\u78BA\u8A8D\u3067\u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B\u4EF6\u6570\u306E\u4E0A\u9650\u30021 \u4EE5\u4E0A\u306E\u6574\u6570\u3002", + dryRun: "\u9001\u4FE1\u3092\u6B62\u3081\u305A\u3001\u30A2\u30FC\u30AB\u30A4\u30D6\u3082\u305B\u305A\u3001\u305D\u3046\u3059\u308B\u4E88\u5B9A\u3060\u3063\u305F\u3053\u3068\u3092\u30ED\u30B0\u306B\u51FA\u3059\u3060\u3051\u306B\u3057\u307E\u3059\u3002" + }, + settingsModeOptions: { block: "block", archive: "archive", both: "both", off: "off" }, + settingsInvalidInteger: (min) => `${min} \u4EE5\u4E0A\u306E\u6574\u6570\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u7A7A\u6B04\u306B\u3059\u308B\u3068\u65E2\u5B9A\u5024\u306B\u623B\u308A\u307E\u3059\u3002`, + settingsOverridden: "\u5909\u66F4\u3042\u308A", + settingsReset: "\u65E2\u5B9A\u5024\u306B\u623B\u3059", + settingsReadOnly: "\u3053\u306E\u74B0\u5883\u3067\u306F\u8A2D\u5B9A\u306F\u8AAD\u307F\u53D6\u308A\u5C02\u7528\u3067\u3059\u3002", + settingsUnavailable: "cache-sentinel \u304C\u52D5\u3044\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u3044\u307E\u306F\u8A2D\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002", + settingsSave: "\u4FDD\u5B58", + settingsSaving: "\u4FDD\u5B58\u4E2D\u2026", + settingsSaveFailed: "\u3053\u306E\u5024\u306F\u53D7\u3051\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u76F4\u305B\u308B\u3088\u3046\u5165\u529B\u306F\u305D\u306E\u307E\u307E\u6B8B\u3057\u3066\u3044\u307E\u3059\u3002", + settingsStateFileNote: "\u72B6\u614B\u30D5\u30A1\u30A4\u30EB\u306E\u5834\u6240(stateFile)\u306F\u3001\u3053\u3053\u3067\u306F\u306A\u304F\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u306E patch \u3067\u8A2D\u5B9A\u3057\u307E\u3059\u3002" }; var zhCN = { noticeBlocked: (idleMinutes) => `\u5DF2\u963B\u6B62\u53D1\u9001(\u8DDD\u6700\u540E\u4E00\u6B21\u54CD\u5E94 ${idleMinutes} \u5206\u949F\uFF0C\u56E0\u4E3A\u7F13\u5B58\u5F88\u53EF\u80FD\u5DF2\u8FC7\u671F)\u3002`, @@ -171,7 +235,39 @@ var zhCN = { configInvalidMode: (modes) => `\u914D\u7F6E mode \u5FC5\u987B\u4E3A ${modes} \u4E4B\u4E00`, commandUnlockDescription: "\u5728\u56E0\u7F13\u5B58\u8FC7\u671F\u800C\u7981\u6B62\u53D1\u9001\u7684\u4F1A\u8BDD\u4E2D\uFF0C\u5141\u8BB8\u4E0B\u4E00\u6B21\u53D1\u9001(cache-sentinel)", commandSentinelDescription: "\u663E\u793A cache-sentinel \u72B6\u6001\u5E76\u5207\u6362\u6A21\u5F0F\uFF1A/sentinel [block|archive|both|off|default]", - commandSentinelInputHint: "[block|archive|both|off|default]" + commandSentinelInputHint: "[block|archive|both|off|default]", + settingsLabels: { + mode: "\u6A21\u5F0F", + idleMinutes: "\u7981\u6B62\u53D1\u9001\u524D\u7684\u5206\u949F\u6570", + archiveAfterMinutes: "\u5F52\u6863\u524D\u7684\u5206\u949F\u6570(both \u6A21\u5F0F)", + unlockTtlMinutes: "/unlock \u7684\u6709\u6548\u5206\u949F\u6570", + checkIntervalSeconds: "\u5F52\u6863\u68C0\u67E5\u95F4\u9694(\u79D2)", + skipPinned: "\u4E0D\u5F52\u6863\u5DF2\u7F6E\u9876\u7684\u4F1A\u8BDD", + archiveExisting: "\u4E5F\u5F52\u6863\u6B64\u524D\u5DF2\u505C\u6B62\u7684\u4F1A\u8BDD", + maxPerCycle: "\u6BCF\u6B21\u68C0\u67E5\u6700\u591A\u5F52\u6863\u7684\u4F1A\u8BDD\u6570", + dryRun: "\u4EC5\u8BB0\u5F55\u65E5\u5FD7(dryRun)" + }, + settingsHints: { + mode: "block\uFF1A\u7981\u6B62\u53D1\u9001\uFF1Barchive\uFF1A\u5F52\u6863\u4F1A\u8BDD\uFF1Bboth\uFF1A\u7981\u6B62\u53D1\u9001\uFF0C\u4E4B\u540E\u518D\u5F52\u6863\uFF1Boff\uFF1A\u4E0D\u6267\u884C\u4EFB\u4F55\u64CD\u4F5C\u3002\u82E5\u7528 /sentinel \u9009\u62E9\u4E86\u6A21\u5F0F\uFF0C\u5219\u4EE5\u5176\u4E3A\u51C6(/sentinel default \u53EF\u6062\u590D\u4E3A\u6B64\u5904\u7684\u503C)\u3002", + idleMinutes: "\u8DDD\u4E0A\u6B21\u54CD\u5E94\u7684\u5206\u949F\u6570\u3002\u5728 archive \u6A21\u5F0F\u4E0B\u4E5F\u662F\u5F52\u6863\u9608\u503C\u3002\u4E0D\u5C0F\u4E8E 1 \u7684\u6574\u6570\u3002", + archiveAfterMinutes: "both \u6A21\u5F0F\u7684\u5F52\u6863\u9608\u503C\u3002\u4E0D\u5C0F\u4E8E 1 \u7684\u6574\u6570\u3002", + unlockTtlMinutes: "/unlock \u8BB8\u53EF\u7684\u6709\u6548\u65F6\u95F4\u3002\u4E0D\u5C0F\u4E8E 1 \u7684\u6574\u6570\u3002", + checkIntervalSeconds: "\u67E5\u627E\u5F85\u5F52\u6863\u4F1A\u8BDD\u7684\u95F4\u9694\u3002\u4E0D\u5C0F\u4E8E 10 \u7684\u6574\u6570\u3002", + skipPinned: "\u5DF2\u7F6E\u9876\u7684\u4F1A\u8BDD\u4E0D\u4F1A\u88AB\u5F52\u6863\u3002", + archiveExisting: "\u5305\u62EC\u9996\u6B21\u542F\u7528\u5F52\u6863\u4E4B\u524D\u5C31\u5DF2\u505C\u6B62\u7684\u4F1A\u8BDD\u3002", + maxPerCycle: "\u6BCF\u6B21\u68C0\u67E5\u5F52\u6863\u7684\u6570\u91CF\u4E0A\u9650\u3002\u4E0D\u5C0F\u4E8E 1 \u7684\u6574\u6570\u3002", + dryRun: "\u65E2\u4E0D\u7981\u6B62\u53D1\u9001\u4E5F\u4E0D\u5F52\u6863\uFF0C\u53EA\u628A\u5C06\u8981\u6267\u884C\u7684\u64CD\u4F5C\u5199\u5165\u65E5\u5FD7\u3002" + }, + settingsModeOptions: { block: "block", archive: "archive", both: "both", off: "off" }, + settingsInvalidInteger: (min) => `\u8BF7\u8F93\u5165\u4E0D\u5C0F\u4E8E ${min} \u7684\u6574\u6570\uFF1B\u7559\u7A7A\u5219\u4F7F\u7528\u9ED8\u8BA4\u503C\u3002`, + settingsOverridden: "\u5DF2\u4FEE\u6539", + settingsReset: "\u6062\u590D\u9ED8\u8BA4", + settingsReadOnly: "\u672C\u90E8\u7F72\u7684\u8BBE\u7F6E\u4E3A\u53EA\u8BFB\u3002", + settingsUnavailable: "cache-sentinel \u672A\u8FD0\u884C\uFF0C\u6682\u65F6\u65E0\u6CD5\u8BBE\u7F6E\u3002", + settingsSave: "\u4FDD\u5B58", + settingsSaving: "\u4FDD\u5B58\u4E2D\u2026", + settingsSaveFailed: "\u8FD9\u4E9B\u503C\u672A\u88AB\u63A5\u53D7\uFF0C\u5DF2\u4FDD\u7559\u4F9B\u4F60\u4FEE\u6539\u3002", + settingsStateFileNote: "\u72B6\u6001\u6587\u4EF6\u7684\u4F4D\u7F6E(stateFile)\u5728\u914D\u7F6E\u6587\u4EF6\u7684 patch \u4E2D\u8BBE\u7F6E\uFF0C\u4E0D\u5728\u6B64\u5904\u3002" }; var MESSAGES = { en, @@ -283,6 +379,274 @@ function describeError(error) { return "unknown error"; } +// src/client/settings-page.ts +var import_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives"); +var import_react = require("react"); + +// src/modes.ts +var MODES = ["block", "archive", "both", "off"]; +function isMode(value) { + return typeof value === "string" && MODES.includes(value); +} + +// src/config.ts +var CONFIG_KEYS = [ + { key: "mode", kind: "mode", live: true }, + { key: "idleMinutes", kind: "integer", min: 1, live: true }, + { key: "archiveAfterMinutes", kind: "integer", min: 1, live: true }, + { key: "unlockTtlMinutes", kind: "integer", min: 1, live: true }, + { key: "checkIntervalSeconds", kind: "integer", min: 10, live: true }, + { key: "skipPinned", kind: "boolean", live: true }, + { key: "archiveExisting", kind: "boolean", live: true }, + { key: "maxPerCycle", kind: "integer", min: 1, live: true }, + { key: "dryRun", kind: "boolean", live: true }, + { key: "stateFile", kind: "string", live: false } +]; +var KNOWN_KEYS = new Set(CONFIG_KEYS.map((spec) => spec.key)); + +// src/client/settings-fields.ts +var SETTINGS_FIELDS = CONFIG_KEYS.flatMap((spec) => { + switch (spec.kind) { + case "mode": + return [{ key: "mode", kind: "mode" }]; + case "integer": + return [{ key: spec.key, kind: "integer", min: spec.min }]; + case "boolean": + return [{ key: spec.key, kind: "boolean" }]; + case "string": + return []; + } +}); +function integerField(field, min) { + return { + field, + format: (value) => typeof value === "number" ? String(value) : "", + parse: (text) => { + const trimmed = text.trim(); + if (trimmed === "") return { kind: "clear" }; + if (!/^[+-]?\d+$/.test(trimmed)) return void 0; + const value = Number(trimmed); + return Number.isSafeInteger(value) && value >= min ? { kind: "set", value } : void 0; + } + }; +} +function booleanField(field) { + return { + field, + format: (value) => value === true ? "true" : value === false ? "false" : "", + parse: (text) => { + if (text === "true") return { kind: "set", value: true }; + if (text === "false") return { kind: "set", value: false }; + return text === "" ? { kind: "clear" } : void 0; + } + }; +} +function modeField(field) { + return { + field, + format: (value) => isMode(value) ? value : "", + parse: (text) => text === "" ? { kind: "clear" } : isMode(text) ? { kind: "set", value: text } : void 0 + }; +} +function fieldSpecs() { + return SETTINGS_FIELDS.map((field) => { + switch (field.kind) { + case "mode": + return modeField(field.key); + case "integer": + return integerField(field.key, field.min); + case "boolean": + return booleanField(field.key); + } + }); +} + +// src/client/settings-page.ts +var ENTRY_ID = "cache-sentinel"; +var PACKAGE_NAME = "cache-sentinel"; +var SettingsPageController = class { + form; + store; + locale; + constructor(scope, locale) { + this.locale = locale; + this.form = new import_dsh_client_ui_primitives.SettingsFormModel(scope, fieldSpecs()); + this.store = this.form.bind(() => this.projection()); + } + projection() { + const fields = Object.fromEntries(SETTINGS_FIELDS.map((field) => [field.key, this.form.field(field.key)])); + return { ...this.form.shell(), ...fields }; + } + face() { + return { hooks: { settingsPage: this.store }, locale: this.locale, ...this.form.actions() }; + } + dispose() { + this.form.dispose(); + } +}; +var CSS = ` +.cache-sentinel-settings-rows { + display: flex; + flex-direction: column; +} +.cache-sentinel-settings-rows > * + * { + border-top: 0.5px solid var(--dsw-alias-border-l2); +} +.cache-sentinel-settings-field { + display: flex; + flex-direction: column; + gap: 6px; + padding: 12px 0; +} +.cache-sentinel-settings-head { + display: flex; + align-items: center; + gap: 8px; +} +.cache-sentinel-settings-label { + flex: 1; + min-width: 0; + color: var(--dsw-alias-label-primary); + font-size: 13px; + font-weight: 500; + line-height: 1.5; +} +.cache-sentinel-settings-badges { + display: inline-flex; + align-items: center; + gap: 8px; +} +.cache-sentinel-settings-reset { + padding: 0; + border: none; + background: none; + color: var(--dsw-alias-label-secondary); + font: inherit; + font-size: 12px; + line-height: 1.5; + cursor: pointer; +} +.cache-sentinel-settings-reset:disabled { + cursor: default; +} +@media (hover: hover) { + .cache-sentinel-settings-reset:hover:not(:disabled) { + color: var(--dsw-alias-label-primary); + } +} +.cache-sentinel-settings-hint, +.cache-sentinel-settings-note { + margin: 0; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + line-height: 1.5; +} +.cache-sentinel-settings-note { + padding-top: 4px; +} +`; +function head(props, key, state, disabled, labelId, control = null) { + const m = MESSAGES[props.locale]; + return (0, import_react.createElement)( + "div", + { className: "cache-sentinel-settings-head" }, + (0, import_react.createElement)("span", { id: labelId, className: "cache-sentinel-settings-label" }, m.settingsLabels[key]), + state.overridden ? (0, import_react.createElement)( + "span", + { className: "cache-sentinel-settings-badges" }, + (0, import_react.createElement)(import_dsh_client_ui_primitives.Tag, { tone: "neutral" }, m.settingsOverridden), + (0, import_react.createElement)( + "button", + { type: "button", className: "cache-sentinel-settings-reset", disabled, onClick: () => props.resetField(key) }, + m.settingsReset + ) + ) : null, + control + ); +} +function SettingsPage(props) { + const state = props.useSettingsPage((snapshot) => snapshot); + if (props.view === "summary") return null; + const m = MESSAGES[props.locale]; + const disabled = !state.writable || state.saving; + const rows = SETTINGS_FIELDS.map((field) => { + const key = field.key; + const id = `cache-sentinel-settings-${key}`; + const fieldState = state[key]; + switch (field.kind) { + case "integer": + return (0, import_react.createElement)(import_dsh_client_ui_primitives.SettingsValueField, { + key, + id, + label: m.settingsLabels[key], + hint: m.settingsHints[key], + overriddenLabel: m.settingsOverridden, + resetLabel: m.settingsReset, + invalidLabel: m.settingsInvalidInteger(field.min), + numeric: true, + disabled, + text: fieldState.text, + overridden: fieldState.overridden, + invalid: fieldState.invalid, + onEdit: (text) => props.edit(key, text), + onReset: () => props.resetField(key) + }); + case "boolean": + return (0, import_react.createElement)( + "div", + { key, className: "cache-sentinel-settings-field", "data-testid": id }, + head( + props, + key, + fieldState, + disabled, + `${id}-label`, + (0, import_react.createElement)(import_dsh_client_ui_primitives.Switch, { + checked: fieldState.text === "true", + label: m.settingsLabels[key], + disabled, + onChange: (next) => props.edit(key, String(next)) + }) + ), + (0, import_react.createElement)("p", { className: "cache-sentinel-settings-hint" }, m.settingsHints[key]) + ); + case "mode": + return (0, import_react.createElement)( + "div", + { key, className: "cache-sentinel-settings-field", "data-testid": id }, + head(props, key, fieldState, disabled, `${id}-label`), + (0, import_react.createElement)(import_dsh_client_ui_primitives.SegmentedControl, { + id, + value: MODES.includes(fieldState.text) ? fieldState.text : "block", + options: MODES.map((mode) => ({ value: mode, label: m.settingsModeOptions[mode] })), + label: m.settingsLabels.mode, + disabled, + onChange: (next) => props.edit("mode", next) + }), + (0, import_react.createElement)("p", { className: "cache-sentinel-settings-hint" }, m.settingsHints.mode) + ); + } + }); + return (0, import_react.createElement)( + import_dsh_client_ui_primitives.SettingsForm, + { + labels: { + unavailable: m.settingsUnavailable, + readOnly: m.settingsReadOnly, + saveFailed: m.settingsSaveFailed, + save: m.settingsSave, + saving: m.settingsSaving + }, + state, + onSave: props.save, + onDiscard: props.discard + }, + (0, import_react.createElement)("style", null, CSS), + (0, import_react.createElement)("div", { className: "cache-sentinel-settings-rows" }, ...rows), + (0, import_react.createElement)("p", { className: "cache-sentinel-settings-note" }, m.settingsStateFileNote) + ); +} + // src/client/index.ts var name = "cache-sentinel-client"; var inject = ["slots", "remote", "remote.commands"]; @@ -309,8 +673,27 @@ function apply(ctx) { Banner ) ); + registerSettingsPage(ctx, slots, locale); } -var CSS = ` +function registerSettingsPage(ctx, slots, locale) { + ctx.inject(["configForms"], (child) => { + const controller = new SettingsPageController(child.configForms.get(ENTRY_ID), locale); + child.effect(() => () => controller.dispose(), "cache-sentinel: settings form"); + const register = () => { + const off = slots.inject( + "plugins.bundle.config", + () => slots.register({ name: "plugins.bundle.config", key: PACKAGE_NAME, inject: () => controller.face() }, SettingsPage) + ); + return () => off?.(); + }; + const forms = child.configForms; + child.effect( + () => typeof forms.whileServed === "function" ? forms.whileServed([ENTRY_ID], register) : register(), + "cache-sentinel: settings page" + ); + }); +} +var CSS2 = ` .cache-sentinel-banner { box-sizing: border-box; display: flex; @@ -395,10 +778,10 @@ var ICON_PATHS = { info: ["M7 11V7.5a5 5 0 0 1 9.6-1.9", "M5 11h14v10H5z"] }; function Icon({ tone }) { - return (0, import_react.createElement)( + return (0, import_react2.createElement)( "span", { className: "cache-sentinel-icon", "aria-hidden": true }, - (0, import_react.createElement)( + (0, import_react2.createElement)( "svg", { width: 16, @@ -410,18 +793,18 @@ function Icon({ tone }) { strokeLinecap: "round", strokeLinejoin: "round" }, - ...ICON_PATHS[tone].map((d) => (0, import_react.createElement)("path", { d })) + ...ICON_PATHS[tone].map((d) => (0, import_react2.createElement)("path", { d })) ) ); } function Banner({ sessionId, locale, unlock }) { - const [status, setStatus] = (0, import_react.useState)(void 0); - const [busy, setBusy] = (0, import_react.useState)(false); - const [failure, setFailure] = (0, import_react.useState)(void 0); - const load = (0, import_react.useCallback)(async () => { + const [status, setStatus] = (0, import_react2.useState)(void 0); + const [busy, setBusy] = (0, import_react2.useState)(false); + const [failure, setFailure] = (0, import_react2.useState)(void 0); + const load = (0, import_react2.useCallback)(async () => { setStatus(await fetchStatus(sessionId, document.baseURI)); }, [sessionId]); - (0, import_react.useEffect)(() => { + (0, import_react2.useEffect)(() => { setStatus(void 0); setFailure(void 0); void load(); @@ -437,7 +820,7 @@ function Banner({ sessionId, locale, unlock }) { }, [load]); const banner = bannerFor(status, Date.now(), locale); const warning = banner?.tone === "warning"; - (0, import_react.useEffect)(() => { + (0, import_react2.useEffect)(() => { if (!warning) setFailure(void 0); }, [warning]); if (banner === void 0) return null; @@ -450,18 +833,18 @@ function Banner({ sessionId, locale, unlock }) { setBusy(false); await load(); }; - return (0, import_react.createElement)( + return (0, import_react2.createElement)( "div", { role: "status", "data-testid": "cache-sentinel-banner", "data-tone": banner.tone, className: "cache-sentinel-banner" }, - (0, import_react.createElement)("style", null, CSS), - (0, import_react.createElement)(Icon, { tone: banner.tone }), - (0, import_react.createElement)( + (0, import_react2.createElement)("style", null, CSS2), + (0, import_react2.createElement)(Icon, { tone: banner.tone }), + (0, import_react2.createElement)( "span", { className: "cache-sentinel-text" }, banner.text, - warning && failure !== void 0 ? (0, import_react.createElement)("span", { role: "alert", "data-testid": "cache-sentinel-unlock-error", className: "cache-sentinel-failure" }, failure) : null + warning && failure !== void 0 ? (0, import_react2.createElement)("span", { role: "alert", "data-testid": "cache-sentinel-unlock-error", className: "cache-sentinel-failure" }, failure) : null ), - warning ? (0, import_react.createElement)( + warning ? (0, import_react2.createElement)( "button", { type: "button", className: "cache-sentinel-button", disabled: busy, onClick: () => void onUnlock() }, unlockLabel(locale) diff --git a/lib/index.js b/lib/index.js index 8161665..96da4c5 100644 --- a/lib/index.js +++ b/lib/index.js @@ -245,7 +245,39 @@ var en = { configInvalidMode: (modes) => `Config key mode must be one of ${modes}`, commandUnlockDescription: "Allow the next send in a session where sending is blocked because the cache expired (cache-sentinel)", commandSentinelDescription: "Show cache-sentinel status and switch mode: /sentinel [block|archive|both|off|default]", - commandSentinelInputHint: "[block|archive|both|off|default]" + commandSentinelInputHint: "[block|archive|both|off|default]", + settingsLabels: { + mode: "Mode", + idleMinutes: "Minutes until sends are blocked", + archiveAfterMinutes: "Minutes until archiving (both mode)", + unlockTtlMinutes: "Minutes /unlock stays valid", + checkIntervalSeconds: "Archive check interval (seconds)", + skipPinned: "Do not archive pinned sessions", + archiveExisting: "Also archive sessions that were already idle", + maxPerCycle: "Sessions archived per check (max)", + dryRun: "Dry run (log only)" + }, + settingsHints: { + mode: "block: block sends; archive: archive sessions; both: block, then archive later; off: do nothing. A mode chosen with /sentinel takes precedence (/sentinel default returns to this one).", + idleMinutes: "Minutes since the last response. Also the archive threshold in archive mode. Integer, 1 or more.", + archiveAfterMinutes: "Archive threshold in both mode. Integer, 1 or more.", + unlockTtlMinutes: "How long an /unlock allowance lasts. Integer, 1 or more.", + checkIntervalSeconds: "How often to look for sessions to archive. Integer, 10 or more.", + skipPinned: "Pinned sessions are never archived.", + archiveExisting: "Include sessions that stopped before archiving was first enabled.", + maxPerCycle: "Upper limit per check. Integer, 1 or more.", + dryRun: "Neither block nor archive; only write what would happen to the log." + }, + settingsModeOptions: { block: "block", archive: "archive", both: "both", off: "off" }, + settingsInvalidInteger: (min) => `Enter an integer of ${min} or more, or leave blank to use the default.`, + settingsOverridden: "Changed", + settingsReset: "Reset to default", + settingsReadOnly: "This deployment stores settings read-only.", + settingsUnavailable: "cache-sentinel is not running, so it cannot be configured right now.", + settingsSave: "Save", + settingsSaving: "Saving\u2026", + settingsSaveFailed: "These values were not accepted; they are kept here for you to correct.", + settingsStateFileNote: "The state file location (stateFile) is set in the profile patch, not here." }; var ja = { noticeBlocked: (idleMinutes) => `\u9001\u4FE1\u3092\u6B62\u3081\u307E\u3057\u305F(\u6700\u7D42\u5FDC\u7B54\u304B\u3089 ${idleMinutes} \u5206\u3002\u30AD\u30E3\u30C3\u30B7\u30E5\u304C\u5207\u308C\u3066\u3044\u308B\u53EF\u80FD\u6027\u304C\u9AD8\u3044\u305F\u3081)\u3002`, @@ -285,7 +317,39 @@ var ja = { configInvalidMode: (modes) => `\u8A2D\u5B9A mode \u306F ${modes} \u306E\u3044\u305A\u308C\u304B\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`, commandUnlockDescription: "\u30AD\u30E3\u30C3\u30B7\u30E5\u5207\u308C\u3067\u5165\u529B\u7981\u6B62\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u3067\u3001\u6B21\u306E\u9001\u4FE1\u3092\u8A31\u53EF\u3059\u308B(cache-sentinel)", commandSentinelDescription: "cache-sentinel \u306E\u72B6\u614B\u8868\u793A\u3068\u30E2\u30FC\u30C9\u5207\u308A\u66FF\u3048: /sentinel [block|archive|both|off|default]", - commandSentinelInputHint: "[block|archive|both|off|default]" + commandSentinelInputHint: "[block|archive|both|off|default]", + settingsLabels: { + mode: "\u30E2\u30FC\u30C9", + idleMinutes: "\u5165\u529B\u7981\u6B62\u307E\u3067\u306E\u5206\u6570", + archiveAfterMinutes: "\u30A2\u30FC\u30AB\u30A4\u30D6\u307E\u3067\u306E\u5206\u6570(both \u30E2\u30FC\u30C9)", + unlockTtlMinutes: "/unlock \u306E\u6709\u52B9\u6642\u9593(\u5206)", + checkIntervalSeconds: "\u30A2\u30FC\u30AB\u30A4\u30D6\u306E\u78BA\u8A8D\u9593\u9694(\u79D2)", + skipPinned: "\u30D4\u30F3\u7559\u3081\u3057\u305F\u30BB\u30C3\u30B7\u30E7\u30F3\u306F\u30A2\u30FC\u30AB\u30A4\u30D6\u3057\u306A\u3044", + archiveExisting: "\u524D\u304B\u3089\u6B62\u307E\u3063\u3066\u3044\u305F\u30BB\u30C3\u30B7\u30E7\u30F3\u3082\u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B", + maxPerCycle: "1 \u56DE\u306B\u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B\u4E0A\u9650", + dryRun: "\u30ED\u30B0\u3060\u3051\u51FA\u3059(dryRun)" + }, + settingsHints: { + mode: "block: \u9001\u4FE1\u3092\u6B62\u3081\u308B / archive: \u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B / both: \u9001\u4FE1\u3092\u6B62\u3081\u3001\u3055\u3089\u306B\u5F8C\u3067\u30A2\u30FC\u30AB\u30A4\u30D6 / off: \u4F55\u3082\u3057\u306A\u3044\u3002/sentinel \u3067\u9078\u3093\u3060\u30E2\u30FC\u30C9\u304C\u3042\u308C\u3070\u305D\u3061\u3089\u304C\u512A\u5148\u3055\u308C\u307E\u3059(/sentinel default \u3067\u3053\u3053\u306E\u5024\u306B\u623B\u308A\u307E\u3059)\u3002", + idleMinutes: "\u6700\u7D42\u5FDC\u7B54\u304B\u3089\u306E\u5206\u6570\u3002archive \u30E2\u30FC\u30C9\u3067\u306F\u30A2\u30FC\u30AB\u30A4\u30D6\u306E\u3057\u304D\u3044\u5024\u306B\u3082\u306A\u308A\u307E\u3059\u30021 \u4EE5\u4E0A\u306E\u6574\u6570\u3002", + archiveAfterMinutes: "both \u30E2\u30FC\u30C9\u306E\u30A2\u30FC\u30AB\u30A4\u30D6\u306E\u3057\u304D\u3044\u5024\u30021 \u4EE5\u4E0A\u306E\u6574\u6570\u3002", + unlockTtlMinutes: "/unlock \u3067\u8A31\u53EF\u3057\u305F\u9001\u4FE1\u306E\u6709\u52B9\u6642\u9593\u30021 \u4EE5\u4E0A\u306E\u6574\u6570\u3002", + checkIntervalSeconds: "\u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B\u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u63A2\u3059\u9593\u9694\u300210 \u4EE5\u4E0A\u306E\u6574\u6570\u3002", + skipPinned: "\u30D4\u30F3\u7559\u3081\u3057\u305F\u30BB\u30C3\u30B7\u30E7\u30F3\u306F\u30A2\u30FC\u30AB\u30A4\u30D6\u3057\u307E\u305B\u3093\u3002", + archiveExisting: "\u30A2\u30FC\u30AB\u30A4\u30D6\u3092\u521D\u3081\u3066\u6709\u52B9\u306B\u3059\u308B\u524D\u306B\u6B62\u307E\u3063\u3066\u3044\u305F\u30BB\u30C3\u30B7\u30E7\u30F3\u3082\u5BFE\u8C61\u306B\u3057\u307E\u3059\u3002", + maxPerCycle: "1 \u56DE\u306E\u78BA\u8A8D\u3067\u30A2\u30FC\u30AB\u30A4\u30D6\u3059\u308B\u4EF6\u6570\u306E\u4E0A\u9650\u30021 \u4EE5\u4E0A\u306E\u6574\u6570\u3002", + dryRun: "\u9001\u4FE1\u3092\u6B62\u3081\u305A\u3001\u30A2\u30FC\u30AB\u30A4\u30D6\u3082\u305B\u305A\u3001\u305D\u3046\u3059\u308B\u4E88\u5B9A\u3060\u3063\u305F\u3053\u3068\u3092\u30ED\u30B0\u306B\u51FA\u3059\u3060\u3051\u306B\u3057\u307E\u3059\u3002" + }, + settingsModeOptions: { block: "block", archive: "archive", both: "both", off: "off" }, + settingsInvalidInteger: (min) => `${min} \u4EE5\u4E0A\u306E\u6574\u6570\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u7A7A\u6B04\u306B\u3059\u308B\u3068\u65E2\u5B9A\u5024\u306B\u623B\u308A\u307E\u3059\u3002`, + settingsOverridden: "\u5909\u66F4\u3042\u308A", + settingsReset: "\u65E2\u5B9A\u5024\u306B\u623B\u3059", + settingsReadOnly: "\u3053\u306E\u74B0\u5883\u3067\u306F\u8A2D\u5B9A\u306F\u8AAD\u307F\u53D6\u308A\u5C02\u7528\u3067\u3059\u3002", + settingsUnavailable: "cache-sentinel \u304C\u52D5\u3044\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u3044\u307E\u306F\u8A2D\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002", + settingsSave: "\u4FDD\u5B58", + settingsSaving: "\u4FDD\u5B58\u4E2D\u2026", + settingsSaveFailed: "\u3053\u306E\u5024\u306F\u53D7\u3051\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u76F4\u305B\u308B\u3088\u3046\u5165\u529B\u306F\u305D\u306E\u307E\u307E\u6B8B\u3057\u3066\u3044\u307E\u3059\u3002", + settingsStateFileNote: "\u72B6\u614B\u30D5\u30A1\u30A4\u30EB\u306E\u5834\u6240(stateFile)\u306F\u3001\u3053\u3053\u3067\u306F\u306A\u304F\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u306E patch \u3067\u8A2D\u5B9A\u3057\u307E\u3059\u3002" }; var zhCN = { noticeBlocked: (idleMinutes) => `\u5DF2\u963B\u6B62\u53D1\u9001(\u8DDD\u6700\u540E\u4E00\u6B21\u54CD\u5E94 ${idleMinutes} \u5206\u949F\uFF0C\u56E0\u4E3A\u7F13\u5B58\u5F88\u53EF\u80FD\u5DF2\u8FC7\u671F)\u3002`, @@ -325,7 +389,39 @@ var zhCN = { configInvalidMode: (modes) => `\u914D\u7F6E mode \u5FC5\u987B\u4E3A ${modes} \u4E4B\u4E00`, commandUnlockDescription: "\u5728\u56E0\u7F13\u5B58\u8FC7\u671F\u800C\u7981\u6B62\u53D1\u9001\u7684\u4F1A\u8BDD\u4E2D\uFF0C\u5141\u8BB8\u4E0B\u4E00\u6B21\u53D1\u9001(cache-sentinel)", commandSentinelDescription: "\u663E\u793A cache-sentinel \u72B6\u6001\u5E76\u5207\u6362\u6A21\u5F0F\uFF1A/sentinel [block|archive|both|off|default]", - commandSentinelInputHint: "[block|archive|both|off|default]" + commandSentinelInputHint: "[block|archive|both|off|default]", + settingsLabels: { + mode: "\u6A21\u5F0F", + idleMinutes: "\u7981\u6B62\u53D1\u9001\u524D\u7684\u5206\u949F\u6570", + archiveAfterMinutes: "\u5F52\u6863\u524D\u7684\u5206\u949F\u6570(both \u6A21\u5F0F)", + unlockTtlMinutes: "/unlock \u7684\u6709\u6548\u5206\u949F\u6570", + checkIntervalSeconds: "\u5F52\u6863\u68C0\u67E5\u95F4\u9694(\u79D2)", + skipPinned: "\u4E0D\u5F52\u6863\u5DF2\u7F6E\u9876\u7684\u4F1A\u8BDD", + archiveExisting: "\u4E5F\u5F52\u6863\u6B64\u524D\u5DF2\u505C\u6B62\u7684\u4F1A\u8BDD", + maxPerCycle: "\u6BCF\u6B21\u68C0\u67E5\u6700\u591A\u5F52\u6863\u7684\u4F1A\u8BDD\u6570", + dryRun: "\u4EC5\u8BB0\u5F55\u65E5\u5FD7(dryRun)" + }, + settingsHints: { + mode: "block\uFF1A\u7981\u6B62\u53D1\u9001\uFF1Barchive\uFF1A\u5F52\u6863\u4F1A\u8BDD\uFF1Bboth\uFF1A\u7981\u6B62\u53D1\u9001\uFF0C\u4E4B\u540E\u518D\u5F52\u6863\uFF1Boff\uFF1A\u4E0D\u6267\u884C\u4EFB\u4F55\u64CD\u4F5C\u3002\u82E5\u7528 /sentinel \u9009\u62E9\u4E86\u6A21\u5F0F\uFF0C\u5219\u4EE5\u5176\u4E3A\u51C6(/sentinel default \u53EF\u6062\u590D\u4E3A\u6B64\u5904\u7684\u503C)\u3002", + idleMinutes: "\u8DDD\u4E0A\u6B21\u54CD\u5E94\u7684\u5206\u949F\u6570\u3002\u5728 archive \u6A21\u5F0F\u4E0B\u4E5F\u662F\u5F52\u6863\u9608\u503C\u3002\u4E0D\u5C0F\u4E8E 1 \u7684\u6574\u6570\u3002", + archiveAfterMinutes: "both \u6A21\u5F0F\u7684\u5F52\u6863\u9608\u503C\u3002\u4E0D\u5C0F\u4E8E 1 \u7684\u6574\u6570\u3002", + unlockTtlMinutes: "/unlock \u8BB8\u53EF\u7684\u6709\u6548\u65F6\u95F4\u3002\u4E0D\u5C0F\u4E8E 1 \u7684\u6574\u6570\u3002", + checkIntervalSeconds: "\u67E5\u627E\u5F85\u5F52\u6863\u4F1A\u8BDD\u7684\u95F4\u9694\u3002\u4E0D\u5C0F\u4E8E 10 \u7684\u6574\u6570\u3002", + skipPinned: "\u5DF2\u7F6E\u9876\u7684\u4F1A\u8BDD\u4E0D\u4F1A\u88AB\u5F52\u6863\u3002", + archiveExisting: "\u5305\u62EC\u9996\u6B21\u542F\u7528\u5F52\u6863\u4E4B\u524D\u5C31\u5DF2\u505C\u6B62\u7684\u4F1A\u8BDD\u3002", + maxPerCycle: "\u6BCF\u6B21\u68C0\u67E5\u5F52\u6863\u7684\u6570\u91CF\u4E0A\u9650\u3002\u4E0D\u5C0F\u4E8E 1 \u7684\u6574\u6570\u3002", + dryRun: "\u65E2\u4E0D\u7981\u6B62\u53D1\u9001\u4E5F\u4E0D\u5F52\u6863\uFF0C\u53EA\u628A\u5C06\u8981\u6267\u884C\u7684\u64CD\u4F5C\u5199\u5165\u65E5\u5FD7\u3002" + }, + settingsModeOptions: { block: "block", archive: "archive", both: "both", off: "off" }, + settingsInvalidInteger: (min) => `\u8BF7\u8F93\u5165\u4E0D\u5C0F\u4E8E ${min} \u7684\u6574\u6570\uFF1B\u7559\u7A7A\u5219\u4F7F\u7528\u9ED8\u8BA4\u503C\u3002`, + settingsOverridden: "\u5DF2\u4FEE\u6539", + settingsReset: "\u6062\u590D\u9ED8\u8BA4", + settingsReadOnly: "\u672C\u90E8\u7F72\u7684\u8BBE\u7F6E\u4E3A\u53EA\u8BFB\u3002", + settingsUnavailable: "cache-sentinel \u672A\u8FD0\u884C\uFF0C\u6682\u65F6\u65E0\u6CD5\u8BBE\u7F6E\u3002", + settingsSave: "\u4FDD\u5B58", + settingsSaving: "\u4FDD\u5B58\u4E2D\u2026", + settingsSaveFailed: "\u8FD9\u4E9B\u503C\u672A\u88AB\u63A5\u53D7\uFF0C\u5DF2\u4FDD\u7559\u4F9B\u4F60\u4FEE\u6539\u3002", + settingsStateFileNote: "\u72B6\u6001\u6587\u4EF6\u7684\u4F4D\u7F6E(stateFile)\u5728\u914D\u7F6E\u6587\u4EF6\u7684 patch \u4E2D\u8BBE\u7F6E\uFF0C\u4E0D\u5728\u6B64\u5904\u3002" }; var MESSAGES = { en, @@ -607,7 +703,7 @@ function createSentinel(config, log, locale, now = Date.now, isActive = () => tr const unlocks = new UnlockStore(); const dedupe = new NoticeDedupe(NOTICE_DEDUPE_INTERVAL_MS); const pending = new PendingNotices(); - const ttlMs = config.unlockTtlMinutes * 6e4; + const ttlMs = () => config.unlockTtlMinutes * 6e4; let noticeCounter = 0; const appendNotice = (session, notice) => { if (session.append === void 0) return; @@ -648,7 +744,7 @@ function createSentinel(config, log, locale, now = Date.now, isActive = () => tr let stepKind; try { const at = now(); - unlocks.prune(at, ttlMs); + unlocks.prune(at, ttlMs()); dedupe.prune(at); sourceKinds = payload.messages.map((message) => message.source?.kind ?? "(source \u306A\u3057)"); stepKind = classifyStep(payload.step, sourceKinds); @@ -735,7 +831,7 @@ function createSentinel(config, log, locale, now = Date.now, isActive = () => tr }, statusOf(session, mode) { const at = now(); - unlocks.prune(at, ttlMs); + unlocks.prune(at, ttlMs()); return computeStatus({ mode, gate: isActive(), @@ -769,7 +865,19 @@ var DEFAULTS = { maxPerCycle: 20, dryRun: false }; -var KNOWN_KEYS = /* @__PURE__ */ new Set([...Object.keys(DEFAULTS), "stateFile"]); +var CONFIG_KEYS = [ + { key: "mode", kind: "mode", live: true }, + { key: "idleMinutes", kind: "integer", min: 1, live: true }, + { key: "archiveAfterMinutes", kind: "integer", min: 1, live: true }, + { key: "unlockTtlMinutes", kind: "integer", min: 1, live: true }, + { key: "checkIntervalSeconds", kind: "integer", min: 10, live: true }, + { key: "skipPinned", kind: "boolean", live: true }, + { key: "archiveExisting", kind: "boolean", live: true }, + { key: "maxPerCycle", kind: "integer", min: 1, live: true }, + { key: "dryRun", kind: "boolean", live: true }, + { key: "stateFile", kind: "string", live: false } +]; +var KNOWN_KEYS = new Set(CONFIG_KEYS.map((spec) => spec.key)); function readInteger(raw, key, min, m) { const value = raw[key]; if (typeof value !== "number") { @@ -819,38 +927,36 @@ function parseConfig(raw, locale) { } } const config = { ...DEFAULTS }; - if (obj.mode !== void 0) { - config.mode = readMode(obj, m); - } - if (obj.idleMinutes !== void 0) { - config.idleMinutes = readInteger(obj, "idleMinutes", 1, m); - } - if (obj.archiveAfterMinutes !== void 0) { - config.archiveAfterMinutes = readInteger(obj, "archiveAfterMinutes", 1, m); - } - if (obj.unlockTtlMinutes !== void 0) { - config.unlockTtlMinutes = readInteger(obj, "unlockTtlMinutes", 1, m); - } - if (obj.checkIntervalSeconds !== void 0) { - config.checkIntervalSeconds = readInteger(obj, "checkIntervalSeconds", 10, m); - } - if (obj.skipPinned !== void 0) { - config.skipPinned = readBoolean(obj, "skipPinned", m); - } - if (obj.archiveExisting !== void 0) { - config.archiveExisting = readBoolean(obj, "archiveExisting", m); - } - if (obj.maxPerCycle !== void 0) { - config.maxPerCycle = readInteger(obj, "maxPerCycle", 1, m); - } - if (obj.dryRun !== void 0) { - config.dryRun = readBoolean(obj, "dryRun", m); - } - if (obj.stateFile !== void 0) { - config.stateFile = readString(obj, "stateFile", m); + for (const spec of CONFIG_KEYS) { + if (obj[spec.key] === void 0) continue; + switch (spec.kind) { + case "mode": + config.mode = readMode(obj, m); + break; + case "integer": + config[spec.key] = readInteger(obj, spec.key, spec.min, m); + break; + case "boolean": + config[spec.key] = readBoolean(obj, spec.key, m); + break; + case "string": + config.stateFile = readString(obj, spec.key, m); + break; + } } return config; } +function plainConfig(raw) { + if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return raw; + const result = {}; + for (const [key, value] of Object.entries(raw)) { + result[key] = isVolatileRef(value) ? value.get() : value; + } + return result; +} +function isVolatileRef(value) { + return typeof value === "object" && value !== null && typeof value.get === "function"; +} // src/decide.ts var MS_PER_MINUTE = 6e4; @@ -1188,6 +1294,56 @@ async function saveState(filePath, state) { } } +// src/config-schema.ts +var DESCRIPTIONS = { + mode: "Default mode: block (reject sends), archive, both, or off. /sentinel can override it.", + idleMinutes: "Minutes since the last response after which sends are blocked (the archive threshold in archive mode).", + archiveAfterMinutes: "Archive threshold in minutes in both mode.", + unlockTtlMinutes: "Minutes an /unlock allowance stays valid.", + checkIntervalSeconds: "Seconds between archive checks.", + skipPinned: "Do not archive pinned sessions.", + archiveExisting: "Also archive sessions that stopped before archiving was first enabled.", + maxPerCycle: "Maximum number of sessions archived per check.", + dryRun: "Only log; neither block nor archive.", + stateFile: "Path of the state file. Defaults to $DSH_HOME/cache-sentinel/profiles//state.json." +}; +function buildConfigSchema(z) { + const dict = {}; + for (const spec of CONFIG_KEYS) { + let node; + switch (spec.kind) { + case "mode": + node = z.union(MODES.map((mode) => z.const(mode))).default(DEFAULTS.mode); + break; + case "integer": + node = z.number().step(1).min(spec.min).default(DEFAULTS[spec.key]); + break; + case "boolean": + node = z.boolean().default(DEFAULTS[spec.key]); + break; + case "string": + node = z.string(); + break; + } + node = node.description(DESCRIPTIONS[spec.key]); + dict[spec.key] = spec.live ? node.volatile() : node; + } + return z.object(dict); +} +async function loadSchemaFactory() { + try { + const specifier = "@deepseek-ai/schemastery"; + const mod = await import(specifier); + return typeof mod.default === "function" ? mod.default : void 0; + } catch { + return void 0; + } +} +var ConfigSchema = await (async () => { + const z = await loadSchemaFactory(); + return z === void 0 ? void 0 : buildConfigSchema(z); +})(); + // src/index.ts var name = "cache-sentinel"; var inject = ["commands", "workspaceRegistry", "sessionPersistence", "sessions", "timer", "connection"]; @@ -1217,7 +1373,8 @@ async function loadInitialState(location, log) { } return state; } -function createRuntime(config, initialState, cycleDeps, log, io, locale) { +function createRuntime(initialConfig, initialState, cycleDeps, log, io, locale) { + let config = initialConfig; let state = initialState; let prevArchived; let running = false; @@ -1233,7 +1390,18 @@ function createRuntime(config, initialState, cycleDeps, log, io, locale) { state = { ...state, baselineAt: io.now() }; return true; }; - const block = createSentinel(config, log, locale, io.now, () => blocks(current().mode)); + const blockSettings = { + get idleMinutes() { + return config.idleMinutes; + }, + get unlockTtlMinutes() { + return config.unlockTtlMinutes; + }, + get dryRun() { + return config.dryRun; + } + }; + const block = createSentinel(blockSettings, log, locale, io.now, () => blocks(current().mode)); const runtime = { mode: () => current().mode, onPreStep: (payload, next) => block.onPreStep(payload, next), @@ -1241,6 +1409,16 @@ function createRuntime(config, initialState, cycleDeps, log, io, locale) { onAgentStatus: (status, session) => block.onAgentStatus(status, session), unlock: (agent) => block.unlock(agent, unlockInactiveMessage(current().mode, locale)), status: (session) => block.statusOf(session, current().mode), + config: () => config, + reconfigure(next) { + const before = current().mode; + config = next; + const after = current().mode; + if (archives(after) && !archives(before)) { + prevArchived = void 0; + void runtime.tick(); + } + }, async sentinel(agent, rawInput) { const command = parseSentinelArgs(rawInput); if (command.kind === "invalid") return { kind: "error", text: usageMessage(locale) }; @@ -1321,6 +1499,9 @@ function statusResponse(request, lookup) { headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } }); } +function describeConfig(config) { + return `\u8A2D\u5B9A\u306E\u30E2\u30FC\u30C9 ${config.mode}, \u5165\u529B\u7981\u6B62 ${config.idleMinutes} \u5206, both \u306E\u30A2\u30FC\u30AB\u30A4\u30D6 ${config.archiveAfterMinutes} \u5206, /unlock ${config.unlockTtlMinutes} \u5206, \u9593\u9694 ${config.checkIntervalSeconds} \u79D2${config.dryRun ? ", dryRun" : ""}`; +} async function apply(ctx, rawConfig) { const locale = resolveLocale([ process.env.LC_ALL, @@ -1328,7 +1509,7 @@ async function apply(ctx, rawConfig) { process.env.LANG, Intl.DateTimeFormat().resolvedOptions().locale ]); - const config = parseConfig(rawConfig, locale); + const config = parseConfig(plainConfig(rawConfig), locale); const log = createLogger(ctx.logger, console); const home = resolveHome(); const profile = profileNameOf(ctx); @@ -1359,23 +1540,39 @@ async function apply(ctx, rawConfig) { input: { hint: MESSAGES[locale].commandSentinelInputHint }, handler: ({ agent, rawInput }) => runtime.sentinel(agent, rawInput) }); - ctx.interval(() => void runtime.tick(), config.checkIntervalSeconds * 1e3); + let stopInterval = ctx.interval(() => void runtime.tick(), config.checkIntervalSeconds * 1e3); + ctx.on("loader/volatile-update", () => { + let next; + try { + next = parseConfig(plainConfig(rawConfig), locale); + } catch (error) { + log.warn(`\u65B0\u3057\u3044\u8A2D\u5B9A\u3092\u53CD\u6620\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F(\u524D\u306E\u8A2D\u5B9A\u306E\u307E\u307E\u52D5\u304D\u307E\u3059): ${String(error)}`); + return; + } + const before = runtime.config(); + runtime.reconfigure(next); + if (next.checkIntervalSeconds !== before.checkIntervalSeconds) { + stopInterval(); + stopInterval = ctx.interval(() => void runtime.tick(), next.checkIntervalSeconds * 1e3); + } + log.info(`\u8A2D\u5B9A\u3092\u53CD\u6620\u3057\u307E\u3057\u305F: ${describeConfig(next)}`); + }); ctx.connection.fetch.register({ path: STATUS_PATH, methods: ["GET"], requestBody: "buffered", fetch: async (request) => statusResponse(request, (id) => runtime.status(ctx.sessions.get(id))) }); - log.info( - `\u958B\u59CB (\u30E2\u30FC\u30C9 ${runtime.mode()}, \u5165\u529B\u7981\u6B62 ${config.idleMinutes} \u5206, both \u306E\u30A2\u30FC\u30AB\u30A4\u30D6 ${config.archiveAfterMinutes} \u5206${config.dryRun ? ", dryRun" : ""})` - ); + log.info(`\u958B\u59CB (\u30E2\u30FC\u30C9 ${runtime.mode()}, ${describeConfig(config)})`); log.info(`\u72B6\u614B\u30D5\u30A1\u30A4\u30EB: ${location.file}${profile === void 0 ? " (\u30D7\u30ED\u30D5\u30A1\u30A4\u30EB\u540D\u306A\u3057)" : ""}`); void runtime.tick(); } export { + ConfigSchema as Config, STATUS_PATH, apply, createRuntime, + describeConfig, inject, loadInitialState, name, diff --git a/src/block.ts b/src/block.ts index 7e9b5c5..aa80d27 100644 --- a/src/block.ts +++ b/src/block.ts @@ -121,6 +121,7 @@ function sessionViewOf(session: SessionLike): SessionView { /** * 設定・ロガー・表示言語・時計・有効判定から入力禁止の部品を作る。 + * `config` の各項目は使うたびに読む(呼び出し側が今の設定を返すオブジェクトを渡せる。#10)。 * 最終応答時刻は、そのとき手元にある Session のイベント列から初回だけ読み、以後は session/event で更新する。 * 会話に書き込むブロック通知は `locale` (プロセスで 1 回決める。spec-ui v0.5 §F) で作る。 */ @@ -141,7 +142,8 @@ export function createSentinel( const unlocks = new UnlockStore() const dedupe = new NoticeDedupe(NOTICE_DEDUPE_INTERVAL_MS) const pending = new PendingNotices() - const ttlMs = config.unlockTtlMinutes * 60_000 + // 設定は呼ばれるたびに読む(設定画面からの変更を読み込み直さずに反映するため。#10)。 + const ttlMs = (): number => config.unlockTtlMinutes * 60_000 let noticeCounter = 0 /** @@ -197,7 +199,7 @@ export function createSentinel( let stepKind: StepKind try { const at = now() - unlocks.prune(at, ttlMs) + unlocks.prune(at, ttlMs()) dedupe.prune(at) sourceKinds = payload.messages.map((message) => message.source?.kind ?? '(source なし)') stepKind = classifyStep(payload.step, sourceKinds) @@ -293,7 +295,7 @@ export function createSentinel( statusOf(session, mode) { const at = now() - unlocks.prune(at, ttlMs) + unlocks.prune(at, ttlMs()) return computeStatus({ mode, gate: isActive(), diff --git a/src/client/index.ts b/src/client/index.ts index 2e345c5..8ef83af 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -8,6 +8,7 @@ import { resolveLocale, type Locale } from '../i18n.ts' import { bannerFor, unlockLabel, type Banner as BannerView, type StatusLike } from './banner.ts' import { fetchStatus } from './fetch-status.ts' import { runUnlock } from './run-unlock.ts' +import { ENTRY_ID, PACKAGE_NAME, SettingsPage, SettingsPageController } from './settings-page.ts' export const name = 'cache-sentinel-client' /** `remote.commands` は `remote` とは別のサービスキーなので、両方を宣言する(docs/spike.md、#26)。 */ @@ -17,11 +18,22 @@ export const inject = ['slots', 'remote', 'remote.commands'] export const POLL_MS = 30_000 interface SlotsService { - inject(name: string, register: () => () => void): void - register( - options: { name: string; id: string; order: number; inject: (sessionId: string) => BannerProps }, - component: (props: BannerProps) => unknown, - ): () => void + inject(name: string, register: () => () => void): (() => void) | void + register

(options: { name: string; id: string; order: number; inject: (sessionId: string) => P }, component: (props: never) => unknown): () => void + register

(options: { name: string; key: string; inject: () => P }, component: (props: never) => unknown): () => void +} + +/** DSH の `configForms`(`@deepseek-ai/dsh-client-ui-settings` の `ConfigForms`)のうち使う部分。 */ +interface ConfigFormsService { + get(entryId: string): ConstructorParameters[0] + /** 0.2.1 以降にある。Host がその名前空間を出している間だけ登録を保つ。 */ + whileServed?(namespaces: readonly string[], register: (served: ReadonlySet) => () => void): () => void +} + +/** cordis の ctx のうち、任意のサービスを待つ子プラグインを作る口と、後始末の口。 */ +interface PluginContext { + inject(deps: readonly string[], callback: (ctx: PluginContext & { configForms: ConfigFormsService }) => void): unknown + effect(execute: () => () => void, label?: string): unknown } interface RemoteService { @@ -60,6 +72,29 @@ export function apply(ctx: unknown): void { Banner, ), ) + registerSettingsPage(ctx as PluginContext, slots, locale) +} + +/** + * プラグイン画面の cache-sentinel のページに設定フォームを出す (#10、docs/spike.md S5)。 + * `configForms` は必須の inject にしない(無い環境でもバナーは動かす)。あるときだけ子プラグインで登録する。 + */ +function registerSettingsPage(ctx: PluginContext, slots: SlotsService, locale: Locale): void { + ctx.inject(['configForms'], (child) => { + const controller = new SettingsPageController(child.configForms.get(ENTRY_ID), locale) + child.effect(() => () => controller.dispose(), 'cache-sentinel: settings form') + const register = (): (() => void) => { + const off = slots.inject('plugins.bundle.config', () => + slots.register({ name: 'plugins.bundle.config', key: PACKAGE_NAME, inject: () => controller.face() }, SettingsPage), + ) + return () => off?.() + } + const forms = child.configForms + child.effect( + () => (typeof forms.whileServed === 'function' ? forms.whileServed([ENTRY_ID], register) : register()), + 'cache-sentinel: settings page', + ) + }) } /** diff --git a/src/client/primitives-shim.d.ts b/src/client/primitives-shim.d.ts new file mode 100644 index 0000000..59ca5b1 --- /dev/null +++ b/src/client/primitives-shim.d.ts @@ -0,0 +1,129 @@ +/** + * `@deepseek-ai/dsh-client-ui-primitives` の最小の型宣言。DSH のシェルが実行時に提供する(バンドルしない)ため、 + * 依存を足さずに、設定ページ (#10) が使う部品だけを宣言する。 + * 形は同パッケージ 0.2.2-alpha.2 の `lib/types/settings-form/*.d.ts`・`Switch.d.ts`・`SegmentedControl.d.ts`・`Tag.d.ts` から + * 書き写した(docs/spike.md S5)。0.2.0-rc.2・0.2.1-rc.5 も同じ名前を export している。 + */ +declare module '@deepseek-ai/dsh-client-ui-primitives' { + export type SettingsFieldWrite = { kind: 'set'; value: unknown } | { kind: 'clear' } + + export interface SettingsFieldSpec { + field: string + format: (value: unknown) => string + parse: (text: string) => SettingsFieldWrite | undefined + } + + export interface SettingsFormScopeSnapshot { + status: 'loading' | 'ready' | 'unavailable' + value: T | undefined + base: unknown + user: unknown + writable: boolean + revision: number | undefined + } + + export type SettingsFormPathOp = + | { op: 'set'; path: readonly string[]; value: unknown } + | { op: 'unset'; path: readonly string[] } + + export interface SettingsFormScope { + getSnapshot(): SettingsFormScopeSnapshot + subscribe(listener: () => void): () => void + mutate(ops: readonly SettingsFormPathOp[], expectedRevision?: number): Promise + } + + export interface SettingsFieldState { + text: string + overridden: boolean + invalid: boolean + } + + export interface SettingsFormShell { + available: boolean + writable: boolean + dirty: boolean + invalid: boolean + saving: boolean + failed: boolean + } + + export interface SettingsFormActions { + edit: (field: string, text: string) => void + resetField: (field: string) => void + save: () => void + discard: () => void + } + + /** `getSnapshot` と `subscribe` の組(スロットの `hooks` に渡すと `use<名前>` になる)。 */ + export interface SnapshotStore { + getSnapshot(): S + subscribe(listener: () => void): () => void + } + + export class SettingsFormModel { + constructor(scope: SettingsFormScope, specs: SettingsFieldSpec[]) + bind(project: () => S): SnapshotStore + shell(): SettingsFormShell + field(field: string): SettingsFieldState + actions(): SettingsFormActions + dispose(): void + } + + export interface SettingsFormLabels { + unavailable: string + readOnly: string + saveFailed: string + save: string + saving: string + } + + export function SettingsForm(props: { + labels: SettingsFormLabels + state: SettingsFormShell + onSave: () => void + onDiscard: () => void + children: unknown + }): unknown + + export function SettingsValueField(props: { + id: string + label: string + hint?: string + text: string + overridden: boolean + invalid: boolean + overriddenLabel: string + resetLabel: string + invalidLabel: string + disabled: boolean + numeric?: boolean + placeholder?: string + onEdit: (text: string) => void + onReset: () => void + }): unknown + + export function Switch(props: { + checked: boolean + onChange: (next: boolean) => void + label: string + disabled?: boolean + title?: string + className?: string + }): unknown + + export function Tag(props: { + tone?: 'outline' | 'solid' | 'neutral' | 'quiet' | 'success' | 'info' | 'warning' | 'danger' + className?: string + children?: unknown + }): unknown + + export function SegmentedControl(props: { + id: string + value: Value + options: readonly { value: Value; label: string; disabled?: boolean; title?: string }[] + onChange: (next: Value) => void + label: string + disabled?: boolean + className?: string + }): unknown +} diff --git a/src/client/settings-fields.ts b/src/client/settings-fields.ts new file mode 100644 index 0000000..550096b --- /dev/null +++ b/src/client/settings-fields.ts @@ -0,0 +1,95 @@ +/** + * 設定ページ (#10) の各欄と、入力文字列 ⇄ 保存する値の変換。純粋関数のみ(React・DSH に依存しない)。 + * + * DSH の設定フォーム(`@deepseek-ai/dsh-client-ui-primitives` の `SettingsFormModel`)は、各欄を + * 「入力中の文字列」で持ち、保存時に `parse` が返す書き込み(set / clear)を Host に送る。 + * `parse` が undefined を返す入力は不正で、保存できない(docs/spike.md S5)。 + * 欄・型・下限は `src/config.ts` の `CONFIG_KEYS` から作るので、キーを足すのは 1 か所で済む。 + */ +import { CONFIG_KEYS } from '../config.ts' +import type { SettingsKey } from '../messages.ts' +import { isMode } from '../modes.ts' + +/** 1 欄の保存時の書き込み(primitives の `SettingsFieldWrite` と同じ形)。 */ +export type FieldWrite = { kind: 'set'; value: unknown } | { kind: 'clear' } + +/** 1 欄の変換(primitives の `SettingsFieldSpec` と同じ形)。 */ +export interface FieldSpec { + field: string + format: (value: unknown) => string + parse: (text: string) => FieldWrite | undefined +} + +/** 設定ページに出す欄の種類。 */ +export type SettingsField = + | { key: 'mode'; kind: 'mode' } + | { key: SettingsKey; kind: 'integer'; min: number } + | { key: SettingsKey; kind: 'boolean' } + +/** 設定ページに出す欄(`CONFIG_KEYS` のうち live のもの。並びも同じ)。 */ +export const SETTINGS_FIELDS: readonly SettingsField[] = CONFIG_KEYS.flatMap((spec): SettingsField[] => { + switch (spec.kind) { + case 'mode': + return [{ key: 'mode', kind: 'mode' }] + case 'integer': + return [{ key: spec.key, kind: 'integer', min: spec.min }] + case 'boolean': + return [{ key: spec.key, kind: 'boolean' }] + case 'string': + return [] // stateFile は設定ページでは変えない(状態ファイルの読み直しが要る) + } +}) + +/** + * 整数の欄。空欄は既定値に戻す(clear)。下限以上の整数だけを受け付ける。 + * 前後の空白は無視する。`1e2` や `0x10` のような書き方は受け付けない(10 進の数字だけ)。 + */ +export function integerField(field: string, min: number): FieldSpec { + return { + field, + format: (value) => (typeof value === 'number' ? String(value) : ''), + parse: (text) => { + const trimmed = text.trim() + if (trimmed === '') return { kind: 'clear' } + if (!/^[+-]?\d+$/.test(trimmed)) return undefined + const value = Number(trimmed) + return Number.isSafeInteger(value) && value >= min ? { kind: 'set', value } : undefined + }, + } +} + +/** on/off の欄。スイッチが `'true'` / `'false'` を入れる。 */ +export function booleanField(field: string): FieldSpec { + return { + field, + format: (value) => (value === true ? 'true' : value === false ? 'false' : ''), + parse: (text) => { + if (text === 'true') return { kind: 'set', value: true } + if (text === 'false') return { kind: 'set', value: false } + return text === '' ? { kind: 'clear' } : undefined + }, + } +} + +/** モードの欄。選択肢(block / archive / both / off)のどれか。 */ +export function modeField(field: string): FieldSpec { + return { + field, + format: (value) => (isMode(value) ? value : ''), + parse: (text) => (text === '' ? { kind: 'clear' } : isMode(text) ? { kind: 'set', value: text } : undefined), + } +} + +/** 設定ページの全欄の変換。 */ +export function fieldSpecs(): FieldSpec[] { + return SETTINGS_FIELDS.map((field) => { + switch (field.kind) { + case 'mode': + return modeField(field.key) + case 'integer': + return integerField(field.key, field.min) + case 'boolean': + return booleanField(field.key) + } + }) +} diff --git a/src/client/settings-page.ts b/src/client/settings-page.ts new file mode 100644 index 0000000..1872f24 --- /dev/null +++ b/src/client/settings-page.ts @@ -0,0 +1,265 @@ +/** + * cache-sentinel の設定ページ (#10)。DSH の「プラグイン」画面の cache-sentinel のページ + * (`plugins.bundle.config` スロット、キーはパッケージ名)に、設定フォームを出す。 + * + * - 値の読み書きは DSH の `configForms`(Host の設定サービスの、エントリ `cache-sentinel` の分)を通す。 + * 保存した値は Host がスキーマで検証してからプロファイルの patch に書き、プラグインに反映する(docs/spike.md S3・S5)。 + * - 欄の並び・型・下限は `settings-fields.ts`(元は `src/config.ts` の `CONFIG_KEYS`)。 + * - 見た目は DSH 公式の設定ページと同じ部品(`SettingsForm`・`SettingsValueField`・`Switch`・`SegmentedControl`)。 + * 公式ページにない「モード」「スイッチ」の行だけ、公式ページ(Web 検索・サブエージェント)と同じ形の CSS を書く。 + */ +import { + SegmentedControl, + SettingsForm, + SettingsFormModel, + SettingsValueField, + Switch, + Tag, + type SettingsFieldState, + type SettingsFormScope, + type SettingsFormShell, + type SnapshotStore, +} from '@deepseek-ai/dsh-client-ui-primitives' +import { createElement as h } from 'react' +import type { Locale } from '../i18n.ts' +import { MESSAGES, type SettingsKey } from '../messages.ts' +import { MODES, type Mode } from '../modes.ts' +import { fieldSpecs, SETTINGS_FIELDS } from './settings-fields.ts' + +/** Host のエントリ id(cordis.patch.yml の `id`)。設定サービスの名前空間になる。 */ +export const ENTRY_ID = 'cache-sentinel' +/** 設定ページを出すスロットのキー(パッケージ名)。 */ +export const PACKAGE_NAME = 'cache-sentinel' + +/** 設定ページの表示状態。 */ +export type SettingsPageState = SettingsFormShell & Record + +/** スロットに渡す face。`hooks.settingsPage` は部品側で `useSettingsPage` になる。 */ +export interface SettingsPageFace { + hooks: { settingsPage: SnapshotStore } + locale: Locale + edit: (field: string, text: string) => void + resetField: (field: string) => void + save: () => void + discard: () => void +} + +/** 部品が受け取る props。 */ +export interface SettingsPageProps { + view?: 'summary' | 'page' + locale: Locale + useSettingsPage: (selector: (state: SettingsPageState) => S) => S + edit: (field: string, text: string) => void + resetField: (field: string) => void + save: () => void + discard: () => void +} + +/** 設定フォームの状態(入力中の値・検証・保存)を持つ。DSH の `SettingsFormModel` に任せる。 */ +export class SettingsPageController { + private readonly form: SettingsFormModel> + private readonly store: SnapshotStore + private readonly locale: Locale + + constructor(scope: SettingsFormScope>, locale: Locale) { + this.locale = locale + this.form = new SettingsFormModel(scope, fieldSpecs()) + this.store = this.form.bind(() => this.projection()) + } + + private projection(): SettingsPageState { + const fields = Object.fromEntries(SETTINGS_FIELDS.map((field) => [field.key, this.form.field(field.key)])) + return { ...this.form.shell(), ...(fields as Record) } + } + + face(): SettingsPageFace { + return { hooks: { settingsPage: this.store }, locale: this.locale, ...this.form.actions() } + } + + dispose(): void { + this.form.dispose() + } +} + +/** + * モード・スイッチの行の見た目。`SettingsValueField` と同じ形(見出しの行・説明・行の間の線・「変更あり」と + * 「既定値に戻す」)にそろえる。値は primitives 0.2.2-alpha.2 の `settings-form/fields.module.css` から写した + * (docs/spike.md S5)。行の間の線は、入力欄の行も含めて全行に引く。 + */ +const CSS = ` +.cache-sentinel-settings-rows { + display: flex; + flex-direction: column; +} +.cache-sentinel-settings-rows > * + * { + border-top: 0.5px solid var(--dsw-alias-border-l2); +} +.cache-sentinel-settings-field { + display: flex; + flex-direction: column; + gap: 6px; + padding: 12px 0; +} +.cache-sentinel-settings-head { + display: flex; + align-items: center; + gap: 8px; +} +.cache-sentinel-settings-label { + flex: 1; + min-width: 0; + color: var(--dsw-alias-label-primary); + font-size: 13px; + font-weight: 500; + line-height: 1.5; +} +.cache-sentinel-settings-badges { + display: inline-flex; + align-items: center; + gap: 8px; +} +.cache-sentinel-settings-reset { + padding: 0; + border: none; + background: none; + color: var(--dsw-alias-label-secondary); + font: inherit; + font-size: 12px; + line-height: 1.5; + cursor: pointer; +} +.cache-sentinel-settings-reset:disabled { + cursor: default; +} +@media (hover: hover) { + .cache-sentinel-settings-reset:hover:not(:disabled) { + color: var(--dsw-alias-label-primary); + } +} +.cache-sentinel-settings-hint, +.cache-sentinel-settings-note { + margin: 0; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + line-height: 1.5; +} +.cache-sentinel-settings-note { + padding-top: 4px; +} +` + +/** 見出しの行: 見出し、既定から変えているときは「変更あり」と「既定値に戻す」、行末の操作(スイッチ)。 */ +function head( + props: SettingsPageProps, + key: SettingsKey, + state: SettingsFieldState, + disabled: boolean, + labelId: string, + control: unknown = null, +) { + const m = MESSAGES[props.locale] + return h( + 'div', + { className: 'cache-sentinel-settings-head' }, + h('span', { id: labelId, className: 'cache-sentinel-settings-label' }, m.settingsLabels[key]), + state.overridden + ? h( + 'span', + { className: 'cache-sentinel-settings-badges' }, + h(Tag, { tone: 'neutral' }, m.settingsOverridden), + h( + 'button', + { type: 'button', className: 'cache-sentinel-settings-reset', disabled, onClick: () => props.resetField(key) }, + m.settingsReset, + ), + ) + : null, + control, + ) +} + +/** 設定ページの部品。`summary` を求められたら何も出さない(バンドルの設定は `page` だけが描かれる)。 */ +export function SettingsPage(props: SettingsPageProps) { + const state = props.useSettingsPage((snapshot) => snapshot) + if (props.view === 'summary') return null + const m = MESSAGES[props.locale] + const disabled = !state.writable || state.saving + + const rows = SETTINGS_FIELDS.map((field) => { + const key = field.key + const id = `cache-sentinel-settings-${key}` + const fieldState = state[key] + switch (field.kind) { + case 'integer': + return h(SettingsValueField, { + key, + id, + label: m.settingsLabels[key], + hint: m.settingsHints[key], + overriddenLabel: m.settingsOverridden, + resetLabel: m.settingsReset, + invalidLabel: m.settingsInvalidInteger(field.min), + numeric: true, + disabled, + text: fieldState.text, + overridden: fieldState.overridden, + invalid: fieldState.invalid, + onEdit: (text: string) => props.edit(key, text), + onReset: () => props.resetField(key), + }) + case 'boolean': + return h( + 'div', + { key, className: 'cache-sentinel-settings-field', 'data-testid': id }, + head( + props, + key, + fieldState, + disabled, + `${id}-label`, + h(Switch, { + checked: fieldState.text === 'true', + label: m.settingsLabels[key], + disabled, + onChange: (next: boolean) => props.edit(key, String(next)), + }), + ), + h('p', { className: 'cache-sentinel-settings-hint' }, m.settingsHints[key]), + ) + case 'mode': + return h( + 'div', + { key, className: 'cache-sentinel-settings-field', 'data-testid': id }, + head(props, key, fieldState, disabled, `${id}-label`), + h(SegmentedControl, { + id, + value: (MODES as readonly string[]).includes(fieldState.text) ? (fieldState.text as Mode) : 'block', + options: MODES.map((mode) => ({ value: mode, label: m.settingsModeOptions[mode] })), + label: m.settingsLabels.mode, + disabled, + onChange: (next: Mode) => props.edit('mode', next), + }), + h('p', { className: 'cache-sentinel-settings-hint' }, m.settingsHints.mode), + ) + } + }) + + return h( + SettingsForm, + { + labels: { + unavailable: m.settingsUnavailable, + readOnly: m.settingsReadOnly, + saveFailed: m.settingsSaveFailed, + save: m.settingsSave, + saving: m.settingsSaving, + }, + state, + onSave: props.save, + onDiscard: props.discard, + }, + h('style', null, CSS), + h('div', { className: 'cache-sentinel-settings-rows' }, ...rows), + h('p', { className: 'cache-sentinel-settings-note' }, m.settingsStateFileNote), + ) +} diff --git a/src/config-schema.ts b/src/config-schema.ts new file mode 100644 index 0000000..46bc471 --- /dev/null +++ b/src/config-schema.ts @@ -0,0 +1,101 @@ +/** + * 設定画面用の Config スキーマ (#10)。キー・型・下限・既定値は `src/config.ts` の `CONFIG_KEYS` と `DEFAULTS` から作る。 + * + * `@deepseek-ai/schemastery` は DSH が実行時に提供するもので、依存には入れない(docs/spike.md S1)。 + * 読み込めない環境(テスト・CI・DSH の外)では `ConfigSchema` は undefined になり、設定画面に項目が出ないだけで + * プラグインの動作は変わらない(検証は `parseConfig` が行う)。 + * トップレベル await を使うので、ブラウザ向けのクライアント半分からは import しない。 + */ +import { CONFIG_KEYS, DEFAULTS, type ConfigKeySpec } from './config.ts' +import { MODES } from './modes.ts' + +/** + * schemastery の、このプラグインが使う部分だけの形 (型定義を依存に持ち込まないため)。 + * 本物は `@deepseek-ai/schemastery`(DSH が実行時に提供する。docs/spike.md S1)。 + */ +export interface SchemaNode { + default(value: unknown): SchemaNode + description(text: string): SchemaNode + min(value: number): SchemaNode + step(value: number): SchemaNode + volatile(): SchemaNode +} + +/** schemastery の既定エクスポート(`Schema`)のうち使う部分。 */ +export interface SchemaFactory { + object(dict: Record): SchemaNode + union(list: readonly SchemaNode[]): SchemaNode + const(value: string): SchemaNode + number(): SchemaNode + boolean(): SchemaNode + string(): SchemaNode +} + +/** + * 各キーの説明(英語)。設定画面の文言はクライアントが表示言語で持つ(src/client/settings-page.ts)ので、 + * ここは `dsh --dump-config-schema` などスキーマを直接読む道具向け。 + */ +const DESCRIPTIONS: Record = { + mode: 'Default mode: block (reject sends), archive, both, or off. /sentinel can override it.', + idleMinutes: 'Minutes since the last response after which sends are blocked (the archive threshold in archive mode).', + archiveAfterMinutes: 'Archive threshold in minutes in both mode.', + unlockTtlMinutes: 'Minutes an /unlock allowance stays valid.', + checkIntervalSeconds: 'Seconds between archive checks.', + skipPinned: 'Do not archive pinned sessions.', + archiveExisting: 'Also archive sessions that stopped before archiving was first enabled.', + maxPerCycle: 'Maximum number of sessions archived per check.', + dryRun: 'Only log; neither block nor archive.', + stateFile: 'Path of the state file. Defaults to $DSH_HOME/cache-sentinel/profiles//state.json.', +} + +/** + * 設定画面用の Config スキーマを `CONFIG_KEYS` と `DEFAULTS` から組む (#10)。 + * - 整数は `number().step(1).min(下限)`(schemastery の `natural()` と同じ作り方で下限だけ変える)。 + * - `live` のキーは `.volatile()`。DSH の設定画面は volatile なキーだけを編集対象にする(docs/spike.md S2)。 + * - 未知キーの拒否とエラー文面の表示言語はスキーマでは表せないので `parseConfig` が受け持つ。 + * `z` を引数で受けるのは、schemastery の無い環境(テスト・CI)でも組み立て方を検査できるようにするため。 + */ +export function buildConfigSchema(z: SchemaFactory): SchemaNode { + const dict: Record = {} + for (const spec of CONFIG_KEYS) { + let node: SchemaNode + switch (spec.kind) { + case 'mode': + node = z.union(MODES.map((mode) => z.const(mode))).default(DEFAULTS.mode) + break + case 'integer': + node = z.number().step(1).min(spec.min).default(DEFAULTS[spec.key]) + break + case 'boolean': + node = z.boolean().default(DEFAULTS[spec.key]) + break + case 'string': + node = z.string() + break + } + node = node.description(DESCRIPTIONS[spec.key]) + dict[spec.key] = spec.live ? node.volatile() : node + } + return z.object(dict) +} + +/** + * DSH が提供する `@deepseek-ai/schemastery` を読み込む。読めない環境(テスト・CI・DSH の外)では undefined。 + * 依存には入れず、ビルドでも `external: ['@deepseek-ai/*']` で外す(docs/spike.md S1)。 + */ +export async function loadSchemaFactory(): Promise { + try { + const specifier = '@deepseek-ai/schemastery' + const mod = (await import(specifier)) as { default?: unknown } + return typeof mod.default === 'function' ? (mod.default as unknown as SchemaFactory) : undefined + } catch { + return undefined + } +} + + +/** DSH が `runtime.Config` として読むスキーマ。`src/index.ts` が `Config` の名前で export する。 */ +export const ConfigSchema: SchemaNode | undefined = await (async () => { + const z = await loadSchemaFactory() + return z === undefined ? undefined : buildConfigSchema(z) +})() diff --git a/src/config.ts b/src/config.ts index 9283761..b4754d4 100644 --- a/src/config.ts +++ b/src/config.ts @@ -28,8 +28,40 @@ export const DEFAULTS: Required> = { dryRun: false, } -/** stateFile は既定値を持たない(未指定なら呼び出し側が場所を決める)ので別に足す。 */ -const KNOWN_KEYS: ReadonlySet = new Set([...Object.keys(DEFAULTS), 'stateFile']) +/** 整数の設定キー。 */ +export type IntegerKey = 'idleMinutes' | 'archiveAfterMinutes' | 'unlockTtlMinutes' | 'checkIntervalSeconds' | 'maxPerCycle' +/** boolean の設定キー。 */ +export type BooleanKey = 'skipPinned' | 'archiveExisting' | 'dryRun' + +/** + * 設定キー 1 つの仕様 (spec §6)。`parseConfig` と設定画面用スキーマ(`buildConfigSchema`)は + * どちらもこの表だけを見る(#10。二重管理しない)。既定値は `DEFAULTS` にある。 + * - `live`: 設定画面から変えられ、保存するとプラグインを読み込み直さずに反映するキー + * (スキーマで `.volatile()` にする。docs/spike.md「設定スキーマ」S2・S4)。 + * `stateFile` は状態ファイルの読み直しが要るので live にしない(YAML だけで変える。変えると再読み込み)。 + */ +export type ConfigKeySpec = + | { readonly key: 'mode'; readonly kind: 'mode'; readonly live: true } + | { readonly key: IntegerKey; readonly kind: 'integer'; readonly min: number; readonly live: true } + | { readonly key: BooleanKey; readonly kind: 'boolean'; readonly live: true } + | { readonly key: 'stateFile'; readonly kind: 'string'; readonly live: false } + +/** 設定キーの一覧 (spec §6)。並びは検証の順序と設定画面の並び順。 */ +export const CONFIG_KEYS: readonly ConfigKeySpec[] = [ + { key: 'mode', kind: 'mode', live: true }, + { key: 'idleMinutes', kind: 'integer', min: 1, live: true }, + { key: 'archiveAfterMinutes', kind: 'integer', min: 1, live: true }, + { key: 'unlockTtlMinutes', kind: 'integer', min: 1, live: true }, + { key: 'checkIntervalSeconds', kind: 'integer', min: 10, live: true }, + { key: 'skipPinned', kind: 'boolean', live: true }, + { key: 'archiveExisting', kind: 'boolean', live: true }, + { key: 'maxPerCycle', kind: 'integer', min: 1, live: true }, + { key: 'dryRun', kind: 'boolean', live: true }, + { key: 'stateFile', kind: 'string', live: false }, +] + +/** stateFile は既定値を持たない(未指定なら呼び出し側が場所を決める)。 */ +const KNOWN_KEYS: ReadonlySet = new Set(CONFIG_KEYS.map((spec) => spec.key)) function readInteger(raw: Record, key: string, min: number, m: Messages): number { const value = raw[key] @@ -97,36 +129,43 @@ export function parseConfig(raw: unknown, locale: Locale): Config { const config: Config = { ...DEFAULTS } - if (obj.mode !== undefined) { - config.mode = readMode(obj, m) - } - if (obj.idleMinutes !== undefined) { - config.idleMinutes = readInteger(obj, 'idleMinutes', 1, m) - } - if (obj.archiveAfterMinutes !== undefined) { - config.archiveAfterMinutes = readInteger(obj, 'archiveAfterMinutes', 1, m) - } - if (obj.unlockTtlMinutes !== undefined) { - config.unlockTtlMinutes = readInteger(obj, 'unlockTtlMinutes', 1, m) - } - if (obj.checkIntervalSeconds !== undefined) { - config.checkIntervalSeconds = readInteger(obj, 'checkIntervalSeconds', 10, m) - } - if (obj.skipPinned !== undefined) { - config.skipPinned = readBoolean(obj, 'skipPinned', m) - } - if (obj.archiveExisting !== undefined) { - config.archiveExisting = readBoolean(obj, 'archiveExisting', m) - } - if (obj.maxPerCycle !== undefined) { - config.maxPerCycle = readInteger(obj, 'maxPerCycle', 1, m) - } - if (obj.dryRun !== undefined) { - config.dryRun = readBoolean(obj, 'dryRun', m) - } - if (obj.stateFile !== undefined) { - config.stateFile = readString(obj, 'stateFile', m) + for (const spec of CONFIG_KEYS) { + if (obj[spec.key] === undefined) continue + switch (spec.kind) { + case 'mode': + config.mode = readMode(obj, m) + break + case 'integer': + config[spec.key] = readInteger(obj, spec.key, spec.min, m) + break + case 'boolean': + config[spec.key] = readBoolean(obj, spec.key, m) + break + case 'string': + config.stateFile = readString(obj, spec.key, m) + break + } } return config } + +/** + * DSH が `apply` に渡す設定を、ふつうの値のオブジェクトに戻す (純粋関数)。 + * スキーマで `.volatile()` にしたキーは、値ではなく `get()` で今の値を返す参照 + * (`@deepseek-ai/cosmokit` の `Volatile`)として渡される(docs/spike.md S3)。 + * 設定の値はすべてプリミティブなので、`get` 関数を持つオブジェクトを参照とみなして中身に置き換える。 + * オブジェクト以外(undefined など)はそのまま返し、検証は `parseConfig` に任せる。 + */ +export function plainConfig(raw: unknown): unknown { + if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return raw + const result: Record = {} + for (const [key, value] of Object.entries(raw)) { + result[key] = isVolatileRef(value) ? value.get() : value + } + return result +} + +function isVolatileRef(value: unknown): value is { get(): unknown } { + return typeof value === 'object' && value !== null && typeof (value as { get?: unknown }).get === 'function' +} diff --git a/src/index.ts b/src/index.ts index 6072b35..8f10a18 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,13 +13,14 @@ import { createDeps, resolveHome, type ArchiveServices } from './archive.ts' import { createSentinel, type AgentLike, + type BlockSettings, type AgentStatus, type CommandResult, type PreStepDecision, type PreStepPayload, type SessionLike, } from './block.ts' -import { parseConfig, type Config } from './config.ts' +import { parseConfig, plainConfig, type Config } from './config.ts' import { runCycle, type CycleDeps } from './cycle.ts' import { resolveLocale, type Locale } from './i18n.ts' import type { TimedEvent } from './last-response.ts' @@ -42,6 +43,12 @@ import type { StatusPayload } from './status.ts' export const name = 'cache-sentinel' export const inject = ['commands', 'workspaceRegistry', 'sessionPersistence', 'sessions', 'timer', 'connection'] +/** + * 設定のスキーマ (#10)。DSH はこれで YAML の値を検証し、設定画面(プラグインのページ)の編集対象を決める。 + * DSH の外では undefined(docs/spike.md「設定スキーマ」S1)。 + */ +export { ConfigSchema as Config } from './config-schema.ts' + /** 送信前表示のための状態の取得口(spec-ui.md §E1)。 */ export const STATUS_PATH = '/api/cache-sentinel.status' @@ -55,6 +62,12 @@ export interface HostContext extends ArchiveServices { options: { prepend: boolean }, ): () => boolean on(name: 'session/event', listener: (session: SessionLike, event: TimedEvent) => void): () => boolean + /** + * 設定画面などで volatile なキーだけが変わり、プラグインを読み込み直さずに新しい値が入ったとき。 + * 型は `@deepseek-ai/cordis-plugin-loader` の `'loader/volatile-update'`(payload は変わったキーのパスの配列)。 + * 自分の fiber にだけ届く(docs/spike.md S3)。 + */ + on(name: 'loader/volatile-update', listener: (paths: readonly (readonly string[])[]) => void): () => boolean /** * エージェントの状態遷移(idle ⇄ running)。 * 型は `@deepseek-ai/dsh-agent` の `runtime-types.d.ts` の `'agent/status'`(payload は `{ agent, status }`)。 @@ -170,16 +183,25 @@ export interface Runtime { tick(): Promise /** 状態の取得口の中身。session が undefined なら読み込まれていないセッション。 */ status(session: SessionLike | undefined): StatusPayload + /** + * 設定を差し替える(設定画面で保存したとき。#10)。以後の判定・アーカイブ・`/sentinel` の表示は新しい設定で行う。 + * 拒否の許可(/unlock)や最終応答時刻など、実行中に覚えている状態は持ち越す。 + * モードがアーカイブしない → する、に変わったらすぐ 1 サイクル回す(`/sentinel` と同じ)。 + */ + reconfigure(next: Config): void + /** 今の設定。 */ + config(): Config } export function createRuntime( - config: Config, + initialConfig: Config, initialState: State, cycleDeps: CycleDeps, log: Logger, io: RuntimeIO, locale: Locale, ): Runtime { + let config = initialConfig let state = initialState let prevArchived: ReadonlySet | undefined let running = false @@ -200,7 +222,19 @@ export function createRuntime( return true } - const block = createSentinel(config, log, locale, io.now, () => blocks(current().mode)) + // 入力禁止の部品には今の設定を読むビューを渡す(reconfigure の後もそのまま使える)。 + const blockSettings: BlockSettings = { + get idleMinutes() { + return config.idleMinutes + }, + get unlockTtlMinutes() { + return config.unlockTtlMinutes + }, + get dryRun() { + return config.dryRun + }, + } + const block = createSentinel(blockSettings, log, locale, io.now, () => blocks(current().mode)) const runtime: Runtime = { mode: () => current().mode, @@ -209,6 +243,17 @@ export function createRuntime( onAgentStatus: (status, session) => block.onAgentStatus(status, session), unlock: (agent) => block.unlock(agent, unlockInactiveMessage(current().mode, locale)), status: (session) => block.statusOf(session, current().mode), + config: () => config, + + reconfigure(next) { + const before = current().mode + config = next + const after = current().mode + if (archives(after) && !archives(before)) { + prevArchived = undefined + void runtime.tick() + } + }, async sentinel(agent, rawInput) { const command = parseSentinelArgs(rawInput) @@ -294,6 +339,15 @@ export function statusResponse(request: Request, lookup: (sessionId: string) => }) } +/** ログに出す設定の要約。 */ +export function describeConfig(config: Config): string { + return ( + `設定のモード ${config.mode}, 入力禁止 ${config.idleMinutes} 分, both のアーカイブ ${config.archiveAfterMinutes} 分, ` + + `/unlock ${config.unlockTtlMinutes} 分, 間隔 ${config.checkIntervalSeconds} 秒` + + `${config.dryRun ? ', dryRun' : ''}` + ) +} + export async function apply(ctx: HostContext, rawConfig?: unknown): Promise { const locale = resolveLocale([ process.env.LC_ALL, @@ -301,7 +355,8 @@ export async function apply(ctx: HostContext, rawConfig?: unknown): Promise runtime.sentinel(agent, rawInput), }) - ctx.interval(() => void runtime.tick(), config.checkIntervalSeconds * 1000) + let stopInterval = ctx.interval(() => void runtime.tick(), config.checkIntervalSeconds * 1000) + // 設定画面で保存した値を、読み込み直さずに反映する(#10、docs/spike.md S3・S4)。 + // 参照の中身は DSH がスキーマで検証済みだが、未知のキーなどスキーマで弾けないものがあるので parseConfig を通す。 + ctx.on('loader/volatile-update', () => { + let next: Config + try { + next = parseConfig(plainConfig(rawConfig), locale) + } catch (error) { + log.warn(`新しい設定を反映できませんでした(前の設定のまま動きます): ${String(error)}`) + return + } + const before = runtime.config() + runtime.reconfigure(next) + if (next.checkIntervalSeconds !== before.checkIntervalSeconds) { + stopInterval() + stopInterval = ctx.interval(() => void runtime.tick(), next.checkIntervalSeconds * 1000) + } + log.info(`設定を反映しました: ${describeConfig(next)}`) + }) ctx.connection.fetch.register({ path: STATUS_PATH, methods: ['GET'], @@ -344,9 +417,7 @@ export async function apply(ctx: HostContext, rawConfig?: unknown): Promise statusResponse(request, (id) => runtime.status(ctx.sessions.get(id))), }) - log.info( - `開始 (モード ${runtime.mode()}, 入力禁止 ${config.idleMinutes} 分, both のアーカイブ ${config.archiveAfterMinutes} 分${config.dryRun ? ', dryRun' : ''})`, - ) + log.info(`開始 (モード ${runtime.mode()}, ${describeConfig(config)})`) // どのプロファイルの状態を使っているかを実機で確認できるようにする(プロファイル名が取れないときは共有ファイル)。 log.info(`状態ファイル: ${location.file}${profile === undefined ? ' (プロファイル名なし)' : ''}`) void runtime.tick() diff --git a/src/messages.ts b/src/messages.ts index 0cf1069..c07c6c4 100644 --- a/src/messages.ts +++ b/src/messages.ts @@ -6,7 +6,12 @@ * 日本語は v0.5 までの文言と 1 文字も変えていない。 */ +import type { Config } from './config.ts' import type { Locale } from './i18n.ts' +import type { Mode } from './modes.ts' + +/** 設定ページで編集できるキー(stateFile 以外。src/config.ts の CONFIG_KEYS の live)。 */ +export type SettingsKey = Exclude /** 表示言語ごとの文言。同じキーは 3 言語で同じ引数を取る。 */ export interface Messages { @@ -97,6 +102,32 @@ export interface Messages { readonly commandSentinelDescription: string /** `/sentinel` の引数のヒント(入力欄のプレースホルダ)。引数は任意。 */ readonly commandSentinelInputHint: string + + // --- 設定ページ (src/client/settings-page.ts、#10) --- + /** 各キーの見出し。 */ + readonly settingsLabels: Readonly> + /** 各キーの説明(見出しの下)。 */ + readonly settingsHints: Readonly> + /** モードの選択肢の表示名。 */ + readonly settingsModeOptions: Readonly> + /** 整数の入力が不正なとき。 */ + readonly settingsInvalidInteger: (min: number) => string + /** 既定から変えている印。 */ + readonly settingsOverridden: string + /** 既定に戻すボタン。 */ + readonly settingsReset: string + /** 設定が読み取り専用のとき。 */ + readonly settingsReadOnly: string + /** Host 側が動いていなくて設定できないとき。 */ + readonly settingsUnavailable: string + /** 保存ボタン。 */ + readonly settingsSave: string + /** 保存中のボタン。 */ + readonly settingsSaving: string + /** 保存が受け付けられなかったとき。 */ + readonly settingsSaveFailed: string + /** stateFile はここでは変えられない旨。 */ + readonly settingsStateFileNote: string } const en: Messages = { @@ -153,6 +184,38 @@ const en: Messages = { commandSentinelDescription: 'Show cache-sentinel status and switch mode: /sentinel [block|archive|both|off|default]', commandSentinelInputHint: '[block|archive|both|off|default]', + settingsLabels: { + mode: 'Mode', + idleMinutes: 'Minutes until sends are blocked', + archiveAfterMinutes: 'Minutes until archiving (both mode)', + unlockTtlMinutes: 'Minutes /unlock stays valid', + checkIntervalSeconds: 'Archive check interval (seconds)', + skipPinned: 'Do not archive pinned sessions', + archiveExisting: 'Also archive sessions that were already idle', + maxPerCycle: 'Sessions archived per check (max)', + dryRun: 'Dry run (log only)', + }, + settingsHints: { + mode: 'block: block sends; archive: archive sessions; both: block, then archive later; off: do nothing. A mode chosen with /sentinel takes precedence (/sentinel default returns to this one).', + idleMinutes: 'Minutes since the last response. Also the archive threshold in archive mode. Integer, 1 or more.', + archiveAfterMinutes: 'Archive threshold in both mode. Integer, 1 or more.', + unlockTtlMinutes: 'How long an /unlock allowance lasts. Integer, 1 or more.', + checkIntervalSeconds: 'How often to look for sessions to archive. Integer, 10 or more.', + skipPinned: 'Pinned sessions are never archived.', + archiveExisting: 'Include sessions that stopped before archiving was first enabled.', + maxPerCycle: 'Upper limit per check. Integer, 1 or more.', + dryRun: 'Neither block nor archive; only write what would happen to the log.', + }, + settingsModeOptions: { block: 'block', archive: 'archive', both: 'both', off: 'off' }, + settingsInvalidInteger: (min) => `Enter an integer of ${min} or more, or leave blank to use the default.`, + settingsOverridden: 'Changed', + settingsReset: 'Reset to default', + settingsReadOnly: 'This deployment stores settings read-only.', + settingsUnavailable: 'cache-sentinel is not running, so it cannot be configured right now.', + settingsSave: 'Save', + settingsSaving: 'Saving…', + settingsSaveFailed: 'These values were not accepted; they are kept here for you to correct.', + settingsStateFileNote: 'The state file location (stateFile) is set in the profile patch, not here.', } const ja: Messages = { @@ -209,6 +272,38 @@ const ja: Messages = { commandSentinelDescription: 'cache-sentinel の状態表示とモード切り替え: /sentinel [block|archive|both|off|default]', commandSentinelInputHint: '[block|archive|both|off|default]', + settingsLabels: { + mode: 'モード', + idleMinutes: '入力禁止までの分数', + archiveAfterMinutes: 'アーカイブまでの分数(both モード)', + unlockTtlMinutes: '/unlock の有効時間(分)', + checkIntervalSeconds: 'アーカイブの確認間隔(秒)', + skipPinned: 'ピン留めしたセッションはアーカイブしない', + archiveExisting: '前から止まっていたセッションもアーカイブする', + maxPerCycle: '1 回にアーカイブする上限', + dryRun: 'ログだけ出す(dryRun)', + }, + settingsHints: { + mode: 'block: 送信を止める / archive: アーカイブする / both: 送信を止め、さらに後でアーカイブ / off: 何もしない。/sentinel で選んだモードがあればそちらが優先されます(/sentinel default でここの値に戻ります)。', + idleMinutes: '最終応答からの分数。archive モードではアーカイブのしきい値にもなります。1 以上の整数。', + archiveAfterMinutes: 'both モードのアーカイブのしきい値。1 以上の整数。', + unlockTtlMinutes: '/unlock で許可した送信の有効時間。1 以上の整数。', + checkIntervalSeconds: 'アーカイブするセッションを探す間隔。10 以上の整数。', + skipPinned: 'ピン留めしたセッションはアーカイブしません。', + archiveExisting: 'アーカイブを初めて有効にする前に止まっていたセッションも対象にします。', + maxPerCycle: '1 回の確認でアーカイブする件数の上限。1 以上の整数。', + dryRun: '送信を止めず、アーカイブもせず、そうする予定だったことをログに出すだけにします。', + }, + settingsModeOptions: { block: 'block', archive: 'archive', both: 'both', off: 'off' }, + settingsInvalidInteger: (min) => `${min} 以上の整数を入力してください。空欄にすると既定値に戻ります。`, + settingsOverridden: '変更あり', + settingsReset: '既定値に戻す', + settingsReadOnly: 'この環境では設定は読み取り専用です。', + settingsUnavailable: 'cache-sentinel が動いていないため、いまは設定できません。', + settingsSave: '保存', + settingsSaving: '保存中…', + settingsSaveFailed: 'この値は受け付けられませんでした。直せるよう入力はそのまま残しています。', + settingsStateFileNote: '状態ファイルの場所(stateFile)は、ここではなくプロファイルの patch で設定します。', } const zhCN: Messages = { @@ -265,6 +360,38 @@ const zhCN: Messages = { commandSentinelDescription: '显示 cache-sentinel 状态并切换模式:/sentinel [block|archive|both|off|default]', commandSentinelInputHint: '[block|archive|both|off|default]', + settingsLabels: { + mode: '模式', + idleMinutes: '禁止发送前的分钟数', + archiveAfterMinutes: '归档前的分钟数(both 模式)', + unlockTtlMinutes: '/unlock 的有效分钟数', + checkIntervalSeconds: '归档检查间隔(秒)', + skipPinned: '不归档已置顶的会话', + archiveExisting: '也归档此前已停止的会话', + maxPerCycle: '每次检查最多归档的会话数', + dryRun: '仅记录日志(dryRun)', + }, + settingsHints: { + mode: 'block:禁止发送;archive:归档会话;both:禁止发送,之后再归档;off:不执行任何操作。若用 /sentinel 选择了模式,则以其为准(/sentinel default 可恢复为此处的值)。', + idleMinutes: '距上次响应的分钟数。在 archive 模式下也是归档阈值。不小于 1 的整数。', + archiveAfterMinutes: 'both 模式的归档阈值。不小于 1 的整数。', + unlockTtlMinutes: '/unlock 许可的有效时间。不小于 1 的整数。', + checkIntervalSeconds: '查找待归档会话的间隔。不小于 10 的整数。', + skipPinned: '已置顶的会话不会被归档。', + archiveExisting: '包括首次启用归档之前就已停止的会话。', + maxPerCycle: '每次检查归档的数量上限。不小于 1 的整数。', + dryRun: '既不禁止发送也不归档,只把将要执行的操作写入日志。', + }, + settingsModeOptions: { block: 'block', archive: 'archive', both: 'both', off: 'off' }, + settingsInvalidInteger: (min) => `请输入不小于 ${min} 的整数;留空则使用默认值。`, + settingsOverridden: '已修改', + settingsReset: '恢复默认', + settingsReadOnly: '本部署的设置为只读。', + settingsUnavailable: 'cache-sentinel 未运行,暂时无法设置。', + settingsSave: '保存', + settingsSaving: '保存中…', + settingsSaveFailed: '这些值未被接受,已保留供你修改。', + settingsStateFileNote: '状态文件的位置(stateFile)在配置文件的 patch 中设置,不在此处。', } /** 表示言語ごとの文言カタログ。 */ diff --git a/tests/client.test.ts b/tests/client.test.ts index 36a3633..576a694 100644 --- a/tests/client.test.ts +++ b/tests/client.test.ts @@ -5,6 +5,7 @@ * ctx は cordis と同じく、inject に宣言していないサービスに触ると例外を投げる * (`cannot get property "" without inject`、docs/spike.md「クライアント側 `remote.commands` の inject」)。 * `remote.commands` は `remote` とは別のサービスキーとして扱う(#26)。 + * `inject`(任意のサービスを待つ子プラグインを作る)と `effect` はサービスではなく ctx のメソッドなので、宣言なしで使える。 */ import assert from 'node:assert/strict' import { readFileSync } from 'node:fs' @@ -28,6 +29,38 @@ interface SlotOptions { inject: (sessionId: string) => { sessionId: string; locale: string; unlock: () => Promise } } +/** 設定ページ (#10) が使う `@deepseek-ai/dsh-client-ui-primitives` の偽物。部品は描画しないので名前だけ。 */ +class FakeSettingsFormModel { + readonly specs: { field: string; parse(text: string): unknown }[] + disposed = false + constructor(_scope: unknown, specs: { field: string; parse(text: string): unknown }[]) { + this.specs = specs + } + bind(project: () => unknown) { + return { getSnapshot: project, subscribe: () => () => {} } + } + shell() { + return { available: true, writable: true, dirty: false, invalid: false, saving: false, failed: false } + } + field() { + return { text: '', overridden: false, invalid: false } + } + actions() { + return { edit() {}, resetField() {}, save() {}, discard() {} } + } + dispose() { + this.disposed = true + } +} +const fakePrimitives = { + SettingsFormModel: FakeSettingsFormModel, + SettingsForm: () => null, + SettingsValueField: () => null, + Switch: () => null, + SegmentedControl: () => null, + Tag: () => null, +} + function loadClient(): ClientModule { let loaded: ClientModule | undefined const window = { @@ -35,6 +68,7 @@ function loadClient(): ClientModule { load({ factory }: { id: string; factory: (require: (id: string) => unknown) => ClientModule }) { loaded = factory((id) => { if (id === 'react') return {} + if (id === '@deepseek-ai/dsh-client-ui-primitives') return fakePrimitives throw new Error(`unexpected require: ${id}`) }) }, @@ -52,8 +86,13 @@ function loadClient(): ClientModule { const plain = (value: unknown): unknown => JSON.parse(JSON.stringify(value)) /** cordis の ctx と同じく、宣言していないサービスへのアクセスで例外を投げる ctx。 */ -function contextFor(inject: readonly string[], services: Record): unknown { +function contextFor( + inject: readonly string[], + services: Record, + methods: { inject?: unknown; effect?: unknown } = { inject: () => {}, effect: () => {} }, +): unknown { const guard = (name: string) => { + if (name === 'inject' || name === 'effect') return methods[name] if (!inject.includes(name)) throw new Error(`cannot get property "${name}" without inject`) return services[name] } @@ -101,3 +140,78 @@ test('client: バナーの unlock がこのセッションに /unlock を実行 assert.deepEqual(await props.unlock(), { ok: true, value: { result: { kind: 'success' } } }) assert.deepEqual(plain(calls), [['ses-1', '/unlock', []]]) }) + +// ---- 設定ページ (#10) ---- + +interface PageRegistration { + name: string + key: string + inject: () => { hooks: { settingsPage: { getSnapshot(): Record } }; locale: string } +} + +test('#10: configForms がある環境では、プラグイン画面の cache-sentinel のページに設定フォームを出す', () => { + const client = loadClient() + const registered: (SlotOptions | PageRegistration)[] = [] + const injectedSlots: string[] = [] + const slots = { + inject(name: string, register: () => () => void) { + injectedSlots.push(name) + return register() + }, + register(options: SlotOptions | PageRegistration) { + registered.push(options) + return () => {} + }, + } + const effects: (() => unknown)[] = [] + const childInjects: string[][] = [] + const served: string[][] = [] + const forms: string[] = [] + const configForms = { + get(entryId: string) { + forms.push(entryId) + return { getSnapshot() {}, subscribe: () => () => {}, mutate: async () => true } + }, + whileServed(namespaces: string[], register: () => () => void) { + served.push([...namespaces]) + return register() + }, + } + const child = { + configForms, + effect: (execute: () => unknown) => { + effects.push(execute) + execute() + }, + } + client.apply( + contextFor( + client.inject, + { slots, remote: {}, 'remote.commands': {} }, + { + inject: (deps: string[], callback: (ctx: unknown) => void) => { + childInjects.push([...deps]) + callback(child) + }, + effect: () => {}, + }, + ), + ) + + // 必須の inject は増やさない(configForms が無くてもバナーは動く)。 + assert.deepEqual(plain(client.inject), ['slots', 'remote', 'remote.commands']) + assert.deepEqual(plain(childInjects), [['configForms']]) + assert.deepEqual(plain(forms), ['cache-sentinel']) + assert.deepEqual(plain(served), [['cache-sentinel']]) + assert.deepEqual(plain(injectedSlots), ['conversation.input.dock', 'plugins.bundle.config']) + const page = registered.find((entry): entry is PageRegistration => entry.name === 'plugins.bundle.config') + assert.ok(page) + assert.equal(page.key, 'cache-sentinel') + const face = page.inject() + assert.equal(face.locale, 'ja') + const snapshot = face.hooks.settingsPage.getSnapshot() + assert.deepEqual( + Object.keys(snapshot).filter((key) => !['available', 'writable', 'dirty', 'invalid', 'saving', 'failed'].includes(key)), + ['mode', 'idleMinutes', 'archiveAfterMinutes', 'unlockTtlMinutes', 'checkIntervalSeconds', 'skipPinned', 'archiveExisting', 'maxPerCycle', 'dryRun'], + ) +}) diff --git a/tests/config-schema.test.ts b/tests/config-schema.test.ts new file mode 100644 index 0000000..8edf584 --- /dev/null +++ b/tests/config-schema.test.ts @@ -0,0 +1,411 @@ +/** + * #10: 設定画面用の Config スキーマ (src/config-schema.ts)、設定キーの表 (src/config.ts の CONFIG_KEYS)、 + * 設定画面で保存したときの反映 (src/index.ts の createRuntime.reconfigure と apply の loader/volatile-update) のテスト。 + * + * 本物の `@deepseek-ai/schemastery` は DSH が実行時に提供するもので、このリポジトリの依存には無い。 + * 本物で確かめるテストは、環境変数 `CACHE_SENTINEL_SCHEMASTERY` にそのパッケージのディレクトリを渡したときだけ動く + * (例: `/node_modules/@deepseek-ai/schemastery`)。渡さなければ skip する。 + */ +import assert from 'node:assert/strict' +import { mkdtemp, rm } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' + +import { CONFIG_KEYS, DEFAULTS, parseConfig, plainConfig, type Config } from '../src/config.ts' +import { buildConfigSchema, ConfigSchema, loadSchemaFactory, type SchemaFactory, type SchemaNode } from '../src/config-schema.ts' +import type { PreStepDecision, PreStepPayload } from '../src/block.ts' +import type { CycleDeps } from '../src/cycle.ts' +import { apply, createRuntime, STATUS_PATH, type HostContext } from '../src/index.ts' +import type { Logger } from '../src/log.ts' +import { MODES } from '../src/modes.ts' +import type { StatusPayload } from '../src/status.ts' + +const MINUTE = 60_000 +const NOW = 1_700_000_000_000 + +/** 整数キーとその下限 (spec §6)。 */ +const INTEGER_KEYS: ReadonlyArray = [ + ['idleMinutes', 1], + ['archiveAfterMinutes', 1], + ['unlockTtlMinutes', 1], + ['checkIntervalSeconds', 10], + ['maxPerCycle', 1], +] +const BOOLEAN_KEYS = ['skipPinned', 'archiveExisting', 'dryRun'] as const + +// ---- 設定キーの表 ---- + +test('#10: CONFIG_KEYS は spec §6 のキー・型・下限と一致し、DEFAULTS と同じキーを持つ', () => { + assert.deepEqual( + CONFIG_KEYS.map((spec) => spec.key), + ['mode', 'idleMinutes', 'archiveAfterMinutes', 'unlockTtlMinutes', 'checkIntervalSeconds', 'skipPinned', 'archiveExisting', 'maxPerCycle', 'dryRun', 'stateFile'], + ) + for (const [key, min] of INTEGER_KEYS) { + const spec = CONFIG_KEYS.find((candidate) => candidate.key === key) + assert.ok(spec?.kind === 'integer', `${key} は integer`) + assert.equal(spec.min, min, `${key} の下限`) + } + for (const key of BOOLEAN_KEYS) { + assert.equal(CONFIG_KEYS.find((spec) => spec.key === key)?.kind, 'boolean', key) + } + assert.deepEqual( + CONFIG_KEYS.filter((spec) => spec.key !== 'stateFile').map((spec) => spec.key).sort(), + Object.keys(DEFAULTS).sort(), + ) +}) + +test('#10: stateFile 以外は設定画面から変えられる(live)', () => { + assert.deepEqual( + CONFIG_KEYS.filter((spec) => !spec.live).map((spec) => spec.key), + ['stateFile'], + ) +}) + +// ---- plainConfig ---- + +/** cosmokit の Volatile と同じ形の参照(get で今の値を返す)。 */ +function ref(value: T): { get(): T; set(next: T): void } { + let current = value + return { + get: () => current, + set: (next) => { + current = next + }, + } +} + +test('#10: plainConfig は volatile の参照を値に戻し、それ以外はそのまま返す', () => { + assert.deepEqual(plainConfig({ mode: ref('both'), idleMinutes: ref(5), stateFile: '/x' }), { + mode: 'both', + idleMinutes: 5, + stateFile: '/x', + }) + for (const raw of [undefined, null, 1, 'x', [1]]) { + assert.deepEqual(plainConfig(raw), raw) + } + // 値に戻した後は parseConfig がこれまでどおり検証する。 + assert.throws(() => parseConfig(plainConfig({ idleMinutes: ref(0) }), 'ja'), /idleMinutes/) + assert.throws(() => parseConfig(plainConfig({ typo: ref(1) }), 'ja'), /typo/) +}) + +// ---- スキーマの組み立て(偽の schemastery で記録する) ---- + +interface Recorded { + type: string + args: unknown[] + calls: [string, unknown][] + dict?: Record + list?: Recorded[] +} + +/** 呼ばれたメソッドを記録するだけの schemastery の偽物。 */ +function recordingFactory(): SchemaFactory { + const node = (type: string, args: unknown[], extra: Partial = {}): SchemaNode & Recorded => { + const self: Recorded = { type, args, calls: [], ...extra } + const chain = (name: string) => (value?: unknown) => { + self.calls.push([name, value]) + return api + } + const api = Object.assign(self, { + default: chain('default'), + description: chain('description'), + min: chain('min'), + step: chain('step'), + volatile: chain('volatile'), + }) as SchemaNode & Recorded + return api + } + return { + object: (dict) => node('object', [], { dict: dict as unknown as Record }), + union: (list) => node('union', [], { list: list as unknown as Recorded[] }), + const: (value) => node('const', [value]), + number: () => node('number', []), + boolean: () => node('boolean', []), + string: () => node('string', []), + } +} + +test('#10: buildConfigSchema は CONFIG_KEYS と DEFAULTS から型・下限・既定値・volatile を組む', () => { + const schema = buildConfigSchema(recordingFactory()) as unknown as Recorded + assert.equal(schema.type, 'object') + const dict = schema.dict ?? {} + assert.deepEqual(Object.keys(dict), CONFIG_KEYS.map((spec) => spec.key)) + + const callsOf = (key: string) => Object.fromEntries(dict[key]?.calls ?? []) + const mode = dict.mode + assert.equal(mode?.type, 'union') + assert.deepEqual(mode?.list?.map((item) => item.args[0]), [...MODES]) + for (const [key, min] of INTEGER_KEYS) { + assert.equal(dict[key]?.type, 'number', key) + assert.equal(callsOf(key).step, 1, `${key} は整数`) + assert.equal(callsOf(key).min, min, `${key} の下限`) + } + for (const key of BOOLEAN_KEYS) assert.equal(dict[key]?.type, 'boolean', key) + assert.equal(dict.stateFile?.type, 'string') + + for (const spec of CONFIG_KEYS) { + const calls = callsOf(spec.key) + assert.equal(typeof calls.description, 'string', `${spec.key} の説明`) + assert.equal('volatile' in calls, spec.live, `${spec.key} の volatile`) + if (spec.key === 'stateFile') assert.equal('default' in calls, false) + else assert.deepEqual(calls.default, DEFAULTS[spec.key], `${spec.key} の既定値`) + } +}) + +test('#10: schemastery が無い環境では Config は undefined', async () => { + // このリポジトリの依存には schemastery が無い(DSH が実行時に提供する)。 + assert.equal(await loadSchemaFactory(), undefined) + assert.equal(ConfigSchema, undefined) +}) + +// ---- 本物の schemastery での検証(環境変数があるときだけ) ---- + +const realDir = process.env.CACHE_SENTINEL_SCHEMASTERY +const real: SchemaFactory | undefined = (() => { + if (realDir === undefined || realDir === '') return undefined + const require = createRequire(join(realDir, 'package.json')) + return require(realDir) as SchemaFactory +})() +const realSkip = real === undefined ? 'CACHE_SENTINEL_SCHEMASTERY が無い(本物の schemastery は DSH が提供する)' : false + +interface RealSchema { + (value: unknown): unknown + dict: Record + '~standard': { validate(value: unknown): { value?: unknown; issues?: readonly { message: string; path?: readonly unknown[] }[] } } +} + +function realSchema(): RealSchema { + assert.ok(real) + return buildConfigSchema(real) as unknown as RealSchema +} + +/** 設定画面とホストの保存処理が通す検証(cordis の resolveConfig と同じ `~standard.validate`)。 */ +function validate(value: unknown) { + return realSchema()['~standard'].validate(value) +} + +test('#10 (本物): 空の設定は DEFAULTS になり、live のキーは get() で読む参照になる', { skip: realSkip }, () => { + const result = validate({}) + assert.equal(result.issues, undefined) + const value = result.value as Record + for (const spec of CONFIG_KEYS) { + if (!spec.live) continue + const item = value[spec.key] as { get?: () => unknown } + assert.equal(typeof item?.get, 'function', `${spec.key} は参照`) + } + assert.deepEqual(parseConfig(plainConfig(value), 'en'), { ...DEFAULTS }) +}) + +test('#10 (本物): 設定画面が編集対象にするのは stateFile 以外の全キー(volatile)', { skip: realSkip }, () => { + const dict = realSchema().dict + for (const spec of CONFIG_KEYS) { + assert.equal(dict[spec.key]?.meta.volatile === true, spec.live, spec.key) + } +}) + +test('#10 (本物): 不正な値を拒否する(下限未満・非整数・型不正・mode)', { skip: realSkip }, () => { + for (const [key, min] of INTEGER_KEYS) { + for (const bad of [min - 1, 1.5 + min, '60', true]) { + const result = validate({ [key]: bad }) + assert.ok(result.issues !== undefined && result.issues.length > 0, `${key}: ${JSON.stringify(bad)} は拒否`) + } + assert.equal(validate({ [key]: min }).issues, undefined, `${key}: 下限ちょうどは受け入れる`) + } + for (const key of BOOLEAN_KEYS) { + assert.ok(validate({ [key]: 'true' }).issues, `${key}: 文字列は拒否`) + } + assert.ok(validate({ stateFile: 1 }).issues, 'stateFile: 数値は拒否') + for (const bad of ['none', 'Block', 1]) { + assert.ok(validate({ mode: bad }).issues, `mode: ${JSON.stringify(bad)} は拒否`) + } + for (const mode of MODES) assert.equal(validate({ mode }).issues, undefined, mode) +}) + +test('#10 (本物): 全キーを指定した設定をそのまま通す', { skip: realSkip }, () => { + const raw = { + mode: 'both', + idleMinutes: 1, + archiveAfterMinutes: 2880, + unlockTtlMinutes: 30, + checkIntervalSeconds: 10, + skipPinned: false, + archiveExisting: true, + maxPerCycle: 5, + dryRun: true, + stateFile: '/var/state.json', + } + const result = validate(raw) + assert.equal(result.issues, undefined) + assert.deepEqual(parseConfig(plainConfig(result.value), 'en'), raw) +}) + +// ---- 保存したときの反映(createRuntime.reconfigure) ---- + +function silentLogger(lines: string[] = []): Logger { + return { + debug: (msg) => lines.push(`debug:${msg}`), + info: (msg) => lines.push(`info:${msg}`), + warn: (msg) => lines.push(`warn:${msg}`), + } +} + +function runtimeWith(config: Config, listCalls: { count: number }) { + const deps: CycleDeps = { + now: () => NOW, + listSessions: async () => { + listCalls.count += 1 + return [] + }, + archivedIds: () => [], + archive: async () => {}, + isActiveError: () => false, + log: silentLogger(), + } + return createRuntime(config, { version: 2, unarchivedAt: {} }, deps, silentLogger(), { now: () => NOW, save: async () => {} }, 'ja') +} + +test('#10: reconfigure の後は新しい idleMinutes で判定する', async () => { + const runtime = runtimeWith(parseConfig({ idleMinutes: 60 }, 'ja'), { count: 0 }) + const payload: PreStepPayload = { + agent: { session: { id: 's1', snapshotEvents: () => [{ type: 'step/end', time: NOW - 30 * MINUTE }] } }, + messages: [{ content: [{ type: 'text', text: '入力' }], source: { kind: 'user' } }], + turn: 1, + step: 1, + } + const next = async (): Promise => ({ kind: 'enter' }) + assert.equal((await runtime.onPreStep(payload, next)).kind, 'enter') + + runtime.reconfigure(parseConfig({ idleMinutes: 20 }, 'ja')) + assert.equal(runtime.config().idleMinutes, 20) + assert.equal((await runtime.onPreStep(payload, next)).kind, 'reject') +}) + +test('#10: reconfigure で設定のモードを変えると実効モードが変わり、アーカイブが有効になればすぐ回す', async () => { + const listCalls = { count: 0 } + const runtime = runtimeWith(parseConfig({ mode: 'block' }, 'ja'), listCalls) + assert.equal(runtime.mode(), 'block') + runtime.reconfigure(parseConfig({ mode: 'archive' }, 'ja')) + assert.equal(runtime.mode(), 'archive') + await new Promise((resolve) => setImmediate(resolve)) + assert.equal(listCalls.count, 1) +}) + +// ---- apply の配線(loader/volatile-update) ---- + +interface FakeHost { + ctx: HostContext + intervals: { delayMs: number; stopped: boolean }[] + emitVolatileUpdate(): void + status(): Promise + logs: string[] +} + +function fakeHost(): FakeHost { + const intervals: { delayMs: number; stopped: boolean }[] = [] + const listeners = new Map unknown>() + const logs: string[] = [] + let route: { fetch: (request: Request) => Promise } | undefined + const raw = { + get: () => undefined, + on(name: string, listener: (...args: unknown[]) => unknown) { + listeners.set(name, listener) + return () => true + }, + commands: { register: () => () => true }, + interval(_callback: () => void, delayMs: number) { + const entry = { delayMs, stopped: false } + intervals.push(entry) + return () => { + entry.stopped = true + } + }, + logger: silentLogger(logs), + workspaceRegistry: { archivedSessionIds: [], pinnedSessionIds: [], archiveSession: async () => {} }, + sessionPersistence: { list: async () => [] }, + sessions: { get: () => undefined }, + connection: { + fetch: { + register(next: { fetch: (request: Request) => Promise }) { + route = next + return {} + }, + }, + }, + } + return { + ctx: raw as unknown as HostContext, + intervals, + logs, + emitVolatileUpdate: () => { + const listener = listeners.get('loader/volatile-update') + assert.ok(listener, 'loader/volatile-update を購読していない') + listener([['idleMinutes']]) + }, + status: async () => { + assert.ok(route) + const response = await route.fetch(new Request(`http://x${STATUS_PATH}?sessionId=s1`)) + return (await response.json()) as StatusPayload + }, + } +} + +test('#10: apply は volatile の参照で渡された設定を読み、保存の通知で新しい値に差し替えて interval を張り直す', async (t) => { + t.mock.method(console, 'log', () => {}) + t.mock.method(console, 'warn', () => {}) + const dir = await mkdtemp(join(tmpdir(), 'cache-sentinel-schema-')) + t.after(() => rm(dir, { recursive: true, force: true })) + const host = fakeHost() + const mode = ref('block') + const dryRun = ref(false) + const interval = ref(30) + const config = { mode, dryRun, checkIntervalSeconds: interval, stateFile: join(dir, 'state.json') } + + await apply(host.ctx, config) + assert.deepEqual(host.intervals, [{ delayMs: 30_000, stopped: false }]) + assert.equal((await host.status()).mode, 'block') + assert.equal((await host.status()).dryRun, false) + + // DSH は参照の中身を書き換えてから loader/volatile-update を出す。 + mode.set('off') + dryRun.set(true) + interval.set(120) + host.emitVolatileUpdate() + + const status = await host.status() + assert.equal(status.mode, 'off') + assert.equal(status.dryRun, true) + assert.deepEqual(host.intervals, [ + { delayMs: 30_000, stopped: true }, + { delayMs: 120_000, stopped: false }, + ]) + assert.ok(host.logs.some((line) => line.startsWith('info:設定を反映しました'))) +}) + +test('#10: 間隔が変わらなければ interval は張り直さない', async (t) => { + t.mock.method(console, 'log', () => {}) + const dir = await mkdtemp(join(tmpdir(), 'cache-sentinel-schema-')) + t.after(() => rm(dir, { recursive: true, force: true })) + const host = fakeHost() + const idle = ref(60) + await apply(host.ctx, { idleMinutes: idle, stateFile: join(dir, 'state.json') }) + idle.set(5) + host.emitVolatileUpdate() + assert.deepEqual(host.intervals, [{ delayMs: 60_000, stopped: false }]) +}) + +test('#10: 反映できない値(スキーマで弾けない未知のキーなど)は warn を出して前の設定のまま動く', async (t) => { + t.mock.method(console, 'log', () => {}) + t.mock.method(console, 'warn', () => {}) + const dir = await mkdtemp(join(tmpdir(), 'cache-sentinel-schema-')) + t.after(() => rm(dir, { recursive: true, force: true })) + const host = fakeHost() + const mode = ref('block') + await apply(host.ctx, { mode, stateFile: join(dir, 'state.json') }) + mode.set('none') + host.emitVolatileUpdate() + assert.equal((await host.status()).mode, 'block') + assert.ok(host.logs.some((line) => line.startsWith('warn:新しい設定を反映できませんでした'))) + assert.equal(host.intervals.length, 1) +}) diff --git a/tests/settings-fields.test.ts b/tests/settings-fields.test.ts new file mode 100644 index 0000000..d5d3e80 --- /dev/null +++ b/tests/settings-fields.test.ts @@ -0,0 +1,69 @@ +/** #10: 設定ページの欄と、入力文字列 ⇄ 保存する値の変換 (src/client/settings-fields.ts)。 */ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { booleanField, fieldSpecs, integerField, modeField, SETTINGS_FIELDS } from '../src/client/settings-fields.ts' +import { CONFIG_KEYS } from '../src/config.ts' +import { LOCALES } from '../src/i18n.ts' +import { MESSAGES } from '../src/messages.ts' +import { MODES } from '../src/modes.ts' + +test('#10: 設定ページの欄は CONFIG_KEYS の live なキーと同じ並び(stateFile は出さない)', () => { + assert.deepEqual( + SETTINGS_FIELDS.map((field) => field.key), + CONFIG_KEYS.filter((spec) => spec.live).map((spec) => spec.key), + ) + assert.deepEqual( + fieldSpecs().map((spec) => spec.field), + SETTINGS_FIELDS.map((field) => field.key), + ) + for (const field of SETTINGS_FIELDS) { + const spec = CONFIG_KEYS.find((candidate) => candidate.key === field.key) + assert.equal(field.kind, spec?.kind, field.key) + if (field.kind === 'integer' && spec?.kind === 'integer') assert.equal(field.min, spec.min, field.key) + } +}) + +test('#10: 整数の欄は下限以上の整数だけを受け付け、空欄は既定値に戻す', () => { + const spec = integerField('checkIntervalSeconds', 10) + assert.equal(spec.format(60), '60') + assert.equal(spec.format(undefined), '') + assert.deepEqual(spec.parse('10'), { kind: 'set', value: 10 }) + assert.deepEqual(spec.parse(' 120 '), { kind: 'set', value: 120 }) + assert.deepEqual(spec.parse(''), { kind: 'clear' }) + assert.deepEqual(spec.parse(' '), { kind: 'clear' }) + for (const bad of ['9', '0', '-1', '1.5', '10.0', '1e2', '0x10', 'abc', '99', '99999999999999999999']) { + assert.equal(spec.parse(bad), undefined, `${bad} は不正`) + } +}) + +test('#10: on/off の欄は true / false を boolean にする', () => { + const spec = booleanField('dryRun') + assert.equal(spec.format(true), 'true') + assert.equal(spec.format(false), 'false') + assert.deepEqual(spec.parse('true'), { kind: 'set', value: true }) + assert.deepEqual(spec.parse('false'), { kind: 'set', value: false }) + assert.equal(spec.parse('yes'), undefined) +}) + +test('#10: モードの欄は MODES のどれかだけを受け付ける', () => { + const spec = modeField('mode') + for (const mode of MODES) { + assert.equal(spec.format(mode), mode) + assert.deepEqual(spec.parse(mode), { kind: 'set', value: mode }) + } + assert.equal(spec.format('none'), '') + assert.equal(spec.parse('Block'), undefined) +}) + +test('#10: 設定ページの文言は 3 言語とも全欄にある', () => { + for (const locale of LOCALES) { + const m = MESSAGES[locale] + for (const field of SETTINGS_FIELDS) { + assert.ok(m.settingsLabels[field.key].length > 0, `${locale} ${field.key} の見出し`) + assert.ok(m.settingsHints[field.key].length > 0, `${locale} ${field.key} の説明`) + } + for (const mode of MODES) assert.ok(m.settingsModeOptions[mode].length > 0, `${locale} ${mode}`) + assert.match(m.settingsInvalidInteger(10), /10/) + } +})