dsh-d365-kit 0.0.0-stage → 0.34.3

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 (79) hide show
  1. package/CHANGELOG.md +318 -0
  2. package/CHANGELOG.zh-CN.md +317 -0
  3. package/INSTALL.md +94 -0
  4. package/INSTALL.zh-CN.md +93 -0
  5. package/LICENSE +21 -0
  6. package/README.md +335 -2
  7. package/README.zh-CN.md +336 -0
  8. package/client.js +1818 -0
  9. package/cordis.patch.yml +44 -0
  10. package/docs/en/architecture.md +172 -0
  11. package/docs/en/checks.md +184 -0
  12. package/docs/en/installation.md +151 -0
  13. package/docs/en/permissions.md +161 -0
  14. package/docs/en/scenarios.md +202 -0
  15. package/docs/en/tools.md +665 -0
  16. package/docs/en/troubleshooting.md +131 -0
  17. package/docs/zh/architecture.md +172 -0
  18. package/docs/zh/checks.md +184 -0
  19. package/docs/zh/installation.md +151 -0
  20. package/docs/zh/permissions.md +161 -0
  21. package/docs/zh/scenarios.md +202 -0
  22. package/docs/zh/tools.md +665 -0
  23. package/docs/zh/troubleshooting.md +131 -0
  24. package/examples/prompts.en.md +206 -0
  25. package/examples/prompts.zh-CN.md +206 -0
  26. package/examples/waivers.example.json +20 -0
  27. package/icon.svg +6 -0
  28. package/index.js +142 -0
  29. package/lib/auth.js +181 -0
  30. package/lib/client.js +496 -0
  31. package/lib/code-check.js +549 -0
  32. package/lib/config.js +323 -0
  33. package/lib/contract-history.js +49 -0
  34. package/lib/contract.js +583 -0
  35. package/lib/csharp-check.js +493 -0
  36. package/lib/data-migrate.js +1318 -0
  37. package/lib/data-policy.js +78 -0
  38. package/lib/error-codes.js +80 -0
  39. package/lib/errors.js +81 -0
  40. package/lib/gitlab.js +161 -0
  41. package/lib/health.js +205 -0
  42. package/lib/migrate.js +732 -0
  43. package/lib/preflight.js +116 -0
  44. package/lib/refs.js +191 -0
  45. package/lib/resources.js +320 -0
  46. package/lib/retention-defaults.js +17 -0
  47. package/lib/retention.js +384 -0
  48. package/lib/runtime.js +232 -0
  49. package/lib/settings-http.js +512 -0
  50. package/lib/settings-store.js +371 -0
  51. package/lib/skill.js +76 -0
  52. package/lib/snapshot.js +149 -0
  53. package/lib/tool-code-check.js +133 -0
  54. package/lib/tool-configure.js +169 -0
  55. package/lib/tool-contract.js +376 -0
  56. package/lib/tool-data-sync.js +559 -0
  57. package/lib/tool-data-write.js +203 -0
  58. package/lib/tool-data.js +282 -0
  59. package/lib/tool-diff.js +484 -0
  60. package/lib/tool-environments.js +106 -0
  61. package/lib/tool-flows.js +540 -0
  62. package/lib/tool-health.js +127 -0
  63. package/lib/tool-invoke.js +284 -0
  64. package/lib/tool-layers.js +497 -0
  65. package/lib/tool-metadata.js +417 -0
  66. package/lib/tool-migrate.js +102 -0
  67. package/lib/tool-refs.js +206 -0
  68. package/lib/tool-reports.js +299 -0
  69. package/lib/tool-sync.js +430 -0
  70. package/lib/tool-trace.js +420 -0
  71. package/lib/tool-write.js +563 -0
  72. package/lib/waivers.js +83 -0
  73. package/lib/write-actions.js +1374 -0
  74. package/lib/write-policy.js +199 -0
  75. package/lib/write-store.js +167 -0
  76. package/locale/en.json +68 -0
  77. package/locale/zh.json +68 -0
  78. package/package.json +59 -4
  79. package/skills/d365-troubleshooting/SKILL.md +115 -0
@@ -0,0 +1,420 @@
1
+ /**
2
+ * `d365_trace` — read plug-in trace logs, the record of what a plug-in actually
3
+ * saw and did.
4
+ *
5
+ * Metadata says which step is registered; only a trace says why it threw. The
6
+ * three actions answer the three questions that come up in that order:
7
+ *
8
+ * list what ran (and failed) in a window
9
+ * get what one trace contains — exception, message block, timings
10
+ * summary which failures repeat, and whether tracing is even switched on
11
+ *
12
+ * Trace rows are business data, not metadata: they carry record ids, payload
13
+ * XML and sometimes credentials in the secure configuration. They are gated by
14
+ * `data.read` for that reason, and `get` leaves the configuration fields out
15
+ * unless asked for them.
16
+ */
17
+ import { loadConfig } from './config.js'
18
+ import { formatTable, makeClient, pickEnvironments, writeArtifact } from './runtime.js'
19
+ import { D365Error } from './errors.js'
20
+
21
+ const ACTIONS = ['list', 'get', 'summary']
22
+ const CONFIG_FIELDS = ['configuration', 'secureconfiguration', 'profile']
23
+
24
+ // `operationtypename` / `modename` are not selectable on plugintracelog (the
25
+ // server answers 0x80060888), so the list keeps to columns that exist: the
26
+ // message name, the plug-in type and the exception are what identify a run.
27
+ const LIST_SELECT = [
28
+ 'plugintracelogid',
29
+ 'typename',
30
+ 'messagename',
31
+ 'primaryentity',
32
+ 'depth',
33
+ 'performanceexecutionduration',
34
+ 'performanceexecutionstarttime',
35
+ 'exceptiondetails',
36
+ ].join(',')
37
+
38
+ /**
39
+ * First line of an exception, normalised enough to group by.
40
+ *
41
+ * Dataverse writes the type and message on the first line and the stack below
42
+ * it; the stack is what differs between two occurrences of the same bug.
43
+ */
44
+ export function exceptionSignature(text) {
45
+ const value = String(text ?? '').replace(/\r/g, '')
46
+ if (!value.trim()) return ''
47
+ const line = value
48
+ .split('\n')
49
+ .map((item) => item.trim())
50
+ .find((item) => item && !item.startsWith('at ')) ?? ''
51
+ return line.length > 160 ? `${line.slice(0, 160)}…` : line
52
+ }
53
+
54
+ /**
55
+ * Short type name.
56
+ *
57
+ * `typename` is assembly-qualified (`Contoso.Plugins.X, Contoso.Plugins,
58
+ * Version=1.0.0.0, Culture=neutral, PublicKeyToken=...`), so splitting on `.`
59
+ * alone produces assembly noise instead of the class name.
60
+ */
61
+ function shortTypeName(value) {
62
+ const text = String(value ?? '').trim()
63
+ if (!text) return '—'
64
+ const withoutAssembly = text.split(',')[0].trim()
65
+ const parts = withoutAssembly.split('.')
66
+ return parts[parts.length - 1] || withoutAssembly
67
+ }
68
+
69
+ /**
70
+ * Mask credentials that plug-ins wrote into their own trace.
71
+ *
72
+ * Real traces embed `secureConfig:{"ClientId": "…", "ClientSecret": "…"}` and
73
+ * `Authorization: Bearer …` inside the message block. The log itself is on the
74
+ * server; this redaction keeps the secret out of the chat transcript and the
75
+ * local artifact, which travel much further.
76
+ * @returns the masked text plus how many values were replaced.
77
+ */
78
+ export function redactSecrets(input) {
79
+ let count = 0
80
+ const text = String(input ?? '')
81
+ .replace(/("(?:[A-Za-z0-9_]*(?:secret|password|pwd|token|apikey|api_key|authorization)[A-Za-z0-9_]*)"\s*:\s*")([^"]*)(")/gi,
82
+ (_match, head, _value, tail) => {
83
+ count += 1
84
+ return `${head}***${tail}`
85
+ })
86
+ .replace(/(authorization\s*:\s*bearer\s+)[^\s"',]+/gi, (_match, head) => {
87
+ count += 1
88
+ return `${head}***`
89
+ })
90
+ return { text, count }
91
+ }
92
+
93
+ /** Shorten a duration in milliseconds for the inline table. */
94
+ function formatDuration(ms) {
95
+ const value = Number(ms)
96
+ if (!Number.isFinite(value) || value <= 0) return '—'
97
+ return value >= 1000 ? `${(value / 1000).toFixed(1)}s` : `${Math.round(value)}ms`
98
+ }
99
+
100
+ function shortTime(value) {
101
+ const text = String(value ?? '')
102
+ return text.length >= 19 ? text.slice(0, 19).replace('T', ' ') : text || '—'
103
+ }
104
+
105
+ async function readTraceLevel(client, signal) {
106
+ try {
107
+ const org = await client.getOne('organizations', { $select: 'plugintracelogsetting' }, signal)
108
+ const level = Number(org?.plugintracelogsetting)
109
+ return Number.isFinite(level) ? level : undefined
110
+ } catch {
111
+ return undefined
112
+ }
113
+ }
114
+
115
+ function traceLevelNote(level) {
116
+ if (level === undefined) return null
117
+ if (level === 0) {
118
+ return '注意:该环境的插件跟踪级别是「关闭」。插件异常只会写进系统作业,不会写跟踪日志——查不到日志通常就是这个原因。'
119
+ }
120
+ if (level === 1) return '插件跟踪级别:「仅异常」。只有抛异常的执行才会留下日志,成功执行不记录。'
121
+ return null
122
+ }
123
+
124
+ export const definition = {
125
+ name: 'd365_trace',
126
+ description:
127
+ 'Read plug-in trace logs: what ran and failed in a window (list), what one trace contains (get), or which failures repeat (summary). '
128
+ + 'Use it after a step fails: metadata tells you the step is registered, only the trace says why it threw. '
129
+ + 'Trace rows are business data (they contain record ids, payload XML and sometimes secrets), so this needs "读取业务数据" (data.read). '
130
+ + 'Credentials that plug-ins wrote into their own trace are masked before anything is shown.',
131
+ parameters: {
132
+ type: 'object',
133
+ additionalProperties: false,
134
+ required: ['action'],
135
+ properties: {
136
+ action: {
137
+ type: 'string',
138
+ enum: ACTIONS,
139
+ description: 'list:窗口内的跟踪列表;get:一条跟踪的完整内容;summary:按异常签名汇总,并检查跟踪是否开启。',
140
+ },
141
+ traceId: {
142
+ type: 'string',
143
+ description: 'action=get 时必填:plugintracelogid(GUID,通常来自 list 输出)。',
144
+ },
145
+ hours: {
146
+ type: 'integer',
147
+ description: 'list/summary 的回看小时数,默认 24。',
148
+ },
149
+ entity: {
150
+ type: 'string',
151
+ description: '只看某张表上的跟踪(primaryentity,逻辑名,如 account)。',
152
+ },
153
+ typename: {
154
+ type: 'string',
155
+ description: '只看某个插件类型的跟踪;支持 contains,例如 "ContactSearch"。',
156
+ },
157
+ message: {
158
+ type: 'string',
159
+ description: '只看某个消息的跟踪(messagename,如 Create、Update)。',
160
+ },
161
+ exceptionOnly: {
162
+ type: 'boolean',
163
+ description: '默认 true:只看抛了异常的跟踪。传 false 连成功执行一起看。',
164
+ },
165
+ includeConfig: {
166
+ type: 'boolean',
167
+ description: 'action=get:是否返回 configuration / secureconfiguration / profile(默认 false,这些字段可能含明文密钥)。',
168
+ },
169
+ top: {
170
+ type: 'integer',
171
+ description: 'list 返回行数(默认 20,最多 200);summary 分析的样本上限(默认 300,最多 500)。',
172
+ },
173
+ environment: {
174
+ type: 'string',
175
+ description: '环境 key,省略则用默认环境。',
176
+ },
177
+ environments: {
178
+ type: 'array',
179
+ items: { type: 'string' },
180
+ description: '一次查多个环境。',
181
+ },
182
+ allEnvironments: {
183
+ type: 'boolean',
184
+ description: '对全部已配置环境执行同一查询。',
185
+ },
186
+ },
187
+ },
188
+ output: {
189
+ schema: {
190
+ type: 'object',
191
+ additionalProperties: false,
192
+ required: ['text'],
193
+ properties: { text: { type: 'string' } },
194
+ },
195
+ render(_args, value) {
196
+ return [{ type: 'text', text: value?.text ?? '' }]
197
+ },
198
+ },
199
+ }
200
+
201
+ function buildFilter(args, sinceIso) {
202
+ const parts = [`createdon ge ${sinceIso}`]
203
+ // A successful trace stores an empty string, not null, so `ne null` alone
204
+ // still matches it — that is how a "failures only" list came back with clean
205
+ // runs.
206
+ if (args.exceptionOnly !== false) parts.push('exceptiondetails ne null', "exceptiondetails ne ''")
207
+ if (args.entity) parts.push(`primaryentity eq '${String(args.entity).replace(/'/g, "''")}'`)
208
+ if (args.message) parts.push(`messagename eq '${String(args.message).replace(/'/g, "''")}'`)
209
+ if (args.typename) {
210
+ const value = String(args.typename).replace(/'/g, "''")
211
+ parts.push(`contains(typename,'${value}')`)
212
+ }
213
+ return parts.join(' and ')
214
+ }
215
+
216
+ export function register(ctx, state) {
217
+ return ctx.tools.register({
218
+ ...definition,
219
+ async execute(args, exec) {
220
+ const config = await loadConfig(state.rawConfig)
221
+ const action = args.action
222
+ if (!ACTIONS.includes(action)) {
223
+ throw new D365Error(`不认识的操作:${action}`, { code: 'unknown-action', hint: `可选:${ACTIONS.join(' / ')}` })
224
+ }
225
+ if (action === 'get' && !String(args.traceId ?? '').trim()) {
226
+ throw new D365Error('action=get 需要 traceId', {
227
+ code: 'missing-trace-id',
228
+ hint: '先跑 action=list,把输出里的 plugintracelogid 传进来。',
229
+ })
230
+ }
231
+
232
+ const envs = pickEnvironments(config, args)
233
+ const hours = Number.isFinite(args.hours) ? Math.max(1, Math.min(24 * 30, args.hours)) : 24
234
+ const sinceIso = new Date(Date.now() - hours * 3600_000).toISOString()
235
+ const reports = []
236
+ const artifact = { action, hours, filter: undefined, environments: {} }
237
+
238
+ for (const env of envs) {
239
+ const client = makeClient(env, config)
240
+ const level = await readTraceLevel(client, exec?.signal)
241
+ const note = traceLevelNote(level)
242
+
243
+ if (action === 'get') {
244
+ const id = String(args.traceId).trim()
245
+ const params = {}
246
+ const rows = await client.requestJson(
247
+ client.buildUrl(`plugintracelogs(${id})`, params),
248
+ { signal: exec?.signal },
249
+ ).catch((error) => {
250
+ if (error?.status === 404) {
251
+ throw new D365Error(`${env.key} 没有 id 为 ${id} 的跟踪记录`, {
252
+ code: 'trace-not-found',
253
+ hint: '跟踪日志会按组织设置被清理;确认 id 属于这个环境,或换一个时间窗口重新 list。',
254
+ })
255
+ }
256
+ throw error
257
+ })
258
+ const row = Array.isArray(rows?.value) ? rows.value[0] : rows
259
+ if (!row) throw new D365Error(`${env.key} 没有返回跟踪 ${id}`, { code: 'trace-not-found' })
260
+ if (!args.includeConfig) {
261
+ for (const field of CONFIG_FIELDS) delete row[field]
262
+ }
263
+ // Plug-ins write their own credentials into the message block; mask
264
+ // them before this text becomes a transcript and a local artifact.
265
+ let masked = 0
266
+ for (const field of ['messageblock', 'exceptiondetails', 'configuration', 'secureconfiguration', 'profile']) {
267
+ if (typeof row[field] !== 'string') continue
268
+ const result = redactSecrets(row[field])
269
+ row[field] = result.text
270
+ masked += result.count
271
+ }
272
+ artifact.environments[env.key] = { traceLevel: level ?? null, trace: row, maskedValues: masked }
273
+ const blocks = [
274
+ `${env.key}:跟踪 ${id}`,
275
+ `- 插件类型:${row.typename ?? '—'}`,
276
+ `- 消息 / 表:${row.messagename ?? '—'} / ${row.primaryentity ?? '—'}`,
277
+ `- 深度:${row.depth ?? '—'}`,
278
+ `- 执行耗时:${formatDuration(row.performanceexecutionduration)}(开始 ${shortTime(row.performanceexecutionstarttime)})`,
279
+ ]
280
+ if (row.exceptiondetails) {
281
+ blocks.push('', '异常:', String(row.exceptiondetails).slice(0, 3000))
282
+ } else {
283
+ blocks.push('', '异常:无(这次执行没有抛异常)')
284
+ }
285
+ if (row.messageblock) {
286
+ blocks.push('', '请求内容(messageblock):', String(row.messageblock).slice(0, 4000))
287
+ }
288
+ if (masked > 0) {
289
+ blocks.push('', `(已屏蔽 ${masked} 处疑似密钥;原值仍在环境里的跟踪日志中,这里不回显。)`)
290
+ }
291
+ if (note) blocks.push('', note)
292
+ if (!args.includeConfig) {
293
+ blocks.push('', '(configuration / secureconfiguration / profile 未返回;需要时传 includeConfig: true,注意其中可能有明文密钥。)')
294
+ }
295
+ reports.push(blocks.join('\n'))
296
+ continue
297
+ }
298
+
299
+ const filter = buildFilter(args, sinceIso)
300
+ artifact.filter = filter
301
+
302
+ if (action === 'list') {
303
+ const top = Number.isFinite(args.top) ? Math.max(1, Math.min(200, args.top)) : 20
304
+ const page = await client.getPaged('plugintracelogs', {
305
+ $select: LIST_SELECT,
306
+ $filter: filter,
307
+ $orderby: 'createdon desc',
308
+ }, top, exec?.signal)
309
+ const rows = page.records ?? []
310
+ // The same masking the get branch does: these rows go into the
311
+ // artifact and the transcript, and plug-ins do write credentials into
312
+ // exception text.
313
+ let masked = 0
314
+ for (const row of rows) {
315
+ for (const field of ['messageblock', 'exceptiondetails']) {
316
+ if (typeof row[field] !== 'string') continue
317
+ const result = redactSecrets(row[field])
318
+ row[field] = result.text
319
+ masked += result.count
320
+ }
321
+ }
322
+ artifact.environments[env.key] = { traceLevel: level ?? null, rows, hasMore: page.hasMore, maskedValues: masked }
323
+ const table = rows.length
324
+ ? formatTable(rows.map((row) => ({
325
+ ...row,
326
+ typename: row.typename ?? '—',
327
+ 'plugin/message': `${shortTypeName(row.typename)} / ${row.messagename ?? '—'}`,
328
+ at: shortTime(row.performanceexecutionstarttime),
329
+ duration: formatDuration(row.performanceexecutionduration),
330
+ exception: exceptionSignature(row.exceptiondetails) || '—',
331
+ })), ['at', 'plugin/message', 'primaryentity', 'duration', 'exception'], { width: 44 })
332
+ : '(这个窗口里没有匹配的跟踪记录)'
333
+ const head = rows.length
334
+ ? `${env.key}:最近 ${hours} 小时${args.exceptionOnly === false ? '' : '失败'}跟踪,返回 ${rows.length} 条${page.hasMore ? '(已达上限,缩小时间窗口或加 entity / typename)' : ''}`
335
+ : `${env.key}:最近 ${hours} 小时没有${args.exceptionOnly === false ? '' : '失败的'}跟踪记录`
336
+ reports.push([head, table, note].filter(Boolean).join('\n'))
337
+ continue
338
+ }
339
+
340
+ // summary: pull a bounded sample of failures and aggregate by signature
341
+ // locally — a memo column (exceptiondetails) cannot be grouped
342
+ // server-side.
343
+ const limit = Number.isFinite(args.top) ? Math.max(1, Math.min(500, args.top)) : 300
344
+ const page = await client.getPaged('plugintracelogs', {
345
+ $select: 'plugintracelogid,typename,messagename,primaryentity,exceptiondetails,performanceexecutionstarttime',
346
+ $filter: buildFilter({ ...args, exceptionOnly: true }, sinceIso),
347
+ $orderby: 'createdon desc',
348
+ }, limit, exec?.signal)
349
+ const rows = page.records ?? []
350
+ let masked = 0
351
+ const groups = new Map()
352
+ for (const raw of rows) {
353
+ if (typeof raw.exceptiondetails === 'string') {
354
+ const result = redactSecrets(raw.exceptiondetails)
355
+ raw.exceptiondetails = result.text
356
+ masked += result.count
357
+ }
358
+ const row = raw
359
+ const signature = exceptionSignature(row.exceptiondetails)
360
+ const key = `${row.typename ?? ''}|${row.messagename ?? ''}|${row.primaryentity ?? ''}|${signature}`
361
+ const entry = groups.get(key) ?? {
362
+ typename: row.typename ?? '—',
363
+ message: row.messagename ?? '—',
364
+ entity: row.primaryentity ?? '—',
365
+ signature: signature || '—',
366
+ count: 0,
367
+ first: shortTime(row.performanceexecutionstarttime),
368
+ last: shortTime(row.performanceexecutionstarttime),
369
+ sampleId: row.plugintracelogid,
370
+ }
371
+ entry.count += 1
372
+ const at = shortTime(row.performanceexecutionstarttime)
373
+ if (at < entry.first) entry.first = at
374
+ if (at > entry.last) entry.last = at
375
+ groups.set(key, entry)
376
+ }
377
+ const summary = [...groups.values()].sort((a, b) => b.count - a.count) // Distinguish "no traces at all" from "traces, but none failed".
378
+ let anyTraces = rows.length > 0
379
+ if (!anyTraces) {
380
+ const probe = await client.getPaged('plugintracelogs', {
381
+ $select: 'plugintracelogid',
382
+ $filter: `createdon ge ${sinceIso}`,
383
+ }, 1, exec?.signal).catch(() => ({ records: [] }))
384
+ anyTraces = (probe.records ?? []).length > 0
385
+ }
386
+ artifact.environments[env.key] = {
387
+ traceLevel: level ?? null,
388
+ sampled: rows.length,
389
+ failures: rows.length,
390
+ signatures: summary,
391
+ maskedValues: masked,
392
+ }
393
+ const head = rows.length === 0
394
+ ? anyTraces
395
+ ? `${env.key}:最近 ${hours} 小时有跟踪记录,但没有带异常的`
396
+ : `${env.key}:最近 ${hours} 小时没有任何跟踪记录`
397
+ : `${env.key}:最近 ${hours} 小时 ${rows.length} 条失败跟踪,归为 ${summary.length} 个签名`
398
+ const table = summary.length
399
+ ? formatTable(summary.map((item) => ({
400
+ ...item,
401
+ 'plugin/message': `${shortTypeName(item.typename)} / ${item.message}`,
402
+ signature: item.signature,
403
+ })), ['count', 'plugin/message', 'entity', 'signature', 'last'], { width: 40 })
404
+ : ''
405
+ const tips = []
406
+ if (note) tips.push(note)
407
+ if (anyTraces && !rows.length) {
408
+ tips.push('窗口内没有异常跟踪。若你在查一个失败,确认消息 / 表 / 插件类型过滤没有把它排除,或把 hours 放大。')
409
+ }
410
+ if (summary.length === 1) {
411
+ tips.push(`只有一个签名:先看它的样例 trace(action=get traceId="${summary[0].sampleId}")。`)
412
+ }
413
+ reports.push([head, table, ...tips].filter(Boolean).join('\n'))
414
+ }
415
+
416
+ const file = await writeArtifact(config, `trace-${action}`, artifact)
417
+ return { text: `${reports.join('\n\n')}\n\n完整结果:${file}` }
418
+ },
419
+ })
420
+ }