dsh-mcviseron-plugin 0.6.6 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-mcviseron-plugin",
3
- "version": "0.6.6",
4
- "description": "DeepSeek Harness (DSH) master plugin — one package hosting MCviseron's DSH components as separate bundle entries: a time-based light/dark Appearance schedule, an Auto-review fix (shutdown preset guard + Chinese approval-reason translation), and a todo plan guard that keeps multi-stage work advancing, one-shot after-session restart/close actions with task-aware waiting, and automatic auth-cookie hygiene for repeated desktop restarts.",
3
+ "version": "0.7.1",
4
+ "description": "DeepSeek Harness (DSH) master plugin — one package hosting MCviseron's DSH components as separate bundle entries: a time-based light/dark Appearance schedule, an Auto-review fix (shutdown preset guard + Chinese approval-reason translation), and a todo plan guard that keeps multi-stage work advancing, one-shot after-session restart/close actions with task-aware waiting, and automatic auth-cookie hygiene for repeated desktop restarts, and model-editable official automation tasks.",
5
5
  "license": "Apache-2.0",
6
6
  "author": {
7
7
  "name": "MCviseron",
@@ -78,7 +78,7 @@
78
78
  "scripts": {
79
79
  "build": "node build.mjs",
80
80
  "typecheck": "tsc --noEmit",
81
- "test": "node --experimental-strip-types test/schedule.test.ts && node --experimental-strip-types test/routes.test.ts && node --experimental-strip-types test/config.test.ts && node --experimental-strip-types test/auto-review-fix.test.ts && node --experimental-strip-types test/auto-review-fix-cordis.test.ts && node --experimental-strip-types test/review-context.test.ts && node --experimental-strip-types test/global-notice.test.ts && node --experimental-strip-types test/task-guard.test.ts && node --experimental-strip-types test/task-guard-cordis.test.ts && node --experimental-strip-types test/session-end.test.ts && node --experimental-strip-types test/auth-cookie.test.ts && node --experimental-strip-types test/restart.test.ts && node --experimental-strip-types test/plugin.test.ts",
81
+ "test": "node --experimental-strip-types test/schedule.test.ts && node --experimental-strip-types test/routes.test.ts && node --experimental-strip-types test/config.test.ts && node --experimental-strip-types test/auto-review-fix.test.ts && node --experimental-strip-types test/auto-review-fix-cordis.test.ts && node --experimental-strip-types test/review-context.test.ts && node --experimental-strip-types test/global-notice.test.ts && node --experimental-strip-types test/task-guard.test.ts && node --experimental-strip-types test/task-guard-cordis.test.ts && node --experimental-strip-types test/session-end.test.ts && node --experimental-strip-types test/auth-cookie.test.ts && node --experimental-strip-types test/automation-tasks.test.ts && node --experimental-strip-types test/restart.test.ts && node --experimental-strip-types test/plugin.test.ts",
82
82
  "check": "pnpm typecheck && pnpm test && pnpm build",
83
83
  "prepare": "pnpm build",
84
84
  "prepublishOnly": "pnpm check",
@@ -89,12 +89,12 @@
89
89
  },
90
90
  "peerDependencies": {
91
91
  "@deepseek-ai/cordis": "^4.0.1",
92
- "@deepseek-ai/dsh-client-connection": "^0.2.0-rc.2 || ^0.2.1-rc.2",
93
- "@deepseek-ai/dsh-client-locale": "^0.2.0-rc.2 || ^0.2.1-rc.2",
94
- "@deepseek-ai/dsh-client-ui-settings": "^0.2.0-rc.2 || ^0.2.1-rc.2",
95
- "@deepseek-ai/dsh-client-ui-slots": "^0.2.0-rc.2 || ^0.2.1-rc.2",
96
- "@deepseek-ai/dsh-host-webserver": "^0.2.0-rc.2 || ^0.2.1-rc.2",
97
- "@deepseek-ai/dsh-settings": "^0.2.0-rc.2 || ^0.2.1-rc.2",
92
+ "@deepseek-ai/dsh-client-connection": "^0.2.0-rc.2 || ^0.2.1-rc.2 || ^0.2.1-rc.3 || ^0.2.1-rc.5",
93
+ "@deepseek-ai/dsh-client-locale": "^0.2.0-rc.2 || ^0.2.1-rc.2 || ^0.2.1-rc.3 || ^0.2.1-rc.5",
94
+ "@deepseek-ai/dsh-client-ui-settings": "^0.2.0-rc.2 || ^0.2.1-rc.2 || ^0.2.1-rc.3 || ^0.2.1-rc.5",
95
+ "@deepseek-ai/dsh-client-ui-slots": "^0.2.0-rc.2 || ^0.2.1-rc.2 || ^0.2.1-rc.3 || ^0.2.1-rc.5",
96
+ "@deepseek-ai/dsh-host-webserver": "^0.2.0-rc.2 || ^0.2.1-rc.2 || ^0.2.1-rc.3 || ^0.2.1-rc.5",
97
+ "@deepseek-ai/dsh-settings": "^0.2.0-rc.2 || ^0.2.1-rc.2 || ^0.2.1-rc.3 || ^0.2.1-rc.5",
98
98
  "react": "^18.2.0",
99
99
  "react-dom": "^18.2.0"
100
100
  },
@@ -129,14 +129,14 @@
129
129
  },
130
130
  "devDependencies": {
131
131
  "@deepseek-ai/cordis": "^4.0.5",
132
- "@deepseek-ai/dsh-client-connection": "^0.2.1-rc.2",
133
- "@deepseek-ai/dsh-client-locale": "^0.2.1-rc.2",
134
- "@deepseek-ai/dsh-client-store": "^0.2.1-rc.2",
135
- "@deepseek-ai/dsh-client-ui-renderer": "^0.2.1-rc.2",
136
- "@deepseek-ai/dsh-client-ui-settings": "^0.2.1-rc.2",
137
- "@deepseek-ai/dsh-client-ui-slots": "^0.2.1-rc.2",
138
- "@deepseek-ai/dsh-host-webserver": "^0.2.1-rc.2",
139
- "@deepseek-ai/dsh-settings": "^0.2.1-rc.2",
132
+ "@deepseek-ai/dsh-client-connection": "^0.2.1-rc.5",
133
+ "@deepseek-ai/dsh-client-locale": "^0.2.1-rc.5",
134
+ "@deepseek-ai/dsh-client-store": "^0.2.1-rc.5",
135
+ "@deepseek-ai/dsh-client-ui-renderer": "^0.2.1-rc.5",
136
+ "@deepseek-ai/dsh-client-ui-settings": "^0.2.1-rc.5",
137
+ "@deepseek-ai/dsh-client-ui-slots": "^0.2.1-rc.5",
138
+ "@deepseek-ai/dsh-host-webserver": "^0.2.1-rc.5",
139
+ "@deepseek-ai/dsh-settings": "^0.2.1-rc.5",
140
140
  "@types/node": "^22.20.0",
141
141
  "@types/nodemailer": "^6.4.15",
142
142
  "@types/react": "~18.3.1",
@@ -147,6 +147,13 @@
147
147
  "react": "^18.3.1",
148
148
  "react-dom": "^18.3.1",
149
149
  "typescript": "~5.7.2",
150
- "zustand": "4.4.7"
150
+ "zustand": "4.4.7",
151
+ "@deepseek-ai/dsh-scope": "^0.2.1-rc.5",
152
+ "@deepseek-ai/dsh-brand": "^0.2.1-rc.5",
153
+ "@deepseek-ai/dsh-session": "^0.2.1-rc.5",
154
+ "@deepseek-ai/dsh-app-boot": "^0.2.1-rc.5",
155
+ "@deepseek-ai/dsh-config-editor": "^0.2.1-rc.5",
156
+ "@deepseek-ai/dsh-home-paths": "^0.2.1-rc.5",
157
+ "@deepseek-ai/dsh-launch-environment": "^0.2.1-rc.5"
151
158
  }
152
159
  }
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env python3
2
+ """Delete old DSH desktop authentication cookies before launching DSH.
3
+
4
+ Chromium stores cookies by host, not port. DSH uses a new loopback port on every
5
+ launch, so its 30-day dsh-auth-* cookies accumulate until the Cookie request
6
+ header exceeds the Host's 16 KiB limit. This runs before the app starts, while
7
+ the cookie DB is unlocked.
8
+
9
+ Only rows for 127.0.0.1 whose name starts with dsh-auth- are removed. The DB is
10
+ backed up first. DSH_COOKIE_DB / DSH_COOKIE_LAUNCHER_DIR are test overrides.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import shutil
16
+ import sqlite3
17
+ import sys
18
+ from datetime import datetime
19
+ from pathlib import Path
20
+
21
+ HOST = "127.0.0.1"
22
+ PREFIX = "dsh-auth-"
23
+ WHERE = "host_key = ? and name like ?"
24
+ ARGS = (HOST, PREFIX + "%")
25
+
26
+
27
+ def main() -> int:
28
+ appdata = Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming"))
29
+ db = Path(os.environ.get("DSH_COOKIE_DB", appdata / "@deepseek-ai" / "dsh-desktop" / "Network" / "Cookies"))
30
+ base = Path(os.environ.get("DSH_COOKIE_LAUNCHER_DIR", Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")) / "dsh-mcviseron"))
31
+ backups = base / "backups"
32
+ log_path = base / "launcher.log"
33
+ base.mkdir(parents=True, exist_ok=True)
34
+
35
+ def log(message: str) -> None:
36
+ try:
37
+ with log_path.open("a", encoding="utf-8") as handle:
38
+ handle.write(datetime.now().astimezone().isoformat() + " " + message + "\n")
39
+ except OSError:
40
+ pass
41
+
42
+ if not db.is_file():
43
+ log("cookie database missing: " + str(db))
44
+ return 0
45
+
46
+ try:
47
+ con = sqlite3.connect(str(db), timeout=2)
48
+ try:
49
+ before = con.execute("select count(*) from cookies where " + WHERE, ARGS).fetchone()[0]
50
+ finally:
51
+ con.close()
52
+ except Exception as error:
53
+ log("cookie database unavailable (DSH may still be running): " + repr(error))
54
+ return 0
55
+
56
+ if before == 0:
57
+ log("no stale dsh-auth cookies")
58
+ return 0
59
+
60
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
61
+ backups.mkdir(parents=True, exist_ok=True)
62
+ backup = backups / ("Cookies-" + stamp)
63
+ try:
64
+ shutil.copy2(db, backup)
65
+ for suffix in ("-wal", "-shm"):
66
+ side = Path(str(db) + suffix)
67
+ if side.is_file():
68
+ shutil.copy2(side, Path(str(backup) + suffix))
69
+ log("backup " + str(backup))
70
+ except OSError as error:
71
+ log("backup failed: " + repr(error))
72
+
73
+ try:
74
+ con = sqlite3.connect(str(db), timeout=2)
75
+ try:
76
+ deleted = con.execute("delete from cookies where " + WHERE, ARGS).rowcount
77
+ con.commit()
78
+ after = con.execute("select count(*) from cookies where " + WHERE, ARGS).fetchone()[0]
79
+ finally:
80
+ con.close()
81
+ log("deleted=" + str(deleted) + " remaining=" + str(after))
82
+ except Exception as error:
83
+ log("delete failed: " + repr(error))
84
+
85
+ try:
86
+ old = sorted(backups.glob("Cookies-*"), key=lambda item: item.stat().st_mtime, reverse=True)
87
+ for extra in old[10:]:
88
+ extra.unlink(missing_ok=True)
89
+ for suffix in ("-wal", "-shm"):
90
+ Path(str(extra) + suffix).unlink(missing_ok=True)
91
+ except OSError:
92
+ pass
93
+ return 0
94
+
95
+
96
+ if __name__ == "__main__":
97
+ sys.exit(main())
@@ -0,0 +1,16 @@
1
+ Option Explicit
2
+ Dim sh, fso, base, python, cleanup, exe
3
+ Set sh = CreateObject("WScript.Shell")
4
+ Set fso = CreateObject("Scripting.FileSystemObject")
5
+ base = sh.ExpandEnvironmentStrings("%LOCALAPPDATA%") & "\dsh-mcviseron"
6
+ python = "D:\Python\Python312\python.exe"
7
+ If Not fso.FileExists(python) Then python = "python.exe"
8
+ cleanup = base & "\clean-dsh-auth-cookies.py"
9
+ If fso.FileExists(cleanup) Then
10
+ On Error Resume Next
11
+ sh.Run """" & python & """ """ & cleanup & """", 0, True
12
+ On Error GoTo 0
13
+ End If
14
+ exe = "D:\DeepSeek Harness\DeepSeek Harness.exe"
15
+ sh.CurrentDirectory = "D:\DeepSeek Harness"
16
+ sh.Run """" & exe & """", 1, False
@@ -0,0 +1,48 @@
1
+ param(
2
+ [string]$ExePath = 'D:\DeepSeek Harness\DeepSeek Harness.exe',
3
+ [string]$LauncherDir = (Join-Path $env:LOCALAPPDATA 'dsh-mcviseron')
4
+ )
5
+ $ErrorActionPreference = 'Stop'
6
+ $source = Join-Path $PSScriptRoot 'dsh-cookie-launcher'
7
+ if (-not (Test-Path -LiteralPath $ExePath)) { throw "DSH executable not found: $ExePath" }
8
+ if (-not (Test-Path -LiteralPath $source)) { throw "launcher sources not found: $source" }
9
+
10
+ New-Item -ItemType Directory -Force -Path $LauncherDir | Out-Null
11
+ Copy-Item -LiteralPath (Join-Path $source 'clean-dsh-auth-cookies.py') -Destination $LauncherDir -Force
12
+ Copy-Item -LiteralPath (Join-Path $source 'launch-dsh.vbs') -Destination $LauncherDir -Force
13
+
14
+ $ws = New-Object -ComObject WScript.Shell
15
+ $roots = @(
16
+ (Join-Path $env:USERPROFILE 'Desktop'),
17
+ (Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu'),
18
+ (Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu'),
19
+ (Join-Path $env:APPDATA 'Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar'),
20
+ 'C:\Users\Public\Desktop'
21
+ ) | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -Unique
22
+
23
+ $changed = 0
24
+ foreach ($root in $roots) {
25
+ Get-ChildItem -LiteralPath $root -Recurse -Filter '*.lnk' -ErrorAction SilentlyContinue | ForEach-Object {
26
+ $lnk = $_.FullName
27
+ $shortcut = $ws.CreateShortcut($lnk)
28
+ if ($shortcut.TargetPath -ne $ExePath) { return }
29
+ $backup = "$lnk.bak-dsh-cookie"
30
+ if (-not (Test-Path -LiteralPath $backup)) {
31
+ Copy-Item -LiteralPath $lnk -Destination $backup -Force
32
+ }
33
+ $shortcut.TargetPath = Join-Path $env:SystemRoot 'System32\wscript.exe'
34
+ $shortcut.Arguments = '//nologo "' + (Join-Path $LauncherDir 'launch-dsh.vbs') + '"'
35
+ $shortcut.WorkingDirectory = Split-Path -Parent $ExePath
36
+ $shortcut.IconLocation = "$ExePath,0"
37
+ $shortcut.Description = 'DeepSeek Harness (clears stale DSH auth cookies before launch)'
38
+ $shortcut.Save()
39
+ $changed += 1
40
+ Write-Output "updated: $lnk"
41
+ }
42
+ }
43
+
44
+ if ($changed -eq 0) {
45
+ Write-Output 'no DSH shortcut was changed; check the Start Menu shortcut target'
46
+ } else {
47
+ Write-Output "changed $changed shortcut(s); launcher: $LauncherDir"
48
+ }
@@ -0,0 +1,337 @@
1
+ import { appendFileSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import type { Context } from '@deepseek-ai/cordis'
5
+
6
+ /**
7
+ * DSH's official schedule tools are mounted only in presets that declare
8
+ * @deepseek-ai/dsh-tool-schedule. The current agent often does not have them,
9
+ * which makes an otherwise session-bound automation task impossible to edit
10
+ * from the conversation. These tools call the Host ctx.schedule service
11
+ * directly; every mutation is persisted by that service.
12
+ */
13
+
14
+ interface ScheduleRecord {
15
+ id: string
16
+ title: string
17
+ prompt: string
18
+ kind: string
19
+ scheduledAt: string
20
+ [key: string]: unknown
21
+ }
22
+
23
+ interface ScheduleService {
24
+ list(filter: { sessionId: string }): Promise<ScheduleRecord[]>
25
+ create(sessionId: string, input: Record<string, unknown>, signal?: AbortSignal): Promise<ScheduleRecord>
26
+ update(input: Record<string, unknown>, signal?: AbortSignal): Promise<Record<string, unknown>>
27
+ delete(input: Record<string, unknown>, signal?: AbortSignal): Promise<Record<string, unknown>>
28
+ }
29
+
30
+ interface ToolExecution {
31
+ agent?: { session?: { id?: string } }
32
+ signal?: AbortSignal
33
+ }
34
+
35
+ interface ToolDefinition {
36
+ name: string
37
+ description: string
38
+ parameters: Record<string, unknown>
39
+ output: {
40
+ schema: Record<string, unknown>
41
+ render: (args: unknown, value: unknown) => Array<{ type: 'text'; text: string }>
42
+ }
43
+ execute: (args: Record<string, any>, exec: ToolExecution) => Promise<unknown>
44
+ }
45
+
46
+ const OUTPUT_SCHEMA = { type: 'object', additionalProperties: true }
47
+ const SELECTOR_KEYS = ['after_seconds', 'at', 'every_seconds', 'daily', 'weekly', 'cron'] as const
48
+
49
+ function output(): ToolDefinition['output'] {
50
+ return {
51
+ schema: OUTPUT_SCHEMA,
52
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
53
+ }
54
+ }
55
+
56
+ function log(message: string): void {
57
+ try {
58
+ appendFileSync(join(tmpdir(), 'dsh-mcviseron-automation-tasks.log'), new Date().toISOString() + ' ' + message + '\n', 'utf8')
59
+ } catch {
60
+ /* diagnostics must never break registration */
61
+ }
62
+ }
63
+
64
+ function sessionIdOf(exec: ToolExecution): string {
65
+ const id = exec.agent?.session?.id
66
+ return typeof id === 'string' ? id : ''
67
+ }
68
+
69
+ function text(value: unknown): value is string {
70
+ return typeof value === 'string' && value.trim() !== ''
71
+ }
72
+
73
+ function selectorCount(args: Record<string, unknown>, keys: readonly string[]): number {
74
+ return keys.filter(key => args[key] !== undefined).length
75
+ }
76
+
77
+ function timingChange(args: Record<string, unknown>): Record<string, unknown> | undefined {
78
+ if (args.at !== undefined) return { kind: 'at', at: args.at }
79
+ if (args.every_seconds !== undefined) return { kind: 'every', every_seconds: args.every_seconds }
80
+ if (args.daily !== undefined) return { kind: 'daily', daily: args.daily }
81
+ if (args.weekly !== undefined) return { kind: 'weekly', weekly: args.weekly }
82
+ if (args.cron !== undefined) return { kind: 'cron', cron: args.cron }
83
+ return undefined
84
+ }
85
+
86
+ function invalid(message: string): { ok: false; code: 'invalid'; error: string } {
87
+ return { ok: false, code: 'invalid', error: message }
88
+ }
89
+
90
+ function serviceFailure(error: unknown): { ok: false; code: 'service_error'; error: string } {
91
+ return { ok: false, code: 'service_error', error: error instanceof Error ? error.message : String(error) }
92
+ }
93
+
94
+ function validateCreate(args: Record<string, unknown>): string | undefined {
95
+ if (!text(args.title)) return 'title must be a non-empty string'
96
+ if (!text(args.prompt)) return 'prompt must be a non-empty string'
97
+ const count = selectorCount(args, SELECTOR_KEYS)
98
+ if (count !== 1) return 'supply exactly one of after_seconds, at, every_seconds, daily, weekly, or cron'
99
+ if (args.after_seconds !== undefined && (!Number.isSafeInteger(args.after_seconds) || Number(args.after_seconds) <= 0)) {
100
+ return 'after_seconds must be a positive integer'
101
+ }
102
+ if (args.every_seconds !== undefined && (!Number.isSafeInteger(args.every_seconds) || Number(args.every_seconds) < 60)) {
103
+ return 'every_seconds must be an integer of at least 60'
104
+ }
105
+ if (args.at !== undefined && !text(args.at)) return 'at must be a non-empty ISO date-time string'
106
+ return undefined
107
+ }
108
+
109
+ function validateUpdate(args: Record<string, unknown>): string | undefined {
110
+ if (!text(args.id)) return 'id must be a non-empty string'
111
+ const keys = ['at', 'every_seconds', 'daily', 'weekly', 'cron']
112
+ if (selectorCount(args, keys) > 1) return 'update accepts at most one timing selector'
113
+ if (args.every_seconds !== undefined && (!Number.isSafeInteger(args.every_seconds) || Number(args.every_seconds) < 60)) {
114
+ return 'every_seconds must be an integer of at least 60'
115
+ }
116
+ if (args.title === undefined && args.prompt === undefined && timingChange(args) === undefined) {
117
+ return 'update needs a new title, prompt, or one timing selector'
118
+ }
119
+ if (args.title !== undefined && !text(args.title)) return 'title must be a non-empty string'
120
+ if (args.prompt !== undefined && !text(args.prompt)) return 'prompt must be a non-empty string'
121
+ return undefined
122
+ }
123
+
124
+ const SELECTOR_SCHEMA = {
125
+ after_seconds: { type: 'number', description: 'Delay in whole seconds; create only.' },
126
+ at: { type: 'string', description: 'Absolute RFC 3339 date-time with offset.' },
127
+ every_seconds: { type: 'number', description: 'Fixed interval in whole seconds, at least 60.' },
128
+ daily: {
129
+ type: 'object', additionalProperties: false, required: ['time', 'time_zone'],
130
+ properties: { time: { type: 'string' }, time_zone: { type: 'string' } },
131
+ },
132
+ weekly: {
133
+ type: 'object', additionalProperties: false, required: ['time', 'time_zone', 'weekdays'],
134
+ properties: {
135
+ time: { type: 'string' },
136
+ time_zone: { type: 'string' },
137
+ weekdays: { type: 'array', items: { type: 'integer', minimum: 1, maximum: 7 } },
138
+ },
139
+ },
140
+ cron: {
141
+ type: 'object', additionalProperties: false, required: ['expression', 'time_zone'],
142
+ properties: { expression: { type: 'string' }, time_zone: { type: 'string' } },
143
+ },
144
+ }
145
+
146
+ const { after_seconds: _createOnlyAfterSeconds, ...UPDATE_SELECTOR_SCHEMA } = SELECTOR_SCHEMA
147
+
148
+ const CREATE_PARAMETERS = {
149
+ type: 'object',
150
+ additionalProperties: false,
151
+ required: ['title', 'prompt'],
152
+ properties: {
153
+ title: { type: 'string', description: 'Short task name; no schedule in the title.' },
154
+ prompt: { type: 'string', description: 'Complete instruction delivered when due.' },
155
+ ...SELECTOR_SCHEMA,
156
+ },
157
+ }
158
+
159
+ const UPDATE_PARAMETERS = {
160
+ type: 'object',
161
+ additionalProperties: false,
162
+ required: ['id'],
163
+ properties: {
164
+ id: { type: 'string', description: 'Exact schedule id from automation_task_list.' },
165
+ title: { type: 'string' },
166
+ prompt: { type: 'string' },
167
+ ...UPDATE_SELECTOR_SCHEMA,
168
+ },
169
+ }
170
+
171
+ const DELETE_PARAMETERS = {
172
+ type: 'object',
173
+ additionalProperties: false,
174
+ required: ['id'],
175
+ properties: { id: { type: 'string', description: 'Exact schedule id.' } },
176
+ }
177
+
178
+ const LIST_PARAMETERS = { type: 'object', additionalProperties: false, properties: {} }
179
+
180
+ /** Build the model-facing tools over one Host Schedule service. */
181
+ export function makeAutomationTaskTools(schedule: ScheduleService): ToolDefinition[] {
182
+ return [
183
+ {
184
+ name: 'automation_task_list',
185
+ description: 'List the official automation tasks bound to the current session. Use this before changing a task so you have its exact id and current prompt.',
186
+ parameters: LIST_PARAMETERS,
187
+ output: output(),
188
+ async execute(_args, exec) {
189
+ const sessionId = sessionIdOf(exec)
190
+ if (sessionId === '') return { ok: false, code: 'no_session', error: 'no current session' }
191
+ try {
192
+ return { ok: true, tasks: await schedule.list({ sessionId }) }
193
+ } catch (error) {
194
+ return serviceFailure(error)
195
+ }
196
+ },
197
+ },
198
+ {
199
+ name: 'automation_task_create',
200
+ description: 'Create an official automation task (DSH schedule) bound to the current session. Supply title, prompt, and exactly one timing selector. The Host schedule service persists it immediately; never edit schedule.json by hand.',
201
+ parameters: CREATE_PARAMETERS,
202
+ output: output(),
203
+ async execute(args, exec) {
204
+ const sessionId = sessionIdOf(exec)
205
+ if (sessionId === '') return { ok: false, code: 'no_session', error: 'no current session' }
206
+ const invalidInput = validateCreate(args)
207
+ if (invalidInput !== undefined) return invalid(invalidInput)
208
+ try {
209
+ const record = await schedule.create(sessionId, {
210
+ ...args,
211
+ title: String(args.title).trim(),
212
+ prompt: String(args.prompt).trim(),
213
+ }, exec.signal)
214
+ return { ok: true, task: record }
215
+ } catch (error) {
216
+ return serviceFailure(error)
217
+ }
218
+ },
219
+ },
220
+ {
221
+ name: 'automation_task_update',
222
+ description: 'Update an existing official automation task in place, keeping its id. Supply id plus a new title, prompt, or at most one timing selector. The Host schedule service persists it immediately; this is the supported way to edit an automation task from the conversation.',
223
+ parameters: UPDATE_PARAMETERS,
224
+ output: output(),
225
+ async execute(args, exec) {
226
+ const sessionId = sessionIdOf(exec)
227
+ if (sessionId === '') return { ok: false, code: 'no_session', error: 'no current session' }
228
+ const invalidInput = validateUpdate(args)
229
+ if (invalidInput !== undefined) return invalid(invalidInput)
230
+ try {
231
+ const id = String(args.id)
232
+ const expected = (await schedule.list({ sessionId })).find(record => record.id === id)
233
+ if (expected === undefined) return { ok: false, code: 'schedule_not_found', error: 'automation task not found in this session: ' + id }
234
+ const change = timingChange(args)
235
+ const result = await schedule.update({
236
+ sessionId,
237
+ id,
238
+ expected,
239
+ ...(change === undefined ? {} : { change }),
240
+ ...(args.title === undefined ? {} : { title: String(args.title).trim() }),
241
+ ...(args.prompt === undefined ? {} : { prompt: String(args.prompt).trim() }),
242
+ }, exec.signal)
243
+ if (result.record !== undefined) return { ok: true, task: result.record }
244
+ return { ok: false, ...result }
245
+ } catch (error) {
246
+ return serviceFailure(error)
247
+ }
248
+ },
249
+ },
250
+ {
251
+ name: 'automation_task_delete',
252
+ description: 'Delete an official automation task in the current session. The Host schedule service removes and persists it immediately.',
253
+ parameters: DELETE_PARAMETERS,
254
+ output: output(),
255
+ async execute(args, exec) {
256
+ const sessionId = sessionIdOf(exec)
257
+ if (sessionId === '') return { ok: false, code: 'no_session', error: 'no current session' }
258
+ if (!text(args.id) || String(args.id).trim() !== String(args.id)) {
259
+ return invalid('id must be a non-empty string without surrounding whitespace')
260
+ }
261
+ try {
262
+ const result = await schedule.delete({ sessionId, id: String(args.id) }, exec.signal)
263
+ return { ok: true, ...result }
264
+ } catch (error) {
265
+ return serviceFailure(error)
266
+ }
267
+ },
268
+ },
269
+ ]
270
+ }
271
+
272
+ function serviceOf(scope: Record<string, unknown>, name: string): unknown {
273
+ try {
274
+ if (scope[name] !== undefined) return scope[name]
275
+ const get = scope.get as ((key: string) => unknown) | undefined
276
+ return typeof get === 'function' ? get.call(scope, name) : undefined
277
+ } catch {
278
+ return undefined
279
+ }
280
+ }
281
+
282
+ /** Register tools and the model guidance through the resolved services. */
283
+ export function apply(ctx: Context): void {
284
+ const inject = (ctx as unknown as { inject?: (deps: string[], callback: (scope: Context) => void) => unknown }).inject
285
+ if (typeof inject !== 'function') return
286
+ try {
287
+ inject.call(ctx, ['tools', 'schedule'], (scope) => {
288
+ const tools = serviceOf(scope as unknown as Record<string, unknown>, 'tools') as {
289
+ register?: (definition: unknown) => (() => void) | undefined
290
+ } | undefined
291
+ const schedule = serviceOf(scope as unknown as Record<string, unknown>, 'schedule') as ScheduleService | undefined
292
+ if (tools === undefined || typeof tools.register !== 'function' || schedule === undefined) {
293
+ log('schedule tools unavailable')
294
+ return
295
+ }
296
+ const dispose = makeAutomationTaskTools(schedule).map(definition => {
297
+ try {
298
+ return tools.register?.(definition)
299
+ } catch (error) {
300
+ log('tool registration failed: ' + (error instanceof Error ? error.message : String(error)))
301
+ return undefined
302
+ }
303
+ }).filter((item): item is () => void => typeof item === 'function')
304
+ const effect = (scope as unknown as { effect?: (body: () => () => void, label: string) => unknown }).effect
305
+ if (typeof effect === 'function') {
306
+ effect.call(scope, () => () => {
307
+ for (const disposeTool of dispose) {
308
+ try { disposeTool() } catch { /* already disposed */ }
309
+ }
310
+ }, 'mcviseron-automation-tasks: tools')
311
+ }
312
+ })
313
+ } catch (error) {
314
+ log('tool injection failed: ' + (error instanceof Error ? error.message : String(error)))
315
+ }
316
+
317
+ try {
318
+ inject.call(ctx, ['systemPrompt'], (scope) => {
319
+ const systemPrompt = serviceOf(scope as unknown as Record<string, unknown>, 'systemPrompt') as {
320
+ section?: (value: unknown) => unknown
321
+ } | undefined
322
+ if (typeof systemPrompt?.section === 'function') {
323
+ systemPrompt.section({
324
+ name: 'plugin:mcviseron-automation-tasks',
325
+ order: 232,
326
+ text: [
327
+ 'Official DSH automation tasks are writable from this conversation.',
328
+ 'Use automation_task_list / automation_task_create / automation_task_update / automation_task_delete; they call the Host schedule service and persist automatically.',
329
+ 'Never edit ~/.dsh/storages/schedule.json by hand, and never tell the user to use a command to change a task when these tools are available.',
330
+ ].join(' '),
331
+ })
332
+ }
333
+ })
334
+ } catch (error) {
335
+ log('system prompt section unavailable: ' + (error instanceof Error ? error.message : String(error)))
336
+ }
337
+ }
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@ import type { Context } from '@deepseek-ai/cordis'
2
2
  import z from '@deepseek-ai/schemastery'
3
3
  import * as appearance from './appearance/index.ts'
4
4
  import * as authCookie from './auth-cookie/index.ts'
5
+ import * as automationTasks from './automation-tasks/index.ts'
5
6
  import * as autoReviewFix from './auto-review-fix/index.ts'
6
7
  import { DEFAULT_AUTO_REVIEW_CONFIG } from './auto-review-fix/index.ts'
7
8
  import * as restart from './restart/index.ts'
@@ -66,6 +67,7 @@ function mount(ctx: Context, component: unknown, config: unknown): void {
66
67
  */
67
68
  export function apply(ctx: Context, rawConfig?: MasterConfig): void {
68
69
  const config = (toPlain(rawConfig) ?? {}) as MasterConfig
70
+ mount(ctx, automationTasks, {})
69
71
  mount(ctx, authCookie, {})
70
72
  mount(ctx, appearance, {
71
73
  enabled: config.enabled ?? DEFAULT_SCHEDULE_CONFIG.enabled,
@@ -538,15 +538,19 @@ function installAgentTool(ctx: Context, controller: SessionEndController, option
538
538
  'Use close only when the user explicitly asks to close DSH. Shutdown is user-only. If unsure whether a restart is required, ask the user instead of arming.',
539
539
  ].join(' '),
540
540
  parameters: {
541
- action: {
542
- type: 'string',
543
- required: true,
544
- enum: ['restart', 'close', 'off'],
545
- description: 'restart DSH after this turn, close DSH, or clear the pending action',
546
- },
547
- reason: {
548
- type: 'string',
549
- description: 'Optional short reason shown in the tool result; the user sees the same action in the composer',
541
+ type: 'object',
542
+ additionalProperties: false,
543
+ required: ['action'],
544
+ properties: {
545
+ action: {
546
+ type: 'string',
547
+ enum: ['restart', 'close', 'off'],
548
+ description: 'restart DSH after this turn, close DSH, or clear the pending action',
549
+ },
550
+ reason: {
551
+ type: 'string',
552
+ description: 'Optional short reason shown in the tool result; the user sees the same action in the composer',
553
+ },
550
554
  },
551
555
  },
552
556
  output: {