@qvac/core 0.11.0 → 0.11.2

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 (104) hide show
  1. package/CHANGELOG.md +148 -1
  2. package/README.md +19 -16
  3. package/dist-lib/index.d.ts +1 -0
  4. package/dist-lib/index.js +1 -0
  5. package/dist-lib/lib/api/chunk-delta.d.ts +6 -2
  6. package/dist-lib/lib/api/chunk-delta.js +69 -7
  7. package/dist-lib/lib/api/chunks.js +10 -4
  8. package/dist-lib/lib/api/config.d.ts +4 -1
  9. package/dist-lib/lib/api/config.js +23 -4
  10. package/dist-lib/lib/api/devices.js +3 -1
  11. package/dist-lib/lib/api/rag.js +11 -7
  12. package/dist-lib/lib/assistant/harness.d.ts +3 -1
  13. package/dist-lib/lib/assistant/harness.js +10 -0
  14. package/dist-lib/lib/assistant/history.d.ts +1 -0
  15. package/dist-lib/lib/assistant/history.js +9 -3
  16. package/dist-lib/lib/assistant/message.js +2 -2
  17. package/dist-lib/lib/assistant-tree.d.ts +2 -0
  18. package/dist-lib/lib/assistant-tree.js +5 -3
  19. package/dist-lib/lib/assistant.d.ts +6 -1
  20. package/dist-lib/lib/assistant.js +77 -24
  21. package/dist-lib/lib/client.js +10 -1
  22. package/dist-lib/lib/compaction.d.ts +2 -1
  23. package/dist-lib/lib/compaction.js +14 -4
  24. package/dist-lib/lib/constants.d.ts +3 -0
  25. package/dist-lib/lib/constants.js +3 -0
  26. package/dist-lib/lib/core/archived-mesh.js +1 -0
  27. package/dist-lib/lib/core/chat-activity.js +12 -15
  28. package/dist-lib/lib/core/chunk.d.ts +14 -3
  29. package/dist-lib/lib/core/chunk.js +112 -22
  30. package/dist-lib/lib/core/collections.d.ts +1 -0
  31. package/dist-lib/lib/core/collections.js +1 -0
  32. package/dist-lib/lib/core/config-value.d.ts +6 -0
  33. package/dist-lib/lib/core/config-value.js +14 -0
  34. package/dist-lib/lib/core/contract/chat.d.ts +1 -0
  35. package/dist-lib/lib/core/contract/chat.js +8 -1
  36. package/dist-lib/lib/core/contract/chunks.js +20 -6
  37. package/dist-lib/lib/core/contract/compute.d.ts +1 -1
  38. package/dist-lib/lib/core/contract/compute.js +2 -1
  39. package/dist-lib/lib/core/contract/devices.js +3 -2
  40. package/dist-lib/lib/core/departures.js +1 -0
  41. package/dist-lib/lib/core/devices.d.ts +2 -1
  42. package/dist-lib/lib/core/devices.js +4 -2
  43. package/dist-lib/lib/core/files/attachments.js +3 -3
  44. package/dist-lib/lib/core/files/index.d.ts +1 -1
  45. package/dist-lib/lib/core/files/index.js +3 -2
  46. package/dist-lib/lib/core/files/processing/index.d.ts +1 -0
  47. package/dist-lib/lib/core/files/processing/index.js +8 -0
  48. package/dist-lib/lib/core/files/processing/settle.d.ts +1 -0
  49. package/dist-lib/lib/core/files/processing/settle.js +20 -13
  50. package/dist-lib/lib/core/files/rag/index.d.ts +1 -1
  51. package/dist-lib/lib/core/files/rag/index.js +1 -1
  52. package/dist-lib/lib/core/files/rag/retrieval/full-text.d.ts +1 -0
  53. package/dist-lib/lib/core/files/rag/retrieval/full-text.js +4 -1
  54. package/dist-lib/lib/core/hosted-agents.d.ts +3 -0
  55. package/dist-lib/lib/core/hosted-agents.js +19 -0
  56. package/dist-lib/lib/core/inference-calls-receiver.js +2 -2
  57. package/dist-lib/lib/core/known-sender.d.ts +3 -0
  58. package/dist-lib/lib/core/known-sender.js +26 -0
  59. package/dist-lib/lib/core/local/index.d.ts +2 -0
  60. package/dist-lib/lib/core/local/index.js +17 -10
  61. package/dist-lib/lib/core/mesh.d.ts +5 -1
  62. package/dist-lib/lib/core/mesh.js +6 -6
  63. package/dist-lib/lib/core/migrations/chat-chunks.d.ts +4 -0
  64. package/dist-lib/lib/core/migrations/chat-chunks.js +43 -0
  65. package/dist-lib/lib/core/notification.js +16 -13
  66. package/dist-lib/lib/core/skill-overlay-receiver.js +2 -2
  67. package/dist-lib/lib/core/skill-secrets.js +2 -2
  68. package/dist-lib/lib/core.d.ts +17 -1
  69. package/dist-lib/lib/core.js +55 -5
  70. package/dist-lib/lib/credential-pusher.d.ts +11 -7
  71. package/dist-lib/lib/credential-pusher.js +40 -8
  72. package/dist-lib/lib/device-tree.d.ts +18 -0
  73. package/dist-lib/lib/device-tree.js +32 -0
  74. package/dist-lib/lib/integrations/setup-routes.js +7 -5
  75. package/dist-lib/lib/kv-cache-retention.d.ts +34 -0
  76. package/dist-lib/lib/kv-cache-retention.js +98 -0
  77. package/dist-lib/schema/content.js +2 -1
  78. package/dist-lib/schema/engine.js +20 -3
  79. package/dist-lib/schema/field-order.js +8 -1
  80. package/dist-lib/schema/local.js +7 -3
  81. package/dist-lib/schema/qvac.js +23 -4
  82. package/dist-lib/spec/hrpc/messages.js +1240 -1194
  83. package/dist-lib/spec/hyperschema/index.js +1240 -1194
  84. package/dist-lib/spec/hyperschema/schema.json +49 -1
  85. package/dist-lib/spec/hyperschema/types.d.ts +12 -1
  86. package/dist-lib/spec/local/hyperdb/messages.js +70 -20
  87. package/dist-lib/spec/local/hyperschema/index.js +36 -11
  88. package/dist-lib/spec/local/hyperschema/schema.json +21 -1
  89. package/dist-lib/spec/local/hyperschema/types.d.ts +5 -1
  90. package/dist-lib/spec/mesh/hyperdb/db.json +17 -1
  91. package/dist-lib/spec/mesh/hyperdb/index.js +83 -2
  92. package/dist-lib/spec/mesh/hyperdb/messages.js +602 -264
  93. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +7 -1
  94. package/dist-lib/spec/mesh/hyperdispatch/index.js +18 -1
  95. package/dist-lib/spec/mesh/hyperdispatch/messages.js +137 -14
  96. package/dist-lib/spec/mesh/hyperschema/index.js +137 -14
  97. package/dist-lib/spec/mesh/hyperschema/schema.json +79 -1
  98. package/dist-lib/spec/mesh/hyperschema/types.d.ts +21 -1
  99. package/package.json +13 -9
  100. package/tui/app.mjs +743 -266
  101. package/tui/boot.mjs +2 -2
  102. package/tui/lib/connect-sheet.mjs +350 -0
  103. package/tui/lib/setup.mjs +59 -25
  104. package/tui/lib/skill-connect.mjs +145 -0
package/tui/boot.mjs CHANGED
@@ -36,8 +36,8 @@ async function startSidecar({ entry, config, logger }) {
36
36
  return {
37
37
  engine,
38
38
  close: () => engine.close(),
39
- skills: async (agentId, modelName, meshId) =>
40
- (await engine.skills({ agentId, modelName, meshId })).skills ?? []
39
+ skills: async (agentId, { modelName, meshId, refresh = false }) =>
40
+ (await engine.skills({ agentId, modelName, meshId, refresh })).skills ?? []
41
41
  }
42
42
  }
43
43
 
@@ -0,0 +1,350 @@
1
+ // the form a skill is set up through: its routes, the fields each asks for, and how it draws
2
+ import { isReady, statusLabel } from './setup.mjs'
3
+
4
+ const MASK_CAP = 24
5
+
6
+ const CONNECTED = {
7
+ oauth: 'connected — fill this in again to change it',
8
+ token: 'connected — fill this in again to change it',
9
+ picker: 'set — pick another folder to change it',
10
+ install: 'installed',
11
+ instructions: 'ready'
12
+ }
13
+
14
+ export function openSheet(skill, { routes, enable = false, field = null }) {
15
+ const sheet = {
16
+ skill,
17
+ routes,
18
+ route: firstRoute(routes, field),
19
+ cursor: Math.max(
20
+ 0,
21
+ routes.findIndex((route) => !route.satisfied && route.credentialKey)
22
+ ),
23
+ focus: 0,
24
+ values: {},
25
+ revealed: false,
26
+ enable,
27
+ phase: 'edit',
28
+ attempt: 0,
29
+ stage: null,
30
+ url: null,
31
+ error: null,
32
+ oauth: null
33
+ }
34
+ if (field) {
35
+ focusField(sheet, field)
36
+ }
37
+
38
+ return sheet
39
+ }
40
+
41
+ // a named field opens the route that holds it; several routes otherwise start on the picker
42
+ function firstRoute(routes, field) {
43
+ const holding = field ? routes.findIndex((route) => hasField(route, field)) : -1
44
+ if (holding >= 0) {
45
+ return holding
46
+ }
47
+
48
+ return routes.length === 1 ? 0 : null
49
+ }
50
+
51
+ export function hasField(route, key) {
52
+ return routeFields(route).some((field) => field.key === key)
53
+ }
54
+
55
+ export function currentRoute(sheet) {
56
+ return sheet.route === null ? null : sheet.routes[sheet.route]
57
+ }
58
+
59
+ export function pickRoute(sheet, index) {
60
+ sheet.route = index
61
+ sheet.focus = 0
62
+ sheet.values = {}
63
+ sheet.error = null
64
+ }
65
+
66
+ export function sheetFields(sheet) {
67
+ const route = currentRoute(sheet)
68
+ return route ? routeFields(route) : []
69
+ }
70
+
71
+ // a picker is one path; a token route without fields still takes its own key
72
+ export function routeFields(route) {
73
+ if (route.kind === 'picker') {
74
+ return [{ key: route.credentialKey, label: 'Folder', placeholder: '~/path/to/folder' }]
75
+ }
76
+
77
+ if (route.kind === 'token' && !route.fields?.length) {
78
+ return [{ key: route.credentialKey, label: route.credentialKey, secret: true }]
79
+ }
80
+
81
+ return route.kind === 'oauth' || route.kind === 'token' ? [...(route.fields ?? [])] : []
82
+ }
83
+
84
+ // every sheet can be left from its own buttons, not only by a key named in the header
85
+ export function sheetButtons(sheet) {
86
+ const route = currentRoute(sheet)
87
+ if (!route) {
88
+ return []
89
+ }
90
+
91
+ if (sheet.phase === 'waiting') {
92
+ return [{ id: 'cancel', label: 'Cancel sign-in' }]
93
+ }
94
+
95
+ return [...actionButtons(sheet, route), { id: 'cancel', label: 'Cancel' }]
96
+ }
97
+
98
+ function actionButtons(sheet, route) {
99
+ const connected = isConnected(sheet)
100
+ const remove = connected && route.credentialKey ? [{ id: 'disconnect', label: 'Disconnect' }] : []
101
+ if (route.kind === 'oauth') {
102
+ return [{ id: 'connect', label: connected ? 'Reconnect' : 'Connect' }, ...remove]
103
+ }
104
+
105
+ if (route.kind === 'token' || route.kind === 'picker') {
106
+ return [{ id: 'save', label: 'Save' }, ...remove]
107
+ }
108
+
109
+ return [{ id: 'check', label: route.kind === 'install' ? 'Check again' : 'Done' }]
110
+ }
111
+
112
+ // with several ways in, the skill being ready says nothing about the one on screen
113
+ export function isConnected(sheet) {
114
+ const route = currentRoute(sheet)
115
+ if (route?.satisfied === true) {
116
+ return true
117
+ }
118
+
119
+ return sheet.routes.length === 1 && isReady(sheet.skill)
120
+ }
121
+
122
+ export function focused(sheet) {
123
+ const fields = sheetFields(sheet)
124
+ if (sheet.focus < fields.length) {
125
+ return { field: fields[sheet.focus] }
126
+ }
127
+
128
+ return { button: sheetButtons(sheet)[sheet.focus - fields.length] ?? null }
129
+ }
130
+
131
+ export function moveFocus(sheet, delta) {
132
+ const count = sheetFields(sheet).length + sheetButtons(sheet).length
133
+ sheet.focus = Math.max(0, Math.min(count - 1, sheet.focus + delta))
134
+ }
135
+
136
+ export function focusField(sheet, key) {
137
+ sheet.focus = Math.max(
138
+ 0,
139
+ sheetFields(sheet).findIndex((entry) => entry.key === key)
140
+ )
141
+ }
142
+
143
+ // a pasted value arrives with the terminal's line breaks and padding, never meant as part of it
144
+ export function typeInto(sheet, text) {
145
+ const { field } = focused(sheet)
146
+ if (!field) {
147
+ return false
148
+ }
149
+
150
+ const value = (sheet.values[field.key] ?? '') + text.replace(/[\r\n]+/g, '')
151
+ sheet.values[field.key] = value.trimStart()
152
+ sheet.error = null
153
+
154
+ return true
155
+ }
156
+
157
+ export function backspace(sheet) {
158
+ const { field } = focused(sheet)
159
+ if (!field) {
160
+ return
161
+ }
162
+
163
+ sheet.values[field.key] = (sheet.values[field.key] ?? '').slice(0, -1)
164
+ }
165
+
166
+ export function enteredValues(sheet) {
167
+ return Object.fromEntries(
168
+ sheetFields(sheet).map((field) => [field.key, (sheet.values[field.key] ?? '').trim()])
169
+ )
170
+ }
171
+
172
+ // `at` is the line the focus sits on, so a long guide scrolls to the field being typed
173
+ export function formatSheet(sheet, fg) {
174
+ const { skill } = sheet
175
+ const route = currentRoute(sheet)
176
+ const title = `Set up ${skill.name}`
177
+ if (!route) {
178
+ return { lines: formatRoutePicker(sheet, fg, title), at: sheet.cursor + 2 }
179
+ }
180
+
181
+ const keys =
182
+ sheet.phase === 'waiting'
183
+ ? 'esc cancel · ctrl+y copy link'
184
+ : 'tab/↑↓ move · enter select · ctrl+r show secrets · esc back'
185
+ const lines = [fg.dim.render(`${title} — ${keys}`), '']
186
+ lines.push(fg.white.render(route.description ?? skill.setup?.summary ?? skill.description))
187
+ lines.push(stateLine(sheet, fg))
188
+ if (route.helpUrl) {
189
+ lines.push(fg.dim.render(route.helpUrl))
190
+ }
191
+
192
+ const fieldAt = pushForm(sheet, lines, fg)
193
+ lines.push('')
194
+ const footerAt = lines.length
195
+ lines.push(...footer(sheet, fg))
196
+ const onField = sheet.focus < sheetFields(sheet).length
197
+
198
+ return { lines, at: onField ? fieldAt + sheet.focus : footerAt }
199
+ }
200
+
201
+ // the guide, the fields, then the steps that follow them; returns the first field's line
202
+ function pushForm(sheet, lines, fg) {
203
+ const guide = guideSteps(sheet)
204
+ if (guide.length) {
205
+ lines.push('')
206
+ guide.forEach((step, i) =>
207
+ lines.push(`${fg.cyan.render(`${i + 1}.`)} ${stepText(sheet, step)}`)
208
+ )
209
+ }
210
+
211
+ const fields = sheetFields(sheet)
212
+ const fieldAt = lines.length + 1
213
+ if (fields.length) {
214
+ lines.push('')
215
+ const width = Math.max(...fields.map((field) => field.label.length))
216
+ fields.forEach((field, i) => lines.push(fieldLine(sheet, { field, i, width }, fg)))
217
+ }
218
+
219
+ const after = stepsAfterFields(sheet)
220
+ if (after.length) {
221
+ lines.push('', ...after.map((step) => fg.dim.render(`• ${stepText(sheet, step)}`)))
222
+ }
223
+
224
+ return fieldAt
225
+ }
226
+
227
+ function formatRoutePicker(sheet, fg, title) {
228
+ const lines = [fg.dim.render(`${title} — ↑/↓ move · enter choose · esc back`), '']
229
+ sheet.routes.forEach((route, i) => {
230
+ const point = i === sheet.cursor ? fg.magenta.render('❯ ') : ' '
231
+ const mark = route.satisfied ? fg.green.render('● ') : fg.dim.render('○ ')
232
+ lines.push(`${point}${mark}${fg.white.render(route.label)}`)
233
+ })
234
+
235
+ return lines
236
+ }
237
+
238
+ function stateLine(sheet, fg) {
239
+ if (isConnected(sheet)) {
240
+ return fg.green.render(`● ${CONNECTED[currentRoute(sheet).kind]}`)
241
+ }
242
+
243
+ if (isReady(sheet.skill)) {
244
+ return fg.dim.render(`○ not set — ${sheet.skill.name} already works another way`)
245
+ }
246
+
247
+ return fg.amber.render(`○ ${statusLabel(sheet.skill.status)}`)
248
+ }
249
+
250
+ // above the fields: what to do before filling them, so a guide's "the fields below" reads true
251
+ function guideSteps(sheet) {
252
+ const route = currentRoute(sheet)
253
+ if (route.kind === 'install') {
254
+ return installSteps(sheet.skill, route)
255
+ }
256
+
257
+ if (route.kind === 'oauth') {
258
+ return ownApp(sheet) ? [...(route.configSteps ?? []), ...redirectStep(sheet)] : []
259
+ }
260
+
261
+ return route.kind === 'token' ? [] : [...(route.steps ?? [])]
262
+ }
263
+
264
+ // below the fields, as desktop draws them: a token's guide and an OAuth consent say "above"
265
+ function stepsAfterFields(sheet) {
266
+ const route = currentRoute(sheet)
267
+ if (route.kind === 'token') {
268
+ return [...(route.steps ?? [])]
269
+ }
270
+
271
+ const guided = ownApp(sheet) && route.configSteps?.length
272
+
273
+ return route.kind === 'oauth' && !guided ? [...(route.steps ?? [])] : []
274
+ }
275
+
276
+ // the user's own app is set up in its console; a built-in client needs only the consent
277
+ function ownApp(sheet) {
278
+ const route = currentRoute(sheet)
279
+ return route.kind === 'oauth' && !!route.fields?.length && !sheet.oauth?.builtIn
280
+ }
281
+
282
+ // a pinned loopback port is the one redirect a provider console can be told in advance
283
+ function redirectStep(sheet) {
284
+ const uri = sheet.oauth?.redirectUri
285
+ return uri ? [`Register this redirect URI in your app: ${uri} (ctrl+y copies it)`] : []
286
+ }
287
+
288
+ // a brew step names a formula, not a command, so the command is spelled out to run by hand
289
+ function installSteps(skill, route) {
290
+ const steps = (skill.install ?? []).map((step) => {
291
+ const command = step.command ?? (step.formula ? `brew install ${step.formula}` : null)
292
+ return command ? `${step.label}: ${command}` : step.label
293
+ })
294
+
295
+ return steps.length ? steps : [...(route.steps ?? [])]
296
+ }
297
+
298
+ function fieldLine(sheet, { field, i, width }, fg) {
299
+ const active = sheet.focus === i && sheet.phase === 'edit'
300
+ const point = active ? fg.magenta.render('❯ ') : ' '
301
+ const value = sheet.values[field.key] ?? ''
302
+ const shown = field.secret && !sheet.revealed ? mask(value) : value
303
+ const cursor = active ? fg.magenta.render('▏') : ''
304
+ const hint = value ? '' : fg.dim.render(fieldHint(sheet, field))
305
+
306
+ return `${point}${field.label.padEnd(width)} ${shown}${cursor}${hint}`
307
+ }
308
+
309
+ // a saved app outranks the built-in one when connecting, so it outranks it here too
310
+ function fieldHint(sheet, field) {
311
+ if (field.secret && sheet.oauth?.savedSecret) {
312
+ return 'blank keeps the saved one'
313
+ }
314
+
315
+ if (sheet.oauth?.builtIn && !sheet.oauth.savedClientId && !sheet.oauth.savedSecret) {
316
+ return 'optional — blank uses the built-in client'
317
+ }
318
+
319
+ return field.placeholder ?? ''
320
+ }
321
+
322
+ function mask(value) {
323
+ return value ? `${'•'.repeat(Math.min(value.length, MASK_CAP))} ${value.length} chars` : ''
324
+ }
325
+
326
+ function footer(sheet, fg) {
327
+ const fields = sheetFields(sheet).length
328
+ const buttons = sheetButtons(sheet).map((button, i) => {
329
+ const label = `[ ${button.label} ]`
330
+ return sheet.focus === fields + i ? fg.magenta.render(label) : fg.white.render(label)
331
+ })
332
+ if (sheet.phase === 'waiting') {
333
+ const url = sheet.url ? [fg.dim.render(sheet.url)] : []
334
+ return [fg.amber.render(sheet.stage ?? 'waiting for the browser…'), ...url, '', buttons[0]]
335
+ }
336
+
337
+ const lines = [buttons.join(' ')]
338
+ if (sheet.error) {
339
+ lines.push('', fg.err.render(sheet.error))
340
+ }
341
+
342
+ return lines
343
+ }
344
+
345
+ // a link is shown with its address, and `{skill}` is the placeholder desktop fills in too
346
+ function stepText(sheet, step) {
347
+ return step
348
+ .replaceAll('{skill}', sheet.skill.name)
349
+ .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '$1 ($2)')
350
+ }
package/tui/lib/setup.mjs CHANGED
@@ -27,18 +27,20 @@ export function connectSlug(credentialKey) {
27
27
  .replaceAll('_', '-')
28
28
  }
29
29
 
30
- // the routes that carry a credential key are also how a skill is reconfigured later
30
+ // every route opens the skill's sheet; one that stores a value is also how it is changed later
31
31
  export function setupActions(skill) {
32
- return (deriveSetupRoutes(skillEntry(skill)).routes ?? []).map((route) =>
33
- routeAction(route, skill)
34
- )
32
+ return skillRoutes(skill).map((route) => routeAction(route, skill))
33
+ }
34
+
35
+ export function skillRoutes(skill) {
36
+ return [...(deriveSetupRoutes(skillEntry(skill)).routes ?? [])]
35
37
  }
36
38
 
37
- // prefers a route the TUI can run over one that only prints instructions
39
+ // prefers a route the sheet can finish over one that only prints instructions
38
40
  export function setupPlan(skill) {
39
41
  const actions = setupActions(skill)
40
42
  const open = actions.filter((action) => !action.satisfied)
41
- const primary = open.find((action) => action.command || action.prefill) ?? open[0] ?? null
43
+ const primary = open.find((action) => action.configurable) ?? open[0] ?? null
42
44
  const others = actions.filter((action) => action !== primary)
43
45
 
44
46
  return { primary, others }
@@ -48,32 +50,22 @@ export function setupAction(skill) {
48
50
  return setupPlan(skill).primary
49
51
  }
50
52
 
51
- // a connected skill keeps these: a route with a credential key is configuration, not a one-off
52
53
  export function configureActions(skill) {
53
54
  const { primary, others } = setupPlan(skill)
54
- return [primary, ...others].filter((action) => action?.command || action?.prefill)
55
+ return [primary, ...others].filter((action) => action?.configurable)
55
56
  }
56
57
 
57
58
  function routeAction(route, skill) {
58
- const action = {
59
- kind: 'steps',
59
+ return {
60
+ kind: route.kind,
60
61
  label: route.label,
61
62
  description: route.description ?? null,
62
63
  helpUrl: route.helpUrl ?? null,
63
64
  satisfied: route.satisfied === true,
64
65
  steps: route.kind === 'install' ? installSteps(skill) : [...(route.steps ?? [])],
65
- command: undefined,
66
- prefill: undefined
67
- }
68
- if (!route.credentialKey) {
69
- return action
70
- }
71
-
72
- if (route.kind === 'oauth') {
73
- return { ...action, kind: 'connect', command: `/connect ${connectSlug(route.credentialKey)}` }
66
+ configurable: Boolean(route.credentialKey),
67
+ command: `/skill ${skill.name}`
74
68
  }
75
-
76
- return { ...action, kind: 'cred', prefill: `/cred ${route.credentialKey} ` }
77
69
  }
78
70
 
79
71
  function installSteps(skill) {
@@ -82,16 +74,14 @@ function installSteps(skill) {
82
74
 
83
75
  // `a|b` credential slots list interchangeable keys, each its own candidate route
84
76
  function skillEntry(skill) {
85
- const credentials = (skill.requires?.credentials ?? skill.credentials ?? []).flatMap((slot) =>
86
- slot.split('|')
87
- )
77
+ const credentials = declaredCredentials(skill)
88
78
  return {
89
79
  metadata: {
90
80
  name: skill.name,
91
81
  description: skill.description,
92
82
  setup: skill.setup,
93
83
  transports: skill.transports,
94
- requires: { ...skill.requires, credentials },
84
+ requires: { credentials },
95
85
  install: skill.install
96
86
  },
97
87
  content: '',
@@ -99,3 +89,47 @@ function skillEntry(skill) {
99
89
  state: skill.status
100
90
  }
101
91
  }
92
+
93
+ // both authoring forms count, as the harness unions them; on the wire `requires` is `requirements`
94
+ export function declaredCredentials(skill) {
95
+ const slots = [...(skill.credentials ?? []), ...(skill.requirements?.credentials ?? [])]
96
+ const keys = slots.flatMap((slot) => slot.split('|')).map((key) => key.trim())
97
+
98
+ return [...new Set(keys.filter(Boolean))]
99
+ }
100
+
101
+ // a skill is named by its name, or by the slug its credential once gave /connect
102
+ export function findSkill(skills, name) {
103
+ return (
104
+ skills.find((skill) => skill.name === name) ??
105
+ skills.find((skill) =>
106
+ skillRoutes(skill).some(
107
+ (route) => route.credentialKey && connectSlug(route.credentialKey) === name
108
+ )
109
+ ) ??
110
+ null
111
+ )
112
+ }
113
+
114
+ export function closestSkill(skills, name) {
115
+ const near = skills
116
+ .map((skill) => ({ name: skill.name, distance: editDistance(skill.name, name) }))
117
+ .filter((entry) => entry.distance <= 2 || entry.name.startsWith(name))
118
+ .sort((a, b) => a.distance - b.distance)
119
+
120
+ return near[0]?.name ?? null
121
+ }
122
+
123
+ function editDistance(a, b) {
124
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i)
125
+ for (let i = 1; i <= a.length; i++) {
126
+ const next = [i]
127
+ for (let j = 1; j <= b.length; j++) {
128
+ next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1))
129
+ }
130
+
131
+ row = next
132
+ }
133
+
134
+ return row[b.length]
135
+ }
@@ -0,0 +1,145 @@
1
+ // where a skill's setup values are stored, and the OAuth connect that fills its token
2
+ import process from 'process'
3
+ import { isDeviceSharedCredentialKey } from '@qvac/harness/lib/tools/skills/scope-key.ts'
4
+ import { settingConfigKey } from '../../dist-lib/lib/credential-pusher.js'
5
+ import { scopedKey } from '../../dist-lib/lib/oauth/keys.js'
6
+
7
+ export function credentialKey(agentId, key) {
8
+ return scopedKey(isDeviceSharedCredentialKey(key) ? undefined : agentId, key)
9
+ }
10
+
11
+ // the client app lives in the skill's own state row, beside the refresh token it minted
12
+ export async function savedClient(engine, { agentId, stateKey }) {
13
+ const state = await readState(engine, scopedKey(agentId, stateKey))
14
+
15
+ return { clientId: state.clientId ?? '', clientSecret: state.clientSecret ?? '' }
16
+ }
17
+
18
+ export function envClient(provider) {
19
+ const env = provider.toUpperCase().replaceAll('-', '_')
20
+
21
+ return {
22
+ clientId: process.env[`${env}_OAUTH_CLIENT_ID`] ?? '',
23
+ clientSecret: process.env[`${env}_OAUTH_CLIENT_SECRET`] ?? ''
24
+ }
25
+ }
26
+
27
+ // one app's id and secret, typed or saved, else the built-in pair: a mix is invalid_client
28
+ export function resolveClient(spec, { entered, saved, env }) {
29
+ if (spec.registrationEndpoint) {
30
+ return { clientId: '' }
31
+ }
32
+
33
+ const needsSecret = spec.tokenAuth !== 'pkce-only'
34
+ const own = !!(entered.clientId || entered.clientSecret || saved.clientId || saved.clientSecret)
35
+ const otherApp = !!entered.clientId && entered.clientId !== saved.clientId
36
+ const clientId = own ? entered.clientId || saved.clientId : env.clientId
37
+ const savedSecret = otherApp ? '' : saved.clientSecret
38
+ const clientSecret = own ? entered.clientSecret || savedSecret : env.clientSecret
39
+ const need = { clientId: !clientId, clientSecret: needsSecret && !clientSecret }
40
+ if (need.clientId || need.clientSecret) {
41
+ return { need }
42
+ }
43
+
44
+ return { clientId, clientSecret: needsSecret ? clientSecret : undefined }
45
+ }
46
+
47
+ // the typed values decide the client app; a missing piece comes back as `need`, not as an error
48
+ export async function connectSkill(engine, { agentId, spec, entered, openUrl, onStage }) {
49
+ const client = resolveClient(spec, {
50
+ entered: { clientId: entered.clientId ?? '', clientSecret: entered.clientSecret ?? '' },
51
+ saved: await savedClient(engine, { agentId, stateKey: spec.stateKey }),
52
+ env: envClient(spec.provider)
53
+ })
54
+ if (client.need) {
55
+ return client
56
+ }
57
+
58
+ await connectOAuth(engine, { agentId, spec, client, openUrl, onStage })
59
+
60
+ return null
61
+ }
62
+
63
+ export async function connectOAuth(engine, { agentId, spec, client, openUrl, onStage }) {
64
+ const { buildProviderConfig, runOAuthFlow } = await import('../../dist-lib/lib/oauth.js')
65
+ const stateKey = scopedKey(agentId, spec.stateKey)
66
+ // the client this run signs in with, whether a prior run registered it or this one does
67
+ let registered = ''
68
+ const tokens = await runOAuthFlow(buildProviderConfig(spec, client), {
69
+ openUrl,
70
+ onStage,
71
+ getClientId: async () => {
72
+ registered = (await readState(engine, stateKey)).clientId || ''
73
+ return registered || undefined
74
+ },
75
+ saveClientId: (id) => {
76
+ registered = id
77
+ }
78
+ })
79
+
80
+ await engine.configSet({ key: scopedKey(agentId, spec.credentialKey), value: tokens.accessToken })
81
+ await engine.configSet({
82
+ key: stateKey,
83
+ value: JSON.stringify({
84
+ refreshToken: tokens.refreshToken,
85
+ expiresAt: tokens.expiresAt,
86
+ clientId: client.clientId || registered,
87
+ clientSecret: client.clientSecret
88
+ })
89
+ })
90
+ }
91
+
92
+ export async function cancelOAuth(spec) {
93
+ const { cancelOAuthFlow } = await import('../../dist-lib/lib/oauth.js')
94
+
95
+ return cancelOAuthFlow({ credentialKey: spec.credentialKey })
96
+ }
97
+
98
+ // an oauth route's fields describe its client app, so they are filed in its state row
99
+ export async function saveFields(engine, { agentId, skillName, route, values }) {
100
+ const entries = Object.entries(values).filter(([, value]) => value !== '')
101
+ if (route.kind === 'oauth') {
102
+ const key = scopedKey(agentId, route.oauth.stateKey)
103
+ const state = await readState(engine, key)
104
+ const typed = Object.fromEntries(entries)
105
+ // a new client id is a new app: the old one's secret and refresh token would pair with it
106
+ const kept = !typed.clientId || typed.clientId === state.clientId ? state : {}
107
+ await engine.configSet({ key, value: JSON.stringify({ ...kept, ...typed }) })
108
+
109
+ return
110
+ }
111
+
112
+ for (const [name, value] of entries) {
113
+ await engine.configSet({ key: fieldStorageKey({ agentId, skillName, route, name }), value })
114
+ }
115
+ }
116
+
117
+ // a disconnected skill keeps its client app, so connecting again needs no retyping
118
+ export async function disconnect(engine, { agentId, route }) {
119
+ await engine.configSet({ key: credentialKey(agentId, route.credentialKey), value: '' })
120
+ if (route.kind !== 'oauth') {
121
+ return
122
+ }
123
+
124
+ const key = scopedKey(agentId, route.oauth.stateKey)
125
+ const { clientId, clientSecret } = await readState(engine, key)
126
+ await engine.configSet({ key, value: clientId ? JSON.stringify({ clientId, clientSecret }) : '' })
127
+ }
128
+
129
+ function fieldStorageKey({ agentId, skillName, route, name }) {
130
+ const field = (route.fields ?? []).find((entry) => entry.key === name)
131
+ if (name === route.credentialKey || field?.secret === true) {
132
+ return credentialKey(agentId, name)
133
+ }
134
+
135
+ return settingConfigKey(undefined, skillName, name)
136
+ }
137
+
138
+ async function readState(engine, key) {
139
+ const { value } = await engine.configGet({ key })
140
+ try {
141
+ return (typeof value === 'string' && value ? JSON.parse(value) : null) ?? {}
142
+ } catch {
143
+ return {}
144
+ }
145
+ }