@qvac/core 1.0.0-rc.3 → 1.0.0-rc.6

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 (135) hide show
  1. package/CHANGELOG.md +147 -36
  2. package/README.md +55 -4
  3. package/dist-lib/index.d.ts +2 -1
  4. package/dist-lib/lib/api/agents.d.ts +2 -1
  5. package/dist-lib/lib/api/agents.js +5 -1
  6. package/dist-lib/lib/api/app-config.d.ts +3 -0
  7. package/dist-lib/lib/api/app-config.js +20 -0
  8. package/dist-lib/lib/api/approval-rules.d.ts +1 -1
  9. package/dist-lib/lib/api/approval-rules.js +5 -1
  10. package/dist-lib/lib/api/config.d.ts +6 -2
  11. package/dist-lib/lib/api/config.js +9 -5
  12. package/dist-lib/lib/api/device-routes.d.ts +1 -1
  13. package/dist-lib/lib/api/device-routes.js +3 -1
  14. package/dist-lib/lib/api/index.d.ts +12 -2
  15. package/dist-lib/lib/api/index.js +8 -2
  16. package/dist-lib/lib/api/projects.js +3 -4
  17. package/dist-lib/lib/api/rag.js +5 -5
  18. package/dist-lib/lib/api/served.d.ts +2 -2
  19. package/dist-lib/lib/api/served.js +24 -1
  20. package/dist-lib/lib/assistant/harness.d.ts +3 -0
  21. package/dist-lib/lib/assistant/history.js +14 -2
  22. package/dist-lib/lib/assistant/message.d.ts +1 -0
  23. package/dist-lib/lib/assistant/model-round.d.ts +3 -0
  24. package/dist-lib/lib/assistant/model-round.js +18 -4
  25. package/dist-lib/lib/assistant/round-host.d.ts +2 -0
  26. package/dist-lib/lib/assistant/round-host.js +8 -0
  27. package/dist-lib/lib/assistant-tree.d.ts +2 -0
  28. package/dist-lib/lib/assistant-tree.js +4 -2
  29. package/dist-lib/lib/assistant.d.ts +12 -1
  30. package/dist-lib/lib/assistant.js +131 -15
  31. package/dist-lib/lib/client.js +4 -1
  32. package/dist-lib/lib/core/agent-copies.js +9 -2
  33. package/dist-lib/lib/core/agent-hosting.js +9 -4
  34. package/dist-lib/lib/core/agent.js +3 -1
  35. package/dist-lib/lib/core/approval-rules.d.ts +5 -1
  36. package/dist-lib/lib/core/approval-rules.js +16 -1
  37. package/dist-lib/lib/core/chat-copy.d.ts +1 -0
  38. package/dist-lib/lib/core/chat-copy.js +13 -2
  39. package/dist-lib/lib/core/chat.d.ts +0 -1
  40. package/dist-lib/lib/core/chat.js +0 -3
  41. package/dist-lib/lib/core/chunk.js +4 -3
  42. package/dist-lib/lib/core/collections.d.ts +7 -7
  43. package/dist-lib/lib/core/collections.js +7 -7
  44. package/dist-lib/lib/core/config-value.d.ts +1 -0
  45. package/dist-lib/lib/core/config-value.js +1 -0
  46. package/dist-lib/lib/core/contract/project-device-keys.d.ts +4 -2
  47. package/dist-lib/lib/core/contract/project-device-keys.js +12 -12
  48. package/dist-lib/lib/core/contract/project-host-keys.d.ts +5 -3
  49. package/dist-lib/lib/core/contract/project-host-keys.js +22 -11
  50. package/dist-lib/lib/core/contract/projects.d.ts +4 -2
  51. package/dist-lib/lib/core/contract/projects.js +29 -17
  52. package/dist-lib/lib/core/contract/workspace.js +2 -2
  53. package/dist-lib/lib/core/deleted-agent-runs.d.ts +8 -0
  54. package/dist-lib/lib/core/deleted-agent-runs.js +57 -0
  55. package/dist-lib/lib/core/files/index.d.ts +1 -1
  56. package/dist-lib/lib/core/files/index.js +4 -2
  57. package/dist-lib/lib/core/helpers/index.d.ts +1 -1
  58. package/dist-lib/lib/core/helpers/index.js +2 -2
  59. package/dist-lib/lib/core/local/index.d.ts +6 -0
  60. package/dist-lib/lib/core/local/index.js +14 -0
  61. package/dist-lib/lib/core/mesh.d.ts +2 -1
  62. package/dist-lib/lib/core/mesh.js +7 -5
  63. package/dist-lib/lib/core/project-keys.d.ts +5 -2
  64. package/dist-lib/lib/core/project-keys.js +15 -6
  65. package/dist-lib/lib/core/skill-secrets.d.ts +3 -2
  66. package/dist-lib/lib/core/skill-secrets.js +4 -1
  67. package/dist-lib/lib/core/sync/index.js +18 -6
  68. package/dist-lib/lib/core/vault-managed-skills.d.ts +18 -0
  69. package/dist-lib/lib/core/vault-managed-skills.js +105 -0
  70. package/dist-lib/lib/core.d.ts +10 -1
  71. package/dist-lib/lib/core.js +165 -31
  72. package/dist-lib/lib/errors.d.ts +8 -0
  73. package/dist-lib/lib/errors.js +8 -0
  74. package/dist-lib/lib/kv-cache-ledger.d.ts +22 -0
  75. package/dist-lib/lib/kv-cache-ledger.js +72 -0
  76. package/dist-lib/lib/kv-cache-retention.d.ts +1 -0
  77. package/dist-lib/lib/kv-cache-retention.js +5 -2
  78. package/dist-lib/lib/mesh-scoped-engine.js +1 -0
  79. package/dist-lib/lib/model-memory-cap.d.ts +3 -0
  80. package/dist-lib/lib/model-memory-cap.js +15 -6
  81. package/dist-lib/lib/run-replay.d.ts +3 -2
  82. package/dist-lib/lib/run-replay.js +16 -5
  83. package/dist-lib/lib/run-transcript.js +1 -1
  84. package/dist-lib/schema/config.d.ts +1 -1
  85. package/dist-lib/schema/config.js +1 -1
  86. package/dist-lib/schema/engine.js +87 -2
  87. package/dist-lib/schema/qvac.js +66 -3
  88. package/dist-lib/spec/bind.js +15 -0
  89. package/dist-lib/spec/calls.js +5 -0
  90. package/dist-lib/spec/capabilities.d.ts +10 -0
  91. package/dist-lib/spec/config/hyperconf/index.js +1 -1
  92. package/dist-lib/spec/hrpc/hrpc.json +65 -0
  93. package/dist-lib/spec/hrpc/index.js +63 -3
  94. package/dist-lib/spec/hrpc/messages.js +1302 -993
  95. package/dist-lib/spec/hyperschema/index.js +1302 -993
  96. package/dist-lib/spec/hyperschema/schema.json +227 -0
  97. package/dist-lib/spec/hyperschema/types.d.ts +45 -0
  98. package/dist-lib/spec/mesh/hyperdb/db.json +110 -0
  99. package/dist-lib/spec/mesh/hyperdb/index.js +498 -2
  100. package/dist-lib/spec/mesh/hyperdb/messages.js +1385 -892
  101. package/dist-lib/spec/mesh/hyperdispatch/messages.js +561 -301
  102. package/dist-lib/spec/mesh/hyperschema/index.js +561 -301
  103. package/dist-lib/spec/mesh/hyperschema/schema.json +343 -178
  104. package/dist-lib/spec/mesh/hyperschema/types.d.ts +40 -1
  105. package/package.json +34 -18
  106. package/tui/README.md +190 -0
  107. package/tui/app.mjs +8247 -0
  108. package/tui/boot.mjs +159 -0
  109. package/tui/index.mjs +89 -0
  110. package/tui/lib/boot-timing.mjs +41 -0
  111. package/tui/lib/busy-words.mjs +116 -0
  112. package/tui/lib/connect-sheet.mjs +350 -0
  113. package/tui/lib/device-target.mjs +64 -0
  114. package/tui/lib/export.mjs +194 -0
  115. package/tui/lib/folders-command.mjs +84 -0
  116. package/tui/lib/fork-command.mjs +43 -0
  117. package/tui/lib/knowledge-command.mjs +190 -0
  118. package/tui/lib/knowledge-import.mjs +153 -0
  119. package/tui/lib/local-path.mjs +21 -0
  120. package/tui/lib/move-command.mjs +17 -0
  121. package/tui/lib/render.mjs +225 -0
  122. package/tui/lib/save-file.mjs +88 -0
  123. package/tui/lib/select.mjs +81 -0
  124. package/tui/lib/selection.mjs +18 -0
  125. package/tui/lib/setup.mjs +135 -0
  126. package/tui/lib/sidebar.mjs +63 -0
  127. package/tui/lib/skill-connect.mjs +145 -0
  128. package/tui/lib/splash-art.mjs +107 -0
  129. package/tui/lib/splash.mjs +18 -0
  130. package/tui/lib/upload-frames.mjs +9 -0
  131. package/tui/lib/usage.mjs +59 -0
  132. package/tui/lib/wrap.mjs +143 -0
  133. package/tui/main.mjs +279 -0
  134. package/tui/plugins.mjs +158 -0
  135. package/worker/assistant-sidecar.mjs +1 -0
@@ -0,0 +1,88 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+
4
+ export async function saveUniqueFile(bytes, target) {
5
+ const saved = await saveUnique(target, (handle) => write(handle, bytes))
6
+ return saved?.file ?? null
7
+ }
8
+
9
+ export function saveUniqueStream(source, target) {
10
+ return saveUnique(target, async (handle) => {
11
+ let bytesWritten = 0
12
+ for await (const data of source) {
13
+ bytesWritten += await write(handle, data)
14
+ }
15
+
16
+ return bytesWritten
17
+ })
18
+ }
19
+
20
+ async function saveUnique(target, writeFile) {
21
+ const tempDir = await fs.promises.mkdtemp(path.join(target.dir, '.qvac-download-'))
22
+ const tempFile = path.join(tempDir, 'download')
23
+ let handle = await fs.promises.open(tempFile, 'w')
24
+ let file = null
25
+
26
+ try {
27
+ file = await claimUniqueFile(target, tempFile)
28
+ if (!file) {
29
+ return null
30
+ }
31
+
32
+ const bytesWritten = await writeFile(handle)
33
+ await handle.close()
34
+ handle = null
35
+
36
+ return { file, bytesWritten }
37
+ } catch (err) {
38
+ await handle.close().catch(noop)
39
+ handle = null
40
+ if (file) {
41
+ await fs.promises.unlink(file).catch(noop)
42
+ }
43
+
44
+ throw err
45
+ } finally {
46
+ // Cleanup must not replace the download error or remove the reserved destination.
47
+ if (handle) {
48
+ await handle.close().catch(noop)
49
+ }
50
+
51
+ await fs.promises.rm(tempDir, { recursive: true, force: true }).catch(noop)
52
+ }
53
+ }
54
+
55
+ async function claimUniqueFile({ dir, fileName, extension }, source) {
56
+ const sanitized = path.basename(fileName).replace(/[^a-zA-Z0-9_.-]/g, '_')
57
+ const safe = !sanitized || sanitized === '.' || sanitized === '..' ? 'download' : sanitized
58
+ const dot = safe.lastIndexOf('.')
59
+ const base = (dot > 0 ? safe.slice(0, dot) : safe) || 'download'
60
+ const ext = dot > 0 ? safe.slice(dot) : (extension ?? '')
61
+
62
+ for (let n = 0; n < 100; n++) {
63
+ const file = path.join(dir, `${base}${n ? `-${n + 1}` : ''}${ext}`)
64
+ try {
65
+ // bare-fs does not preserve O_EXCL for concurrent opens; link is the atomic reservation.
66
+ await fs.promises.link(source, file)
67
+ return file
68
+ } catch (err) {
69
+ if (err.code !== 'EEXIST') {
70
+ throw err
71
+ }
72
+ }
73
+ }
74
+
75
+ return null
76
+ }
77
+
78
+ async function write(handle, data) {
79
+ let offset = 0
80
+ while (offset < data.length) {
81
+ const result = await handle.write(offset ? data.subarray(offset) : data)
82
+ offset += result.bytesWritten
83
+ }
84
+
85
+ return data.length
86
+ }
87
+
88
+ function noop() {}
@@ -0,0 +1,81 @@
1
+ import { cells } from './wrap.mjs'
2
+
3
+ const REVERSE = '\x1b[7m'
4
+ const REVERSE_OFF = '\x1b[27m'
5
+ // anything that would drop reverse video mid-span, the input's own cursor cell included
6
+ const RESETS = new Set(['\x1b[0m', '\x1b[m', REVERSE_OFF])
7
+
8
+ function ordered(anchor, focus) {
9
+ const [from, to] =
10
+ anchor.row < focus.row || (anchor.row === focus.row && anchor.col <= focus.col)
11
+ ? [anchor, focus]
12
+ : [focus, anchor]
13
+ return { from, to }
14
+ }
15
+
16
+ function span(row, from, to) {
17
+ if (row < from.row || row > to.row) return null
18
+ return {
19
+ start: row === from.row ? from.col : 0,
20
+ end: row === to.row ? to.col + 1 : Infinity
21
+ }
22
+ }
23
+
24
+ function walk(line, start, end) {
25
+ let col = 0
26
+ let text = ''
27
+ let painted = ''
28
+ let on = false
29
+ for (const cell of cells(line)) {
30
+ if (cell.esc) {
31
+ painted += cell.esc
32
+ if (on && RESETS.has(cell.esc)) {
33
+ painted += REVERSE
34
+ }
35
+
36
+ continue
37
+ }
38
+
39
+ const inside = col >= start && col < end
40
+ if (inside && !on) {
41
+ painted += REVERSE
42
+ }
43
+
44
+ if (!inside && on) {
45
+ painted += REVERSE_OFF
46
+ }
47
+
48
+ on = inside
49
+ if (inside) {
50
+ text += cell.ch
51
+ }
52
+
53
+ painted += cell.ch
54
+ col += cell.w
55
+ }
56
+
57
+ if (on) {
58
+ painted += REVERSE_OFF
59
+ }
60
+
61
+ return { text: text.replace(/ +$/, ''), painted }
62
+ }
63
+
64
+ export function selectionText(lines, anchor, focus) {
65
+ const { from, to } = ordered(anchor, focus)
66
+ const rows = []
67
+ for (let row = from.row; row <= Math.min(to.row, lines.length - 1); row++) {
68
+ const at = span(row, from, to)
69
+ rows.push(walk(lines[row], at.start, at.end).text)
70
+ }
71
+
72
+ return rows.join('\n').replace(/^\n+|\n+$/g, '')
73
+ }
74
+
75
+ export function paintSelection(lines, anchor, focus) {
76
+ const { from, to } = ordered(anchor, focus)
77
+ return lines.map((line, row) => {
78
+ const at = span(row, from, to)
79
+ return at ? walk(line, at.start, at.end).painted : line
80
+ })
81
+ }
@@ -0,0 +1,18 @@
1
+ // setConfig replaces the whole writable record, so the untouched fields ride along from the read
2
+ export async function rememberSelection(engine, { agentId, chatId }) {
3
+ const current = await engine.getConfig({})
4
+ if (current.activeAgentId === agentId && current.activeChatId === chatId) {
5
+ return current
6
+ }
7
+
8
+ const { thinkingEnabled, ctxSize, onboardingCompleted, delegation } = current
9
+
10
+ return engine.setConfig({
11
+ activeAgentId: agentId,
12
+ activeChatId: chatId,
13
+ thinkingEnabled,
14
+ ctxSize,
15
+ onboardingCompleted,
16
+ delegation
17
+ })
18
+ }
@@ -0,0 +1,135 @@
1
+ // routes come from the shared integrations registry so the TUI and desktop agree on setup
2
+ import { deriveSetupRoutes } from '../../dist-lib/lib/integrations/index.js'
3
+
4
+ const STATUS_LABELS = {
5
+ ready: 'ready',
6
+ 'needs-setup': 'needs setup',
7
+ disconnected: 'reconnect',
8
+ outdated: 'update available',
9
+ failed: 'failed',
10
+ disabled: 'disabled',
11
+ unsupported: 'unsupported here',
12
+ 'incompatible-model': 'needs a bigger model'
13
+ }
14
+
15
+ export function statusLabel(status) {
16
+ return STATUS_LABELS[status] ?? status ?? 'unknown'
17
+ }
18
+
19
+ export function isReady(skill) {
20
+ return skill?.status === 'ready'
21
+ }
22
+
23
+ export function connectSlug(credentialKey) {
24
+ return credentialKey
25
+ .replace(/_access_token$/, '')
26
+ .replace(/_mcp$/, '')
27
+ .replaceAll('_', '-')
28
+ }
29
+
30
+ // every route opens the skill's sheet; one that stores a value is also how it is changed later
31
+ export function setupActions(skill) {
32
+ return skillRoutes(skill).map((route) => routeAction(route, skill))
33
+ }
34
+
35
+ export function skillRoutes(skill) {
36
+ return [...(deriveSetupRoutes(skillEntry(skill)).routes ?? [])]
37
+ }
38
+
39
+ // prefers a route the sheet can finish over one that only prints instructions
40
+ export function setupPlan(skill) {
41
+ const actions = setupActions(skill)
42
+ const open = actions.filter((action) => !action.satisfied)
43
+ const primary = open.find((action) => action.configurable) ?? open[0] ?? null
44
+ const others = actions.filter((action) => action !== primary)
45
+
46
+ return { primary, others }
47
+ }
48
+
49
+ export function setupAction(skill) {
50
+ return setupPlan(skill).primary
51
+ }
52
+
53
+ export function configureActions(skill) {
54
+ const { primary, others } = setupPlan(skill)
55
+ return [primary, ...others].filter((action) => action?.configurable)
56
+ }
57
+
58
+ function routeAction(route, skill) {
59
+ return {
60
+ kind: route.kind,
61
+ label: route.label,
62
+ description: route.description ?? null,
63
+ helpUrl: route.helpUrl ?? null,
64
+ satisfied: route.satisfied === true,
65
+ steps: route.kind === 'install' ? installSteps(skill) : [...(route.steps ?? [])],
66
+ configurable: Boolean(route.credentialKey),
67
+ command: `/skill ${skill.name}`
68
+ }
69
+ }
70
+
71
+ function installSteps(skill) {
72
+ return (skill.install ?? []).map((s) => (s.command ? `${s.label} → ${s.command}` : s.label))
73
+ }
74
+
75
+ // `a|b` credential slots list interchangeable keys, each its own candidate route
76
+ function skillEntry(skill) {
77
+ const credentials = declaredCredentials(skill)
78
+ return {
79
+ metadata: {
80
+ name: skill.name,
81
+ description: skill.description,
82
+ setup: skill.setup,
83
+ transports: skill.transports,
84
+ requires: { credentials },
85
+ install: skill.install
86
+ },
87
+ content: '',
88
+ available: isReady(skill),
89
+ state: skill.status
90
+ }
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,63 @@
1
+ // the chat sidebar's row model; only `chat` rows are selectable
2
+
3
+ export const SIDEBAR_COLS = 26
4
+
5
+ export function sidebarRows(chats, groups, activeId) {
6
+ const live = [...(chats ?? [])].reverse().filter((chat) => !chat.deletedAt)
7
+ const rows = []
8
+ for (const group of groups ?? []) {
9
+ const held = live.filter((chat) => chat.groupId === group.id)
10
+ rows.push({ kind: 'group', label: group.name })
11
+ if (!held.length) {
12
+ rows.push({ kind: 'empty', label: '(empty)' })
13
+ }
14
+
15
+ for (const chat of held) {
16
+ rows.push(chatRow(chat, activeId))
17
+ }
18
+ }
19
+
20
+ const loose = live.filter((chat) => !chat.groupId)
21
+ if (loose.length && rows.length) {
22
+ rows.push({ kind: 'group', label: '(ungrouped)' })
23
+ }
24
+
25
+ for (const chat of loose) {
26
+ rows.push(chatRow(chat, activeId))
27
+ }
28
+
29
+ return rows
30
+ }
31
+
32
+ export function moveRows(groups, groupId) {
33
+ const rows = (groups ?? [])
34
+ .filter((group) => group.id !== groupId)
35
+ .map((group) => ({ kind: 'target', label: group.name, groupId: group.id }))
36
+ if (groupId) {
37
+ rows.unshift({ kind: 'target', label: '(no group)', groupId: null })
38
+ }
39
+
40
+ rows.push({ kind: 'new-group', label: 'New group…' })
41
+
42
+ return rows
43
+ }
44
+
45
+ export function nextSelectable(rows, from, delta) {
46
+ for (let i = from + delta; i >= 0 && i < rows.length; i += delta) {
47
+ if (selectable(rows[i])) return i
48
+ }
49
+
50
+ return selectable(rows[from]) ? from : firstSelectable(rows)
51
+ }
52
+
53
+ export function firstSelectable(rows) {
54
+ return rows.findIndex(selectable)
55
+ }
56
+
57
+ export function selectable(row) {
58
+ return row?.kind === 'chat' || row?.kind === 'target' || row?.kind === 'new-group'
59
+ }
60
+
61
+ function chatRow(chat, activeId) {
62
+ return { kind: 'chat', label: chat.title, chatId: chat.id, active: chat.id === activeId }
63
+ }
@@ -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/skill-state'
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
+ }