dsh-work-fish 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +44 -12
  2. package/THIRD-PARTY-NOTICES.md +3 -5
  3. package/cordis.patch.yml +5 -6
  4. package/{board → lib/board}/client.js +13 -20
  5. package/{core → lib/core}/approve.mjs +1 -1
  6. package/{core → lib/core}/bootstrap.mjs +7 -7
  7. package/{core → lib/core}/events.mjs +5 -5
  8. package/{core → lib/core}/guard.mjs +7 -7
  9. package/{core → lib/core}/index.mjs +33 -26
  10. package/{tools → lib/tools}/lib/persona.mjs +2 -2
  11. package/{tools → lib/tools}/lib/taskboard.mjs +12 -17
  12. package/{tools → lib/tools}/wf-metrics.mjs +2 -2
  13. package/{tools → lib/tools}/wf-preview.mjs +2 -4
  14. package/{tools → lib/tools}/wf-rule.mjs +2 -2
  15. package/{tools → lib/tools}/wf-spec.mjs +2 -2
  16. package/{tools → lib/tools}/wf-task.mjs +2 -7
  17. package/locale/en.json +1 -1
  18. package/locale/zh.json +1 -1
  19. package/package.json +11 -13
  20. package/rules/experience-pool.md +2 -2
  21. package/rules/file-rules.md +4 -4
  22. package/rules/memory-rules.md +2 -2
  23. package/skills/task-setup/SKILL.md +1 -1
  24. package/template/AGENTS.template.md +1 -1
  25. package/core/pet-bridge.mjs +0 -439
  26. /package/{core → lib/core}/approve-paths.mjs +0 -0
  27. /package/{core → lib/core}/approve-paths.test.mjs +0 -0
  28. /package/{core → lib/core}/parse.mjs +0 -0
  29. /package/{core → lib/core}/persona.mjs +0 -0
  30. /package/{core → lib/core}/report.mjs +0 -0
  31. /package/{core → lib/core}/skills.mjs +0 -0
  32. /package/{tools → lib/tools}/lib/paths.mjs +0 -0
  33. /package/{tools → lib/tools}/wf-audit.cmd +0 -0
  34. /package/{tools → lib/tools}/wf-audit.ps1 +0 -0
  35. /package/{tools → lib/tools}/wf-mem.mjs +0 -0
  36. /package/{tools → lib/tools}/wf-persona.mjs +0 -0
  37. /package/{tools → lib/tools}/wf-pool.mjs +0 -0
  38. /package/{tools → lib/tools}/wf-recent.mjs +0 -0
  39. /package/{tools → lib/tools}/wf-review.mjs +0 -0
  40. /package/{tools → lib/tools}/wf-snapshot.mjs +0 -0
@@ -594,9 +594,9 @@ function checkSpec() {
594
594
  // ── 引用完整性(--refs)────────────────────────────────────────────────────
595
595
  // 说明性文件里引用的路径如果指不到东西,就是配置漂移:改名、删文件之后没跟上的地方。
596
596
 
597
- /** The plugin package root (`app/`), one level above `app/tools/`. */
597
+ /** The package root, two levels above `lib/tools/`; it holds `rules/`, `template/` and `lib/`. */
598
598
  function pluginRoot() {
599
- return resolve(dirname(fileURLToPath(import.meta.url)), '..')
599
+ return resolve(dirname(fileURLToPath(import.meta.url)), '..', '..')
600
600
  }
601
601
 
602
602
  // 只查带目录的引用:裸文件名通常是「泛指某类文件」,不是可解析的路径。
@@ -97,7 +97,6 @@ function cmdNew(opts) {
97
97
  next: opts.next,
98
98
  note: opts.note,
99
99
  mode: opts.mode,
100
- source: opts.source,
101
100
  eventsFile: eventsOf(opts),
102
101
  })
103
102
  print(result)
@@ -117,7 +116,6 @@ function cmdBump(opts) {
117
116
  who: opts.who,
118
117
  what: opts.what,
119
118
  chase: opts.chase,
120
- source: opts.source,
121
119
  eventsFile: eventsOf(opts),
122
120
  })
123
121
  print(result)
@@ -140,7 +138,6 @@ function cmdMove(opts) {
140
138
  chase: opts.chase,
141
139
  note: opts.note,
142
140
  marker: opts.marker,
143
- source: opts.source,
144
141
  eventsFile: eventsOf(opts),
145
142
  })
146
143
  print(result)
@@ -153,7 +150,6 @@ function cmdProgress(opts) {
153
150
  expectRev: Number.isInteger(expect) ? expect : undefined,
154
151
  text: opts.text,
155
152
  next: opts.next,
156
- source: opts.source,
157
153
  eventsFile: eventsOf(opts),
158
154
  })
159
155
  print(result)
@@ -165,7 +161,6 @@ function cmdDrop(opts) {
165
161
  task: opts.task,
166
162
  expectRev: Number.isInteger(expect) ? expect : undefined,
167
163
  reason: opts.reason,
168
- source: opts.source,
169
164
  eventsFile: eventsOf(opts),
170
165
  })
171
166
  print(result)
@@ -228,9 +223,9 @@ function selfTest() {
228
223
  const created = newTask(file, { title: '新事项', accept: '可检查', relation: '协作', section: '待办', eventsFile: events })
229
224
  ok('new 成功', created.ok && /^T-\d{8}-01$/.test(created.task))
230
225
  ok('事件日志有记录', fs.existsSync(events) && fs.readFileSync(events, 'utf8').trim().split('\n').length >= 2)
231
- newTask(file, { title: '带来源', accept: 'x', relation: '协作', source: '桌宠', eventsFile: events })
226
+ newTask(file, { title: '不带来源', accept: 'x', relation: '协作', eventsFile: events })
232
227
  const lastEvent = JSON.parse(fs.readFileSync(events, 'utf8').trim().split('\n').pop())
233
- ok('事件记录带上写入来源', lastEvent.source === '桌宠', JSON.stringify(lastEvent))
228
+ ok('事件不再记录写入来源', lastEvent.source === undefined, JSON.stringify(lastEvent))
234
229
  const moved = moveTask(file, { task: 'T-20261106-02', expectRev: 1, to: '进行中', eventsFile: events })
235
230
  ok('move 待办→进行中', moved.ok && moved.from === '待办' && moved.to === '进行中', moved.message)
236
231
  const movedRow = findTask(loadLedger(file), 'T-20261106-02')
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "Work Fish",
3
+ "title": "dsh-work-fish",
4
4
  "description": "Standing work assistant: turns a request into an acceptance-checkable task card, tracks it on a task board with deadlines and next steps, and files deliverables under the workbench's out/ directory. Unofficial plugin, not affiliated with DeepSeek.",
5
5
  "detail": "docs/DETAIL.md"
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "大肥鱼",
3
+ "title": "dsh-work-fish",
4
4
  "description": "常驻的工作助手:先把需求写成可验收的任务卡,在任务板上跟踪截止与下一步,交付物落到工作台的 out/ 目录。非官方插件,与 DeepSeek 官方无关。",
5
5
  "detail": "docs/DETAIL.zh.md"
6
6
  }
package/package.json CHANGED
@@ -1,27 +1,25 @@
1
1
  {
2
2
  "name": "dsh-work-fish",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "license": "MIT",
5
- "description": "Unofficial Work Fish plugin for DeepSeek Harness: task setup, task board tracking and delivery, with a task panel fed to the dsh-pet desktop pet. Not affiliated with DeepSeek.",
5
+ "description": "Unofficial Work Fish plugin for DeepSeek Harness: task setup, task board tracking and delivery, with a floating task panel. Not affiliated with DeepSeek.",
6
6
  "type": "module",
7
- "main": "./core/index.mjs",
7
+ "main": "./lib/core/index.mjs",
8
8
  "exports": {
9
- ".": "./core/index.mjs",
10
- "./board": "./board/client.js",
11
- "./core/guard": "./core/guard.mjs",
12
- "./core/approve": "./core/approve.mjs",
13
- "./core/persona": "./core/persona.mjs",
14
- "./core/skills": "./core/skills.mjs",
15
- "./client": "./board/client.js",
9
+ ".": "./lib/core/index.mjs",
10
+ "./board": "./lib/board/client.js",
11
+ "./client": "./lib/board/client.js",
12
+ "./core/guard": "./lib/core/guard.mjs",
13
+ "./core/approve": "./lib/core/approve.mjs",
14
+ "./core/persona": "./lib/core/persona.mjs",
15
+ "./core/skills": "./lib/core/skills.mjs",
16
16
  "./locale/*.json": "./locale/*.json",
17
17
  "./icon": "./icon.png",
18
18
  "./package.json": "./package.json"
19
19
  },
20
20
  "files": [
21
- "board/**",
22
- "core/**",
21
+ "lib/**",
23
22
  "skills/**",
24
- "tools/**",
25
23
  "rules/**",
26
24
  "template/**",
27
25
  "locale/*.json",
@@ -34,7 +34,7 @@ A candidate is an unproven hypothesis; a rule is a proven conclusion. **No evide
34
34
 
35
35
  - Sample 5 U rules a month (plugin G rules are read-only; sample them only for the weekly report): "any applicable case in the last 30 days?" Two consecutive "no" → dormancy candidate.
36
36
  - Citation counts are hints only, never a criterion.
37
- - After user sign-off, move it into the dormant section of `memory/user-rules.md` — text kept, ID never reused.
37
+ - After user sign-off, move it into the dormant section of `rules/user-rules.md` — text kept, ID never reused.
38
38
  - Three consecutive months with net growth > 2 rules/month → run dormancy before adding more.
39
39
 
40
40
  ## 5. Five elements of a promoted rule (none optional)
@@ -56,4 +56,4 @@ Self-check: an assistant that never did the original work can follow the rule as
56
56
 
57
57
  ## Pool
58
58
 
59
- The live queue is the **workbench's** `rules/experience-pool.md` (seeded from `template/memory/pool/experience.md`): this file is read-only and carries the rules only. Read the queue there and add rows there, never here.
59
+ The live queue is the **workbench's** `memory/pool/experience.md` (seeded from `template/memory/pool/experience.md`): this file is read-only and carries the rules only. Read the queue there and add rows there, never here.
@@ -18,7 +18,7 @@
18
18
  | Output | `out/` | Deliverables handed to the user | Drafts, scratch files |
19
19
  | Archive | `archive/` | Finished or voided task documents | Live work |
20
20
 
21
- Inside the package (read-only for the user): `board/` (browser half, the task panel), `core/` (host half, routes and seeding), `skills/` (methods), `tools/` (CLI), `rules/` and `template/` (copied to the workbench on first run).
21
+ Inside the package (read-only for the user): code lives under `lib/` — `lib/board/` (browser half, the task panel), `lib/core/` (host half, routes and seeding), `lib/tools/` (CLI); `skills/` (methods), `rules/` and `template/` sit at the package root, the latter two copied to the workbench on first run.
22
22
 
23
23
  ## 2. Admission and placement test (ask in order)
24
24
 
@@ -46,7 +46,7 @@ Inside the package (read-only for the user): `board/` (browser half, the task pa
46
46
  |---|---|---|---|
47
47
  | `AGENTS.md` | Start-up and close-out procedure, coordination protocol, task-board conventions | Maintainer | Every session (auto-loaded) |
48
48
  | `rules/INDEX.md` | Generated pointer to the plugin rule files below | Bootstrap | Every session |
49
- | `rules/experience-pool.md` | Your undecided experience, queue only | Assistant | Close-out, weekly review |
49
+ | `memory/pool/experience.md` | Your undecided experience, queue only | Assistant | Close-out, weekly review |
50
50
  | plugin `file-rules.md` | This file | Maintainer (release) | Placing files |
51
51
  | plugin `task-rules.md` | Task board: admission, row shape, ceilings, retention, commit discipline | Maintainer (release) | Before any board write |
52
52
  | plugin `memory-rules.md` | Memory layers, writing and cleaning | Maintainer (release) | Maintaining memory |
@@ -54,7 +54,7 @@ Inside the package (read-only for the user): `board/` (browser half, the task pa
54
54
  | `tasks/index.md` | Single source of truth for tasks | Assistant via `<tools>/wf-task.mjs` | Every session starts here |
55
55
  | `memory/user-profile.md` | Who the user is, role, stakeholders, goals | Assistant, incrementally | When the task needs context |
56
56
  | `memory/preferences.md` | Output preferences, tone, taboos | Assistant, incrementally | Before producing a deliverable |
57
- | `memory/user-rules.md` | Your own promoted rules (U numbers); wins over the plugin baseline | Assistant, incrementally | When a rule conflicts with the plugin baseline |
57
+ | `rules/user-rules.md` | Your own promoted rules (U numbers); wins over the plugin baseline | Assistant, incrementally | When a rule conflicts with the plugin baseline |
58
58
  | `memory/projects/README.md` | One line per project | Assistant | Every session (index) |
59
59
  | `memory/projects/<code>/profile.md` | Project facts, rules, pitfalls (stable layer) | Assistant | When the task concerns that project |
60
60
  | `memory/projects/<code>/state.md` | Branch, uncommitted, current mainline (volatile layer) | Assistant, overwritten at close-out | Same |
@@ -86,7 +86,7 @@ memory/projects/<code>/{profile.md, state.md, journal/, sources/}
86
86
  | Kind | Pattern | Example |
87
87
  |---|---|---|
88
88
  | CLI | `<tools>/wf-<action>.mjs` | `wf-task.mjs`, `wf-spec.mjs` |
89
- | Library | `tools/lib/<object>.mjs` | `taskboard.mjs`, `paths.mjs` |
89
+ | Library | `lib/tools/lib/<object>.mjs` | `taskboard.mjs`, `paths.mjs` |
90
90
  | Skill | `skills/<domain>-<action>/SKILL.md` | `task-setup`, `git-flow` |
91
91
  | Rule file | `rules/<object>-rules.md` | `task-rules.md` |
92
92
 
@@ -7,7 +7,7 @@
7
7
 
8
8
  - **The workbench is the only write point**: `<workbench>/memory/`. Project directories keep no personal memory.
9
9
  - `AGENTS.md`, `docs/` and `openspec/` inside a project are **team assets**: never migrate or rewrite them. Team assets describe how the project is built; personal memory describes how I work on it.
10
- - Layers: `code-rules.md` (plugin engineering baseline, read-only), `memory/user-rules.md` (your own promoted rules, U numbers), this file (how memory is written and cleaned), `memory/preferences.md` (output and reporting taste), `memory/projects/<code>/` (project-specific facts).
10
+ - Layers: `code-rules.md` (plugin engineering baseline, read-only), `rules/user-rules.md` (your own promoted rules, U numbers), this file (how memory is written and cleaned), `memory/preferences.md` (output and reporting taste), `memory/projects/<code>/` (project-specific facts).
11
11
 
12
12
  ## 2. Three layers (knowing all projects without hoarding raw text)
13
13
 
@@ -44,7 +44,7 @@ Context budget: index plus one project's profile and state ≤ 20 KB; even a mul
44
44
 
45
45
  ## 4. Promotion
46
46
 
47
- - A rule used by ≥2 projects, or unrelated to any project (comment style, Git operations, line endings, verification), is **promoted** out of a project profile: engineering rules go to `memory/user-rules.md` (U numbers; the plugin's `code-rules.md` only changes with a release), output taste to `memory/preferences.md`, memory upkeep here. Leave the old number **empty and unused** in the profile, with a one-line pointer.
47
+ - A rule used by ≥2 projects, or unrelated to any project (comment style, Git operations, line endings, verification), is **promoted** out of a project profile: engineering rules go to `rules/user-rules.md` (U numbers; the plugin's `code-rules.md` only changes with a release), output taste to `memory/preferences.md`, memory upkeep here. Leave the old number **empty and unused** in the profile, with a one-line pointer.
48
48
  - Distilling rules from task experience (candidate → pool → promotion → dormancy) is described in [experience-pool.md](experience-pool.md); this section only answers where a distilled rule lands.
49
49
  - A project profile keeps only what is specific to that project (entry points, layout, pipelines, commands, pitfalls). General rules are not repeated per project.
50
50
  - Contracts or acceptance criteria a team must keep belong in the project's `openspec/specs/`, not in personal memory.
@@ -83,7 +83,7 @@ node <tools>/wf-task.mjs brief # summary firs
83
83
  node <tools>/wf-task.mjs decide --kind amend --task T-... --expect-rev 3 --relation 协作
84
84
  ```
85
85
 
86
- - `<tools>` is the absolute path printed in `rules/INDEX.md`: the workbench has no `tools/` directory, so a bare `tools/wf-task.mjs` resolves to nothing.
86
+ - `<tools>` is the absolute path printed in `rules/INDEX.md`: the workbench has no `tools/` directory, so a bare `lib/tools/wf-task.mjs` resolves to nothing.
87
87
  - Continue only on `ACC`. `STALE` means the board moved — re-read it and decide again. `MISSING` means the id is wrong.
88
88
  - `new` needs no expectRev but must state a relation.
89
89
  - Quick tasks never open a row; only accepted and standing work gets this far.
@@ -2,7 +2,7 @@
2
2
 
3
3
  > Root: `WF_HOME` or `$DSH_HOME/work-fish`; every path absolute.
4
4
  > Your own rules go to `rules/user-rules.md` and `rules/projects/<code>.md` (tool `wf-rule`); layout and token budget are in `rules/INDEX.md`.
5
- > `<tools>` = the plugin package's `tools/`; the absolute path is in `rules/INDEX.md`.
5
+ > `<tools>` = the plugin package's `lib/tools/`; the absolute path is in `rules/INDEX.md`.
6
6
 
7
7
  ## Start-up
8
8
 
@@ -1,439 +0,0 @@
1
- /**
2
- * The bridge between the Work Fish ledger and the `dsh-pet` character.
3
- *
4
- * Work Fish used to draw its own pet. Since the character belongs to `dsh-pet`,
5
- * this module is the whole of the relationship: a few HTTP calls over the Web
6
- * server's own origin, never an import, so either plugin can be upgraded or
7
- * removed without the other one failing to load.
8
- *
9
- * Three things travel over it:
10
- *
11
- * 1. **Menu items** — the pet's right-click menu gets a 「大肥鱼」 group
12
- * (`/menu/item`). A click comes back through `/menu/events`, which this
13
- * module long-polls; that is how the task panel is opened from the
14
- * character and how 「开始下一件」「完成进行中」become ledger writes.
15
- * 2. **Work status** — the top in-progress row is pushed as the pet's task
16
- * line (`/work-status`), so the character says what is being worked on.
17
- * 3. **Reminders** — a new overdue row earns one short bubble (`/broadcast`).
18
- *
19
- * Every call is best-effort: `dsh-pet` may be disabled, missing, asleep or
20
- * holding its lock, and none of that is an error worth surfacing to the user.
21
- * The bridge therefore never throws, never retries in a tight loop, and reports
22
- * its own state through `status()` so `/wf/info` can show it.
23
- *
24
- * @module dsh-work-fish/core/pet-bridge
25
- */
26
-
27
- import fs from 'node:fs'
28
- import { pushEvent } from './events.mjs'
29
-
30
- /** Registry key for our menu group; also the group label the pet shows. */
31
- const OWNER = '大肥鱼'
32
-
33
- /** The three menu items, in menu order. Labels double as click identifiers. */
34
- const LABELS = {
35
- board: '打开任务板',
36
- start: '开始下一件',
37
- finish: '完成进行中',
38
- }
39
-
40
- /** Wait ceiling for the menu long-poll, matching `dsh-pet`'s own limit. */
41
- const POLL_WAIT_MS = 10_000
42
-
43
- /** Backoff after a failed call: long enough that a missing pet costs nothing. */
44
- const RETRY_MS = 15_000
45
-
46
- /**
47
- * Sleep without holding anything.
48
- * @param {number} ms milliseconds.
49
- * @returns {Promise<void>} resolves after `ms`.
50
- */
51
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
52
-
53
- /**
54
- * Cut a string to `max` code points so a proxy pair never splits.
55
- * @param {string} text source text.
56
- * @param {number} max code points allowed.
57
- * @returns {string} the (possibly shortened) text.
58
- */
59
- function clip(text, max) {
60
- const points = Array.from(String(text ?? ''))
61
- return points.length > max ? `${points.slice(0, max - 1).join('')}…` : points.join('')
62
- }
63
-
64
- /**
65
- * Start the bridge. Safe to call once per mount; every failure stays inside.
66
- *
67
- * @param {object} deps dependencies, all supplied by the host entry.
68
- * @param {{homeDir: string, timeZone: string, allowWrites: boolean}} deps.options resolved row options.
69
- * @param {{info?: Function, warn?: Function, error?: Function}} [deps.logger] Cordis logger.
70
- * @param {() => string} deps.getOrigin returns the Web server origin, or `''`.
71
- * @param {(args: string[]) => Promise<object>} deps.runCli runs `wf-task` and returns its JSON.
72
- * @param {(options: object) => Promise<object>} deps.buildReport reads the ledger into the panel payload.
73
- * @returns {{status: () => object}} liveness facts for `/wf/info`.
74
- */
75
- export function startPetBridge({ options, logger, getOrigin, runCli, buildReport }) {
76
- /** @type {{connected: boolean, petId: string, display: string, reason: string, lastFeedAt: number, lastAction: string}} */
77
- const state = { connected: false, petId: '', display: '', reason: 'starting', lastFeedAt: 0, lastAction: '' }
78
-
79
- /** Set once `dsh-pet` accepted our menu registration; cleared on any failure. */
80
- let registered = false
81
-
82
- /** Overdue count last announced, so a reminder is news rather than a loop. */
83
- let announcedOverdue = -1
84
-
85
- /** Last time a reminder was shown, in ms; reminders are rate-limited. */
86
- let remindedAt = 0
87
-
88
- /** Set by `stop()`; every loop checks it before continuing. */
89
- let stopped = false
90
-
91
- /** Handle of the feed interval, cleared by `stop()`. */
92
- let feedTimer = undefined
93
-
94
- /** Ledger mtime last seen, used to nudge open panels. */
95
- let ledgerStamp = ''
96
-
97
- /**
98
- * `dsh-pet` mounts every route under one constant segment; this is the only
99
- * place that spells it, and the probe in `/wf/info` shows when it stops matching.
100
- * @returns {string} `origin + segment`, or `''` before the server knows its origin.
101
- */
102
- const base = () => {
103
- const origin = String(getOrigin() ?? '')
104
- return origin === '' ? '' : `${origin.replace(/\/+$/u, '')}/dsh-pet-7340`
105
- }
106
-
107
- /**
108
- * One JSON call against `dsh-pet`.
109
- *
110
- * `signal` bounds the long poll: without it a half-open socket would keep the
111
- * loop from ever retrying. Every non-2xx answer is a rejection here so the
112
- * caller has one branch, not two.
113
- *
114
- * @param {string} url absolute URL.
115
- * @param {{method?: string, body?: object, timeoutMs?: number}} [init] request shape.
116
- * @returns {Promise<object>} the parsed body, or `{ ok: false }` on any failure.
117
- */
118
- async function call(url, init = {}) {
119
- const controller = new AbortController()
120
- const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 5_000)
121
- try {
122
- const response = await fetch(url, {
123
- method: init.method ?? 'GET',
124
- headers: init.body === undefined ? { accept: 'application/json' } : { accept: 'application/json', 'content-type': 'application/json' },
125
- body: init.body === undefined ? undefined : JSON.stringify(init.body),
126
- signal: controller.signal,
127
- cache: 'no-store',
128
- })
129
- const text = await response.text()
130
- let body = {}
131
- try {
132
- body = text === '' ? {} : JSON.parse(text)
133
- } catch {
134
- body = { ok: false, code: 'bad-json', message: `HTTP ${response.status}` }
135
- }
136
- if (!response.ok) return { ...body, ok: false, code: body?.code ?? `http-${response.status}` }
137
- return body
138
- } catch (error) {
139
- return { ok: false, code: 'unreachable', message: error instanceof Error ? error.message : String(error) }
140
- } finally {
141
- clearTimeout(timer)
142
- }
143
- }
144
-
145
- /**
146
- * Learn which character to address.
147
- *
148
- * `dsh-pet` requires an explicit `?pet=` on every feed call and refuses to
149
- * guess, so the id is read from its merged config instead of being assumed.
150
- * That config is keyed by pet id (`{ main: {...} }`), one entry per layer —
151
- * it is not the same shape as the `pets[]` array in the on-disk file.
152
- *
153
- * The merged config is keyed by animation-entry name and each entry carries
154
- * the `pets[]` array; the first pet's id is what `?pet=` wants, and its
155
- * `display` decides which `surface` a bubble is allowed to target (`dsh-pet`
156
- * refuses a bubble for a surface the pet is not shown on).
157
- *
158
- * @param {string} root `origin + segment`.
159
- * @returns {Promise<{id: string, display: string}>} the first pet, or blanks.
160
- */
161
- async function discoverPet(root) {
162
- const config = await call(`${root}/config`)
163
- if (config === null || typeof config !== 'object') return { id: '', display: '' }
164
- for (const key of Object.keys(config)) {
165
- const layer = config[key]
166
- const pets = Array.isArray(layer?.pets) ? layer.pets : []
167
- const pet = pets.find((candidate) => typeof candidate?.id === 'string' && candidate.id.trim() !== '')
168
- if (pet !== undefined) {
169
- return { id: pet.id.trim(), display: typeof pet.display === 'string' ? pet.display : '' }
170
- }
171
- }
172
- return { id: '', display: '' }
173
- }
174
-
175
- /**
176
- * (Re)register the 「大肥鱼」 menu group.
177
- *
178
- * Registration replaces the whole owner, so this is idempotent; it is repeated
179
- * whenever a poll reports the owner is gone, which is what a `dsh-pet` restart
180
- * looks like from here.
181
- *
182
- * @param {string} root `origin + segment`.
183
- * @returns {Promise<boolean>} whether the group is in place.
184
- */
185
- async function registerMenu(root) {
186
- const result = await call(`${root}/menu/item`, {
187
- method: 'POST',
188
- body: { owner: OWNER, labels: Object.values(LABELS), target: 'both' },
189
- })
190
- if (result?.ok === true) return true
191
- logger?.warn?.(`wf: 桌宠菜单注册失败(${result?.reason ?? result?.code ?? 'unknown'})`)
192
- return false
193
- }
194
-
195
- /**
196
- * Forget the pet address so the next poll discovers it again.
197
- *
198
- * `dsh-pet` answers `unknown-pet` after the character is renamed or removed;
199
- * without this the bridge would keep feeding an id nobody owns while still
200
- * reporting itself as connected.
201
- */
202
- function forgetPet() {
203
- state.petId = ''
204
- state.display = ''
205
- state.connected = false
206
- state.reason = 'pet id no longer exists, rediscovering'
207
- registered = false
208
- }
209
-
210
- /**
211
- * Show one short line on the character.
212
- *
213
- * The `surface` must match where the character is actually shown, so it is
214
- * read from its own config rather than assumed; `both` is the tolerant default.
215
- *
216
- * @param {string} text what to say; `dsh-pet` cuts a long line itself.
217
- * @returns {Promise<boolean>} whether the character accepted the line.
218
- */
219
- async function say(text) {
220
- const root = base()
221
- if (root === '' || state.petId === '') return false
222
- const surface = state.display === 'desktop' || state.display === 'web' ? state.display : 'both'
223
- const result = await call(`${root}/broadcast?pet=${encodeURIComponent(state.petId)}&surface=${surface}`, {
224
- method: 'POST',
225
- body: { text: clip(text, 120), duration: 8_000, anim: false },
226
- })
227
- if (result?.ok === true) return true
228
- if (result?.reason === 'unknown-pet' || result?.reason === 'pet-required') forgetPet()
229
- return false
230
- }
231
-
232
- /**
233
- * Push (or clear) the pet's task line from the top in-progress row.
234
- * @returns {Promise<void>} resolves when the call is done or has failed.
235
- */
236
- async function feed() {
237
- const root = base()
238
- if (root === '' || state.petId === '') return
239
- const query = `?pet=${encodeURIComponent(state.petId)}`
240
- let report
241
- try {
242
- report = await buildReport(options)
243
- } catch (error) {
244
- logger?.warn?.(`wf: 台账读取失败(${error instanceof Error ? error.message : String(error)})`)
245
- return
246
- }
247
- const current = Array.isArray(report?.inProgress) ? report.inProgress[0] : undefined
248
- /** Nothing in progress hands the slot back rather than leaving a stale line. */
249
- const status =
250
- current === undefined
251
- ? await call(`${root}/work-status${query}`, { method: 'DELETE' })
252
- : await call(`${root}/work-status${query}`, {
253
- method: 'POST',
254
- body: { state: 'working', task: clip(`${current.id} ${current.title ?? ''}`.trim(), 40) },
255
- })
256
- if (status?.reason === 'unknown-pet' || status?.reason === 'pet-required') {
257
- forgetPet()
258
- return
259
- }
260
- state.lastFeedAt = Date.now()
261
-
262
- const overdue = Number(report?.counts?.overdue ?? 0)
263
- if (overdue > 0 && overdue !== announcedOverdue && Date.now() - remindedAt > 30 * 60_000) {
264
- const late = [...(report?.inProgress ?? []), ...(report?.todo ?? [])].find((row) => Number(row?.overdueDays) > 0)
265
- const spoken = await say(late === undefined ? `今天逾期 ${overdue} 件` : `逾期 ${overdue} 件,先看 ${late.id}`)
266
- // Only a delivered line counts as told: a mute pet must not swallow the reminder.
267
- if (spoken) remindedAt = Date.now()
268
- else return
269
- }
270
- announcedOverdue = overdue
271
- }
272
-
273
- /**
274
- * Move one ledger row through the shared CLI.
275
- * @param {object} row panel row (`id`, `rev`).
276
- * @param {string} to target section name.
277
- * @param {string[]} [extra] additional CLI flags.
278
- * @returns {Promise<object>} the CLI verdict.
279
- */
280
- async function move(row, to, extra = []) {
281
- const result = await runCli([
282
- 'move',
283
- '--task', String(row.id),
284
- '--expect-rev', String(row.rev),
285
- '--to', to,
286
- ...extra,
287
- '--source', '桌宠',
288
- ])
289
- state.lastAction = `${to} ${row.id}`
290
- pushEvent('changed')
291
- if (result?.ok === true) return result
292
- if (result?.verdict === 'STALE') await say('台账刚被改过,已刷新')
293
- else await say(`没写成:${clip(result?.message ?? '未知原因', 40)}`)
294
- return result
295
- }
296
-
297
- /**
298
- * React to one click on a menu item, in order of what the user asked for.
299
- * @param {string} label the clicked label.
300
- * @returns {Promise<void>} resolves when the action is done.
301
- */
302
- async function onMenuClick(label) {
303
- if (label === LABELS.board) {
304
- pushEvent('open')
305
- return
306
- }
307
- if (options.allowWrites !== true) {
308
- await say('台账写入已关闭')
309
- return
310
- }
311
- let report
312
- try {
313
- report = await buildReport(options)
314
- } catch {
315
- await say('台账读不到')
316
- return
317
- }
318
- if (label === LABELS.start) {
319
- const next = Array.isArray(report?.todo) ? report.todo[0] : undefined
320
- if (next === undefined) {
321
- await say('待办里没有可开的任务')
322
- return
323
- }
324
- const result = await move(next, '进行中')
325
- if (result?.ok === true) await say(`开始 ${next.id}`)
326
- return
327
- }
328
- if (label === LABELS.finish) {
329
- const current = Array.isArray(report?.inProgress) ? report.inProgress[0] : undefined
330
- if (current === undefined) {
331
- await say('没有进行中的任务')
332
- return
333
- }
334
- const result = await move(current, '已完成', ['--result', '已完成'])
335
- if (result?.ok === true) await say(`完成 ${current.id}`)
336
- }
337
- }
338
-
339
- /** One poll round: discover, register, then drain clicks until aborted. */
340
- async function pollLoop() {
341
- while (!stopped) {
342
- const root = base()
343
- if (root === '') {
344
- state.reason = 'web server origin unknown'
345
- await sleep(RETRY_MS)
346
- continue
347
- }
348
- if (state.petId === '') {
349
- const found = await discoverPet(root)
350
- state.petId = found.id
351
- state.display = found.display
352
- if (state.petId === '') {
353
- state.connected = false
354
- state.reason = 'dsh-pet 未安装或未启用'
355
- await sleep(RETRY_MS)
356
- continue
357
- }
358
- }
359
- if (!registered) {
360
- registered = await registerMenu(root)
361
- if (!registered) {
362
- state.connected = false
363
- state.reason = 'menu registration refused'
364
- await sleep(RETRY_MS)
365
- continue
366
- }
367
- state.connected = true
368
- state.reason = ''
369
- }
370
- const batch = await call(
371
- `${root}/menu/events?owner=${encodeURIComponent(OWNER)}&wait=${POLL_WAIT_MS}`,
372
- { timeoutMs: POLL_WAIT_MS + 5_000 },
373
- )
374
- if (batch?.ok !== true) {
375
- // A leftover long poll and a `dsh-pet` restart look the same here: drop
376
- // the registration and let the next round re-establish both.
377
- registered = false
378
- state.connected = false
379
- state.reason = 'pet unreachable'
380
- await sleep(RETRY_MS)
381
- continue
382
- }
383
- // `dsh-pet` answers `{ ok, events: { label: petId | null } }`: a null slot
384
- // means "registered but not clicked", which is the common case.
385
- const clicks = batch?.events !== null && typeof batch?.events === 'object' ? batch.events : {}
386
- for (const [label, pet] of Object.entries(clicks)) {
387
- if (typeof pet !== 'string' || pet === '') continue // unused click slot
388
- try {
389
- await onMenuClick(label)
390
- } catch (error) {
391
- logger?.warn?.(`wf: 菜单动作失败(${error instanceof Error ? error.message : String(error)})`)
392
- }
393
- }
394
- }
395
- }
396
-
397
- /** Refresh the feed and nudge open panels when the ledger file moved. */
398
- function watchLoop() {
399
- feedTimer = setInterval(() => {
400
- if (stopped) return
401
- try {
402
- const stamp = String(fs.statSync(`${options.homeDir}/tasks/index.md`).mtimeMs)
403
- if (ledgerStamp !== '' && stamp !== ledgerStamp) pushEvent('changed')
404
- ledgerStamp = stamp
405
- } catch {
406
- // An unreadable ledger is the panel's problem to show, not the loop's.
407
- }
408
- void feed()
409
- }, 30_000)
410
- feedTimer.unref?.()
411
- }
412
-
413
- void pollLoop()
414
- watchLoop()
415
-
416
- return {
417
- /** Liveness facts for `/wf/info` and the settings page. */
418
- status() {
419
- return {
420
- connected: state.connected,
421
- owner: OWNER,
422
- petId: state.petId,
423
- display: state.display,
424
- labels: Object.values(LABELS),
425
- reason: state.reason,
426
- lastFeedAt: state.lastFeedAt,
427
- lastAction: state.lastAction,
428
- }
429
- },
430
- /** Stop polling; used when the row is disposed. */
431
- stop() {
432
- stopped = true
433
- if (feedTimer !== undefined) {
434
- clearInterval(feedTimer)
435
- feedTimer = undefined
436
- }
437
- },
438
- }
439
- }
File without changes
File without changes
File without changes
File without changes
File without changes