dsh-feiyu-memgate 0.3.2 → 0.4.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 (103) hide show
  1. package/CHANGELOG.md +73 -12
  2. package/README.md +68 -11
  3. package/README.zh.md +93 -36
  4. package/client/README.md +267 -0
  5. package/client/art/mascot-asleep.webp +0 -0
  6. package/client/art/mascot-busy.webp +0 -0
  7. package/client/art/mascot-nag.webp +0 -0
  8. package/client/art/mascot-ready.webp +0 -0
  9. package/client/art/mascot-trouble.webp +0 -0
  10. package/client/client.js +4226 -1269
  11. package/client/src/clipboard.cjs +52 -0
  12. package/client/src/constants.cjs +43 -0
  13. package/client/src/fields.cjs +960 -0
  14. package/client/src/hooks.cjs +220 -0
  15. package/client/src/i18n.cjs +444 -0
  16. package/client/src/index.cjs +69 -0
  17. package/client/src/kit/controls.cjs +189 -0
  18. package/client/src/kit/icons.cjs +40 -0
  19. package/client/src/kit/layout.cjs +124 -0
  20. package/client/src/layout.cjs +143 -0
  21. package/client/src/model/changelog.cjs +29 -0
  22. package/client/src/model/feedback.cjs +168 -0
  23. package/client/src/model/form.cjs +83 -0
  24. package/client/src/model/models.cjs +87 -0
  25. package/client/src/model/overview.cjs +111 -0
  26. package/client/src/model/page.cjs +104 -0
  27. package/client/src/model/status.cjs +57 -0
  28. package/client/src/model/trial.cjs +111 -0
  29. package/client/src/net.cjs +101 -0
  30. package/client/src/react.cjs +11 -0
  31. package/client/src/theme/page.css +1284 -0
  32. package/client/src/theme/styles.cjs +43 -0
  33. package/client/src/view/feedback.cjs +180 -0
  34. package/client/src/view/field-row.cjs +98 -0
  35. package/client/src/view/hero.cjs +54 -0
  36. package/client/src/view/markdown.cjs +96 -0
  37. package/client/src/view/models.cjs +154 -0
  38. package/client/src/view/page.cjs +199 -0
  39. package/client/src/view/settings-tab.cjs +78 -0
  40. package/client/src/view/tabs.cjs +71 -0
  41. package/client/src/view/trial.cjs +84 -0
  42. package/docs/DETAIL.en.md +55 -6
  43. package/docs/DETAIL.md +63 -14
  44. package/locale/zh.json +1 -1
  45. package/package.json +2 -1
  46. package/python/GATEWAY_VERSION.json +37 -31
  47. package/python/feiyu_memgate/backends/_sqlfile.py +293 -0
  48. package/python/feiyu_memgate/backends/base.py +121 -6
  49. package/python/feiyu_memgate/backends/embedding.py +265 -178
  50. package/python/feiyu_memgate/backends/hybrid.py +330 -83
  51. package/python/feiyu_memgate/backends/inmemory.py +115 -24
  52. package/python/feiyu_memgate/backends/openviking.py +7 -10
  53. package/python/feiyu_memgate/backends/sqlite.py +129 -145
  54. package/python/feiyu_memgate/builtins.py +1 -0
  55. package/python/feiyu_memgate/cli.py +124 -20
  56. package/python/feiyu_memgate/client/block.py +4 -2
  57. package/python/feiyu_memgate/client/http.py +106 -19
  58. package/python/feiyu_memgate/client/local.py +4 -3
  59. package/python/feiyu_memgate/config.py +118 -24
  60. package/python/feiyu_memgate/core/limits.py +2 -1
  61. package/python/feiyu_memgate/core/pool.py +29 -2
  62. package/python/feiyu_memgate/core/recall.py +179 -10
  63. package/python/feiyu_memgate/core/redact.py +4 -2
  64. package/python/feiyu_memgate/core/stages.py +52 -9
  65. package/python/feiyu_memgate/core/tidy.py +2 -1
  66. package/python/feiyu_memgate/core/watch.py +3 -2
  67. package/python/feiyu_memgate/core/write.py +9 -3
  68. package/python/feiyu_memgate/forgetting/archive.py +38 -10
  69. package/python/feiyu_memgate/forgetting/engine.py +46 -10
  70. package/python/feiyu_memgate/forgetting/stage.py +4 -2
  71. package/python/feiyu_memgate/gateway/app.py +168 -272
  72. package/python/feiyu_memgate/gateway/fields.py +121 -0
  73. package/python/feiyu_memgate/gateway/policies.py +162 -0
  74. package/python/feiyu_memgate/gateway/server.py +12 -4
  75. package/python/feiyu_memgate/gateway/tokens.py +137 -0
  76. package/python/feiyu_memgate/gateway/validate.py +120 -0
  77. package/python/feiyu_memgate/identity.py +152 -0
  78. package/python/feiyu_memgate/model.py +170 -2
  79. package/python/feiyu_memgate/registry.py +6 -3
  80. package/python/feiyu_memgate/tools/crypto.py +5 -4
  81. package/python/feiyu_memgate/tools/evaluate.py +2 -1
  82. package/python/feiyu_memgate/tools/tenants.py +2 -0
  83. package/src/block.js +9 -3
  84. package/src/capture.js +98 -0
  85. package/src/catalogue.js +4 -4
  86. package/src/changelog.js +72 -0
  87. package/src/client.js +145 -10
  88. package/src/commands.js +112 -62
  89. package/src/config.js +139 -62
  90. package/src/followup.js +139 -0
  91. package/src/gateway.js +79 -4
  92. package/src/migrate.py +54 -9
  93. package/src/mirror.py +44 -7
  94. package/src/plugin.js +416 -412
  95. package/src/pool.js +298 -0
  96. package/src/recent.js +68 -0
  97. package/src/relevance.js +80 -0
  98. package/src/routes.js +320 -0
  99. package/src/setup.js +36 -36
  100. package/src/shared.js +77 -0
  101. package/src/tiers.js +4 -4
  102. package/src/time.js +27 -0
  103. package/src/tools.js +164 -0
@@ -0,0 +1,168 @@
1
+ 'use strict'
2
+ // Feedback: what a person wrote, turned into the address of GitHub's "new issue" page with the title
3
+ // and the text filled in. The plugin sends nothing anywhere. The person's own browser opens the
4
+ // address, shows what is filled in, and the report exists only once they press GitHub's own button.
5
+ //
6
+ // Pure, and the one module of the page that the host half loads as well (src/commands.js, for
7
+ // /memgate feedback), so that both build the same address. It requires the constants and nothing else.
8
+ //
9
+ // The same report can also be posted to the project's own receiver (feedback-worker/); payload()
10
+ // is what is posted, and usableEndpoint() says whether an address may be posted to at all.
11
+ //
12
+ // What may go into a report besides the person's own words is decided here and nowhere else:
13
+ // environment() takes version numbers and state names from the status, and every value has to look
14
+ // like one (SAFE) or is replaced by a question mark. So a path, an address, a file name, a count of
15
+ // memories or a secret cannot get in, whatever a later version of the status holds.
16
+
17
+ const { LINKS } = require('../constants.cjs')
18
+
19
+ /** What a report is about, in the order the page offers them. */
20
+ const KINDS = ['idea', 'problem', 'other']
21
+ // The start of the issue title, so that the list of issues can be read at a glance.
22
+ const TITLE_TAGS = { idea: '[idea]', problem: '[bug]', other: '[feedback]' }
23
+ /** The longest text the page accepts, in characters. */
24
+ const MAX_TEXT = 4000
25
+ // The title is the first line of the text, up to this many characters.
26
+ const MAX_TITLE = 60
27
+ // The longest address that is handed to a browser. GitHub answers 414 somewhere above 8,000
28
+ // characters; a Chinese character takes nine once it is percent-encoded.
29
+ const MAX_URL = 6000
30
+ // A version number, a state name, a model id: letters, digits, dots, dashes, at most 40 characters.
31
+ const SAFE = /^[A-Za-z0-9][A-Za-z0-9 ._+-]{0,39}$/
32
+ // A half of a surrogate pair without its other half: encodeURIComponent throws on one.
33
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g
34
+ const ENV_HEADING = 'Environment (added by dsh-feiyu-memgate)'
35
+ const CUT_NOTE = '(Cut here: the text was too long for a link. Paste the whole text over this.)'
36
+
37
+ /** A value of the status as it may appear in a report: itself when it looks like a name or a number, else '?'. */
38
+ function safe(value) {
39
+ const text = typeof value === 'number' ? String(value) : value
40
+ return typeof text === 'string' && SAFE.test(text) ? text : '?'
41
+ }
42
+
43
+ /**
44
+ * The environment lines of a report, from the answer of the status route.
45
+ * @param {object | null | undefined} status
46
+ * @returns {[string, string][]} name and value pairs; empty when there is no status to take them from
47
+ */
48
+ function environment(status) {
49
+ if (!status || typeof status !== 'object') return []
50
+ const rows = [['plugin', 'dsh-feiyu-memgate ' + safe(status.version)]]
51
+ const embed = status.embed
52
+ rows.push(['add-on', embed
53
+ ? ['dsh-feiyu-memgate-embed ' + safe(embed.version), safe(embed.state)].concat(embed.model ? [safe(embed.model)] : []).join(', ')
54
+ : 'not installed'])
55
+ const gateway = status.gateway || {}
56
+ rows.push(['gateway', safe(gateway.mode) + ', ' + safe(gateway.state)])
57
+ if (gateway.mode !== 'external') {
58
+ const retrieval = status.retrieval || {}
59
+ rows.push(['retrieval', safe(retrieval.setting)
60
+ + (retrieval.active ? ' -> ' + safe(retrieval.active) : '')
61
+ + (retrieval.hybrid && retrieval.hybrid.active ? ' + keyword' : '')])
62
+ const python = status.python
63
+ rows.push(['python', !python ? 'not checked' : python.found ? safe(python.version) : 'not found'])
64
+ }
65
+ const runtime = status.runtime
66
+ if (runtime) rows.push(['system', safe(runtime.platform) + ' ' + safe(runtime.arch) + ', Node ' + safe(runtime.node)])
67
+ rows.push(['language', safe(status.language)])
68
+ return rows
69
+ }
70
+
71
+ /** The text as it is used: one kind of line break, no stray half characters, trimmed, at most MAX_TEXT characters. */
72
+ function cleanText(text) {
73
+ const tidy = String(text === null || text === undefined ? '' : text).replace(/\r\n?/g, '\n').replace(LONE_SURROGATE, '�').trim()
74
+ const points = Array.from(tidy)
75
+ return points.length > MAX_TEXT ? points.slice(0, MAX_TEXT).join('').trim() : tidy
76
+ }
77
+
78
+ /** The issue title: the tag of the kind, then the first line of the text, shortened. */
79
+ function titleOf(kind, text) {
80
+ const tag = TITLE_TAGS[kind] || TITLE_TAGS.other
81
+ const first = cleanText(text).split('\n').map((line) => line.trim()).find(Boolean) || ''
82
+ const points = Array.from(first)
83
+ const line = points.length > MAX_TITLE ? points.slice(0, MAX_TITLE).join('').trim() + '…' : first
84
+ return line ? tag + ' ' + line : tag
85
+ }
86
+
87
+ /** The issue text: the person's words, then the environment lines under a rule when there are any. */
88
+ function bodyOf(text, rows) {
89
+ const parts = []
90
+ if (text) parts.push(text)
91
+ if (rows && rows.length) parts.push('---\n' + ENV_HEADING + '\n' + rows.map((row) => '- ' + row[0] + ': ' + row[1]).join('\n'))
92
+ return parts.join('\n\n')
93
+ }
94
+
95
+ /** The address of GitHub's new-issue page with a title and a text filled in. */
96
+ function addressOf(title, body) {
97
+ return LINKS.newIssue + '?title=' + encodeURIComponent(title) + '&body=' + encodeURIComponent(body)
98
+ }
99
+
100
+ /**
101
+ * A report, ready to hand over.
102
+ * @param {{ kind?: string, text?: string, environment?: [string, string][], cutNote?: string }} draft
103
+ * `environment` is environment() or an empty list when the person does not want it attached;
104
+ * `cutNote` is the line that marks a cut, in the person's language.
105
+ * @returns {{ ready: boolean, title: string, body: string, url: string, clipped: boolean }}
106
+ * `ready`: there is something written. `title` and `body` are the whole report. `url` opens the
107
+ * new-issue page with them filled in; when they do not fit into an address (`clipped`), the text in
108
+ * the address is cut and ends with the note, and the whole report has to travel by the clipboard.
109
+ */
110
+ function compose(draft) {
111
+ const input = draft || {}
112
+ const text = cleanText(input.text)
113
+ const rows = Array.isArray(input.environment) ? input.environment : []
114
+ const title = titleOf(input.kind, text)
115
+ const body = bodyOf(text, rows)
116
+ let url = addressOf(title, body)
117
+ const clipped = url.length > MAX_URL
118
+ if (clipped) {
119
+ // The longest beginning of the text that still fits with the note and the environment lines.
120
+ const note = '\n\n' + (input.cutNote || CUT_NOTE)
121
+ const points = Array.from(text)
122
+ const fits = (count) => addressOf(title, bodyOf(points.slice(0, count).join('') + note, rows)).length <= MAX_URL
123
+ let low = 0
124
+ let high = points.length
125
+ while (low < high) {
126
+ const middle = Math.ceil((low + high) / 2)
127
+ if (fits(middle)) low = middle
128
+ else high = middle - 1
129
+ }
130
+ url = addressOf(title, bodyOf(points.slice(0, low).join('').trim() + note, rows))
131
+ }
132
+ return { ready: text.length > 0, title, body, url, clipped }
133
+ }
134
+
135
+ /** The whole report as one text, for the clipboard. */
136
+ function reportText(composed) {
137
+ return composed.title + '\n\n' + composed.body
138
+ }
139
+
140
+ /**
141
+ * What is posted to the feedback receiver (feedback-worker/worker.js reads exactly this shape).
142
+ * @param {{ kind?: string, text?: string }} draft
143
+ * @param {[string, string][]} rows environment(), or an empty list when it is not to be attached
144
+ * @returns {{ v: 1, kind: string, text: string, environment: [string, string][] }}
145
+ */
146
+ function payload(draft, rows) {
147
+ const input = draft || {}
148
+ return {
149
+ v: 1,
150
+ kind: KINDS.includes(input.kind) ? input.kind : 'other',
151
+ text: cleanText(input.text),
152
+ environment: Array.isArray(rows) ? rows : [],
153
+ }
154
+ }
155
+
156
+ /**
157
+ * The address of a receiver the page may post to, or '' when there is none: an https address, or
158
+ * one on this computer (the preview and tests).
159
+ */
160
+ function usableEndpoint(value) {
161
+ if (typeof value !== 'string' || /\s/.test(value)) return ''
162
+ return /^https:\/\/[^/]+(\/|$)/.test(value) || /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?(\/|$)/.test(value) ? value : ''
163
+ }
164
+
165
+ module.exports = {
166
+ KINDS, TITLE_TAGS, MAX_TEXT, MAX_TITLE, MAX_URL,
167
+ safe, environment, cleanText, titleOf, bodyOf, compose, reportText, payload, usableEndpoint,
168
+ }
@@ -0,0 +1,83 @@
1
+ 'use strict'
2
+
3
+ // The settings form as plain data: what each field shows, which staged edits are valid, and the
4
+ // Settings operations a save sends. Pure functions of their arguments; never touches React or the DOM.
5
+
6
+ const { INDEX } = require('../fields.cjs')
7
+
8
+ // A value inside nested objects by path, or undefined when any step is missing (own properties only).
9
+ function at(value, path) {
10
+ let node = value
11
+ for (const key of path) {
12
+ if (node === null || typeof node !== 'object' || !Object.prototype.hasOwnProperty.call(node, key)) return undefined
13
+ node = node[key]
14
+ }
15
+ return node
16
+ }
17
+
18
+ /** Whether a staged text is a value the field accepts (the host validates again on save). */
19
+ function checkText(field, text) {
20
+ const raw = String(text).trim()
21
+ if (field.kind === 'integer') {
22
+ if (!/^-?\d{1,9}$/.test(raw)) return false
23
+ const n = Number(raw)
24
+ return n >= field.min && n <= field.max
25
+ }
26
+ if (field.kind === 'string' && field.format === 'url' && raw) return /^https?:\/\/[^\s/]+\S*$/i.test(raw)
27
+ return true
28
+ }
29
+
30
+ /** What one field shows: its current or staged value, whether it is changed, invalid or being cleared. */
31
+ function fieldView(field, groupKey, state, draft, secrets) {
32
+ const k = groupKey + '.' + field.key
33
+ const staged = draft[k]
34
+ const path = [groupKey, field.key]
35
+ if (field.secret) {
36
+ return {
37
+ k, field, secret: true,
38
+ text: staged && !staged.unset ? staged.value : '',
39
+ clearing: Boolean(staged && staged.unset),
40
+ configured: secrets && typeof secrets[k] === 'boolean' ? secrets[k] : null,
41
+ invalid: false, overridden: false,
42
+ }
43
+ }
44
+ const inherited = at(state.base, path) !== undefined ? at(state.base, path) : field.default
45
+ const stored = at(state.value, path) !== undefined ? at(state.value, path) : field.default
46
+ const value = staged ? (staged.unset ? inherited : staged.value) : stored
47
+ const text = field.kind === 'integer' || field.kind === 'string' ? String(value) : value
48
+ return {
49
+ k, field, secret: false, value, text,
50
+ overridden: staged ? !staged.unset : at(state.user, path) !== undefined,
51
+ invalid: (field.kind === 'integer' || field.kind === 'string') && !checkText(field, text),
52
+ }
53
+ }
54
+
55
+ /** The staged edits as Settings path operations, in field order. */
56
+ function buildOps(draft) {
57
+ const ops = []
58
+ for (const k of Object.keys(INDEX)) {
59
+ const staged = draft[k]
60
+ if (!staged) continue
61
+ const field = INDEX[k]
62
+ const path = [field.group, field.key]
63
+ if (staged.unset) {
64
+ ops.push({ op: 'unset', path })
65
+ continue
66
+ }
67
+ if (field.secret && staged.value === '') continue // an empty secret draft keeps the stored value
68
+ let value = staged.value
69
+ if (field.kind === 'integer') value = Number(String(value).trim())
70
+ else if (field.kind === 'string') value = String(value).trim()
71
+ ops.push({ op: 'set', path, value })
72
+ }
73
+ return ops
74
+ }
75
+
76
+ /** Write every staged edit in one mutation, fenced by the revision the edits were made against. */
77
+ async function saveDraft(form, draft) {
78
+ const ops = buildOps(draft)
79
+ if (!ops.length) return true
80
+ return (await form.mutate(ops, form.state.revision)) === true
81
+ }
82
+
83
+ module.exports = { at, checkText, fieldView, buildOps, saveDraft }
@@ -0,0 +1,87 @@
1
+ 'use strict'
2
+
3
+ // The local embedding models list as plain data: texts, sizes, which buttons a row offers, the line
4
+ // on where the setup stands. Pure; the view decides how to draw it. Never touches React or the DOM.
5
+
6
+ /** A { en, zh } text from the host half in the page's language. */
7
+ function pickText(text, lang) {
8
+ if (!text || typeof text !== 'object') return ''
9
+ return text[lang] || text.en || ''
10
+ }
11
+
12
+ /** A download size as "1.2 GB" or "345.0 MB" (decimal units); "?" when the size is not a positive number. */
13
+ function formatSize(bytes) {
14
+ if (typeof bytes !== 'number' || !(bytes > 0)) return '?'
15
+ return bytes >= 1e9 ? (bytes / 1e9).toFixed(1) + ' GB' : (bytes / 1e6).toFixed(1) + ' MB'
16
+ }
17
+
18
+ // The add-on's measurement { loaded, peak } (MB) as "about N MB": the loaded figure, the memory the
19
+ // model process holds while it serves; "not measured" when there is none.
20
+ function memoryText(memoryMB, t) {
21
+ const mb = memoryMB && typeof memoryMB === 'object' ? (memoryMB.loaded > 0 ? memoryMB.loaded : memoryMB.peak > 0 ? memoryMB.peak : null) : null
22
+ return mb ? t('memoryAbout', { mb: String(Math.round(mb)) }) : t('memoryUnknown')
23
+ }
24
+
25
+ /**
26
+ * What a model row offers: the primary button (label, action, whether it can be pressed) and a
27
+ * secondary one (cancel while downloading, delete when downloaded and not in use).
28
+ */
29
+ function modelActions(model, view, accepted) {
30
+ const otherBusy = view.busy && view.chain.target !== model.id
31
+ const needsTick = Boolean(model.requiresAcceptance) && model.state === 'absent' && !accepted
32
+ switch (model.state) {
33
+ case 'downloading':
34
+ return {
35
+ primary: { label: model.percent === null || model.percent === undefined ? ['actDownloadingPlain'] : ['actDownloading', { percent: model.percent }], action: null, enabled: false },
36
+ secondary: { label: ['actCancel'], action: 'cancel' },
37
+ }
38
+ case 'installed':
39
+ return { primary: { label: ['actUse'], action: 'use', enabled: !otherBusy }, secondary: { label: ['actRemove'], action: 'remove' } }
40
+ case 'active':
41
+ return { primary: { label: ['actActive'], action: null, enabled: false }, secondary: null }
42
+ case 'loading':
43
+ return { primary: { label: ['actLoading'], action: null, enabled: false }, secondary: null }
44
+ case 'paused':
45
+ return { primary: { label: ['actResume'], action: 'install', enabled: !otherBusy }, secondary: { label: ['actCancel'], action: 'cancel' } }
46
+ default: {
47
+ const mine = view.busy && view.chain.target === model.id
48
+ return {
49
+ primary: { label: ['actInstall'], action: 'install', enabled: !otherBusy && !mine && !needsTick },
50
+ secondary: mine && view.chain.phase === 'addon' ? { label: ['actCancel'], action: 'cancel' } : null,
51
+ }
52
+ }
53
+ }
54
+ }
55
+
56
+ /** The line on where the setup stands, or null. */
57
+ function chainLine(view, t) {
58
+ const c = view.chain
59
+ if (!c || !c.target) return null
60
+ const model = c.target
61
+ switch (c.phase) {
62
+ case 'addon': {
63
+ const s = c.installState && c.installState.phase ? ' · ' + t('installState.' + c.installState.phase) : ''
64
+ return t('phase.addon') + s
65
+ }
66
+ case 'addon-starting':
67
+ return t('phase.addon-starting')
68
+ case 'paused':
69
+ return t('phase.paused', { model })
70
+ case 'model':
71
+ return c.percent === null || c.percent === undefined ? t('phase.model', { model }) : t('phase.modelPercent', { model, percent: c.percent })
72
+ case 'activating':
73
+ return t('phase.activating', { model })
74
+ case 'done':
75
+ return t('phase.done', { model })
76
+ default:
77
+ return null
78
+ }
79
+ }
80
+
81
+ // The answer to a click and the stored state of the chain often carry the same failure (a declined
82
+ // install script is both). Found in a real host: the message was shown twice. Show the stored one.
83
+ function sameProblem(a, b) {
84
+ return Boolean(a && b && a.code && a.code === b.code)
85
+ }
86
+
87
+ module.exports = { pickText, formatSize, memoryText, modelActions, chainLine, sameProblem }
@@ -0,0 +1,111 @@
1
+ 'use strict'
2
+ // The status of the plugin boiled down for the top of the page: one mood, one headline, one line of
3
+ // explanation, and a few facts. Pure: it takes what GET feiyu-memgate/status answered and returns
4
+ // translation keys with their parameters; it never touches React or the DOM.
5
+ //
6
+ // The mood decides which drawing of the mascot is shown, so the order of the checks below is the
7
+ // order of what a person needs to hear first: something is broken, then something is still on its
8
+ // way, then nothing is running, and only then "all is well".
9
+
10
+ /** The four moods, each with the drawing that goes with it (view/hero.cjs). */
11
+ const MOODS = ['ready', 'busy', 'asleep', 'trouble']
12
+
13
+ // Gateway states (src/gateway.js for the bundled gateway, src/plugin.js for an external one).
14
+ const BUSY_STATES = ['idle', 'starting', 'restarting']
15
+ const ASLEEP_STATES = ['off', 'stopped', 'unused']
16
+
17
+ const text = (key, params) => ({ key, params: params || {} })
18
+
19
+ /** Whole numbers with thousands separators, the same in both languages (1,284). */
20
+ function formatCount(value) {
21
+ return String(Math.trunc(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
22
+ }
23
+
24
+ /**
25
+ * The reason the plugin cannot work right now, or null.
26
+ * @returns {{ key: string, params: object } | null} the explanation line
27
+ */
28
+ function trouble(data) {
29
+ const gateway = data.gateway || {}
30
+ const managed = gateway.mode !== 'external'
31
+ if (managed && data.python && data.python.found === false) return text('overview.trouble.python')
32
+ if (gateway.state === 'failed') return text('overview.trouble.failed')
33
+ if (!managed && gateway.state === 'incomplete') return text('overview.trouble.incomplete')
34
+ return null
35
+ }
36
+
37
+ /**
38
+ * What is still on its way, or null: the gateway starting, a model loading, memories being copied.
39
+ * The copy comes last: the plugin already answers while it runs.
40
+ */
41
+ function busy(data) {
42
+ const gateway = data.gateway || {}
43
+ if (BUSY_STATES.includes(gateway.state)) return text('overview.busy.gateway')
44
+ if (data.embed && data.embed.state === 'loading') return text('overview.busy.model', { model: data.embed.model || '' })
45
+ const copy = data.migration
46
+ if (copy && (copy.state === 'running' || copy.state === 'partial')) {
47
+ return text('overview.busy.copy', { copied: formatCount(copy.copied || 0), total: formatCount(copy.total || 0) })
48
+ }
49
+ return null
50
+ }
51
+
52
+ /** The explanation line of a working plugin: where the memories are and how they are found. */
53
+ function readyLine(data) {
54
+ const gateway = data.gateway || {}
55
+ if (gateway.mode === 'external') return text('overview.ready.external')
56
+ const retrieval = data.retrieval || {}
57
+ const tier = retrieval.active || 'keyword'
58
+ const hybrid = Boolean(retrieval.hybrid && retrieval.hybrid.active)
59
+ return text('overview.ready.' + tier + (hybrid && tier !== 'keyword' ? '.hybrid' : ''), { model: (data.embed && data.embed.model) || '' })
60
+ }
61
+
62
+ /**
63
+ * The short facts under the headline, most useful first. Each is { id, key, params, tone }, where
64
+ * tone is 'plain' or 'warn' (a fact the person should look at).
65
+ */
66
+ function facts(data) {
67
+ const out = []
68
+ const gateway = data.gateway || {}
69
+ const managed = gateway.mode !== 'external'
70
+ const store = data.store
71
+ if (managed && store && store.count !== null && store.count !== undefined) {
72
+ out.push({ id: 'count', key: 'overview.fact.count', params: { count: formatCount(store.count) }, tone: 'plain' })
73
+ }
74
+ if (managed && data.retrieval && data.retrieval.active) {
75
+ const hybrid = Boolean(data.retrieval.hybrid && data.retrieval.hybrid.active)
76
+ // Keyword retrieval has no hybrid form: the switch only adds keyword search to a vector tier.
77
+ const tier = data.retrieval.active
78
+ out.push({ id: 'tier', key: 'overview.fact.tier.' + tier + (hybrid && tier !== 'keyword' ? '.hybrid' : ''), params: {}, tone: 'plain' })
79
+ }
80
+ out.push({ id: 'gateway', key: managed ? 'overview.fact.managed' : 'overview.fact.external', params: {}, tone: 'plain' })
81
+ if (data.embed && data.embed.state === 'error') out.push({ id: 'embed', key: 'overview.fact.embedError', params: {}, tone: 'warn' })
82
+ if (data.migration && data.migration.refused > 0) {
83
+ out.push({ id: 'refused', key: 'overview.fact.refused', params: { count: formatCount(data.migration.refused) }, tone: 'warn' })
84
+ }
85
+ return out
86
+ }
87
+
88
+ /**
89
+ * The top of the page for one status answer.
90
+ * @param {object | null} data the answer of the status route, or null when there is none yet
91
+ * @param {string | null} error the code of a failed read, or null
92
+ * @param {boolean} loading whether the first read is still under way
93
+ * @returns {{ mood: string, headline: object, line: object, facts: object[] }}
94
+ */
95
+ function summarise(data, error, loading) {
96
+ if (!data) {
97
+ if (loading) return { mood: 'busy', headline: text('overview.head.loading'), line: text('overview.line.loading'), facts: [] }
98
+ return { mood: 'trouble', headline: text('overview.head.unknown'), line: text('overview.line.unknown', { code: error || '' }), facts: [] }
99
+ }
100
+ const state = (data.gateway || {}).state
101
+ const broken = trouble(data)
102
+ if (broken) return { mood: 'trouble', headline: text('overview.head.trouble'), line: broken, facts: facts(data) }
103
+ if (ASLEEP_STATES.includes(state)) {
104
+ return { mood: 'asleep', headline: text('overview.head.asleep'), line: text('overview.asleep.' + state), facts: facts(data) }
105
+ }
106
+ const waiting = busy(data)
107
+ if (waiting) return { mood: 'busy', headline: text('overview.head.busy'), line: waiting, facts: facts(data) }
108
+ return { mood: 'ready', headline: text('overview.head.ready'), line: readyLine(data), facts: facts(data) }
109
+ }
110
+
111
+ module.exports = { MOODS, formatCount, summarise }
@@ -0,0 +1,104 @@
1
+ 'use strict'
2
+ // The settings of the page arranged for drawing: the layout table (layout.cjs) joined with the field
3
+ // table (fields.cjs) and the state of the form (model/form.cjs). Pure: no React, no DOM.
4
+ //
5
+ // Two ideas live here.
6
+ // - Dependence. A setting with `needs` (src/config.js) only has an effect while another setting has
7
+ // a fitting value; the page shows it as a sub-row of that setting, and only then. The value that
8
+ // counts is the one on screen (a staged edit included), so flipping a switch opens its sub-rows
9
+ // before anything is saved.
10
+ // - Change marks. A tab or a group that is closed still has to say that something inside it was
11
+ // edited or cannot be saved, so both are counted per section and per tab.
12
+
13
+ const { INDEX } = require('../fields.cjs')
14
+ const { TABS } = require('../layout.cjs')
15
+ const { fieldView } = require('./form.cjs')
16
+
17
+ /**
18
+ * Split an option label of the form "name: what it means" (both the ASCII and the full-width colon
19
+ * are used in src/config.js) into its two parts. A label without a colon is all name.
20
+ * @returns {{ name: string, note: string }}
21
+ */
22
+ function splitOption(label) {
23
+ const text = String(label === undefined || label === null ? '' : label)
24
+ const match = /^([^::]{1,24})[::]\s*(.+)$/.exec(text)
25
+ return match ? { name: match[1].trim(), note: match[2].trim() } : { name: text, note: '' }
26
+ }
27
+
28
+ /** Whether a setting's `needs` is met by the values on screen (`values`: key → value). */
29
+ function isMet(field, values) {
30
+ if (!field.needs) return true
31
+ return field.needs.in.includes(values[field.needs.key])
32
+ }
33
+
34
+ /**
35
+ * One section ready to draw.
36
+ * @param {object} section a section of layout.cjs
37
+ * @param {object} state the form state of the host ({ value, base, user })
38
+ * @param {object} draft the staged edits (key → { value } | { unset })
39
+ * @param {object | null} secrets which secrets hold a value (key → boolean), from the status route
40
+ * @returns {{ section: object, rows: object[], staged: number, invalid: number, overridden: number }}
41
+ * rows: { view, parent, shown }: `view` is fieldView()'s answer, `parent` the key this row depends
42
+ * on (or null), `shown` whether its `needs` is met. Counts cover shown and hidden rows alike:
43
+ * a staged edit of a row that has since been hidden is still saved.
44
+ */
45
+ function sectionView(section, state, draft, secrets) {
46
+ const views = section.fields.map((key) => {
47
+ const field = INDEX[key]
48
+ return fieldView(field, field.group, state, draft, secrets)
49
+ })
50
+ // The values on screen for every setting some row of this section depends on.
51
+ const values = {}
52
+ for (const view of views) {
53
+ const needs = view.field.needs
54
+ if (!needs || needs.key in values) continue
55
+ const other = INDEX[needs.key]
56
+ values[needs.key] = fieldView(other, other.group, state, draft, secrets).value
57
+ }
58
+ const rows = views.map((view) => ({
59
+ view,
60
+ parent: view.field.needs && section.fields.includes(view.field.needs.key) ? view.field.needs.key : null,
61
+ shown: isMet(view.field, values),
62
+ }))
63
+ return {
64
+ section,
65
+ rows,
66
+ staged: views.filter((view) => draft[view.k] !== undefined).length,
67
+ invalid: rows.filter((row) => row.shown && row.view.invalid).length,
68
+ overridden: views.filter((view) => view.overridden).length,
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Every settings tab ready to draw: { tab, sections: sectionView[], staged, invalid }.
74
+ */
75
+ function pageView(state, draft, secrets) {
76
+ return TABS.map((tab) => {
77
+ const sections = tab.sections.map((section) => sectionView(section, state, draft, secrets))
78
+ return {
79
+ tab,
80
+ sections,
81
+ staged: sections.reduce((sum, s) => sum + s.staged, 0),
82
+ invalid: sections.reduce((sum, s) => sum + s.invalid, 0),
83
+ }
84
+ })
85
+ }
86
+
87
+ /**
88
+ * The staged edits a save may write: all of them, except an edit the field would refuse on a row
89
+ * that is closed right now. Such a draft cannot be seen, so it cannot be corrected; dropping it
90
+ * keeps one forgotten entry from blocking every later save.
91
+ * @param {object} draft the staged edits
92
+ * @param {object[]} tabViews pageView()'s answer for the same draft
93
+ */
94
+ function savable(draft, tabViews) {
95
+ const out = Object.assign({}, draft)
96
+ for (const tabView of tabViews) {
97
+ for (const section of tabView.sections) {
98
+ for (const row of section.rows) if (!row.shown && row.view.invalid) delete out[row.view.k]
99
+ }
100
+ }
101
+ return out
102
+ }
103
+
104
+ module.exports = { splitOption, isMet, sectionView, pageView, savable }
@@ -0,0 +1,57 @@
1
+ 'use strict'
2
+
3
+ // The status block as text: turns the answer of GET feiyu-memgate/status into [label, text] rows.
4
+ // Pure; it takes the translate function t as an argument and never touches React or the DOM.
5
+
6
+ /** The words for a state name ('running', 'no-model'); a name the dictionary does not know is shown as it is. */
7
+ function stateText(t, state) {
8
+ const key = 'state.' + state
9
+ const text = t(key)
10
+ return text && text !== key ? text : String(state)
11
+ }
12
+
13
+ /** The status block as [label, text] rows. */
14
+ function statusRows(data, t) {
15
+ const rows = []
16
+ const g = data.gateway || {}
17
+ const managed = g.mode !== 'external'
18
+ rows.push([t('gateway'), (managed ? t('managed') : t('external')) + ' · ' + stateText(t, g.state) + (!managed && g.url ? ' · ' + g.url : '')])
19
+ if (managed) {
20
+ const p = data.python
21
+ rows.push([t('python'), !p ? t('pythonUnknown') : p.found ? p.version + ' (' + p.source + ') · ' + p.executable : t('pythonNone')])
22
+ const r = data.retrieval || {}
23
+ rows.push([t('retrieval'), r.setting + (r.active ? ' → ' + r.active + (r.hybrid && r.hybrid.active ? ' + ' + t('hybridWord') : '') : '')])
24
+ if (data.store) {
25
+ const count = data.store.count === null || data.store.count === undefined ? t('countUnknown') : t('memories', { count: data.store.count })
26
+ rows.push([t('store'), data.store.type + ' · ' + data.store.file + (data.store.keywordFile ? ' + ' + data.store.keywordFile : '') + ' · ' + count])
27
+ }
28
+ } else {
29
+ rows.push([t('retrieval'), t('retrievalExternal')])
30
+ }
31
+ const e = data.embed
32
+ if (!e) rows.push([t('embed'), t('notInstalled')])
33
+ else {
34
+ const parts = [stateText(t, e.state)]
35
+ if (e.error) parts.push(e.error)
36
+ if (e.model) parts.push(e.model)
37
+ if (e.dimensions) parts.push(e.dimensions + 'd')
38
+ if (e.parity === 'approximate') parts.push(t('approximate'))
39
+ rows.push([t('embed'), parts.join(' · ')])
40
+ }
41
+ const m = data.migration
42
+ if (m) {
43
+ const state = m.state === 'running' ? 'running-copy' : m.state
44
+ const refused = m.refused > 0 ? ' · ' + t('refusedCount', { count: m.refused }) : ''
45
+ rows.push([t('migration'), stateText(t, state) + ' · ' + t('progress', { copied: m.copied || 0, total: m.total || 0 }) + refused])
46
+ }
47
+ const r = data.relevance
48
+ if (r && r.enabled) {
49
+ const kinds = Object.keys(r.skipped || {})
50
+ const skipped = kinds.reduce((sum, kind) => sum + (r.skipped[kind] || 0), 0)
51
+ rows.push([t('relevance'), t('relevanceRow', { calls: r.calls || 0, kept: r.kept || 0, rejected: r.rejected || 0 })
52
+ + (skipped > 0 ? ' · ' + t('relevanceSkipped', { count: skipped, kinds: kinds.map((kind) => kind + ' ' + r.skipped[kind]).join(', ') }) : '')])
53
+ }
54
+ return rows
55
+ }
56
+
57
+ module.exports = { stateText, statusRows }