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,284 @@
1
+ /**
2
+ * `d365_invoke` — call a Dataverse action or function once, and show what came
3
+ * back.
4
+ *
5
+ * This is the tool that turns "the POST failed with some 400" into something a
6
+ * person can look at: an action such as `WinOpportunity` behaves exactly like
7
+ * a plugin step, so reproducing a failure means sending the same message with
8
+ * the same parameters. Nothing here is a batch API: one message, one call, one
9
+ * confirmation.
10
+ *
11
+ * It is deliberately narrow:
12
+ * - the environment must grant `message.invoke` (off by default, high risk);
13
+ * - every call asks in the chat first and prints the exact path and body;
14
+ * - a failed call returns the HTTP status, the Dataverse error code and the
15
+ * response body instead of throwing them away — that body is usually the only
16
+ * place the failing field or plugin trace GUID appears.
17
+ */
18
+ import { loadConfig } from './config.js'
19
+ import { makeClient, pickEnvironments, writeArtifact } from './runtime.js'
20
+ import { D365Error } from './errors.js'
21
+ import { allows, readPolicy } from './write-policy.js'
22
+ import { odataString } from './resources.js'
23
+
24
+ const CONFIRM_ID = 'd365-invoke-confirm'
25
+ const APPROVE = '调用'
26
+ const CANCEL = '取消'
27
+ const ALLOWED_METHODS = ['POST', 'GET']
28
+
29
+ /** Format one function parameter as an OData literal. */function odataLiteral(value) {
30
+ if (value === null || value === undefined) return 'null'
31
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value)
32
+ if (Array.isArray(value)) return `[${value.map((item) => odataLiteral(item)).join(',')}]`
33
+ if (typeof value === 'object') return JSON.stringify(value)
34
+ return `'${odataString(String(value))}'`
35
+ }
36
+
37
+ /**
38
+ * Build the request path plus query for one message.
39
+ *
40
+ * Bound actions hang off the record (`accounts(<id>)/Microsoft.Dynamics.CRM.X`);
41
+ * unbound ones are a bare segment. A GET function carries its parameters as
42
+ * aliases (`Name(x=@p0)?@p0=...`), which is the only form Dataverse accepts.
43
+ */
44
+ export function buildInvokeRequest({ message, method, entity, id, parameters }) {
45
+ const name = String(message ?? '').trim()
46
+ if (!name) throw new D365Error('message 不能为空', { code: 'missing-message', hint: '例如 WinOpportunity 或 contoso_DoSomething。' })
47
+ const verb = String(method ?? 'POST').toUpperCase()
48
+ if (!ALLOWED_METHODS.includes(verb)) {
49
+ throw new D365Error(`不支持的方法:${method}`, { code: 'bad-method', hint: '只支持 POST(action)与 GET(function)。' })
50
+ }
51
+ if (verb === 'GET' && (entity || id)) {
52
+ throw new D365Error('GET function 不支持绑定到记录', {
53
+ code: 'bad-binding',
54
+ hint: '带 entity + id 的调用是绑定 action,只能 POST。',
55
+ })
56
+ }
57
+
58
+ const base = entity
59
+ ? `${String(entity).trim()}(${String(id ?? '').trim()})/Microsoft.Dynamics.CRM.${name}`
60
+ : name
61
+
62
+ if (verb === 'POST') {
63
+ const body = parameters && typeof parameters === 'object' && !Array.isArray(parameters) ? parameters : {}
64
+ return { path: base, query: {}, body }
65
+ }
66
+
67
+ const entries = parameters && typeof parameters === 'object' && !Array.isArray(parameters)
68
+ ? Object.entries(parameters)
69
+ : []
70
+ const query = {}
71
+ const args = entries.map(([key, value], index) => {
72
+ const alias = `@p${index}`
73
+ query[alias] = odataLiteral(value)
74
+ return `${key}=${alias}`
75
+ })
76
+ return { path: `${base}(${args.join(',')})`, query, body: undefined }
77
+ }
78
+
79
+ /** Human-readable one-liner for the confirmation card. */
80
+ export function describeInvoke(envKey, message, method, path, body) {
81
+ const verb = String(method ?? 'POST').toUpperCase()
82
+ const lines = [
83
+ `环境:${envKey}`,
84
+ `消息:${message}(${verb})`,
85
+ `路径:/${path}`,
86
+ ]
87
+ if (body !== undefined) {
88
+ const text = JSON.stringify(body, null, 2)
89
+ lines.push('请求体:', text.length > 1200 ? `${text.slice(0, 1200)}…` : text)
90
+ }
91
+ lines.push(
92
+ '',
93
+ '这条消息由目标环境的插件实现,可能写数据、发通知或调用外部系统;工具不猜测它做了什么。',
94
+ )
95
+ return lines.join('\n')
96
+ }
97
+
98
+ function truncate(text, limit) {
99
+ return text.length > limit ? `${text.slice(0, limit)}…(共 ${text.length} 字符)` : text
100
+ }
101
+
102
+ export const definition = {
103
+ name: 'd365_invoke',
104
+ description:
105
+ 'Call one Dataverse action or function (e.g. WinOpportunity, contoso_DoSomething) and return the HTTP status and response body — to reproduce a failure or to see what a message returns. '
106
+ + 'A GET function is a read and needs "读取业务数据" (data.read); a POST action needs "调用消息" (message.invoke), off by default, and is confirmed in the chat with its exact path and body. '
107
+ + 'A failed call reports the status, the Dataverse error code and the body instead of throwing them away.',
108
+ parameters: {
109
+ type: 'object',
110
+ additionalProperties: false,
111
+ required: ['message'],
112
+ properties: {
113
+ message: {
114
+ type: 'string',
115
+ description: '消息名,例如 WinOpportunity、RetrieveTotalRecordCount、contoso_DoSomething。',
116
+ },
117
+ method: {
118
+ type: 'string',
119
+ enum: ['POST', 'GET'],
120
+ description: 'POST=action(默认,可带请求体);GET=function(参数按 OData 别名拼进 URL,不能绑定记录)。',
121
+ },
122
+ entity: {
123
+ type: 'string',
124
+ description: '绑定 action 时必填:记录的实体集名(如 accounts)。',
125
+ },
126
+ id: {
127
+ type: 'string',
128
+ description: '绑定 action 时必填:记录主键 GUID。',
129
+ },
130
+ parameters: {
131
+ type: 'object',
132
+ description: 'POST 为请求体(action 的输入参数);GET 为 function 的命名参数(值会按 OData 字面量格式化)。',
133
+ },
134
+ environment: {
135
+ type: 'string',
136
+ description: '环境 key,省略则用默认环境。',
137
+ },
138
+ rationale: {
139
+ type: 'string',
140
+ description: '为什么要调这条消息,会写进产物与执行记录。',
141
+ },
142
+ },
143
+ },
144
+ output: {
145
+ schema: {
146
+ type: 'object',
147
+ additionalProperties: false,
148
+ required: ['text'],
149
+ properties: { text: { type: 'string' } },
150
+ },
151
+ render(_args, value) {
152
+ return [{ type: 'text', text: value?.text ?? '' }]
153
+ },
154
+ },
155
+ }
156
+
157
+ export function register(ctx, state) {
158
+ return ctx.tools.register({
159
+ ...definition,
160
+ async execute(args, exec) {
161
+ const config = await loadConfig(state.rawConfig)
162
+ const [env] = pickEnvironments(config, { environment: args.environment })
163
+ if (!env) throw new D365Error('没有可用的环境', { code: 'no-environments' })
164
+
165
+ const policy = await readPolicy(config.configFile)
166
+ // A GET function only reads (RetrieveTotalRecordCount and friends), so it
167
+ // belongs to `data.read`; a POST action runs plug-ins and needs the
168
+ // separate `message.invoke` grant.
169
+ const verb = String(args.method ?? 'POST').toUpperCase()
170
+ const capability = verb === 'GET' ? 'data.read' : 'message.invoke'
171
+ if (!allows(policy, env.key, capability)) {
172
+ throw new D365Error(
173
+ capability === 'data.read'
174
+ ? `环境 ${env.key} 未授权读取业务数据`
175
+ : `环境 ${env.key} 未授权调用消息`,
176
+ {
177
+ code: capability === 'data.read' ? 'data-read-forbidden' : 'message-invoke-forbidden',
178
+ hint: `在设置页「D365 工具箱 → 权限」里给 ${env.key} 勾上${capability === 'data.read' ? '「读取业务数据」' : '「调用消息」'}后再试。`,
179
+ },
180
+ )
181
+ }
182
+
183
+ const request = buildInvokeRequest({
184
+ message: args.message,
185
+ method: args.method,
186
+ entity: args.entity,
187
+ id: args.id,
188
+ parameters: args.parameters,
189
+ })
190
+
191
+ // A GET function changes nothing, so it runs without a card; a POST
192
+ // action is confirmed every time because the target's plug-ins decide
193
+ // what happens next.
194
+ if (verb === 'POST') {
195
+ const userQuestions = ctx.get('userQuestions')
196
+ if (!userQuestions?.ask) {
197
+ throw new D365Error('当前会话没有可用的确认界面', {
198
+ hint: '调用消息必须在对话里确认;这个工具没有「不确认直接发」的路径。',
199
+ })
200
+ }
201
+ if (!exec?.agent) throw new D365Error('需要可交互的会话', { hint: '请在主对话里调用。' })
202
+
203
+ const answer = await userQuestions.ask({
204
+ questions: [{
205
+ id: CONFIRM_ID,
206
+ header: `确认调用消息 ${env.key}`,
207
+ question: `要在 ${env.key} 上调用 ${args.message}(${verb})吗?`,
208
+ detail: describeInvoke(env.key, args.message, verb, request.path, request.body),
209
+ options: [
210
+ { label: APPROVE, description: '立即调用一次' },
211
+ { label: CANCEL, description: '不调用,什么都不发生' },
212
+ ],
213
+ }],
214
+ agent: exec.agent,
215
+ ...(exec.signal ? { signal: exec.signal } : {}),
216
+ wait: { callId: exec.callId },
217
+ })
218
+ const chosen = answer?.answers?.find((item) => item.id === CONFIRM_ID)?.selected?.[0]
219
+ if (chosen !== APPROVE) return { text: `未调用。${env.key} 没有收到任何消息。` }
220
+ }
221
+
222
+ const client = makeClient(env, config)
223
+ const url = client.buildUrl(request.path, request.query)
224
+ const started = Date.now()
225
+ let status = 200
226
+ let payload
227
+ let failure
228
+ try {
229
+ payload = await client.requestJson(url, {
230
+ method: verb,
231
+ ...(verb === 'POST' ? { body: request.body ?? {} } : {}),
232
+ capability: verb === 'POST' ? 'message.invoke' : undefined,
233
+ headers: { Prefer: 'return=representation' },
234
+ signal: exec?.signal,
235
+ })
236
+ } catch (error) {
237
+ // The body of a failed call is the reason this tool exists: return it,
238
+ // do not wrap it into something the caller has to unpack again.
239
+ if (error?.code === 'http' || error?.status) {
240
+ status = error.status ?? 0
241
+ failure = error
242
+ payload = error.body
243
+ } else {
244
+ throw error
245
+ }
246
+ }
247
+ const elapsedMs = Date.now() - started
248
+
249
+ const artifact = {
250
+ kind: 'invoke',
251
+ at: new Date().toISOString(),
252
+ envKey: env.key,
253
+ message: args.message,
254
+ method: verb,
255
+ path: request.path,
256
+ query: request.query,
257
+ body: request.body,
258
+ status,
259
+ elapsedMs,
260
+ rationale: args.rationale,
261
+ response: failure ? undefined : payload,
262
+ error: failure ? { status, errorCode: failure.errorCode, body: failure.body } : undefined,
263
+ }
264
+ const file = await writeArtifact(config, `invoke-${String(args.message).replace(/[^a-zA-Z0-9._-]+/g, '-')}`, artifact)
265
+
266
+ if (failure) {
267
+ const parts = [
268
+ `${env.key}:${args.message} 失败(HTTP ${status},${elapsedMs}ms)`,
269
+ failure.errorCode ? `错误码:${failure.errorCode}` : '',
270
+ '',
271
+ truncate(String(failure.body ?? failure.message ?? ''), 3000),
272
+ '',
273
+ `完整记录:${file}`,
274
+ ].filter((line, index, all) => line !== '' || all[index - 1] !== '')
275
+ return { text: parts.join('\n') }
276
+ }
277
+
278
+ const text = payload === null || payload === undefined ? '(无响应体)' : truncate(JSON.stringify(payload, null, 2), 3000)
279
+ return {
280
+ text: `${env.key}:${args.message} 成功(HTTP ${status},${elapsedMs}ms)\n\n${text}\n\n完整记录:${file}`,
281
+ }
282
+ },
283
+ })
284
+ }