@tavlo-dsh/dsh-plugin-tapd 0.0.0-stage → 0.5.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.
package/settings.js ADDED
@@ -0,0 +1,338 @@
1
+ import { credentialKey } from '@deepseek-ai/dsh-credentials'
2
+ import { clientRequestSchema } from '@deepseek-ai/dsh-client-connection'
3
+ import { z } from 'zod'
4
+ import { DEFAULTS, authorizationHeader, parseConfig, projectConfig, resolveAuthorization } from './runtime.js'
5
+ import { AutomaticProjectListError, discoverProjectNames, discoverProjects, discoverStatuses, discoveryErrorCode, requiredTapdNickname, tapdNickname } from './metadata.js'
6
+ import { TapdError } from './tapd.js'
7
+
8
+ export const SETTINGS_METHOD = 'tavlo-tapd/settings'
9
+ export const SETTINGS_KEY = credentialKey('tavlo-tapd', 'settings')
10
+ const endpoint = `/api/${SETTINGS_METHOD}`
11
+ const revision = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER - 1)
12
+ const workspaceOption = z.object({ id: z.uuid(), title: z.string(), path: z.string() })
13
+ const authMode = z.enum(['bearer', 'basic'])
14
+ const tapdId = z.string().regex(/^\d{1,32}$/u)
15
+ const visualConfig = z.strictObject({
16
+ enabled: z.boolean(), auth: authMode,
17
+ owner: tapdNickname, projects: z.array(projectConfig).max(20), companyId: tapdId.optional(), seedWorkspaceId: tapdId.optional(),
18
+ intervalSeconds: z.number().int().min(30).max(86400), maxNewPerScope: z.number().int().min(1).max(1000),
19
+ lookbackDays: z.number().int().min(1).max(365).optional(),
20
+ })
21
+ const secretValues = z.union([
22
+ z.strictObject({ token: z.string().min(1).max(4096) }),
23
+ z.strictObject({ apiUser: z.string().min(1).max(512), apiKey: z.string().min(1).max(4096) }),
24
+ ])
25
+ const credentialChange = z.union([
26
+ z.strictObject({ mode: z.literal('use-refs') }),
27
+ z.strictObject({ mode: z.literal('replace'), token: z.string().min(1).max(4096) }),
28
+ z.strictObject({ mode: z.literal('replace'), apiUser: z.string().min(1).max(512), apiKey: z.string().min(1).max(4096) }),
29
+ ])
30
+ const saveInput = z.strictObject({ expectedRevision: revision, config: z.unknown(), credentials: z.unknown().optional() })
31
+ const saveCredentialsInput = z.strictObject({ expectedRevision: revision, auth: authMode, credentials: z.unknown() })
32
+ const discoveryAuth = { auth: authMode, credentials: z.unknown().optional() }
33
+ const projectDiscoveryInput = z.union([
34
+ z.strictObject({ ...discoveryAuth, auth: z.literal('bearer'), auto: z.literal(true) }),
35
+ z.strictObject({
36
+ ...discoveryAuth, companyId: tapdId.optional(), seedWorkspaceId: tapdId.optional(),
37
+ nick: requiredTapdNickname.optional(),
38
+ }),
39
+ ])
40
+ const statusDiscoveryInput = z.strictObject({ ...discoveryAuth, workspaceId: tapdId })
41
+ const projectNamesInput = z.strictObject({
42
+ auth: authMode, workspaceIds: z.array(tapdId).min(1).max(20).refine(ids => new Set(ids).size === ids.length),
43
+ })
44
+ const grant = z.strictObject({
45
+ version: z.literal(1), revision: revision.min(1), config: visualConfig, secret: secretValues.optional(),
46
+ })
47
+ const emptyInput = z.strictObject({})
48
+
49
+ class SettingsError extends Error {
50
+ constructor(code) { super(code); this.code = code }
51
+ }
52
+
53
+ const messages = {
54
+ 'bad-request': 'Invalid TAPD settings request.',
55
+ 'revision-conflict': 'Settings changed. Reload the latest settings before saving.',
56
+ 'invalid-config': 'Check the project IDs, status keys, owner and sync limits.',
57
+ 'duplicate-project': 'Each TAPD project can only appear once.',
58
+ 'missing-scopes': 'To enable sync, configure at least one project and work item status.',
59
+ 'invalid-credentials': 'Check the selected credential type and credential fields.',
60
+ 'workspace-unavailable': 'The selected DSH workspace is unavailable. Refresh the list or choose another workspace.',
61
+ 'settings-unavailable': 'TAPD settings are temporarily unavailable.',
62
+ 'project-context-required': 'Enter a TAPD company ID or a known project ID, and for a personal token also enter the TAPD nickname.',
63
+ }
64
+ const explicitProjectFallback = 'To try explicit discovery, enter a TAPD company ID or known project ID and your TAPD nickname. You can also enter project IDs manually.'
65
+ const discoveryMessages = {
66
+ 'tapd/auth': 'TAPD rejected the supplied credentials.',
67
+ 'tapd/current-user-unavailable': `TAPD could not look up a usable current-user nickname with this token. ${explicitProjectFallback}`,
68
+ 'tapd/discovery-forbidden': 'The selected TAPD credential does not have access to this metadata. You can enter the values manually.',
69
+ 'tapd/rate-limit': 'TAPD rate limit reached. Try again later.',
70
+ 'tapd/http': 'TAPD returned an HTTP error.',
71
+ 'tapd/network': 'Could not reach TAPD.',
72
+ 'tapd/aborted': 'TAPD discovery was cancelled.',
73
+ 'tapd/timeout': 'TAPD discovery timed out.',
74
+ 'tapd/malformed': 'TAPD did not return usable metadata. You can enter the values manually.',
75
+ 'tapd/api': 'TAPD did not allow or could not complete discovery. Check the selected credentials and their permissions, or enter the values manually.',
76
+ 'tapd/discovery-limit': 'The TAPD status list exceeds the discovery limit. Enter the status keys manually.',
77
+ }
78
+
79
+ const automaticProjectListMessages = {
80
+ 'tapd/discovery-forbidden': `This TAPD token is not permitted to list participant projects without a company context. ${explicitProjectFallback}`,
81
+ 'tapd/malformed': `TAPD did not return a usable participant project list without a company context. ${explicitProjectFallback}`,
82
+ 'tapd/api': `TAPD could not list participant projects without a company context. ${explicitProjectFallback}`,
83
+ }
84
+
85
+ function discoveryFailure(error) {
86
+ const code = discoveryErrorCode(error)
87
+ if (code === undefined) return undefined
88
+ if (error instanceof AutomaticProjectListError) {
89
+ if (code === 'tapd/http' && error.status === 400) return {
90
+ code: 'tapd/project-context-required',
91
+ message: `TAPD rejected the participant project request without a company context. ${explicitProjectFallback}`,
92
+ }
93
+ if (Object.hasOwn(automaticProjectListMessages, code)) return { code, message: automaticProjectListMessages[code] }
94
+ }
95
+ if (Object.hasOwn(discoveryMessages, code)) return { code, message: discoveryMessages[code] }
96
+ }
97
+
98
+ function checkAborted(signal) {
99
+ if (signal?.aborted) throw new TapdError('tapd/aborted')
100
+ }
101
+
102
+ function projectDiscoveryContext(input, config) {
103
+ if ('auto' in input) return { auto: true }
104
+ const seedWorkspaceId = input.seedWorkspaceId ?? (input.companyId ? undefined : tapdId.safeParse(config.seedWorkspaceId).data)
105
+ // A linked project takes precedence over the legacy company setting unless a caller expressly supplies a company.
106
+ const companyId = input.companyId ?? (seedWorkspaceId ? undefined : tapdId.safeParse(config.companyId).data)
107
+ const hasContext = companyId !== undefined || seedWorkspaceId !== undefined
108
+ // For a context-free bearer request, the credential's nickname is authoritative, not the saved owner.
109
+ if (input.auth === 'bearer' && !hasContext) return { auto: true }
110
+ const nick = input.nick ?? requiredTapdNickname.safeParse(config.owner).data
111
+ if (!hasContext || (input.auth === 'bearer' && !nick)) throw new SettingsError('project-context-required')
112
+ return { companyId, seedWorkspaceId, nick }
113
+ }
114
+
115
+ function admitConfig(input) {
116
+ const parsed = visualConfig.safeParse(input)
117
+ if (!parsed.success) throw new SettingsError('invalid-config')
118
+ const config = parsed.data
119
+ if (new Set(config.projects.map(row => row.workspaceId)).size !== config.projects.length) {
120
+ throw new SettingsError('duplicate-project')
121
+ }
122
+ if (config.enabled && (!config.projects.length || !config.projects.some(row => row.stories.length || row.tasks.length))) {
123
+ throw new SettingsError('missing-scopes')
124
+ }
125
+ try { parseConfig(config) }
126
+ catch (error) { throw new SettingsError(error?.code === 'missing-scopes' ? 'missing-scopes' : 'invalid-config') }
127
+ return config
128
+ }
129
+
130
+ function admitCredentialChange(input, auth) {
131
+ const change = credentialChange.safeParse(input)
132
+ if (!change.success) throw new SettingsError('invalid-credentials')
133
+ const { mode, ...secret } = change.data
134
+ if (mode === 'use-refs') return { mode }
135
+ try { authorizationHeader(auth, secret) }
136
+ catch { throw new SettingsError('invalid-credentials') }
137
+ return { mode, secret }
138
+ }
139
+
140
+ function admitRecord(record) {
141
+ if (record === undefined) return undefined
142
+ const parsed = grant.safeParse(record?.payload)
143
+ if (record?.kind !== 'grant' || !parsed.success) throw new SettingsError('settings-unavailable')
144
+ return parsed.data
145
+ }
146
+
147
+ function projection(config) {
148
+ const { enabled, auth, owner, projects, intervalSeconds, maxNewPerScope, companyId, seedWorkspaceId, lookbackDays } = config
149
+ return { enabled, auth, owner, projects, intervalSeconds, maxNewPerScope,
150
+ ...(companyId === undefined ? {} : { companyId }), ...(seedWorkspaceId === undefined ? {} : { seedWorkspaceId }),
151
+ ...(lookbackDays === undefined ? {} : { lookbackDays }) }
152
+ }
153
+
154
+ /** One owner-scoped grant keeps the settings revision and any visual credentials atomic. */
155
+ export async function createSettings(credentials, profileConfig, isBoardReady, listWorkspaces, { fetchImpl } = {}) {
156
+ const profile = { ...DEFAULTS, ...profileConfig }
157
+ async function workspaceCatalog() {
158
+ try {
159
+ const parsed = z.array(workspaceOption).safeParse(await listWorkspaces?.())
160
+ if (parsed.success) return { workspaceStatus: 'ready', workspaces: parsed.data }
161
+ } catch { /* The settings remain editable if the registry is unavailable. */ }
162
+ return { workspaceStatus: 'unavailable', workspaces: [] }
163
+ }
164
+ const loadRecord = async () => admitRecord(await credentials.readRecord?.(SETTINGS_KEY))
165
+ let initial
166
+ try { initial = await loadRecord() } catch { throw new SettingsError('settings-unavailable') }
167
+ let current = initial
168
+ // In a visual record, omitted lookback/seed values mean unrestricted history and no linked project.
169
+ const { lookbackDays: _profileLookback, seedWorkspaceId: _profileSeed, ...profileFallback } = profile
170
+ const effective = record => record ? { ...profileFallback, ...record.config } : { ...profile }
171
+ const authorization = (options, signal, record = current) => {
172
+ // A credential set for the other auth mode must never be sent to TAPD.
173
+ const relevant = record?.secret && (('token' in record.secret) === (options.auth === 'bearer'))
174
+ if (relevant) return authorizationHeader(options.auth, record.secret)
175
+ return resolveAuthorization(credentials, options, signal)
176
+ }
177
+ async function discoveryAuthorization(auth, changeInput, config, record, signal) {
178
+ checkAborted(signal)
179
+ const change = changeInput === undefined ? undefined : credentialChange.safeParse(changeInput)
180
+ if (change && !change.success) throw new SettingsError('invalid-credentials')
181
+ try {
182
+ if (change?.data.mode === 'replace') return authorizationHeader(auth, change.data)
183
+ const options = { ...config, auth }
184
+ return change?.data.mode === 'use-refs'
185
+ ? await resolveAuthorization(credentials, options, signal)
186
+ : await authorization(options, signal, record)
187
+ } catch {
188
+ checkAborted(signal)
189
+ throw new SettingsError('invalid-credentials')
190
+ }
191
+ }
192
+ async function view(record) {
193
+ const config = effective(record)
194
+ let credentialSource = 'none'
195
+ try {
196
+ await authorization(config, undefined, record)
197
+ credentialSource = record?.secret && (('token' in record.secret) === (config.auth === 'bearer')) ? 'visual' : 'refs'
198
+ } catch { /* Only presence is projected, never errors from the backing store. */ }
199
+ return { revision: record?.revision ?? 0, source: record ? 'visual' : 'profile', config: projection(config),
200
+ configured: credentialSource !== 'none', credentialSource,
201
+ syncState: !config.enabled ? 'disabled' : isBoardReady() ? 'ready' : 'waiting-for-board',
202
+ ...await workspaceCatalog() }
203
+ }
204
+ async function update(expectedRevision, build) {
205
+ const result = await credentials.modifyRecord(SETTINGS_KEY, async raw => {
206
+ const previous = admitRecord(raw)
207
+ if ((previous?.revision ?? 0) !== expectedRevision) throw new SettingsError('revision-conflict')
208
+ const { config, secret } = await build(previous)
209
+ const next = { version: 1, revision: expectedRevision + 1, config }
210
+ if (secret !== undefined) next.secret = secret
211
+ if (!grant.safeParse(next).success) throw new SettingsError('settings-unavailable')
212
+ return { kind: 'grant', payload: next }
213
+ })
214
+ const committed = admitRecord(result)
215
+ if (!committed) throw new SettingsError('settings-unavailable')
216
+ current = committed
217
+ return view(committed)
218
+ }
219
+ return {
220
+ snapshot() {
221
+ const record = current
222
+ return { config: effective(record), authorization: (options, signal) => authorization(options, signal, record) }
223
+ },
224
+ async get() { return view(await loadRecord()) },
225
+ async discoverProjects(input, signal) {
226
+ const parsed = projectDiscoveryInput.safeParse(input)
227
+ if (!parsed.success) throw new SettingsError('bad-request')
228
+ checkAborted(signal)
229
+ const record = await loadRecord()
230
+ checkAborted(signal)
231
+ const config = effective(record)
232
+ const { auth, credentials: change } = parsed.data
233
+ const context = projectDiscoveryContext(parsed.data, config)
234
+ const header = await discoveryAuthorization(auth, change, config, record, signal)
235
+ return discoverProjects({ auth, ...context, authorization: header, signal, fetchImpl })
236
+ },
237
+ async discoverProjectNames(input, signal) {
238
+ const parsed = projectNamesInput.safeParse(input)
239
+ if (!parsed.success) throw new SettingsError('bad-request')
240
+ checkAborted(signal)
241
+ const record = await loadRecord()
242
+ const { auth, workspaceIds } = parsed.data
243
+ const header = await discoveryAuthorization(auth, undefined, effective(record), record, signal)
244
+ return discoverProjectNames({ workspaceIds, authorization: header, signal, fetchImpl })
245
+ },
246
+ async discoverStatuses(input, signal) {
247
+ const parsed = statusDiscoveryInput.safeParse(input)
248
+ if (!parsed.success) throw new SettingsError('bad-request')
249
+ checkAborted(signal)
250
+ const record = await loadRecord()
251
+ const { auth, credentials: change, workspaceId } = parsed.data
252
+ const header = await discoveryAuthorization(auth, change, effective(record), record, signal)
253
+ return discoverStatuses({ workspaceId, authorization: header, signal, fetchImpl })
254
+ },
255
+ async save(input) {
256
+ const parsed = saveInput.safeParse(input)
257
+ if (!parsed.success) throw new SettingsError('bad-request')
258
+ const config = admitConfig(parsed.data.config)
259
+ const change = parsed.data.credentials === undefined ? undefined : admitCredentialChange(parsed.data.credentials, config.auth)
260
+ return update(parsed.data.expectedRevision, async previous => {
261
+ const oldTargets = new Map(effective(previous).projects.map(row => [row.workspaceId, row.targetWorkspaceId]))
262
+ const changed = config.projects.filter(row => row.targetWorkspaceId && row.targetWorkspaceId !== oldTargets.get(row.workspaceId))
263
+ if (changed.length) {
264
+ const { workspaces } = await workspaceCatalog()
265
+ const available = new Set(workspaces.map(row => row.id))
266
+ if (changed.some(row => !available.has(row.targetWorkspaceId))) throw new SettingsError('workspace-unavailable')
267
+ }
268
+ return { config, secret: change ? change.secret : previous?.secret }
269
+ })
270
+ },
271
+ async saveCredentials(input) {
272
+ const parsed = saveCredentialsInput.safeParse(input)
273
+ if (!parsed.success) throw new SettingsError('bad-request')
274
+ const { expectedRevision, auth, credentials: change } = parsed.data
275
+ const { secret } = admitCredentialChange(change, auth)
276
+ // Keep the saved config as-is rather than copying any draft or inherited fields into it.
277
+ return update(expectedRevision, previous => ({
278
+ config: { ...(previous?.config ?? projection(effective())), auth }, secret,
279
+ }))
280
+ },
281
+ }
282
+ }
283
+
284
+ /** Mount on the exact owner-only Connection route, not a generic public RPC handler. */
285
+ export function mountSettings(connection, settings, onSaved) {
286
+ let writes = Promise.resolve()
287
+ const dispose = connection.fetch.register({
288
+ path: endpoint, methods: ['POST'], requestBody: 'buffered',
289
+ async fetch(request) {
290
+ const headers = { 'cache-control': 'no-store' }
291
+ if (request.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase() !== 'application/json') {
292
+ return new Response('Expected JSON', { status: 415, headers })
293
+ }
294
+ let body
295
+ try { body = await request.text() } catch { return new Response('Bad request', { status: 400, headers }) }
296
+ if (body.length > 131_072) return new Response('Request too large', { status: 413, headers })
297
+ let envelope
298
+ try { envelope = clientRequestSchema.safeParse(JSON.parse(body)) } catch { /* handled below */ }
299
+ if (!envelope?.success || envelope.data.method !== SETTINGS_METHOD) return new Response('Bad request', { status: 400, headers })
300
+ const { rpcId, payload } = envelope.data
301
+ let result
302
+ try {
303
+ if (!payload || typeof payload !== 'object' || Object.keys(payload).length !== 2 || !Object.hasOwn(payload, 'input')) throw new SettingsError('bad-request')
304
+ if (payload.operation === 'get' && emptyInput.safeParse(payload.input).success) {
305
+ result = { ok: true, value: await settings.get() }
306
+ } else if (payload.operation === 'save' || payload.operation === 'save-credentials') {
307
+ const writing = writes.then(async () => {
308
+ request.signal.throwIfAborted()
309
+ const value = payload.operation === 'save'
310
+ ? await settings.save(payload.input)
311
+ : await settings.saveCredentials(payload.input)
312
+ await onSaved()
313
+ return value
314
+ })
315
+ writes = writing.catch(() => {})
316
+ result = { ok: true, value: await writing }
317
+ } else if (payload.operation === 'discover-projects') {
318
+ result = { ok: true, value: await settings.discoverProjects(payload.input, request.signal) }
319
+ } else if (payload.operation === 'discover-statuses') {
320
+ result = { ok: true, value: await settings.discoverStatuses(payload.input, request.signal) }
321
+ } else if (payload.operation === 'discover-project-names') {
322
+ result = { ok: true, value: await settings.discoverProjectNames(payload.input, request.signal) }
323
+ } else throw new SettingsError('bad-request')
324
+ } catch (error) {
325
+ const discovery = ['discover-projects', 'discover-statuses', 'discover-project-names'].includes(payload?.operation)
326
+ const failure = discovery ? discoveryFailure(error) : undefined
327
+ if (failure) {
328
+ result = { ok: false, error: failure }
329
+ } else {
330
+ const code = error instanceof SettingsError && Object.hasOwn(messages, error.code) ? error.code : 'settings-unavailable'
331
+ result = { ok: false, error: { code: `tapd/${code}`, message: messages[code] } }
332
+ }
333
+ }
334
+ return Response.json({ type: 'server-response', rpcId, result }, { headers })
335
+ },
336
+ })
337
+ return async () => { await dispose(); await writes }
338
+ }
package/sync.js ADDED
@@ -0,0 +1,245 @@
1
+ import { randomUUID } from 'node:crypto'
2
+
3
+ // TaskService v1: ../tavlo-plugins-tasks/docs/task-service.md (External sources and retries).
4
+ const identityFields = ['provider', 'connectionId', 'scopeId', 'objectType', 'objectId']
5
+ const isTapdId = value => typeof value === 'string' && /^[0-9]{1,32}$/.test(value)
6
+ const isObjectType = value => value === 'story' || value === 'task'
7
+ const sameSource = (ref, identity) => !!ref && identityFields.every(field => ref[field] === identity[field])
8
+ const defaultRetryAfterMs = 60_000
9
+
10
+ class SyncFailure extends Error {
11
+ constructor(code, retryAfterMs) {
12
+ super(code)
13
+ this.code = code
14
+ this.retryAfterMs = retryAfterMs
15
+ }
16
+ }
17
+
18
+ function safeFailure(error, fallback) {
19
+ const status = error?.status ?? error?.statusCode
20
+ if (status === 429 || error?.code === 'tapd/rate-limit') {
21
+ const delay = error?.retryAfterMs
22
+ return new SyncFailure('rate-limit', Number.isFinite(delay) && delay >= 0 ? delay : defaultRetryAfterMs)
23
+ }
24
+ if (fallback === 'scan-failed') {
25
+ if (status === 401 || status === 403 || error?.code === 'tapd/auth') return new SyncFailure('auth')
26
+ if (status === 408 || error?.code === 'tapd/timeout') return new SyncFailure('timeout')
27
+ if (error?.code === 'tapd/scan-limit') return new SyncFailure('scan-limit')
28
+ if (error?.code === 'tapd/aborted') return new SyncFailure('aborted')
29
+ } else if (fallback === 'task-failed') {
30
+ if (error?.code === 'tasks/limit-reached') return new SyncFailure('task-capacity')
31
+ if (error?.code === 'tasks/persistence-unknown') return new SyncFailure('task-write-unknown')
32
+ if (error?.code === 'tasks/workspace-unavailable') return new SyncFailure('workspace-unavailable')
33
+ }
34
+ return new SyncFailure(fallback)
35
+ }
36
+
37
+ function supported(capabilities) {
38
+ const { contractVersion, operations, features, limits } = capabilities ?? {}
39
+ return contractVersion === 1 && Array.isArray(operations)
40
+ && operations.includes('create') && operations.includes('list')
41
+ && ['externalRef', 'externalRefUnique', 'filteredList'].every(feature => features?.[feature] === true)
42
+ && Number.isSafeInteger(limits?.maxTitleLength) && limits.maxTitleLength > 0
43
+ && Number.isSafeInteger(limits?.maxBriefLength) && limits.maxBriefLength >= 0
44
+ }
45
+
46
+ function sourceUrl(value) {
47
+ if (typeof value !== 'string' || !/^https?:\/\//i.test(value) || value.length > 2048 || /[\x00-\x20\x7f<>\\]/.test(value)) return false
48
+ try {
49
+ const url = new URL(value)
50
+ return (url.protocol === 'https:' || url.protocol === 'http:') && !url.username && !url.password
51
+ } catch { return false }
52
+ }
53
+
54
+ function dateOnly(value) {
55
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000-')) return false
56
+ const parsed = new Date(value)
57
+ return Number.isFinite(parsed.valueOf()) && parsed.toISOString().slice(0, 10) === value
58
+ }
59
+
60
+ function clip(text, limit) {
61
+ // Limits are UTF-16 lengths; a cap must not cut a surrogate pair in two.
62
+ return text.slice(0, limit).replace(/[\ud800-\udbff]$/, '').trimEnd()
63
+ }
64
+
65
+ function newInput(row, identity, limits, targetWorkspaceId) {
66
+ const title = row.title.toWellFormed().replace(/\s+/g, ' ').trim() || `TAPD ${row.id}`
67
+ const target = row.url.replaceAll('&', '&amp;')
68
+ const source = [`[Open in TAPD](<${target}>)`, `[TAPD](<${target}>)`, `<${row.url}>`]
69
+ .find(link => link.length <= limits.maxBriefLength) ?? ''
70
+ // scan already converts HTML to plain text (no raw TAPD HTML). An indented
71
+ // Markdown code block keeps that text literal, including images, links and
72
+ // autolinks. Put the connector's own link first so truncation can't break it.
73
+ const description = row.description.toWellFormed().replace(/\r\n?/g, '\n').trim()
74
+ const brief = clip(description ? `${source ? `${source}\n\n` : ''}${description.replace(/^/gm, ' ')}` : source, limits.maxBriefLength)
75
+ return {
76
+ requestId: `tapd.${randomUUID()}`,
77
+ title: clip(title, limits.maxTitleLength) || 'T',
78
+ brief,
79
+ externalRef: { ...identity, url: row.url },
80
+ ...(targetWorkspaceId ? { workspaceId: targetWorkspaceId } : {}),
81
+ ...(dateOnly(row.dueDate) ? { dueDate: row.dueDate } : {}),
82
+ }
83
+ }
84
+
85
+ function reportData(scope) {
86
+ return {
87
+ workspaceId: isTapdId(scope?.workspaceId) ? scope.workspaceId : undefined,
88
+ objectType: isObjectType(scope?.objectType) ? scope.objectType : undefined,
89
+ code: 'ok', scanned: 0, candidates: 0, created: 0, duplicates: 0, suppressed: 0, failed: 0,
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Run a single round. The caller serializes rounds for the persistent connection and owns scheduling.
95
+ * `report`, if supplied, is a synchronous observer called once per reached scope with safe IDs,
96
+ * a stable code and counts. `candidates` includes pending replays that could still create a task;
97
+ * `created` counts successful create acknowledgements even if the subsequent ledger write fails.
98
+ */
99
+ export async function syncRound({ tasks, ledger, connectionId, scopes, maxNewPerScope, authorization, scan, signal, report, hasWorkspace }) {
100
+ function notify(data) {
101
+ try { report?.(data) } catch { /* Reporting is observational. */ }
102
+ }
103
+
104
+ function checkAbort() {
105
+ if (signal?.aborted) throw new SyncFailure('aborted')
106
+ }
107
+
108
+ async function checked(action, fallback) {
109
+ checkAbort()
110
+ try {
111
+ const value = await action()
112
+ checkAbort()
113
+ return value
114
+ } catch (error) {
115
+ checkAbort()
116
+ throw safeFailure(error, fallback)
117
+ }
118
+ }
119
+
120
+ const execute = (operation, input) => checked(() => tasks.execute(operation, input, signal), 'task-failed')
121
+ const put = (key, record) => checked(() => ledger.put(key, record), 'ledger-failed')
122
+ const markImported = key => put(key, { kind: 'imported' })
123
+
124
+ if (signal?.aborted) return {}
125
+ let capabilities
126
+ try {
127
+ capabilities = await checked(() => tasks.capabilities(), 'unsupported-tasks')
128
+ if (!supported(capabilities) || typeof tasks.execute !== 'function') throw new SyncFailure('unsupported-tasks')
129
+ } catch (error) {
130
+ if (!signal?.aborted) {
131
+ const failure = error instanceof SyncFailure ? error : safeFailure(error, 'unsupported-tasks')
132
+ for (const scope of scopes) {
133
+ notify({ ...reportData(scope), code: failure.code, failed: 1 })
134
+ if (failure.code === 'rate-limit' || signal?.aborted) break
135
+ }
136
+ if (failure.code === 'rate-limit') return { retryAfterMs: failure.retryAfterMs }
137
+ }
138
+ return {}
139
+ }
140
+
141
+ for (const scope of scopes) {
142
+ if (signal?.aborted) break
143
+ const data = reportData(scope)
144
+ let stop
145
+ function failed(error, fallback) {
146
+ const failure = error instanceof SyncFailure ? error : safeFailure(error, fallback)
147
+ const halts = failure.code === 'aborted' || failure.code === 'rate-limit'
148
+ data.failed++
149
+ // Preserve the first ordinary failure; a stop condition takes precedence.
150
+ if (data.code === 'ok' || halts) data.code = failure.code
151
+ if (halts) stop = failure
152
+ }
153
+
154
+ try {
155
+ if (!data.workspaceId || !data.objectType) throw new SyncFailure('scan-failed')
156
+ const { targetWorkspaceId, ...query } = scope
157
+ const rows = await checked(() => scan({ ...query, authorization, signal }), 'scan-failed')
158
+ if (!Array.isArray(rows)) throw new SyncFailure('scan-failed')
159
+ data.scanned = rows.length
160
+ const seen = new Set()
161
+ const plan = []
162
+ for (const row of rows) {
163
+ if (!isTapdId(row?.id) || typeof row.title !== 'string' || typeof row.description !== 'string' || !sourceUrl(row.url)) {
164
+ throw new SyncFailure('scan-failed')
165
+ }
166
+ if (seen.has(row.id)) {
167
+ data.duplicates++
168
+ continue
169
+ }
170
+ seen.add(row.id)
171
+ const identity = { provider: 'tapd', connectionId, scopeId: scope.workspaceId, objectType: scope.objectType, objectId: row.id }
172
+ const key = `${scope.workspaceId}:${scope.objectType}:${row.id}`
173
+ const record = await checked(() => ledger.get(key), 'ledger-failed')
174
+ if (record?.kind === 'imported') {
175
+ data.duplicates++
176
+ continue
177
+ }
178
+ if (record != null && (record.kind !== 'pending' || !sameSource(record.input?.externalRef, identity))) {
179
+ throw new SyncFailure('ledger-failed')
180
+ }
181
+ // External identity excludes the URL. A local edit or different URL cannot defeat dedupe.
182
+ const result = await execute('list', { externalRef: identity, limit: 1 })
183
+ if (result?.ok !== true) throw safeFailure(result?.error, 'task-failed')
184
+ const hits = result.value?.tasks
185
+ if (!Array.isArray(hits) || hits.some(task => !sameSource(task?.externalRef, identity))) {
186
+ throw new SyncFailure('task-failed')
187
+ }
188
+ if (hits.length) {
189
+ data.duplicates++
190
+ plan.push({ key })
191
+ } else {
192
+ data.candidates++
193
+ plan.push({ key, row, identity, pending: record?.input })
194
+ }
195
+ }
196
+
197
+ // No writes whatsoever (including import markers or replays) before the
198
+ // entire scope has been scanned and its possible creates counted.
199
+ if (!Number.isSafeInteger(maxNewPerScope) || maxNewPerScope < 0 || data.candidates > maxNewPerScope) {
200
+ data.code = 'scope-limit'
201
+ } else {
202
+ let workspaceAvailable
203
+ for (const { key, row, identity, pending } of plan) {
204
+ try {
205
+ if (row) {
206
+ // Reject a missing destination before persisting a new immutable intent.
207
+ // A replay must retain its original input regardless of today's mapping.
208
+ if (!pending && targetWorkspaceId && hasWorkspace) {
209
+ workspaceAvailable ??= await checked(() => hasWorkspace(targetWorkspaceId), 'workspace-unavailable')
210
+ if (!workspaceAvailable) throw new SyncFailure('workspace-unavailable')
211
+ }
212
+ const input = pending ?? newInput(row, identity, capabilities.limits, targetWorkspaceId)
213
+ // Persist the whole immutable intent before asking TaskService to create.
214
+ if (!pending) await put(key, { kind: 'pending', input })
215
+ const result = await execute('create', input)
216
+ if (result?.ok === true) {
217
+ // A replay may return the already-created task in its current, unbound form.
218
+ if (pending && !sameSource(result.value?.task?.externalRef, identity)) data.suppressed++
219
+ else data.created++
220
+ } else if (result?.error?.code === 'tasks/deleted') {
221
+ data.suppressed++
222
+ } else if (result?.error?.code === 'tasks/external-conflict' && result.error.details?.reason === 'duplicate') {
223
+ // V1 explicitly confirms an exact duplicate under its write lock.
224
+ data.duplicates++
225
+ } else {
226
+ // Keep the pending record unchanged; the next round can retry the same request.
227
+ throw safeFailure(result?.error, 'task-failed')
228
+ }
229
+ }
230
+ await markImported(key)
231
+ } catch (error) {
232
+ failed(error, 'task-failed')
233
+ if (stop) break
234
+ }
235
+ }
236
+ }
237
+ } catch (error) {
238
+ failed(error, 'scan-failed')
239
+ }
240
+ notify(data)
241
+ if (stop?.code === 'rate-limit') return { retryAfterMs: stop.retryAfterMs }
242
+ if (stop) break
243
+ }
244
+ return {}
245
+ }
@@ -0,0 +1,21 @@
1
+ # Copy the config override into the list in $DSH_HOME/profiles/web/cordis.patch.yml.
2
+ # Replace the sample values before changing enabled to true. Do not put secrets here.
3
+ - id: tavlo-tapd
4
+ name: '@tavlo-dsh/dsh-plugin-tapd'
5
+ config:
6
+ enabled: false
7
+ auth: bearer
8
+ tokenRef: TAVLO_TAPD_TOKEN
9
+ # For auth: basic, use these references instead of tokenRef:
10
+ # apiUserRef: TAVLO_TAPD_API_USER
11
+ # apiKeyRef: TAVLO_TAPD_API_KEY
12
+ owner: 'TAPD 处理人昵称'
13
+ projects:
14
+ - workspaceId: '12345678' # TAPD project ID, not the DSH workspace.
15
+ # targetWorkspaceId: '550e8400-e29b-41d4-a716-446655440000' # Existing DSH workspace UUID; omit for ungrouped.
16
+ stories: ['planning'] # Example only: use your project's actual status keys.
17
+ tasks: ['open', 'progressing']
18
+ # companyId: '12345678' # Optional; used for the UI project picker, not for polling.
19
+ # lookbackDays: 30 # Optional; only import work items modified in the last 30 days. Omit for all dates.
20
+ intervalSeconds: 300
21
+ maxNewPerScope: 25