@sparkelf/dsh-dataops-managed 0.3.32 → 0.3.34

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/lib/index.js DELETED
@@ -1,4798 +0,0 @@
1
- import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
2
- import { fileURLToPath } from "node:url";
3
- import { credentialRef } from "@deepseek-ai/dsh-credentials";
4
- import * as McpClient from "@sparkelf/dsh-plugin-mcp-credentials";
5
- import { BUNDLED_SKILL_RANK } from "@deepseek-ai/dsh-skill";
6
- import z from "@deepseek-ai/schemastery";
7
- import { basename, dirname, extname, join } from "node:path";
8
- import { defineTool } from "@deepseek-ai/dsh-tools";
9
- import { randomUUID } from "node:crypto";
10
- //#region src/auth-state.ts
11
- let state = "unknown";
12
- const listeners = /* @__PURE__ */ new Set();
13
- /**
14
- * Observe every recorded transition.
15
- *
16
- * The tool manager uses this to drop its disclosure as soon as any DataOps call reports a 401:
17
- * the scope that produced the tool list can no longer be trusted, and waiting for another
18
- * explicit sync would leave tools offered against an ended session. Listener failures are
19
- * contained so a broken observer cannot turn a credential observation into a failed call.
20
- * @param listener - Called with the new state after it is recorded.
21
- * @returns The exact unsubscriber.
22
- */
23
- const onAuthStateChange = (listener) => {
24
- listeners.add(listener);
25
- return () => {
26
- listeners.delete(listener);
27
- };
28
- };
29
- /** Record one observation and notify observers. */
30
- const setState = (next) => {
31
- state = next;
32
- for (const listener of listeners) try {
33
- listener(next);
34
- } catch {}
35
- };
36
- /**
37
- * Record that a DataOps call was accepted.
38
- *
39
- * Called on any non-401 answer, including ones that carry a refusal for another reason: a 403
40
- * says the session is fine and the permission is not, so it must not raise the sign-in prompt.
41
- */
42
- const noteAccepted = () => {
43
- setState("valid");
44
- };
45
- /** Record that DataOps refused the credential, which means the session is over. */
46
- const noteExpired = () => {
47
- setState("expired");
48
- };
49
- /**
50
- * Read the current observation.
51
- *
52
- * @returns `unknown` before any call has completed, then what the last one said.
53
- */
54
- const currentAuthState = () => state;
55
- /**
56
- * Test-only reset, so one case cannot leak its observation into the next.
57
- */
58
- const resetAuthState = () => {
59
- setState("unknown");
60
- };
61
- //#endregion
62
- //#region src/model-settings.ts
63
- /** Profile entry id whose Config holds the model providers. */
64
- const MODEL_SETTINGS_NAMESPACE = "llm-pi-ai";
65
- /** Field within that entry's Config holding provider profiles keyed by provider id. */
66
- const PROVIDERS_FIELD = "providers";
67
- /** Model ids inside a provider profile, as the plugin stores them. */
68
- const MODELS_FIELD = "models";
69
- /** Read a model's stable identity inside a provider profile. */
70
- function modelIdOf(entry) {
71
- const id = entry.id;
72
- return typeof id === "string" && id.trim() !== "" ? id : null;
73
- }
74
- /** Narrow an unknown value to a plain object. */
75
- function asRecord$4(value) {
76
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
77
- }
78
- /** Read provider profiles out of a settings value. */
79
- function providersOf(value) {
80
- const root = asRecord$4(value);
81
- const providers = root === null ? null : asRecord$4(root[PROVIDERS_FIELD]);
82
- if (providers === null) return {};
83
- const result = {};
84
- for (const [providerId, profile] of Object.entries(providers)) {
85
- const narrowed = asRecord$4(profile);
86
- if (narrowed !== null) result[providerId] = narrowed;
87
- }
88
- return result;
89
- }
90
- /**
91
- * Read the models this workspace currently holds.
92
- *
93
- * A missing section is an empty result rather than an error: a fresh workspace has never
94
- * opened the models page, and that is the normal state for the first user to arrive.
95
- * @param ctx - DSH Host context carrying the settings service.
96
- * @returns Provider profiles and the revision the read observed.
97
- */
98
- function readModels(ctx) {
99
- const descriptor = ctx.settings.describe().find((entry) => entry.ns === MODEL_SETTINGS_NAMESPACE);
100
- if (descriptor === void 0) return {
101
- providers: {},
102
- revision: void 0
103
- };
104
- return {
105
- providers: providersOf(descriptor.value),
106
- revision: descriptor.revision
107
- };
108
- }
109
- /**
110
- * Collect every model id a workspace holds, grouped by provider.
111
- * @param providers - Provider profiles to walk.
112
- * @returns Model ids offered by each provider.
113
- */
114
- function modelIdsByProvider(providers) {
115
- const result = {};
116
- for (const [providerId, profile] of Object.entries(providers)) {
117
- const models = profile[MODELS_FIELD];
118
- if (!Array.isArray(models)) continue;
119
- result[providerId] = models.map((entry) => asRecord$4(entry)).filter((entry) => entry !== null).map((entry) => modelIdOf(entry)).filter((id) => id !== null);
120
- }
121
- return result;
122
- }
123
- /**
124
- * Narrow published providers to the models their publisher offers.
125
- *
126
- * The publisher decides which of its models other users may use; a model it kept private is
127
- * dropped here, so it is never written into a reader's settings at all.
128
- * @param providers - Published provider profiles.
129
- * @param sharedModelIds - Model ids the publisher offers.
130
- * @returns Providers holding only the offered models.
131
- */
132
- function selectSharedModels(providers, sharedModelIds) {
133
- const offered = new Set(sharedModelIds);
134
- if (offered.size === 0) return {};
135
- const result = {};
136
- for (const [providerId, profile] of Object.entries(providers)) {
137
- const models = profile[MODELS_FIELD];
138
- if (!Array.isArray(models)) continue;
139
- const kept = models.filter((entry) => {
140
- const narrowed = asRecord$4(entry);
141
- const id = narrowed === null ? null : modelIdOf(narrowed);
142
- return id !== null && offered.has(id);
143
- });
144
- if (kept.length === 0) continue;
145
- result[providerId] = {
146
- ...profile,
147
- [MODELS_FIELD]: kept
148
- };
149
- }
150
- return result;
151
- }
152
- /**
153
- * Merge adopted provider profiles into the ones a workspace already holds.
154
- *
155
- * A provider the user already has keeps its own models and gains the adopted ones that are
156
- * missing, so adopting never removes a model the user configured. The user's own entry for a
157
- * model wins on conflict: that is what keeps a local edit from being overwritten.
158
- * @param local - Providers the workspace holds now.
159
- * @param adopted - Providers the publisher offers.
160
- * @returns Providers to write, and whether anything changed.
161
- */
162
- function mergeProviders(local, adopted) {
163
- const result = { ...local };
164
- let changed = false;
165
- for (const [providerId, adoptedProfile] of Object.entries(adopted)) {
166
- const adoptedModels = Array.isArray(adoptedProfile[MODELS_FIELD]) ? adoptedProfile[MODELS_FIELD] : [];
167
- const localProfile = result[providerId];
168
- if (localProfile === void 0) {
169
- result[providerId] = adoptedProfile;
170
- changed = changed || adoptedModels.length > 0;
171
- continue;
172
- }
173
- const localModels = Array.isArray(localProfile[MODELS_FIELD]) ? localProfile[MODELS_FIELD] : [];
174
- const localIds = new Set(localModels.map((entry) => asRecord$4(entry)).filter((entry) => entry !== null).map((entry) => modelIdOf(entry)).filter((id) => id !== null));
175
- const missing = adoptedModels.filter((entry) => {
176
- const narrowed = asRecord$4(entry);
177
- const id = narrowed === null ? null : modelIdOf(narrowed);
178
- return id !== null && !localIds.has(id);
179
- });
180
- if (missing.length === 0) continue;
181
- result[providerId] = {
182
- ...localProfile,
183
- [MODELS_FIELD]: [...localModels, ...missing]
184
- };
185
- changed = true;
186
- }
187
- return {
188
- providers: result,
189
- changed
190
- };
191
- }
192
- /**
193
- * Write provider profiles into this workspace's settings.
194
- *
195
- * The write presents the revision the read observed. A settings service that has moved on
196
- * refuses it with its own conflict error, which the caller surfaces rather than retrying:
197
- * silently overwriting a concurrent edit is exactly what this feature must not do.
198
- * @param ctx - DSH Host context carrying the settings service.
199
- * @param providers - Providers to store.
200
- * @param revision - Revision from the read this write is based on.
201
- */
202
- async function writeModels(ctx, providers, revision) {
203
- await ctx.settings.update(MODEL_SETTINGS_NAMESPACE, { [PROVIDERS_FIELD]: providers }, revision);
204
- }
205
- //#endregion
206
- //#region src/model-sync.ts
207
- /** Narrow an unknown value to a plain object. */
208
- function asRecord$3(value) {
209
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
210
- }
211
- /**
212
- * Own the model-sync state one workspace keeps.
213
- *
214
- * The state lives in this workspace rather than in DataOps, because whether a user has written
215
- * their own models is a fact about this workspace. Keeping it here is also what makes the
216
- * promise hold across restarts: a user who chose their own models is not adopted again.
217
- */
218
- var ModelSync = class {
219
- ctx;
220
- config;
221
- store;
222
- constructor(ctx, config, store) {
223
- this.ctx = ctx;
224
- this.config = config;
225
- this.store = store;
226
- }
227
- /**
228
- * Read the DataOps JWT this workspace is currently authorized with.
229
- * @returns The token, or undefined when the workspace has no session yet.
230
- */
231
- async token() {
232
- return (await this.ctx.credentials.resolve(credentialRef(this.config.credentialRef)))?.value;
233
- }
234
- /** The DataOps API origin this workspace reports to. */
235
- apiBase() {
236
- return new URL(this.config.baseUrl).origin;
237
- }
238
- /**
239
- * Fetch the publication this workspace may adopt.
240
- * @returns The published snapshot, or undefined when the workspace is not authorized.
241
- */
242
- async fetchPublished() {
243
- const token = await this.token();
244
- if (token === void 0) return void 0;
245
- const response = await fetch(new URL("/api/ai/shared-models/published", this.apiBase()), {
246
- method: "POST",
247
- headers: { authorization: `Bearer ${token}` }
248
- });
249
- if (response.status === 401) {
250
- noteExpired();
251
- return;
252
- }
253
- noteAccepted();
254
- if (!response.ok) throw new Error(`Shared model read failed with HTTP ${String(response.status)}`);
255
- const body = asRecord$3(await response.json());
256
- if (body === null) return void 0;
257
- const payload = asRecord$3(body.payload);
258
- const providers = payload === null ? null : asRecord$3(payload.providers);
259
- return {
260
- sharingEnabled: body.sharingEnabled === true,
261
- payload: {
262
- providers: providers === null ? {} : providers,
263
- sharedModelIds: Array.isArray(payload?.sharedModelIds) ? payload.sharedModelIds.filter((id) => typeof id === "string") : []
264
- },
265
- updatedAt: typeof body.updatedAt === "string" ? body.updatedAt : null
266
- };
267
- }
268
- /**
269
- * The models this workspace offers to others.
270
- *
271
- * Every model is offered unless the administrator marked it private, which is what makes a
272
- * newly added model shared without an extra step.
273
- * @param providers - Providers this workspace holds.
274
- * @param privateModelIds - Model ids kept private.
275
- * @returns Model ids to offer.
276
- */
277
- offeredModelIds(providers, privateModelIds) {
278
- const held = Object.values(modelIdsByProvider(providers)).flat();
279
- const privateIds = new Set(privateModelIds);
280
- return held.filter((id) => !privateIds.has(id));
281
- }
282
- /**
283
- * Report this workspace's models to DataOps as a publication.
284
- *
285
- * Called when an administrator turns sharing on, or edits their models while it is on. The
286
- * workspace stays the owner of the configuration; DataOps stores only this copy.
287
- * @param sharingEnabled - Whether sharing is on.
288
- */
289
- async publish(sharingEnabled) {
290
- const token = await this.token();
291
- if (token === void 0) throw new Error("This workspace has no DataOps session to publish with");
292
- const state = this.store.read();
293
- const current = readModels(this.ctx);
294
- const response = await fetch(new URL("/api/ai/shared-models/publication", this.apiBase()), {
295
- method: "PUT",
296
- headers: {
297
- authorization: `Bearer ${token}`,
298
- "content-type": "application/json"
299
- },
300
- body: JSON.stringify({
301
- sharingEnabled,
302
- providers: current.providers,
303
- sharedModelIds: this.offeredModelIds(current.providers, state.privateModelIds),
304
- sections: await this.config.collectSections?.() ?? []
305
- })
306
- });
307
- if (!response.ok) throw new Error(`Shared model publish failed with HTTP ${String(response.status)}`);
308
- }
309
- /**
310
- * Read the current user's own publication state and whether they may change it.
311
- *
312
- * The permission rule lives in DataOps; the browser only displays what this reports, so
313
- * nothing in the page decides who is an administrator.
314
- * @returns The state, or null when the workspace is not authorized.
315
- */
316
- async readOwnState() {
317
- const token = await this.token();
318
- if (token === void 0) return null;
319
- const response = await fetch(new URL("/api/ai/shared-models/publication", this.apiBase()), { headers: { authorization: `Bearer ${token}` } });
320
- if (response.status === 401) {
321
- noteExpired();
322
- return null;
323
- }
324
- noteAccepted();
325
- if (!response.ok) throw new Error(`Shared model status read failed with HTTP ${String(response.status)}`);
326
- const body = asRecord$3(await response.json());
327
- return {
328
- sharingEnabled: body?.sharingEnabled === true,
329
- canPublish: body?.canPublish === true
330
- };
331
- }
332
- /**
333
- * Record which models the administrator keeps private.
334
- * @param privateModelIds - Model ids not offered to other users.
335
- * @param sharingEnabled - Whether sharing is on, so the change reaches readers now.
336
- */
337
- async setPrivateModels(privateModelIds, sharingEnabled) {
338
- const state = this.store.read();
339
- await this.store.write({
340
- ...state,
341
- privateModelIds: [...new Set(privateModelIds)]
342
- });
343
- if (sharingEnabled) await this.publish(true);
344
- }
345
- /**
346
- * Adopt the published models into this workspace.
347
- *
348
- * Does nothing when the user here writes their own models, which is what keeps a local edit
349
- * from being replaced by the publisher's version. Otherwise it merges: models the workspace
350
- * lacks are added, and a model it already holds is left exactly as it is.
351
- * @returns Adopted provider profiles, or null when nothing was adopted.
352
- */
353
- async adopt() {
354
- const state = this.store.read();
355
- if (state.detached) return null;
356
- const published = await this.fetchPublished();
357
- if (published === void 0 || !published.sharingEnabled) return null;
358
- const offered = selectSharedModels(published.payload.providers, published.payload.sharedModelIds);
359
- if (Object.keys(offered).length === 0) return null;
360
- const offeredIds = [...new Set(Object.values(modelIdsByProvider(offered)).flat())];
361
- const current = readModels(this.ctx);
362
- if (this.editedSinceAdoption(current.providers, state.adoptedModelIds)) {
363
- await this.store.write({
364
- ...state,
365
- detached: true
366
- });
367
- return null;
368
- }
369
- const merged = mergeProviders(current.providers, offered);
370
- if (merged.changed) await writeModels(this.ctx, merged.providers, current.revision);
371
- await this.store.write({
372
- ...state,
373
- adoptedModelIds: offeredIds
374
- });
375
- return offered;
376
- }
377
- /**
378
- * Whether this workspace holds models adoption did not put there.
379
- *
380
- * A model the workspace has now and adoption did not write is the user's own, so adopting
381
- * again would discard their work. An empty record means adoption never ran here, and the
382
- * first pass must not read the workspace's existing models as an edit.
383
- * @param current - Providers the workspace holds now.
384
- * @param adoptedModelIds - Model ids adoption last wrote.
385
- * @returns True when the workspace holds something adoption did not write.
386
- */
387
- editedSinceAdoption(current, adoptedModelIds) {
388
- if (adoptedModelIds.length === 0) return false;
389
- const adopted = new Set(adoptedModelIds);
390
- return Object.values(modelIdsByProvider(current)).flat().some((id) => !adopted.has(id));
391
- }
392
- /**
393
- * Stop following the publisher and keep what this workspace holds now.
394
- *
395
- * A user who chose their own models must not be pulled back, so this choice is stored and
396
- * survives the next start.
397
- */
398
- async detach() {
399
- await this.store.write({
400
- ...this.store.read(),
401
- detached: true
402
- });
403
- }
404
- /**
405
- * Read the settings sections the current publication offers.
406
- *
407
- * Separate from `adopt`, which owns the models: a workspace adopts models and settings from one
408
- * publication but keeps separate bookkeeping for each, because a user who changed the permission
409
- * default has not thereby chosen their own models.
410
- * @returns The offered sections, or an empty list when nobody publishes or none are offered.
411
- */
412
- async readPublishedSections() {
413
- try {
414
- const published = await this.fetchPublished();
415
- if (published === void 0 || !published.sharingEnabled) return [];
416
- return published.payload.sections ?? [];
417
- } catch (error) {
418
- return [];
419
- }
420
- }
421
- /**
422
- * Follow the publisher again, adopting its models on the next pass.
423
- */
424
- async resumeFollowing() {
425
- await this.store.write({
426
- ...this.store.read(),
427
- detached: false
428
- });
429
- }
430
- /**
431
- * Describe the current state for the settings UI.
432
- * @returns The sync state, whether the viewer may publish, and their own models.
433
- */
434
- async status() {
435
- const state = this.store.read();
436
- const own = await this.readOwnState();
437
- const published = await this.fetchPublished();
438
- const offered = published === void 0 || !published.sharingEnabled ? {} : selectSharedModels(published.payload.providers, published.payload.sharedModelIds);
439
- const held = [...new Set(Object.values(modelIdsByProvider(readModels(this.ctx).providers)).flat())];
440
- const privateIds = new Set(state.privateModelIds);
441
- return {
442
- followState: state.detached ? "detached" : "following",
443
- publisherSharing: published?.sharingEnabled === true,
444
- adoptedCount: Object.values(modelIdsByProvider(offered)).flat().length,
445
- privateModelIds: state.privateModelIds,
446
- publishedAt: published?.updatedAt ?? null,
447
- canPublish: own?.canPublish === true,
448
- models: held.map((id) => ({
449
- id,
450
- shared: !privateIds.has(id)
451
- }))
452
- };
453
- }
454
- };
455
- //#endregion
456
- //#region src/settings-sync.ts
457
- /** Default state before this workspace stored anything. */
458
- const SECTION_SYNC_DEFAULT = { sections: {} };
459
- /** Narrow an unknown value to a plain object. */
460
- function asRecord$2(value) {
461
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
462
- }
463
- /**
464
- * A stable rendering of one section's values.
465
- *
466
- * Key order is normalized so two reads of the same values match, and a publication that only
467
- * reordered its keys does not read as a change the user made.
468
- * @param value - Section values.
469
- * @returns A fingerprint comparable across reads.
470
- */
471
- function fingerprintSection(value) {
472
- const keys = Object.keys(value).sort();
473
- const normalized = {};
474
- for (const key of keys) normalized[key] = value[key];
475
- return JSON.stringify(normalized);
476
- }
477
- /**
478
- * Own the distributed settings one workspace keeps.
479
- *
480
- * The state lives in this workspace rather than in DataOps because whether a user has written
481
- * their own values is a fact about this workspace, and keeping it here is what makes the promise
482
- * hold across restarts: a user who chose their own settings is not adopted again.
483
- */
484
- var SettingsSync = class {
485
- ctx;
486
- store;
487
- constructor(ctx, store) {
488
- this.ctx = ctx;
489
- this.store = store;
490
- }
491
- /**
492
- * Read one namespace as this workspace currently holds it.
493
- * @param ns - Settings namespace to read.
494
- * @returns The values and revision, or undefined when no plugin owns that namespace.
495
- */
496
- readSection(ns) {
497
- const descriptor = this.ctx.settings.describe().find((entry) => entry.ns === ns);
498
- if (descriptor === void 0) return void 0;
499
- const value = asRecord$2(descriptor.value);
500
- if (value === null) return void 0;
501
- return {
502
- value,
503
- revision: descriptor.revision
504
- };
505
- }
506
- /** Read this workspace's per-namespace bookkeeping. */
507
- recordOf(state, ns) {
508
- return state.sections[ns] ?? {
509
- detached: false,
510
- adoptedFingerprint: null
511
- };
512
- }
513
- /**
514
- * Take the published values for every namespace this workspace has not already diverged from.
515
- *
516
- * A namespace the user has written is skipped and marked detached, so a local edit is never
517
- * replaced. A namespace whose current values match what adoption last wrote is still following,
518
- * so the publisher's newer values replace them. Everything else is a default a user may change.
519
- * @param sections - Sections the publisher offers.
520
- * @returns Namespaces that were written, for logging.
521
- */
522
- async adopt(sections) {
523
- const state = this.store.read();
524
- const next = { sections: { ...state.sections } };
525
- const written = [];
526
- let stateChanged = false;
527
- for (const section of sections) {
528
- const record = this.recordOf(state, section.ns);
529
- if (record.detached) continue;
530
- const current = this.readSection(section.ns);
531
- if (current === void 0) continue;
532
- const currentFingerprint = fingerprintSection(current.value);
533
- const publishedFingerprint = fingerprintSection(section.value);
534
- if (record.adoptedFingerprint !== null && currentFingerprint !== record.adoptedFingerprint) {
535
- next.sections[section.ns] = {
536
- detached: true,
537
- adoptedFingerprint: record.adoptedFingerprint
538
- };
539
- stateChanged = true;
540
- continue;
541
- }
542
- if (currentFingerprint === publishedFingerprint) {
543
- if (record.adoptedFingerprint !== publishedFingerprint) {
544
- next.sections[section.ns] = {
545
- detached: false,
546
- adoptedFingerprint: publishedFingerprint
547
- };
548
- stateChanged = true;
549
- }
550
- continue;
551
- }
552
- await this.ctx.settings.update(section.ns, section.value);
553
- next.sections[section.ns] = {
554
- detached: false,
555
- adoptedFingerprint: publishedFingerprint
556
- };
557
- stateChanged = true;
558
- written.push(section.ns);
559
- }
560
- if (stateChanged) await this.store.write(next);
561
- return written;
562
- }
563
- /**
564
- * Describe the distributed settings for the settings UI.
565
- *
566
- * Reports every namespace the deployment offers, whether this workspace still follows the
567
- * publisher for it, and whether a plugin here owns it. A namespace no plugin owns cannot be
568
- * applied, so a panel marks that row rather than offering a control that would do nothing.
569
- * @param namespaces - Namespaces the deployment distributes.
570
- * @returns One entry per namespace, in the order given.
571
- */
572
- status(namespaces) {
573
- const state = this.store.read();
574
- return namespaces.map((ns) => {
575
- const record = this.recordOf(state, ns);
576
- return {
577
- ns,
578
- followState: record.detached ? "detached" : "following",
579
- applied: record.adoptedFingerprint !== null,
580
- mounted: this.readSection(ns) !== void 0
581
- };
582
- });
583
- }
584
- /**
585
- * Stop following the publisher for one namespace and keep what this workspace holds now.
586
- * @param ns - Settings namespace to detach.
587
- */
588
- async detach(ns) {
589
- const state = this.store.read();
590
- const record = this.recordOf(state, ns);
591
- await this.store.write({ sections: {
592
- ...state.sections,
593
- [ns]: {
594
- ...record,
595
- detached: true
596
- }
597
- } });
598
- }
599
- };
600
- //#endregion
601
- //#region src/skill-plaza.ts
602
- /** Narrow an unknown value to a plain object. */
603
- function asRecord$1(value) {
604
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
605
- }
606
- /**
607
- * Read the skills this workspace holds.
608
- *
609
- * The official skill registry is the reader, so the list is the same one the skill center
610
- * shows and includes every source. It is read-only here; sharing a copy of one is what the
611
- * plaza does with it.
612
- * @param ctx - DSH Host context carrying the skill registry.
613
- * @returns Each skill's name, description, and body.
614
- */
615
- async function readLocalSkills(ctx) {
616
- const snapshot = await ctx.skills.snapshot({});
617
- const candidates = [];
618
- for (const summary of snapshot.skills) {
619
- const definition = await ctx.skills.get(summary.name, {});
620
- if (definition === void 0) continue;
621
- candidates.push({
622
- name: definition.name,
623
- description: definition.description === "" ? void 0 : definition.description,
624
- instruction: definition.content
625
- });
626
- }
627
- return candidates;
628
- }
629
- /**
630
- * The skill plaza, as this workspace sees it.
631
- *
632
- * Every call carries the workspace's own DataOps JWT, so DataOps decides who may read and
633
- * share. The plaza copy lives in DataOps rather than here: a reader installs it into their own
634
- * workspace and keeps working after the author edits or stops sharing.
635
- */
636
- var SkillPlaza = class {
637
- ctx;
638
- config;
639
- constructor(ctx, config) {
640
- this.ctx = ctx;
641
- this.config = config;
642
- }
643
- /** The DataOps API origin this workspace reports to. */
644
- apiBase() {
645
- return new URL(this.config.baseUrl).origin;
646
- }
647
- /**
648
- * Read the DataOps JWT this workspace is currently authorized with.
649
- * @returns The token, or undefined when the workspace has no session yet.
650
- */
651
- async token() {
652
- return (await this.ctx.credentials.resolve(credentialRef(this.config.credentialRef)))?.value;
653
- }
654
- /**
655
- * Call one DataOps endpoint with this workspace's identity.
656
- * @param path - API path below the origin.
657
- * @param init - Method, body, and any extra headers.
658
- * @returns The parsed JSON body, or undefined when the workspace is not authorized.
659
- */
660
- async call(path, init = {}) {
661
- const token = await this.token();
662
- if (token === void 0) return void 0;
663
- const response = await fetch(new URL(path, this.apiBase()), {
664
- ...init,
665
- headers: {
666
- authorization: `Bearer ${token}`,
667
- ...init.body === void 0 ? {} : { "content-type": "application/json" },
668
- ...init.headers
669
- }
670
- });
671
- if (response.status === 401) {
672
- noteExpired();
673
- return;
674
- }
675
- noteAccepted();
676
- if (!response.ok) throw new Error(`Skill plaza request failed with HTTP ${String(response.status)}`);
677
- return response.status === 204 ? null : await response.json();
678
- }
679
- /**
680
- * List plaza entries, optionally filtered.
681
- * @param options - Tag and text filters.
682
- * @returns Entries, newest first; empty when the workspace is not authorized.
683
- */
684
- async list(options = {}) {
685
- return (await this.listPage(options)).skills;
686
- }
687
- /** List with the server's tab counts, which the plaza shows without re-counting a page. */
688
- async listPage(options = {}) {
689
- const params = new URLSearchParams();
690
- if (options.tag !== void 0 && options.tag !== "") params.set("tag", options.tag);
691
- if (options.query !== void 0 && options.query !== "") params.set("q", options.query);
692
- if (options.status !== void 0 && options.status !== "") params.set("status", options.status);
693
- if (options.scope !== void 0 && options.scope !== "") params.set("scope", options.scope);
694
- if (options.departmentCode !== void 0 && options.departmentCode !== "") params.set("departmentCode", options.departmentCode);
695
- const suffix = params.size === 0 ? "" : `?${params.toString()}`;
696
- const body = await this.call(`/api/ai/skill-plaza/skills${suffix}`);
697
- const record = asRecord$1(body);
698
- const rows = Array.isArray(body) ? body : Array.isArray(record?.items) ? record.items : [];
699
- const rawCounts = asRecord$1(record?.counts);
700
- return {
701
- skills: rows.flatMap((row) => this.toPlazaSkill(row)),
702
- ...rawCounts === null ? {} : { counts: {
703
- pending: Number(rawCounts.pending ?? 0),
704
- approved: Number(rawCounts.approved ?? 0),
705
- rejected: Number(rawCounts.rejected ?? 0),
706
- total: Number(rawCounts.total ?? rows.length)
707
- } }
708
- };
709
- }
710
- /**
711
- * Every tag in use, so the browser offers existing labels.
712
- * @returns Distinct tags.
713
- */
714
- async tags() {
715
- const body = await this.call("/api/ai/skill-plaza/tags");
716
- if (!Array.isArray(body)) return [];
717
- return body.filter((tag) => typeof tag === "string");
718
- }
719
- /**
720
- * Publish one skill to the plaza.
721
- * @param input - Skill content and its tags.
722
- * @returns The stored entry.
723
- */
724
- async share(input) {
725
- const body = await this.call("/api/ai/skill-plaza/skills", {
726
- method: "POST",
727
- body: JSON.stringify(input)
728
- });
729
- return body === void 0 ? null : this.toPlazaSkill(body)[0] ?? null;
730
- }
731
- /**
732
- * Stop sharing one entry.
733
- * @param id - Plaza entry.
734
- */
735
- async unshare(id) {
736
- await this.call(`/api/ai/skill-plaza/skills/${String(id)}`, { method: "DELETE" });
737
- }
738
- /**
739
- * Install one entry into this workspace.
740
- * @param skillId - Plaza entry.
741
- * @returns What happened, or null when the workspace is not authorized.
742
- */
743
- async install(skillId) {
744
- const body = await this.call("/api/ai/skill-plaza/install", {
745
- method: "POST",
746
- body: JSON.stringify({ skillId })
747
- });
748
- const record = body === void 0 ? null : asRecord$1(body);
749
- if (record === null) return null;
750
- return {
751
- installed: record.installed === true,
752
- skillKey: typeof record.skillKey === "string" ? record.skillKey : null,
753
- keptLocal: record.keptLocal === true
754
- };
755
- }
756
- /** Project one API row into the shape the browser reads. */
757
- toPlazaSkill(value) {
758
- const row = asRecord$1(value);
759
- if (row === null || typeof row.id !== "number" || typeof row.name !== "string") return [];
760
- return [{
761
- id: row.id,
762
- name: row.name,
763
- description: typeof row.description === "string" ? row.description : void 0,
764
- instruction: typeof row.instruction === "string" ? row.instruction : "",
765
- tags: Array.isArray(row.tags) ? row.tags.filter((tag) => typeof tag === "string") : [],
766
- sharedByMe: row.sharedByMe === true,
767
- updatedAt: typeof row.updatedAt === "string" ? row.updatedAt : "",
768
- reviewStatus: row.reviewStatus === "pending" || row.reviewStatus === "rejected" ? row.reviewStatus : "approved",
769
- visibility: row.visibility === "department" || row.visibility === "private" ? row.visibility : "global",
770
- departmentCode: typeof row.departmentCode === "string" ? row.departmentCode : null,
771
- departmentName: typeof row.departmentName === "string" ? row.departmentName : void 0,
772
- departmentPath: Array.isArray(row.departmentPath) ? row.departmentPath.flatMap((entry) => {
773
- const node = asRecord$1(entry);
774
- return node !== null && typeof node.name === "string" ? [{
775
- code: typeof node.code === "string" ? node.code : "",
776
- name: node.name
777
- }] : [];
778
- }) : void 0,
779
- ownerName: typeof row.ownerName === "string" ? row.ownerName : void 0,
780
- riskReport: row.riskReport ?? null,
781
- reviewNote: typeof row.reviewNote === "string" ? row.reviewNote : null,
782
- submittedAt: typeof row.submittedAt === "string" ? row.submittedAt : void 0
783
- }];
784
- }
785
- };
786
- //#endregion
787
- //#region src/review-api.ts
788
- /** Cookie-free same-origin bridge to the review endpoints. */
789
- var ReviewApi = class {
790
- ctx;
791
- config;
792
- constructor(ctx, config) {
793
- this.ctx = ctx;
794
- this.config = config;
795
- }
796
- apiBase() {
797
- return new URL(this.config.baseUrl).origin;
798
- }
799
- async token() {
800
- return (await this.ctx.credentials.resolve(credentialRef(this.config.credentialRef)))?.value;
801
- }
802
- /**
803
- * Call one DataOps endpoint with the workspace JWT.
804
- * @param path - API path below the DataOps origin.
805
- * @param init - Method, body and extra headers.
806
- * @returns The upstream status and parsed body; 503 when this workspace has no session.
807
- */
808
- async request(path, init = {}) {
809
- const token = await this.token();
810
- if (token === void 0) return {
811
- status: 503,
812
- body: { error: "DataOps is not connected" }
813
- };
814
- const isMultipart = typeof FormData !== "undefined" && init.body instanceof FormData;
815
- const response = await fetch(new URL(path, this.apiBase()), {
816
- ...init,
817
- headers: {
818
- authorization: `Bearer ${token}`,
819
- ...init.body === void 0 || isMultipart ? {} : { "content-type": "application/json" },
820
- ...init.headers
821
- }
822
- });
823
- if (response.status === 401) {
824
- noteExpired();
825
- return {
826
- status: 401,
827
- body: { error: "DataOps session expired" }
828
- };
829
- }
830
- noteAccepted();
831
- const text = await response.text();
832
- let body = null;
833
- if (text !== "") try {
834
- body = JSON.parse(text);
835
- } catch {
836
- body = { error: text };
837
- }
838
- return {
839
- status: response.status,
840
- body
841
- };
842
- }
843
- };
844
- //#endregion
845
- //#region src/tool-scope.ts
846
- /**
847
- * Tool-to-capability disclosure map.
848
- *
849
- * `review_notifications_list/read` intentionally carry no policy: every authenticated principal
850
- * owns their own notification inbox. `dataops_api_docs` is gated by the role itself because the
851
- * backend grants the OpenAPI reader to 超级管理员 by default; an administrator who happens to hold
852
- * `developer:openapi:read` is still outside that role and does not receive the tool.
853
- */
854
- const AI_TOOL_ACCESS = {
855
- skill_list: { permission: "skill:read" },
856
- skill_get: { permission: "skill:read" },
857
- skill_submit: { permission: "skill:submit" },
858
- skill_install: { permission: "skill:install" },
859
- skill_uninstall: { permission: "skill:install" },
860
- skill_enable: { permission: "skill:manage" },
861
- skill_disable: { permission: "skill:manage" },
862
- skill_unshare: { permission: "skill:manage" },
863
- skill_delete: { permission: "skill:manage" },
864
- review_scan: {
865
- permission: "skill:read",
866
- reviewer: true
867
- },
868
- review_decide: {
869
- permission: "skill:review:decide",
870
- reviewer: true
871
- },
872
- review_notifications_list: {},
873
- review_notifications_read: {},
874
- dataops_api_docs: { superAdminOnly: true },
875
- dataops_collect_preview: { permission: "data:resource:manage" },
876
- dataops_collect_plan: { permission: "data:resource:manage" },
877
- dataops_collect_execute: { permission: "data:resource:manage" },
878
- dataops_collect_resources: { permission: "data:resource:read" },
879
- dataops_open_resource_tab: {},
880
- dataops_resource_pending_list: {
881
- capability: "resource.manage",
882
- adminOnly: true,
883
- defaultEnabled: true
884
- },
885
- dataops_resource_grant_list: {
886
- capability: "resource.manage",
887
- adminOnly: true,
888
- defaultEnabled: true
889
- },
890
- dataops_resource_grant_batch: {
891
- capability: "resource.manage",
892
- adminOnly: true,
893
- defaultEnabled: true
894
- },
895
- dataops_resource_approval_decide: {
896
- capability: "resource.manage",
897
- adminOnly: true,
898
- defaultEnabled: true
899
- },
900
- dataops_resource_grant_revoke: {
901
- capability: "resource.manage",
902
- adminOnly: true,
903
- defaultEnabled: true
904
- }
905
- };
906
- /** Every managed tool name, in the order the manager considers them. */
907
- const AI_TOOL_NAMES = Object.keys(AI_TOOL_ACCESS);
908
- /**
909
- * Backend permission aliases.
910
- *
911
- * The DataOps role matrix stores the capability family as `skill:capability:*`; this task's
912
- * disclosure contract names them `skill:*`. Accepting both keeps the plugin working against
913
- * either spelling without asking the backend to rename a published key.
914
- */
915
- const PERMISSION_ALIASES = {
916
- "skill:read": ["skill:read", "skill:capability:read"],
917
- "skill:submit": ["skill:submit", "skill:capability:submit"],
918
- "skill:install": ["skill:install", "skill:capability:install"],
919
- "skill:manage": ["skill:manage", "skill:capability:manage"],
920
- "skill:review:decide": ["skill:review:decide"]
921
- };
922
- const SUPER_ADMIN = "超级管理员";
923
- const ADMIN = "管理员";
924
- const DEPARTMENT_ADMIN = "部门管理员";
925
- const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
926
- const strings$1 = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : void 0;
927
- const roleSet = (scope) => new Set(scope.roleCodes ?? []);
928
- /** Whether the context carries the stable super-administrator role. */
929
- const isSuperAdmin = (scope) => roleSet(scope).has(SUPER_ADMIN) || scope.primaryRole === SUPER_ADMIN || (scope.systemKeys ?? []).includes("SUPER_ADMIN");
930
- /** Whether the context carries an administrator or super-administrator role. */
931
- const isAdmin = (scope) => isSuperAdmin(scope) || roleSet(scope).has(ADMIN) || scope.primaryRole === ADMIN || (scope.systemKeys ?? []).includes("ADMIN");
932
- /** Whether the context carries a department-administrator role. */
933
- const isDepartmentAdmin = (scope) => roleSet(scope).has(DEPARTMENT_ADMIN) || scope.primaryRole === DEPARTMENT_ADMIN || (scope.systemKeys ?? []).includes("DEPT_ADMIN");
934
- /**
935
- * Whether the caller may run review operations.
936
- *
937
- * The current backend returns `canReview` at the top level; the nested `review` shape is
938
- * accepted for older contexts. Role membership is a fallback, not an override.
939
- */
940
- const canReview = (scope) => scope.canReview === true || scope.review?.canReview === true || isAdmin(scope) || isDepartmentAdmin(scope);
941
- /** The effective permission list, or `undefined` for a context that predates permission keys. */
942
- const permissionList = (scope) => scope.permissions ?? scope.permissionKeys;
943
- /**
944
- * Whether the caller holds one capability.
945
- *
946
- * A context that carries a permission list is authoritative. Before the list existed, the
947
- * four-role fallback kept the old behavior; it is only used when neither spelling is present.
948
- */
949
- const hasPermission = (scope, key) => {
950
- const permissions = permissionList(scope);
951
- if (permissions !== void 0) {
952
- const set = new Set(permissions);
953
- return (PERMISSION_ALIASES[key] ?? [key]).some((alias) => set.has(alias));
954
- }
955
- if (isAdmin(scope)) return true;
956
- if (isDepartmentAdmin(scope)) return key !== "skill:review:global";
957
- if (roleSet(scope).size === 0) return false;
958
- return key === "skill:read" || key === "skill:install" || key === "skill:submit";
959
- };
960
- /**
961
- * Whether one tool should be registered for this scope.
962
- *
963
- * Every check is disclosure metadata, not an execution gate: a visible tool still lets DataOps
964
- * answer with 403 when the underlying grant changed between a scope sync and the call.
965
- */
966
- function isToolCapabilityEnabled(name, state) {
967
- const policy = AI_TOOL_ACCESS[name];
968
- if (policy.capability === void 0) return true;
969
- if (!state.enabled) return false;
970
- return state.capabilities[policy.capability] ?? policy.defaultEnabled ?? false;
971
- }
972
- function isToolVisible(name, scope) {
973
- const policy = AI_TOOL_ACCESS[name];
974
- if (policy.superAdminOnly === true && !isSuperAdmin(scope)) return false;
975
- if (policy.adminOnly === true && !isAdmin(scope)) return false;
976
- if (policy.reviewer === true && !canReview(scope)) return false;
977
- if (policy.permission !== void 0 && !hasPermission(scope, policy.permission)) return false;
978
- return true;
979
- }
980
- /**
981
- * Validate one `/api/ai/review/context` body.
982
- *
983
- * A body without `roleCodes` is not a usable scope: treating it as "no roles" would let the
984
- * role-name fallback hand an ordinary capability set to an answer this plugin cannot interpret.
985
- * @param body - Parsed JSON from the context endpoint.
986
- * @returns The normalized scope, or undefined when the answer is not a context document.
987
- */
988
- function normalizeScope(body) {
989
- if (!isRecord$1(body)) return void 0;
990
- const roleCodes = strings$1(body.roleCodes);
991
- if (roleCodes === void 0) return void 0;
992
- const roleSystemKeys = (Array.isArray(body.roles) ? body.roles : []).flatMap((entry) => {
993
- if (!isRecord$1(entry)) return [];
994
- return typeof entry.systemKey === "string" ? [entry.systemKey] : [];
995
- });
996
- const explicitSystemKeys = strings$1(body.systemKeys) ?? [];
997
- const systemKeys = Array.from(/* @__PURE__ */ new Set([...explicitSystemKeys, ...roleSystemKeys]));
998
- const permissions = strings$1(body.permissions) ?? (Array.isArray(body.permissionKeys) ? strings$1(body.permissionKeys) : void 0);
999
- const review = isRecord$1(body.review) ? {
1000
- ...typeof body.review.canReview === "boolean" ? { canReview: body.review.canReview } : {},
1001
- ...typeof body.review.canReviewGlobal === "boolean" ? { canReviewGlobal: body.review.canReviewGlobal } : {},
1002
- ...typeof body.review.canManagePermissions === "boolean" ? { canManagePermissions: body.review.canManagePermissions } : {}
1003
- } : void 0;
1004
- return {
1005
- ...typeof body.userId === "string" ? { userId: body.userId } : {},
1006
- ...typeof body.username === "string" ? { username: body.username } : {},
1007
- roleCodes,
1008
- ...typeof body.primaryRole === "string" ? { primaryRole: body.primaryRole } : {},
1009
- ...systemKeys.length === 0 ? {} : { systemKeys },
1010
- ...typeof body.departmentCode === "string" || body.departmentCode === null ? { departmentCode: body.departmentCode } : {},
1011
- ...permissions === void 0 ? {} : { permissions },
1012
- ...isRecord$1(body.dataScope) ? { dataScope: body.dataScope } : {},
1013
- ...review === void 0 ? {} : { review },
1014
- ...typeof body.canReview === "boolean" ? { canReview: body.canReview } : {},
1015
- ...typeof body.canReviewGlobal === "boolean" ? { canReviewGlobal: body.canReviewGlobal } : {}
1016
- };
1017
- }
1018
- //#endregion
1019
- //#region src/connector-state.ts
1020
- /**
1021
- * The DataOps connector's workspace-visible state and skill-center catalogue.
1022
- *
1023
- * The skill center is skill-first, with connectors as its fourth tab. DataOps contributes one
1024
- * connector whose capability rows are derived from the same scope that drives tool disclosure;
1025
- * a capability the account cannot use is omitted rather than rendered as a disabled placeholder.
1026
- *
1027
- * This module owns only state and presentation. It never authorizes a tool call or a DataOps
1028
- * request: the backend remains the final boundary.
1029
- *
1030
- * @module connector-state
1031
- */
1032
- /** Same-origin route the skill center's connector tab reads and writes. */
1033
- const CONNECTORS_PATH = "/api/dsh-skill-center/connectors";
1034
- /** Connector id shown in the skill center. */
1035
- const DATAOPS_CONNECTOR_ID = "dataops-managed";
1036
- /** Resolve the persisted state file without depending on a global DSH path. */
1037
- const CONNECTOR_STATE_PATH = join(process.env.DSH_HOME?.trim() || "/workspace/.dataops/dsh", "dataops-managed", "connector-state.json");
1038
- /**
1039
- * Capability definitions before permission filtering.
1040
- *
1041
- * The set follows `dataops/docs/dataops-connector-development-spec.md` §2.3's credential list.
1042
- * `approval.push` was renamed to `resource.manage` when the capability grew from approval push
1043
- * into resource approval and authorization. Skill plaza and review queue are governed by
1044
- * `skill:*` permissions and stay out of the connector's capability switches.
1045
- */
1046
- const CAPABILITIES = [
1047
- {
1048
- id: "data.query",
1049
- name: "数据查询",
1050
- description: "通过 DataOps 数据查询能力回答业务问题",
1051
- defaultEnabled: true,
1052
- visible: () => true,
1053
- allowed: () => true
1054
- },
1055
- {
1056
- id: "resource.manage",
1057
- name: "资源管理",
1058
- description: "在对话中批量审批资源申请,给用户或角色授予资源访问权限",
1059
- defaultEnabled: true,
1060
- visible: (scope) => isAdmin(scope),
1061
- allowed: (scope) => isAdmin(scope)
1062
- },
1063
- {
1064
- id: "admin.manage",
1065
- name: "万相中台管理",
1066
- description: "登录万相中台后台执行管理动作",
1067
- defaultEnabled: true,
1068
- visible: (scope) => isAdmin(scope),
1069
- allowed: (scope) => isAdmin(scope)
1070
- }
1071
- ];
1072
- /**
1073
- * Persisted ids that moved to a new capability id.
1074
- *
1075
- * `approval.push` shipped before the capability grew from approval push into resource
1076
- * approval and authorization. Its stored toggle carries over to `resource.manage`; when both
1077
- * keys are present the current id wins.
1078
- */
1079
- const CAPABILITY_ALIASES = { "approval.push": "resource.manage" };
1080
- /** The ids the catalogue accepts; any other persisted key is a legacy value. */
1081
- const CAPABILITY_IDS = CAPABILITIES.map((capability) => capability.id);
1082
- /**
1083
- * Keep only boolean values for known capability ids.
1084
- *
1085
- * A state file written before the catalogue changed may still hold retired ids. Those keys are
1086
- * ignored rather than treated as a corrupt file; a missing new key takes the capability's
1087
- * `defaultEnabled`.
1088
- * @param value - the `capabilities` member of a parsed state file.
1089
- * @returns the readable toggles, keyed by current capability id.
1090
- */
1091
- function migrateCapabilities(value) {
1092
- if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
1093
- const stored = value;
1094
- const capabilities = {};
1095
- for (const id of CAPABILITY_IDS) if (typeof stored[id] === "boolean") capabilities[id] = stored[id];
1096
- for (const [legacyId, id] of Object.entries(CAPABILITY_ALIASES)) if (capabilities[id] === void 0 && typeof stored[legacyId] === "boolean") capabilities[id] = stored[legacyId];
1097
- return capabilities;
1098
- }
1099
- /** Read state; a missing or corrupt file is a safe disabled state. */
1100
- async function readConnectorState(path = CONNECTOR_STATE_PATH) {
1101
- try {
1102
- const payload = JSON.parse(await readFile(path, "utf8"));
1103
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return {
1104
- enabled: false,
1105
- capabilities: {}
1106
- };
1107
- const record = payload;
1108
- return {
1109
- enabled: record.enabled === true,
1110
- capabilities: migrateCapabilities(record.capabilities)
1111
- };
1112
- } catch {
1113
- return {
1114
- enabled: false,
1115
- capabilities: {}
1116
- };
1117
- }
1118
- }
1119
- /** Persist state atomically. */
1120
- async function writeConnectorState(state, path = CONNECTOR_STATE_PATH) {
1121
- await mkdir(dirname(path), { recursive: true });
1122
- const temporary = path + ".tmp-" + process.pid.toString();
1123
- const payload = {
1124
- enabled: state.enabled,
1125
- capabilities: migrateCapabilities(state.capabilities)
1126
- };
1127
- await writeFile(temporary, JSON.stringify(payload, null, 2), "utf8");
1128
- await rename(temporary, path);
1129
- }
1130
- /** Build the connector row for one current scope. */
1131
- function buildConnectorView(scope, state) {
1132
- const capabilities = scope === void 0 ? [] : CAPABILITIES.filter((capability) => capability.visible(scope) && capability.allowed(scope)).map((capability) => ({
1133
- id: capability.id,
1134
- name: capability.name,
1135
- description: capability.description,
1136
- enabled: state.capabilities[capability.id] ?? capability.defaultEnabled,
1137
- permitted: true
1138
- }));
1139
- return {
1140
- id: DATAOPS_CONNECTOR_ID,
1141
- name: "万相AI中台连接器",
1142
- vendor: "DataOps",
1143
- description: "把万相AI中台的技能、审核和数据能力接入当前工作区。",
1144
- enabled: state.enabled,
1145
- connected: scope !== void 0,
1146
- capabilities
1147
- };
1148
- }
1149
- /** Whether one capability id is in the fixed catalogue. */
1150
- function hasCapability(id) {
1151
- return CAPABILITIES.some((capability) => capability.id === id);
1152
- }
1153
- //#endregion
1154
- //#region src/collect-api.ts
1155
- /**
1156
- * DataOps spreadsheet-import transport for the collection skill.
1157
- *
1158
- * The host reads a workspace attachment, uploads it as multipart, asks DataOps for a
1159
- * create-table or existing-table plan, and only executes when the model calls the
1160
- * execute tool after the user's plan confirmation. Nothing here creates a table on
1161
- * preview/plan; execution is the single mutating call.
1162
- *
1163
- * @module collect-api
1164
- */
1165
- /** Largest spreadsheet the DataOps importer accepts. */
1166
- const COLLECT_FILE_MAX_BYTES = 20971520;
1167
- /** Extensions the importer understands. */
1168
- const SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
1169
- ".xlsx",
1170
- ".xls",
1171
- ".csv",
1172
- ".tsv"
1173
- ]);
1174
- const statusError = (result, operation) => {
1175
- const body = result.body;
1176
- const reason = typeof body?.error === "string" ? body.error : typeof body?.message === "string" ? body.message : "";
1177
- if (result.status === 401) return /* @__PURE__ */ new Error("Unauthorized (401): DataOps session expired");
1178
- if (result.status === 403) return /* @__PURE__ */ new Error("Forbidden (403): " + (reason || "the current role may not import resources"));
1179
- return /* @__PURE__ */ new Error(`${operation} failed: HTTP ${result.status}${reason ? ": " + reason : ""}`);
1180
- };
1181
- const unwrap$1 = (result, operation) => {
1182
- if (result.status < 200 || result.status >= 300) throw statusError(result, operation);
1183
- return result.body;
1184
- };
1185
- /** Read and validate one spreadsheet attachment from the workspace. */
1186
- const readCollectFile = async (filePath) => {
1187
- const trimmed = filePath.trim();
1188
- if (!trimmed) throw new Error("file_path is required");
1189
- const extension = extname(trimmed).toLowerCase();
1190
- if (!SUPPORTED_EXTENSIONS.has(extension)) throw new Error(`unsupported spreadsheet extension "${extension || "(none)"}"; expected .xlsx, .xls, .csv or .tsv`);
1191
- const info = await stat(trimmed);
1192
- if (!info.isFile()) throw new Error(`not a regular file: ${trimmed}`);
1193
- if (info.size <= 0) throw new Error(`empty file: ${trimmed}`);
1194
- if (info.size > 20971520) throw new Error(`file exceeds the ${(COLLECT_FILE_MAX_BYTES / 1024 / 1024).toFixed(0)}MB import limit`);
1195
- return {
1196
- buffer: await readFile(trimmed),
1197
- fileName: basename(trimmed),
1198
- sizeBytes: info.size
1199
- };
1200
- };
1201
- /** Spreadsheet import calls bound to one workspace credential. */
1202
- var CollectApi = class {
1203
- reviewApi;
1204
- constructor(reviewApi) {
1205
- this.reviewApi = reviewApi;
1206
- }
1207
- async preview(filePath) {
1208
- const file = await readCollectFile(filePath);
1209
- const form = new FormData();
1210
- form.append("file", new Blob([new Uint8Array(file.buffer)]), file.fileName);
1211
- const result = await this.reviewApi.request("/api/resources/spreadsheet-import/preview", {
1212
- method: "POST",
1213
- body: form
1214
- });
1215
- return unwrap$1(result, "spreadsheet preview");
1216
- }
1217
- async dataSources() {
1218
- const result = await this.reviewApi.request("/api/resources/spreadsheet-import/data-sources", { method: "GET" });
1219
- const body = unwrap$1(result, "import data sources");
1220
- return Array.isArray(body.dataSources) ? body.dataSources : [];
1221
- }
1222
- async plan(payload) {
1223
- const result = await this.reviewApi.request("/api/resources/spreadsheet-import/plan", {
1224
- method: "POST",
1225
- body: JSON.stringify(payload)
1226
- });
1227
- return unwrap$1(result, "spreadsheet plan");
1228
- }
1229
- async execute(payload) {
1230
- const result = await this.reviewApi.request("/api/resources/spreadsheet-import/execute", {
1231
- method: "POST",
1232
- body: JSON.stringify(payload)
1233
- });
1234
- return unwrap$1(result, "spreadsheet execute");
1235
- }
1236
- async listResources(query = "", limit = 20) {
1237
- const result = await this.reviewApi.request("/api/resources", { method: "GET" });
1238
- const body = unwrap$1(result, "resource list");
1239
- const rows = Array.isArray(body.resources) ? body.resources : [];
1240
- const keyword = query.trim().toLowerCase();
1241
- return rows.filter((row) => row.resourceType === void 0 || row.resourceType === "TABLE").filter((row) => {
1242
- if (!keyword) return true;
1243
- return [
1244
- row.chineseName,
1245
- row.sourceTable,
1246
- row.urn
1247
- ].filter(Boolean).join(" ").toLowerCase().includes(keyword);
1248
- }).slice(0, Math.max(1, Math.min(50, limit)));
1249
- }
1250
- };
1251
- //#endregion
1252
- //#region src/resource-management-api.ts
1253
- /**
1254
- * DataOps resource-management transport: pending approval tasks, existing access grants,
1255
- * batch grant/revoke, and approval decisions. Disclosure is handled by tool-scope; this file
1256
- * only speaks to the existing DataOps APIs.
1257
- */
1258
- const reasonOf = (body) => {
1259
- if (typeof body !== "object" || body === null || Array.isArray(body)) return "";
1260
- const record = body;
1261
- if (typeof record.error === "string") return record.error;
1262
- if (typeof record.message === "string") return record.message;
1263
- const details = record.details;
1264
- return Array.isArray(details?.errors) ? details.errors.filter((v) => typeof v === "string").join("; ") : "";
1265
- };
1266
- const unwrap = (result, operation) => {
1267
- if (result.status < 200 || result.status >= 300) {
1268
- const reason = reasonOf(result.body);
1269
- throw new Error(operation + " failed: HTTP " + result.status.toString() + (reason ? ": " + reason : ""));
1270
- }
1271
- return result.body;
1272
- };
1273
- /** Thin typed wrapper over the existing DataOps REST endpoints. */
1274
- var ResourceManagementApi = class {
1275
- reviewApi;
1276
- constructor(reviewApi) {
1277
- this.reviewApi = reviewApi;
1278
- }
1279
- async call(path, init = {}) {
1280
- return unwrap(await this.reviewApi.request(path, init), path);
1281
- }
1282
- async listPendingTasks(query = "", limit = 20) {
1283
- const params = new URLSearchParams({
1284
- status: "pending",
1285
- page: "1"
1286
- });
1287
- const keyword = query.trim();
1288
- if (keyword) params.set("keyword", keyword);
1289
- const rows = (await this.call("/api/tasks?" + params.toString(), { method: "GET" })).tasks;
1290
- return Array.isArray(rows) ? rows.filter((row) => typeof row === "object" && row !== null).slice(0, Math.max(1, Math.min(100, limit))) : [];
1291
- }
1292
- async listGrants(resourceId) {
1293
- const rows = (await this.call("/api/resources/" + resourceId.toString() + "/access-grants", { method: "GET" })).grants;
1294
- return Array.isArray(rows) ? rows.filter((row) => typeof row === "object" && row !== null) : [];
1295
- }
1296
- async listApplications() {
1297
- const rows = (await this.call("/api/tasks/asset-access-applications", { method: "GET" })).applications;
1298
- return Array.isArray(rows) ? rows.filter((row) => typeof row === "object" && row !== null) : [];
1299
- }
1300
- async replaceGrants(resourceId, grants) {
1301
- return this.call("/api/resources/" + resourceId.toString() + "/access-grants", {
1302
- method: "PUT",
1303
- body: JSON.stringify({ grants })
1304
- });
1305
- }
1306
- async getTask(taskId) {
1307
- const task = (await this.call("/api/tasks/" + taskId.toString(), { method: "GET" })).task;
1308
- if (typeof task !== "object" || task === null) throw new Error("task detail is unavailable");
1309
- return task;
1310
- }
1311
- async decideTask(decision) {
1312
- const action = decision.decision === "approve" ? "complete" : "reject";
1313
- return this.call("/api/tasks/" + decision.taskId.toString() + "/user-tasks/" + encodeURIComponent(decision.userTaskId) + "/" + action, {
1314
- method: "POST",
1315
- headers: { "idempotency-key": decision.idempotencyKey?.trim() || "dataops-managed-" + randomUUID() },
1316
- body: JSON.stringify({
1317
- expectedVersion: decision.expectedVersion ?? 0,
1318
- comment: decision.comment?.trim() || (decision.decision === "approve" ? "同意" : "驳回")
1319
- })
1320
- });
1321
- }
1322
- };
1323
- //#endregion
1324
- //#region src/api-docs.ts
1325
- /** Raised when the upstream body is not an OpenAPI document this module can search. */
1326
- var ApiDocsUnavailableError = class extends Error {};
1327
- /** HTTP methods a path item may declare, in a stable presentation order. */
1328
- const HTTP_METHODS = [
1329
- "get",
1330
- "post",
1331
- "put",
1332
- "patch",
1333
- "delete",
1334
- "head",
1335
- "options",
1336
- "trace"
1337
- ];
1338
- /** Cap on returned operations, so one broad query cannot flood a model turn. */
1339
- const MAX_RESULTS = 50;
1340
- /** Cap on projected schema properties. */
1341
- const MAX_PROPERTIES = 25;
1342
- /** Cap on projected parameters. */
1343
- const MAX_PARAMETERS = 25;
1344
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1345
- const strings = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : void 0;
1346
- const normalized = (value) => (value ?? "").trim().toLowerCase();
1347
- /** Split a query into whitespace-separated keywords; an empty query matches everything. */
1348
- const keywords = (query) => normalized(query).split(/\s+/u).filter((token) => token !== "");
1349
- /** Resolve one local JSON pointer such as `#/components/schemas/ReviewQuery`. */
1350
- function resolvePointer(document, ref) {
1351
- if (!ref.startsWith("#/")) return void 0;
1352
- let current = document;
1353
- for (const raw of ref.slice(2).split("/")) {
1354
- if (!isRecord(current)) return void 0;
1355
- const key = decodeURIComponent(raw).replace(/~1/gu, "/").replace(/~0/gu, "~");
1356
- current = current[key];
1357
- }
1358
- return current;
1359
- }
1360
- /** Resolve one `$ref` object one level, leaving a non-reference value unchanged. */
1361
- function dereference(value, document, depth = 0) {
1362
- if (!isRecord(value) || typeof value.$ref !== "string" || depth >= 4) return value;
1363
- return dereference(resolvePointer(document, value.$ref), document, depth + 1);
1364
- }
1365
- /** The final segment of a local reference, used as a stable type label. */
1366
- function refName(ref) {
1367
- const segment = ref.split("/").pop() ?? ref;
1368
- return decodeURIComponent(segment).replace(/~1/gu, "/").replace(/~0/gu, "~");
1369
- }
1370
- /** A short type label for one schema, resolving one local reference chain when useful. */
1371
- function schemaType(schema, document, depth = 0) {
1372
- const resolved = dereference(schema, document, depth);
1373
- if (!isRecord(resolved)) return "unknown";
1374
- if (typeof resolved.type === "string") {
1375
- if (resolved.type === "array" && isRecord(resolved.items)) return schemaType(resolved.items, document, depth + 1) + "[]";
1376
- return resolved.type;
1377
- }
1378
- if (isRecord(resolved.properties)) return "object";
1379
- if (resolved.items !== void 0) return "array";
1380
- if (typeof resolved.$ref === "string") return refName(resolved.$ref);
1381
- return "unknown";
1382
- }
1383
- /** Project one schema into a bounded summary without following cycles forever. */
1384
- function summarizeSchema(schema, document, depth = 0) {
1385
- if (!isRecord(schema)) return null;
1386
- const ref = typeof schema.$ref === "string" ? refName(schema.$ref) : void 0;
1387
- const resolved = dereference(schema, document, depth);
1388
- if (!isRecord(resolved)) return ref === void 0 ? null : { ref };
1389
- const required = strings(resolved.required) ?? [];
1390
- const requiredSet = new Set(required);
1391
- const properties = isRecord(resolved.properties) ? Object.entries(resolved.properties).slice(0, MAX_PROPERTIES).map(([name, property]) => ({
1392
- name,
1393
- type: schemaType(property, document, depth + 1),
1394
- required: requiredSet.has(name)
1395
- })) : void 0;
1396
- const type = typeof resolved.type === "string" ? resolved.type : isRecord(resolved.properties) ? "object" : resolved.items === void 0 ? void 0 : "array";
1397
- return {
1398
- ...type === void 0 ? {} : { type },
1399
- ...ref === void 0 ? {} : { ref },
1400
- ...required.length === 0 ? {} : { required },
1401
- ...properties === void 0 ? {} : { properties }
1402
- };
1403
- }
1404
- /** Merge path-level and operation-level parameters; the operation wins on name+location. */
1405
- function summarizeParameters(pathItem, operation, document) {
1406
- const merged = /* @__PURE__ */ new Map();
1407
- for (const source of [pathItem.parameters, operation.parameters]) {
1408
- if (!Array.isArray(source)) continue;
1409
- for (const raw of source) {
1410
- const parameter = dereference(raw, document);
1411
- if (!isRecord(parameter)) continue;
1412
- if (typeof parameter.name !== "string" || typeof parameter.in !== "string") continue;
1413
- const schema = parameter.schema !== void 0 ? parameter.schema : parameter;
1414
- merged.set(parameter.in + ":" + parameter.name, {
1415
- name: parameter.name,
1416
- in: parameter.in,
1417
- required: parameter.required === true,
1418
- type: schemaType(schema, document)
1419
- });
1420
- }
1421
- }
1422
- return [...merged.values()].slice(0, MAX_PARAMETERS);
1423
- }
1424
- /** Describe the request body's chosen media type and bounded schema fields. */
1425
- function summarizeRequestBody(operation, document) {
1426
- const body = dereference(operation.requestBody, document);
1427
- if (!isRecord(body) || !isRecord(body.content)) return null;
1428
- const contentTypes = Object.keys(body.content);
1429
- if (contentTypes.length === 0) return null;
1430
- const preferred = contentTypes.includes("application/json") ? "application/json" : contentTypes[0];
1431
- const media = body.content[preferred];
1432
- const schema = isRecord(media) ? summarizeSchema(media.schema, document) : null;
1433
- return {
1434
- required: body.required === true,
1435
- contentTypes,
1436
- schema
1437
- };
1438
- }
1439
- /** The security requirement list that applies to one operation. */
1440
- function summarizeSecurity(operation, document) {
1441
- return (Array.isArray(operation.security) ? operation.security : Array.isArray(document.security) ? document.security : []).filter(isRecord);
1442
- }
1443
- /** Read one operation into its compact projection. */
1444
- function compactOperation(method, path, pathItem, operation, document) {
1445
- return {
1446
- method: method.toUpperCase(),
1447
- path,
1448
- operationId: typeof operation.operationId === "string" ? operation.operationId : null,
1449
- summary: typeof operation.summary === "string" ? operation.summary : null,
1450
- tags: strings(operation.tags) ?? [],
1451
- parameters: summarizeParameters(pathItem, operation, document),
1452
- requestBody: summarizeRequestBody(operation, document),
1453
- security: summarizeSecurity(operation, document)
1454
- };
1455
- }
1456
- /** Whether one operation passes every supplied filter. */
1457
- function matches(operation, filters, tokens) {
1458
- if (filters.tag !== "" && !operation.tags.some((tag) => tag.toLowerCase() === filters.tag)) return false;
1459
- if (filters.path !== "" && !operation.path.toLowerCase().includes(filters.path)) return false;
1460
- if (filters.operationId !== "" && !(operation.operationId ?? "").toLowerCase().includes(filters.operationId)) return false;
1461
- if (filters.method !== "" && operation.method !== filters.method) return false;
1462
- if (tokens.length === 0) return true;
1463
- const haystack = [
1464
- operation.path,
1465
- operation.operationId ?? "",
1466
- operation.summary ?? "",
1467
- operation.description,
1468
- operation.tags.join(" ")
1469
- ].join(" ").toLowerCase();
1470
- return tokens.every((token) => haystack.includes(token));
1471
- }
1472
- /** Relevance used only to order matches; equal scores keep the document order. */
1473
- function scoreOf(operation, tokens) {
1474
- if (tokens.length === 0) return 0;
1475
- let score = 0;
1476
- const operationId = (operation.operationId ?? "").toLowerCase();
1477
- const path = operation.path.toLowerCase();
1478
- const summary = (operation.summary ?? "").toLowerCase();
1479
- const tags = operation.tags.map((tag) => tag.toLowerCase());
1480
- const description = operation.description.toLowerCase();
1481
- for (const token of tokens) {
1482
- if (operationId === token) score += 5;
1483
- else if (operationId.includes(token)) score += 3;
1484
- if (path.includes(token)) score += 2;
1485
- if (summary.includes(token)) score += 1;
1486
- if (tags.some((tag) => tag.includes(token))) score += 1;
1487
- if (description.includes(token)) score += 2;
1488
- }
1489
- return score;
1490
- }
1491
- /**
1492
- * Search one parsed OpenAPI document.
1493
- * @param document - Parsed `/api/openapi.json` body.
1494
- * @param filters - Keyword, tag, path, operationId and method filters.
1495
- * @returns Matching operations, bounded and ordered by relevance.
1496
- * @throws ApiDocsUnavailableError when the document has no searchable `paths` object.
1497
- */
1498
- function searchOpenApiDocument(document, filters = {}) {
1499
- if (!isRecord(document)) throw new ApiDocsUnavailableError("DataOps API docs are unavailable: the response is not an OpenAPI document");
1500
- if (!isRecord(document.paths)) throw new ApiDocsUnavailableError("DataOps API docs are unavailable: the document has no paths object");
1501
- const wanted = {
1502
- tag: normalized(filters.tag),
1503
- path: normalized(filters.path),
1504
- operationId: normalized(filters.operation_id),
1505
- method: normalized(filters.method)
1506
- };
1507
- const tokens = keywords(filters.query);
1508
- const matched = [];
1509
- let index = 0;
1510
- for (const [path, rawPathItem] of Object.entries(document.paths)) {
1511
- const pathItem = dereference(rawPathItem, document);
1512
- if (!isRecord(pathItem)) continue;
1513
- for (const method of HTTP_METHODS) {
1514
- const operation = pathItem[method];
1515
- if (!isRecord(operation)) continue;
1516
- const candidate = {
1517
- method,
1518
- path,
1519
- operationId: typeof operation.operationId === "string" ? operation.operationId : null,
1520
- summary: typeof operation.summary === "string" ? operation.summary : null,
1521
- tags: strings(operation.tags) ?? [],
1522
- description: typeof operation.description === "string" ? operation.description : "",
1523
- pathItem,
1524
- operation,
1525
- index
1526
- };
1527
- index += 1;
1528
- if (!matches(candidate, wanted, tokens)) continue;
1529
- matched.push({
1530
- operation: candidate,
1531
- score: scoreOf(candidate, tokens)
1532
- });
1533
- }
1534
- }
1535
- matched.sort((left, right) => right.score - left.score || left.operation.index - right.operation.index);
1536
- const results = matched.slice(0, MAX_RESULTS).map(({ operation }) => compactOperation(operation.method, operation.path, operation.pathItem, operation.operation, document));
1537
- const info = isRecord(document.info) ? document.info : {};
1538
- return {
1539
- title: typeof info.title === "string" ? info.title : null,
1540
- version: typeof info.version === "string" ? info.version : null,
1541
- openapi: typeof document.openapi === "string" ? document.openapi : typeof document.swagger === "string" ? "swagger " + document.swagger : null,
1542
- total: matched.length,
1543
- returned: results.length,
1544
- truncated: matched.length > results.length,
1545
- results
1546
- };
1547
- }
1548
- //#endregion
1549
- //#region src/tool-output.ts
1550
- /** An open object schema: tools declare their canonical shape in code and docs. */
1551
- const OPEN_OBJECT_SCHEMA = {
1552
- type: "object",
1553
- additionalProperties: true
1554
- };
1555
- /** Render one canonical value as pretty JSON text. */
1556
- const renderJson = (_args, value) => [{
1557
- type: "text",
1558
- text: JSON.stringify(value, null, 2)
1559
- }];
1560
- //#endregion
1561
- //#region src/tools.ts
1562
- /** Parse one plaza response body into rows without trusting its shape. */
1563
- function rowsOf(body) {
1564
- if (Array.isArray(body)) return body.filter((row) => typeof row === "object" && row !== null);
1565
- if (typeof body === "object" && body !== null && Array.isArray(body.skills)) return body.skills.filter((row) => typeof row === "object" && row !== null);
1566
- return [];
1567
- }
1568
- const forbidden = (message) => /* @__PURE__ */ new Error("Forbidden (403): " + message);
1569
- /**
1570
- * Build every managed tool definition.
1571
- *
1572
- * The definitions are built once; `readScope` is a live getter so a tool that survives a role
1573
- * change reports the scope the manager currently holds instead of the one it was registered
1574
- * with. An undefined scope can only be observed by an in-flight call during disposal, where the
1575
- * safe behavior is to show only the public catalogue.
1576
- * @param ctx - Host context used for local skills, approval and audit.
1577
- * @param reviewApi - Same-origin bridge holding the workspace JWT.
1578
- * @param readScope - Live accessor for the manager's current scope.
1579
- * @returns One definition per managed tool name.
1580
- */
1581
- function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
1582
- const collectApi = new CollectApi(reviewApi);
1583
- const resourceManagementApi = new ResourceManagementApi(reviewApi);
1584
- const approve = async (tool, exec, reason) => {
1585
- if (exec.agent === void 0) throw new Error(tool + " requires an initiating agent");
1586
- const outcome = await ctx.approval.request({
1587
- agent: exec.agent,
1588
- toolName: tool,
1589
- callId: exec.callId,
1590
- signal: exec.signal,
1591
- reason
1592
- });
1593
- if (outcome !== "allowed-once") throw new Error(tool + " approval was " + outcome);
1594
- };
1595
- const audit = (tool, exec, detail) => {
1596
- try {
1597
- const agent = exec.agent;
1598
- ctx.logger.info("[audit] " + tool + " " + JSON.stringify({
1599
- sessionId: agent?.session?.id ?? null,
1600
- callId: exec.callId,
1601
- ...detail
1602
- }));
1603
- } catch {}
1604
- };
1605
- const call = async (path, init = {}) => {
1606
- const result = await reviewApi.request(path, init);
1607
- if (result.status === 401) throw new Error("Unauthorized (401): DataOps session expired");
1608
- const detail = result.body;
1609
- const reason = typeof detail?.error === "string" ? detail.error : typeof detail?.message === "string" ? detail.message : "";
1610
- if (result.status === 403) throw forbidden(reason || "the current role may not perform this action");
1611
- if (result.status === 409) throw new Error("Conflict (409): " + (reason || "the skill still has installations"));
1612
- if (result.status < 200 || result.status >= 300) throw new Error("DataOps " + path + " failed: HTTP " + result.status.toString() + (reason ? ": " + reason : ""));
1613
- return result.body;
1614
- };
1615
- const listSkills = async (scope, includeLocal) => {
1616
- const mine = rowsOf(await call("/api/ai/skill-plaza/skills?scope=mine"));
1617
- const publicRows = rowsOf(await call("/api/ai/skill-plaza/skills"));
1618
- const admin = isAdmin(scope) ? rowsOf(await call("/api/ai/skill-plaza/admin/skills")) : [];
1619
- const byId = /* @__PURE__ */ new Map();
1620
- for (const row of [
1621
- ...mine,
1622
- ...publicRows,
1623
- ...admin
1624
- ]) if (typeof row.id === "number") byId.set(row.id, {
1625
- ...byId.get(row.id),
1626
- ...row
1627
- });
1628
- const rows = [...byId.values()];
1629
- return {
1630
- catalog: {
1631
- local: includeLocal ? (await readLocalSkills(ctx)).map((skill) => ({
1632
- name: skill.name,
1633
- description: skill.description ?? null,
1634
- source: "local"
1635
- })) : [],
1636
- pending: rows.filter((row) => row.reviewStatus === "pending"),
1637
- approved: rows.filter((row) => row.reviewStatus === "approved"),
1638
- rejected: rows.filter((row) => row.reviewStatus === "rejected")
1639
- },
1640
- canReview: canReview(scope),
1641
- isAdmin: isAdmin(scope),
1642
- isDepartmentAdmin: isDepartmentAdmin(scope),
1643
- departmentCode: scope.departmentCode ?? null,
1644
- skills: rows
1645
- };
1646
- };
1647
- /**
1648
- * Build the enable/disable pair.
1649
- *
1650
- * The two tools share one body so their approval reason, audit detail and endpoint stay in
1651
- * step; only the verb and the boolean they send differ.
1652
- */
1653
- function defineSkillStatusTool(enabled) {
1654
- const name = enabled ? "skill_enable" : "skill_disable";
1655
- return defineTool({
1656
- name,
1657
- description: (enabled ? "Enable" : "Disable") + " one plaza skill for distribution. Administrator only. Requires user approval; audited.",
1658
- parameters: { skill_id: {
1659
- type: "number",
1660
- required: true,
1661
- description: "Plaza skill id."
1662
- } },
1663
- output: {
1664
- schema: OPEN_OBJECT_SCHEMA,
1665
- render: renderJson
1666
- },
1667
- execute: async (args, exec) => {
1668
- await approve(name, exec, (enabled ? "Enable" : "Disable") + " skill " + args.skill_id.toString());
1669
- await call("/api/ai/skill-plaza/admin/skills/" + args.skill_id.toString() + "/status", {
1670
- method: "PATCH",
1671
- body: JSON.stringify({ enabled })
1672
- });
1673
- audit(name, exec, {
1674
- skillId: args.skill_id,
1675
- enabled
1676
- });
1677
- return {
1678
- skillId: args.skill_id,
1679
- enabled
1680
- };
1681
- }
1682
- });
1683
- }
1684
- const parseJsonObject = (tool, label, value) => {
1685
- if (value === void 0 || value.trim() === "") return void 0;
1686
- let parsed;
1687
- try {
1688
- parsed = JSON.parse(value);
1689
- } catch {
1690
- throw new Error(tool + ": " + label + " must be valid JSON");
1691
- }
1692
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(tool + ": " + label + " must be a JSON object");
1693
- return parsed;
1694
- };
1695
- const parseJsonArray = (tool, label, value) => {
1696
- if (value === void 0 || value.trim() === "") return [];
1697
- let parsed;
1698
- try {
1699
- parsed = JSON.parse(value);
1700
- } catch {
1701
- throw new Error(tool + ": " + label + " must be valid JSON");
1702
- }
1703
- if (!Array.isArray(parsed)) throw new Error(tool + ": " + label + " must be a JSON array");
1704
- return parsed;
1705
- };
1706
- /**
1707
- * Keep only the fields the DataOps execute DTO accepts. The plan tool returns
1708
- * `createSql`/`targetSchema`/`notes` beside `createTable`; if the model passes
1709
- * the whole plan (or rebuilds it after a table-name edit), the backend's
1710
- * `forbidNonWhitelisted` pipe rejects the call with a generic 400.
1711
- */
1712
- const normalizeCreatePlan = (tool, plan) => {
1713
- if (plan === void 0) return void 0;
1714
- const tableName = typeof plan.tableName === "string" ? plan.tableName.trim() : "";
1715
- if (!tableName) throw new Error(tool + ": create_plan_json.tableName is required");
1716
- const rawColumns = Array.isArray(plan.columns) ? plan.columns : [];
1717
- if (!rawColumns.length) throw new Error(tool + ": create_plan_json.columns is required");
1718
- const columns = rawColumns.map((raw, index) => {
1719
- const column = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
1720
- const sourceKey = typeof column.sourceKey === "string" ? column.sourceKey : "";
1721
- const name = typeof column.name === "string" ? column.name : "";
1722
- const chineseName = typeof column.chineseName === "string" ? column.chineseName : "";
1723
- const dataType = typeof column.dataType === "string" ? column.dataType : "";
1724
- if (!sourceKey || !name || !chineseName || !dataType) throw new Error(tool + ": create_plan_json.columns[" + index + "] needs sourceKey/name/chineseName/dataType");
1725
- return {
1726
- sourceKey,
1727
- name,
1728
- chineseName,
1729
- dataType,
1730
- ...typeof column.nullable === "boolean" ? { nullable: column.nullable } : {},
1731
- ...typeof column.comment === "string" ? { comment: column.comment } : {}
1732
- };
1733
- });
1734
- return {
1735
- tableName,
1736
- ...typeof plan.tableChineseName === "string" && plan.tableChineseName.trim() ? { tableChineseName: plan.tableChineseName.trim() } : {},
1737
- ...typeof plan.tableComment === "string" && plan.tableComment.trim() ? { tableComment: plan.tableComment.trim() } : {},
1738
- columns
1739
- };
1740
- };
1741
- return [
1742
- {
1743
- name: "skill_list",
1744
- definition: defineTool({
1745
- name: "skill_list",
1746
- description: "List skills in the DataOps skill centre: local workspace skills plus the caller's pending/rejected submissions and the approved plaza entries they may install. Scope follows the caller role (department admins see their department; ordinary users see their own and approved entries). Read-only.",
1747
- parameters: { include_local: {
1748
- type: "boolean",
1749
- description: "Include local workspace skills (default true)."
1750
- } },
1751
- output: {
1752
- schema: OPEN_OBJECT_SCHEMA,
1753
- render: renderJson
1754
- },
1755
- execute: async (args) => {
1756
- return await listSkills(readScope() ?? {}, args.include_local !== false);
1757
- }
1758
- })
1759
- },
1760
- {
1761
- name: "skill_get",
1762
- definition: defineTool({
1763
- name: "skill_get",
1764
- description: "Read one skill-centre entry by id: description, instruction, review status, review note, risk report and visibility. Only entries visible to the caller can be read.",
1765
- parameters: { skill_id: {
1766
- type: "number",
1767
- required: true,
1768
- description: "Skill/plaza id from skill_list."
1769
- } },
1770
- output: {
1771
- schema: OPEN_OBJECT_SCHEMA,
1772
- render: renderJson
1773
- },
1774
- execute: async (args) => {
1775
- const found = (await listSkills(readScope() ?? {}, false)).skills.find((row) => row.id === args.skill_id);
1776
- if (found === void 0) throw new Error("Skill not found or not visible: " + args.skill_id.toString());
1777
- return found;
1778
- }
1779
- })
1780
- },
1781
- {
1782
- name: "skill_submit",
1783
- definition: defineTool({
1784
- name: "skill_submit",
1785
- description: "Submit the caller's own skill for plaza review. When the workspace review switch is off DataOps approves immediately; otherwise the entry becomes pending. Requires user approval; audited.",
1786
- parameters: { skill_id: {
1787
- type: "number",
1788
- required: true,
1789
- description: "Own skill/plaza id."
1790
- } },
1791
- output: {
1792
- schema: OPEN_OBJECT_SCHEMA,
1793
- render: renderJson
1794
- },
1795
- execute: async (args, exec) => {
1796
- await approve("skill_submit", exec, "Submit skill " + args.skill_id.toString() + " for review");
1797
- const value = await call("/api/ai/skill-plaza/skills/" + args.skill_id.toString() + "/submit", {
1798
- method: "POST",
1799
- body: "{}"
1800
- });
1801
- audit("skill_submit", exec, { skillId: args.skill_id });
1802
- return value;
1803
- }
1804
- })
1805
- },
1806
- {
1807
- name: "skill_install",
1808
- definition: defineTool({
1809
- name: "skill_install",
1810
- description: "Install one approved, visible plaza skill into the caller's workspace. Requires user approval; audited. The secret-free result reports the local skill key.",
1811
- parameters: { skill_id: {
1812
- type: "number",
1813
- required: true,
1814
- description: "Plaza skill id."
1815
- } },
1816
- output: {
1817
- schema: OPEN_OBJECT_SCHEMA,
1818
- render: renderJson
1819
- },
1820
- execute: async (args, exec) => {
1821
- await approve("skill_install", exec, "Install skill " + args.skill_id.toString());
1822
- const value = await call("/api/ai/skill-plaza/install", {
1823
- method: "POST",
1824
- body: JSON.stringify({ skillId: args.skill_id })
1825
- });
1826
- audit("skill_install", exec, { skillId: args.skill_id });
1827
- return value;
1828
- }
1829
- })
1830
- },
1831
- {
1832
- name: "skill_uninstall",
1833
- definition: defineTool({
1834
- name: "skill_uninstall",
1835
- description: "Uninstall one skill from the caller's own workspace only: deletes the current user's installation record. The plaza entry, its review status, visibility and enabled flag are unchanged and no “unpublished” notification is sent. Requires user approval; audited.",
1836
- parameters: { skill_id: {
1837
- type: "number",
1838
- required: true,
1839
- description: "Plaza skill id."
1840
- } },
1841
- output: {
1842
- schema: OPEN_OBJECT_SCHEMA,
1843
- render: renderJson
1844
- },
1845
- execute: async (args, exec) => {
1846
- await approve("skill_uninstall", exec, "Uninstall skill " + args.skill_id.toString() + " from the current workspace");
1847
- const result = await call("/api/ai/skill-plaza/skills/" + args.skill_id.toString() + "/install", { method: "DELETE" });
1848
- audit("skill_uninstall", exec, {
1849
- skillId: args.skill_id,
1850
- scope: "installation-only",
1851
- removed: result.removed ?? null
1852
- });
1853
- return {
1854
- uninstalled: result.uninstalled === true,
1855
- removed: typeof result.removed === "number" ? result.removed : 0
1856
- };
1857
- }
1858
- })
1859
- },
1860
- {
1861
- name: "skill_enable",
1862
- definition: defineSkillStatusTool(true)
1863
- },
1864
- {
1865
- name: "skill_disable",
1866
- definition: defineSkillStatusTool(false)
1867
- },
1868
- {
1869
- name: "skill_unshare",
1870
- definition: defineTool({
1871
- name: "skill_unshare",
1872
- description: "Stop sharing one plaza skill (soft unpublish): the entry and its installations remain, review status/visibility are kept, and DataOps sends an “unpublished” notification. Owners may unshare their own entries; 超级管理员/管理员 any entry; 部门管理员 their department. Requires user approval; audited.",
1873
- parameters: { skill_id: {
1874
- type: "number",
1875
- required: true,
1876
- description: "Plaza skill id."
1877
- } },
1878
- output: {
1879
- schema: OPEN_OBJECT_SCHEMA,
1880
- render: renderJson
1881
- },
1882
- execute: async (args, exec) => {
1883
- await approve("skill_unshare", exec, "Unshare skill " + args.skill_id.toString());
1884
- await call("/api/ai/skill-plaza/skills/" + args.skill_id.toString(), { method: "DELETE" });
1885
- audit("skill_unshare", exec, {
1886
- skillId: args.skill_id,
1887
- effect: "soft-unpublish"
1888
- });
1889
- return {
1890
- unshared: args.skill_id,
1891
- effect: "plaza-sharing-disabled"
1892
- };
1893
- }
1894
- })
1895
- },
1896
- {
1897
- name: "skill_delete",
1898
- definition: defineTool({
1899
- name: "skill_delete",
1900
- description: "Permanently delete one plaza skill. This is not unshare: the record is removed, DataOps sends a “deleted” notification (not “unpublished”), and the audit entry records the permanent action. Requires confirm=true as a second confirmation; owners may delete their own entries, 超级管理员/管理员 any entry, 部门管理员 their department. If installations still exist the backend returns 409 and the error is passed through. Requires user approval; audited.",
1901
- parameters: {
1902
- skill_id: {
1903
- type: "number",
1904
- required: true,
1905
- description: "Plaza skill id."
1906
- },
1907
- confirm: {
1908
- type: "boolean",
1909
- required: true,
1910
- description: "Must be true: explicitly confirms permanent deletion."
1911
- }
1912
- },
1913
- output: {
1914
- schema: OPEN_OBJECT_SCHEMA,
1915
- render: renderJson
1916
- },
1917
- execute: async (args, exec) => {
1918
- if (args.confirm !== true) throw new Error("skill_delete requires confirm=true (permanent deletion)");
1919
- await approve("skill_delete", exec, "Permanently delete skill " + args.skill_id.toString());
1920
- await call("/api/ai/skill-plaza/skills/" + args.skill_id.toString() + "/permanent", { method: "DELETE" });
1921
- audit("skill_delete", exec, {
1922
- skillId: args.skill_id,
1923
- permanent: true
1924
- });
1925
- return {
1926
- deleted: args.skill_id,
1927
- permanent: true
1928
- };
1929
- }
1930
- })
1931
- },
1932
- {
1933
- name: "review_scan",
1934
- definition: defineTool({
1935
- name: "review_scan",
1936
- description: "Run the DataOps AI risk scan for skill and/or workflow ids. Reviewers only; the tool is disclosed to principals with review capability and skill read access, and DataOps still enforces the permission on every call. Read-only.",
1937
- parameters: {
1938
- skills: {
1939
- type: "array",
1940
- items: { type: "number" },
1941
- description: "Skill ids to scan."
1942
- },
1943
- workflows: {
1944
- type: "array",
1945
- items: { type: "string" },
1946
- description: "Workflow ids to scan."
1947
- }
1948
- },
1949
- output: {
1950
- schema: OPEN_OBJECT_SCHEMA,
1951
- render: renderJson
1952
- },
1953
- execute: async (args) => {
1954
- return await call("/api/ai/review/scan", {
1955
- method: "POST",
1956
- body: JSON.stringify({
1957
- skills: args.skills ?? [],
1958
- workflows: args.workflows ?? []
1959
- })
1960
- });
1961
- }
1962
- })
1963
- },
1964
- {
1965
- name: "review_decide",
1966
- definition: defineTool({
1967
- name: "review_decide",
1968
- description: "Approve or reject skills/workflows. Requires authorization.confirmed=true (the administrator explicitly confirmed), a reviewer role, resource scope and the review-decide capability; DataOps enforces all of them on the call. Requires a second user approval at tool level and writes an audit entry.",
1969
- parameters: {
1970
- skills: {
1971
- type: "array",
1972
- items: { type: "number" },
1973
- description: "Skill ids."
1974
- },
1975
- workflows: {
1976
- type: "array",
1977
- items: { type: "string" },
1978
- description: "Workflow ids."
1979
- },
1980
- decision: {
1981
- type: "string",
1982
- required: true,
1983
- description: "approve or reject."
1984
- },
1985
- note: {
1986
- type: "string",
1987
- description: "Review note (max 2000 chars)."
1988
- },
1989
- confirmed: {
1990
- type: "boolean",
1991
- required: true,
1992
- description: "Must be true: the administrator confirmed this decision."
1993
- }
1994
- },
1995
- output: {
1996
- schema: OPEN_OBJECT_SCHEMA,
1997
- render: renderJson
1998
- },
1999
- execute: async (args, exec) => {
2000
- if (args.confirmed !== true) throw new Error("authorization.confirmed=true is required for review_decide");
2001
- if (args.decision !== "approve" && args.decision !== "reject") throw new Error("decision must be approve or reject");
2002
- if ((args.skills ?? []).length === 0 && (args.workflows ?? []).length === 0) throw new Error("at least one skill or workflow id is required");
2003
- await approve("review_decide", exec, "Review " + args.decision + " for " + (args.skills ?? []).length.toString() + " skill(s) / " + (args.workflows ?? []).length.toString() + " workflow(s)");
2004
- const value = await call("/api/ai/review/decide", {
2005
- method: "POST",
2006
- body: JSON.stringify({
2007
- skills: args.skills ?? [],
2008
- workflows: args.workflows ?? [],
2009
- decision: args.decision,
2010
- note: args.note ?? "",
2011
- authorization: { confirmed: true }
2012
- })
2013
- });
2014
- audit("review_decide", exec, {
2015
- decision: args.decision,
2016
- skills: args.skills ?? [],
2017
- workflows: args.workflows ?? [],
2018
- confirmed: true
2019
- });
2020
- return value;
2021
- }
2022
- })
2023
- },
2024
- {
2025
- name: "review_notifications_list",
2026
- definition: defineTool({
2027
- name: "review_notifications_list",
2028
- description: "List the caller's review notifications and unread count. Read-only and always scoped to the current DataOps user.",
2029
- parameters: {
2030
- unread_only: {
2031
- type: "boolean",
2032
- description: "Only unread notifications."
2033
- },
2034
- limit: {
2035
- type: "number",
2036
- description: "Maximum rows (default 20)."
2037
- }
2038
- },
2039
- output: {
2040
- schema: OPEN_OBJECT_SCHEMA,
2041
- render: renderJson
2042
- },
2043
- execute: async (args) => {
2044
- const query = new URLSearchParams({
2045
- unreadOnly: args.unread_only === true ? "true" : "false",
2046
- limit: String(args.limit ?? 20)
2047
- });
2048
- return await call("/api/ai/review-notifications?" + query.toString());
2049
- }
2050
- })
2051
- },
2052
- {
2053
- name: "review_notifications_read",
2054
- definition: defineTool({
2055
- name: "review_notifications_read",
2056
- description: "Mark the caller's review notifications as read, either selected ids or all. Scoped to the current DataOps user; no secret is involved.",
2057
- parameters: {
2058
- ids: {
2059
- type: "array",
2060
- items: { type: "string" },
2061
- description: "Notification ids to mark read."
2062
- },
2063
- all: {
2064
- type: "boolean",
2065
- description: "Mark every notification read."
2066
- }
2067
- },
2068
- output: {
2069
- schema: OPEN_OBJECT_SCHEMA,
2070
- render: renderJson
2071
- },
2072
- execute: async (args, exec) => {
2073
- const value = await call("/api/ai/review-notifications/read", {
2074
- method: "POST",
2075
- body: JSON.stringify({
2076
- ids: args.ids ?? [],
2077
- all: args.all === true
2078
- })
2079
- });
2080
- audit("review_notifications_read", exec, {
2081
- count: args.ids?.length ?? 0,
2082
- all: args.all === true
2083
- });
2084
- return value;
2085
- }
2086
- })
2087
- },
2088
- {
2089
- name: "dataops_api_docs",
2090
- definition: defineTool({
2091
- name: "dataops_api_docs",
2092
- description: "Search the DataOps HTTP API reference (OpenAPI 3) for endpoint contracts. Super administrators only; read-only. Returns compact operations — method, path, operationId, summary, tags, parameters, request-body fields and security — filtered by keyword, tag, path, operationId or HTTP method. It only reads the fixed /api/openapi.json document and cannot execute arbitrary requests.",
2093
- parameters: {
2094
- query: {
2095
- type: "string",
2096
- description: "Case-insensitive keywords matched against path, operationId, summary, tags and description. All keywords must match."
2097
- },
2098
- tag: {
2099
- type: "string",
2100
- description: "Exact OpenAPI tag (case-insensitive)."
2101
- },
2102
- path: {
2103
- type: "string",
2104
- description: "Case-insensitive substring of the operation path."
2105
- },
2106
- operation_id: {
2107
- type: "string",
2108
- description: "Case-insensitive substring of the operationId."
2109
- },
2110
- method: {
2111
- type: "string",
2112
- description: "HTTP method: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS or TRACE."
2113
- }
2114
- },
2115
- output: {
2116
- schema: OPEN_OBJECT_SCHEMA,
2117
- render: renderJson
2118
- },
2119
- execute: async (args) => {
2120
- const result = await reviewApi.request("/api/openapi.json");
2121
- if (result.status === 401) throw new Error("Unauthorized (401): DataOps session expired; sign in again to read the API reference");
2122
- if (result.status === 403) throw new Error("Forbidden (403): the DataOps OpenAPI document is not available to this role");
2123
- if (result.status === 404) throw new Error("DataOps API docs are unavailable: /api/openapi.json is not configured (DATAOPS_OPENAPI_UNAVAILABLE)");
2124
- if (result.status === 503) throw new Error("DataOps API docs are unavailable: this workspace has no DataOps session");
2125
- if (result.status < 200 || result.status >= 300) throw new Error("DataOps API docs request failed: HTTP " + result.status.toString());
2126
- try {
2127
- return searchOpenApiDocument(result.body, args);
2128
- } catch (error) {
2129
- if (error instanceof ApiDocsUnavailableError) throw new Error(error.message);
2130
- throw error;
2131
- }
2132
- }
2133
- })
2134
- },
2135
- {
2136
- name: "dataops_collect_preview",
2137
- definition: defineTool({
2138
- name: "dataops_collect_preview",
2139
- description: "Parse one spreadsheet attachment from the workspace and return DataOps's preview plus the importable database destinations. Read-only: it does not create a table and does not write rows. Use this first in the data-collection skill, then ask the user to choose the destination when more than one is returned.",
2140
- parameters: {
2141
- file_path: {
2142
- type: "string",
2143
- required: true,
2144
- description: "Absolute or workspace-relative path to one .xlsx/.xls/.csv/.tsv file."
2145
- },
2146
- model_id: {
2147
- type: "number",
2148
- description: "Optional shared AI model id for the later plan call."
2149
- }
2150
- },
2151
- output: {
2152
- schema: OPEN_OBJECT_SCHEMA,
2153
- render: renderJson
2154
- },
2155
- execute: async (args, exec) => {
2156
- const preview = await collectApi.preview(args.file_path);
2157
- const dataSources = await collectApi.dataSources();
2158
- audit("dataops_collect_preview", exec, {
2159
- filePath: args.file_path,
2160
- sessionId: preview.sessionId,
2161
- dataSourceCount: dataSources.length
2162
- });
2163
- return {
2164
- sessionId: preview.sessionId,
2165
- preview,
2166
- dataSources
2167
- };
2168
- }
2169
- })
2170
- },
2171
- {
2172
- name: "dataops_collect_plan",
2173
- definition: defineTool({
2174
- name: "dataops_collect_plan",
2175
- description: "Generate a create-table plan or an existing-table field mapping for a parsed spreadsheet session. Read-only: DataOps only plans, it does not execute DDL or write rows. Call this after the user has chosen a data source; pass root_schema + root_table only when appending to an existing table.",
2176
- parameters: {
2177
- session_id: {
2178
- type: "string",
2179
- required: true,
2180
- description: "Session id returned by dataops_collect_preview."
2181
- },
2182
- data_source_urn: {
2183
- type: "string",
2184
- required: true,
2185
- description: "Destination URN from the preview result."
2186
- },
2187
- target_schema: {
2188
- type: "string",
2189
- description: "Existing-table schema; required when root_table is set."
2190
- },
2191
- target_table: {
2192
- type: "string",
2193
- description: "Existing table name; omit to create a new table."
2194
- },
2195
- model_id: {
2196
- type: "number",
2197
- description: "Optional shared AI model id."
2198
- }
2199
- },
2200
- output: {
2201
- schema: OPEN_OBJECT_SCHEMA,
2202
- render: renderJson
2203
- },
2204
- execute: async (args, exec) => {
2205
- const plan = await collectApi.plan({
2206
- sessionId: args.session_id,
2207
- dataSourceUrn: args.data_source_urn,
2208
- ...args.target_table ? { targetTable: {
2209
- schema: args.target_schema || "",
2210
- table: args.target_table
2211
- } } : {},
2212
- ...args.model_id === void 0 ? {} : { modelId: args.model_id }
2213
- });
2214
- audit("dataops_collect_plan", exec, {
2215
- sessionId: args.session_id,
2216
- dataSourceUrn: args.data_source_urn,
2217
- targetTable: args.target_table ?? null
2218
- });
2219
- return plan;
2220
- }
2221
- })
2222
- },
2223
- {
2224
- name: "dataops_collect_execute",
2225
- definition: defineTool({
2226
- name: "dataops_collect_execute",
2227
- description: "Execute one confirmed spreadsheet import: create a table (or write to an existing table), insert rows, and register the DataOps resource. This is the ONLY collection tool that mutates data. Call it only after the user explicitly confirms the read-only plan in natural language (e.g. 确认/开始吧); never call it while the plan is still being edited.",
2228
- parameters: {
2229
- session_id: {
2230
- type: "string",
2231
- required: true,
2232
- description: "Session id from dataops_collect_preview."
2233
- },
2234
- data_source_urn: {
2235
- type: "string",
2236
- required: true,
2237
- description: "Destination URN."
2238
- },
2239
- mode: {
2240
- type: "string",
2241
- required: true,
2242
- description: "CREATE_TABLE or EXISTING_TABLE."
2243
- },
2244
- target_schema: {
2245
- type: "string",
2246
- description: "Target schema for EXISTING_TABLE."
2247
- },
2248
- target_table: {
2249
- type: "string",
2250
- description: "Target table for EXISTING_TABLE."
2251
- },
2252
- create_plan_json: {
2253
- type: "string",
2254
- description: "Only plan.createTable (tableName/tableChineseName/tableComment/columns). Do not send createSql/targetSchema/notes; if the user edits the table name, call dataops_collect_plan again and pass its createTable."
2255
- },
2256
- mappings_json: {
2257
- type: "string",
2258
- description: "JSON array of {sourceKey,targetColumn} for EXISTING_TABLE."
2259
- },
2260
- resource_name: {
2261
- type: "string",
2262
- description: "Resource display name drafted by the plan and confirmed by the user."
2263
- },
2264
- resource_description: {
2265
- type: "string",
2266
- description: "Optional resource description."
2267
- },
2268
- resource_tags: {
2269
- type: "array",
2270
- items: { type: "string" },
2271
- description: "Optional resource tags."
2272
- },
2273
- ai_visible: {
2274
- type: "boolean",
2275
- description: "Whether AI may retrieve this resource. Defaults to true."
2276
- },
2277
- access_level: {
2278
- type: "string",
2279
- description: "PUBLIC, PROTECTED or PRIVATE. Defaults to PRIVATE."
2280
- }
2281
- },
2282
- output: {
2283
- schema: OPEN_OBJECT_SCHEMA,
2284
- render: renderJson
2285
- },
2286
- execute: async (args, exec) => {
2287
- if (args.mode !== "CREATE_TABLE" && args.mode !== "EXISTING_TABLE") throw new Error("dataops_collect_execute: mode must be CREATE_TABLE or EXISTING_TABLE");
2288
- const createPlan = normalizeCreatePlan("dataops_collect_execute", parseJsonObject("dataops_collect_execute", "create_plan_json", args.create_plan_json));
2289
- const mappings = parseJsonArray("dataops_collect_execute", "mappings_json", args.mappings_json);
2290
- if (args.mode === "CREATE_TABLE" && createPlan === void 0) throw new Error("dataops_collect_execute: create_plan_json is required for CREATE_TABLE");
2291
- if (args.mode === "EXISTING_TABLE" && (!args.target_schema || !args.target_table)) throw new Error("dataops_collect_execute: target_schema and target_table are required for EXISTING_TABLE");
2292
- const payload = {
2293
- sessionId: args.session_id,
2294
- dataSourceUrn: args.data_source_urn,
2295
- mode: args.mode,
2296
- mappings,
2297
- ...createPlan === void 0 ? {} : { createPlan },
2298
- ...args.target_schema && args.target_table ? { targetTable: {
2299
- schema: args.target_schema,
2300
- table: args.target_table
2301
- } } : {},
2302
- ...args.resource_name === void 0 ? {} : { resourceName: args.resource_name },
2303
- ...args.resource_description === void 0 ? {} : { resourceDescription: args.resource_description },
2304
- ...args.resource_tags === void 0 ? {} : { resourceTags: args.resource_tags },
2305
- ...args.ai_visible === void 0 ? {} : { aiVisible: args.ai_visible },
2306
- ...args.access_level === void 0 ? {} : { accessLevel: args.access_level }
2307
- };
2308
- const result = await collectApi.execute(payload);
2309
- const resource = result.resource;
2310
- audit("dataops_collect_execute", exec, {
2311
- sessionId: args.session_id,
2312
- mode: args.mode,
2313
- resourceId: resource?.id ?? null,
2314
- importedRows: result.importedRows ?? null
2315
- });
2316
- return result;
2317
- }
2318
- })
2319
- },
2320
- {
2321
- name: "dataops_collect_resources",
2322
- definition: defineTool({
2323
- name: "dataops_collect_resources",
2324
- description: "Search the current DataOps resource catalog for an append target. Read-only and scoped by DataOps resource visibility. Use it when the user chooses \"追加到已有资源\" instead of a remote select control.",
2325
- parameters: {
2326
- query: {
2327
- type: "string",
2328
- description: "Resource name, table name or URN keyword."
2329
- },
2330
- limit: {
2331
- type: "number",
2332
- description: "Maximum rows (default 20, max 50)."
2333
- }
2334
- },
2335
- output: {
2336
- schema: OPEN_OBJECT_SCHEMA,
2337
- render: renderJson
2338
- },
2339
- execute: async (args) => {
2340
- return { resources: await collectApi.listResources(args.query ?? "", args.limit ?? 20) };
2341
- }
2342
- })
2343
- },
2344
- {
2345
- name: "dataops_open_resource_tab",
2346
- definition: defineTool({
2347
- name: "dataops_open_resource_tab",
2348
- description: "Open or focus the DataOps resource tab in the right sidebar. This only navigates the browser: it does not grant access or mutate data. Use mode=focus after an import succeeds, grant for 分配权限, detail for 查看详情, and audit for 查看操作记录.",
2349
- parameters: {
2350
- resource_id: {
2351
- type: "number",
2352
- required: true,
2353
- description: "DataOps resource id."
2354
- },
2355
- resource_name: {
2356
- type: "string",
2357
- description: "Display name used as the tab subtitle."
2358
- },
2359
- mode: {
2360
- type: "string",
2361
- description: "focus | grant | detail | audit. Defaults to focus."
2362
- }
2363
- },
2364
- output: {
2365
- schema: OPEN_OBJECT_SCHEMA,
2366
- render: renderJson
2367
- },
2368
- execute: async (args, exec) => {
2369
- if (!Number.isSafeInteger(args.resource_id) || args.resource_id <= 0) throw new Error("dataops_open_resource_tab: resource_id must be a positive integer");
2370
- const requested = args.mode ?? "focus";
2371
- const mode = requested === "grant" || requested === "detail" || requested === "audit" ? requested : "focus";
2372
- const payload = collectHub.broadcast({
2373
- resourceId: args.resource_id,
2374
- resourceName: args.resource_name ?? null,
2375
- mode,
2376
- nonce: Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
2377
- });
2378
- audit("dataops_open_resource_tab", exec, {
2379
- resourceId: args.resource_id,
2380
- mode,
2381
- subscribers: collectHub.size()
2382
- });
2383
- return {
2384
- opened: collectHub.size() > 0,
2385
- mode,
2386
- resourceId: args.resource_id,
2387
- requestId: payload.requestId,
2388
- subscribers: collectHub.size()
2389
- };
2390
- }
2391
- })
2392
- },
2393
- {
2394
- name: "dataops_resource_pending_list",
2395
- definition: defineTool({
2396
- name: "dataops_resource_pending_list",
2397
- description: "List pending DataOps approval tasks and their active user tasks. Administrator only; the resource.manage connector capability must be on. Read-only.",
2398
- parameters: {
2399
- query: {
2400
- type: "string",
2401
- description: "Optional keyword over task title/code/requester."
2402
- },
2403
- limit: {
2404
- type: "number",
2405
- description: "Maximum tasks (default 20, max 100)."
2406
- }
2407
- },
2408
- output: {
2409
- schema: OPEN_OBJECT_SCHEMA,
2410
- render: renderJson
2411
- },
2412
- execute: async (args) => {
2413
- const limit = Math.max(1, Math.min(100, Math.round(args.limit ?? 20)));
2414
- const tasks = await resourceManagementApi.listPendingTasks(args.query ?? "", limit);
2415
- return {
2416
- tasks: tasks.map((task) => ({
2417
- id: task.id,
2418
- code: task.code,
2419
- title: task.title,
2420
- status: task.status,
2421
- requester: task.requester,
2422
- requesterUserId: task.requesterUserId,
2423
- workflow: task.workflow,
2424
- userTasks: task.userTasks,
2425
- updatedAt: task.updatedAt
2426
- })),
2427
- count: tasks.length
2428
- };
2429
- }
2430
- })
2431
- },
2432
- {
2433
- name: "dataops_resource_grant_list",
2434
- definition: defineTool({
2435
- name: "dataops_resource_grant_list",
2436
- description: "List the current access grants of one DataOps resource. Administrator only; resource.manage capability must be on. Read-only.",
2437
- parameters: { resource_id: {
2438
- type: "number",
2439
- required: true,
2440
- description: "DataOps resource id."
2441
- } },
2442
- output: {
2443
- schema: OPEN_OBJECT_SCHEMA,
2444
- render: renderJson
2445
- },
2446
- execute: async (args) => {
2447
- if (!Number.isSafeInteger(args.resource_id) || args.resource_id <= 0) throw new Error("resource_id must be a positive integer");
2448
- const grants = await resourceManagementApi.listGrants(args.resource_id);
2449
- return {
2450
- resourceId: args.resource_id,
2451
- grants
2452
- };
2453
- }
2454
- })
2455
- },
2456
- {
2457
- name: "dataops_resource_grant_batch",
2458
- definition: defineTool({
2459
- name: "dataops_resource_grant_batch",
2460
- description: "Batch grant READ/MANAGE access on one DataOps resource to users, roles or departments. Administrator only; resource.manage capability must be on. The existing grants are preserved; the operation is audited by DataOps.",
2461
- parameters: {
2462
- resource_id: {
2463
- type: "number",
2464
- required: true,
2465
- description: "DataOps resource id."
2466
- },
2467
- application_id: {
2468
- type: "number",
2469
- description: "Application id used for the grants. Defaults to an existing grant application or the first selectable application."
2470
- },
2471
- grants: {
2472
- type: "array",
2473
- required: true,
2474
- description: "Targets to grant.",
2475
- items: {
2476
- type: "object",
2477
- properties: {
2478
- targetType: {
2479
- type: "string",
2480
- description: "USER, ROLE, DEPARTMENT or APPLICATION."
2481
- },
2482
- targetId: {
2483
- type: "string",
2484
- description: "User id, role code, department code or application id."
2485
- },
2486
- permission: {
2487
- type: "string",
2488
- description: "READ or MANAGE. Defaults to READ."
2489
- },
2490
- grantType: {
2491
- type: "string",
2492
- description: "REGULAR or TEMPORARY. Defaults to REGULAR."
2493
- },
2494
- applicationId: {
2495
- type: "number",
2496
- description: "Optional per-grant application id override."
2497
- }
2498
- },
2499
- additionalProperties: false
2500
- }
2501
- }
2502
- },
2503
- output: {
2504
- schema: OPEN_OBJECT_SCHEMA,
2505
- render: renderJson
2506
- },
2507
- execute: async (args, exec) => {
2508
- if (!Number.isSafeInteger(args.resource_id) || args.resource_id <= 0) throw new Error("resource_id must be a positive integer");
2509
- if (!Array.isArray(args.grants) || args.grants.length === 0) throw new Error("grants must be a non-empty array");
2510
- const existing = await resourceManagementApi.listGrants(args.resource_id);
2511
- let appId = args.application_id;
2512
- if (appId === void 0) appId = existing.map((g) => Number(g.applicationId)).find((id) => Number.isSafeInteger(id) && id > 0);
2513
- if (appId === void 0) appId = (await resourceManagementApi.listApplications()).map((app) => Number(app.id)).find((id) => Number.isSafeInteger(id) && id > 0);
2514
- if (appId === void 0) throw new Error("no application is available for access grants");
2515
- const merged = /* @__PURE__ */ new Map();
2516
- for (const grant of existing) {
2517
- const targetType = String(grant.targetType ?? "");
2518
- const targetId = String(grant.targetId ?? "");
2519
- if (!targetType || !targetId) continue;
2520
- const applicationId = Number(grant.applicationId) || appId;
2521
- merged.set(targetType + ":" + targetId + ":" + applicationId, {
2522
- targetType,
2523
- targetId,
2524
- permission: String(grant.permission ?? "READ"),
2525
- grantType: String(grant.grantType ?? "REGULAR"),
2526
- applicationId
2527
- });
2528
- }
2529
- for (const grant of args.grants) {
2530
- const targetType = String(grant.targetType ?? "").trim().toUpperCase();
2531
- const targetId = String(grant.targetId ?? "").trim();
2532
- if (![
2533
- "USER",
2534
- "ROLE",
2535
- "DEPARTMENT",
2536
- "APPLICATION"
2537
- ].includes(targetType) || !targetId) throw new Error("each grant needs targetType and targetId");
2538
- const permission = String(grant.permission ?? "READ").trim().toUpperCase();
2539
- if (![
2540
- "READ",
2541
- "WRITE",
2542
- "MANAGE"
2543
- ].includes(permission)) throw new Error("permission must be READ, WRITE or MANAGE");
2544
- const applicationId = grant.applicationId ?? appId;
2545
- merged.set(targetType + ":" + targetId + ":" + applicationId, {
2546
- targetType,
2547
- targetId,
2548
- permission,
2549
- grantType: String(grant.grantType ?? "REGULAR").trim().toUpperCase(),
2550
- applicationId
2551
- });
2552
- }
2553
- const grants = [...merged.values()];
2554
- await resourceManagementApi.replaceGrants(args.resource_id, grants);
2555
- audit("dataops_resource_grant_batch", exec, {
2556
- resourceId: args.resource_id,
2557
- count: grants.length,
2558
- applicationId: appId
2559
- });
2560
- return {
2561
- resourceId: args.resource_id,
2562
- applicationId: appId,
2563
- grants,
2564
- count: grants.length
2565
- };
2566
- }
2567
- })
2568
- },
2569
- {
2570
- name: "dataops_resource_approval_decide",
2571
- definition: defineTool({
2572
- name: "dataops_resource_approval_decide",
2573
- description: "Approve or reject pending DataOps user tasks in batch. Administrator only; resource.manage capability must be on. Each decision needs task_id and user_task_id; expected_version is read from the task when omitted.",
2574
- parameters: { decisions: {
2575
- type: "array",
2576
- required: true,
2577
- description: "Approval decisions.",
2578
- items: {
2579
- type: "object",
2580
- properties: {
2581
- task_id: {
2582
- type: "number",
2583
- description: "DataOps task id."
2584
- },
2585
- user_task_id: {
2586
- type: "string",
2587
- description: "BPMN user task UUID."
2588
- },
2589
- decision: {
2590
- type: "string",
2591
- description: "approve or reject."
2592
- },
2593
- comment: {
2594
- type: "string",
2595
- description: "Decision comment."
2596
- },
2597
- expected_version: {
2598
- type: "number",
2599
- description: "Current taskVersion; read from task detail when omitted."
2600
- },
2601
- idempotency_key: {
2602
- type: "string",
2603
- description: "Optional replay key; reuse the original key to retry a timed-out command."
2604
- }
2605
- },
2606
- additionalProperties: false
2607
- }
2608
- } },
2609
- output: {
2610
- schema: OPEN_OBJECT_SCHEMA,
2611
- render: renderJson
2612
- },
2613
- execute: async (args, exec) => {
2614
- if (!Array.isArray(args.decisions) || args.decisions.length === 0) throw new Error("decisions must be a non-empty array");
2615
- const results = [];
2616
- for (const decision of args.decisions) {
2617
- const taskId = Number(decision.task_id);
2618
- const userTaskId = String(decision.user_task_id ?? "");
2619
- const action = String(decision.decision ?? "").toLowerCase();
2620
- if (!Number.isSafeInteger(taskId) || taskId <= 0 || !userTaskId || action !== "approve" && action !== "reject") {
2621
- results.push({
2622
- taskId,
2623
- userTaskId,
2624
- ok: false,
2625
- error: "invalid decision"
2626
- });
2627
- continue;
2628
- }
2629
- try {
2630
- let expectedVersion = decision.expected_version;
2631
- if (expectedVersion === void 0) {
2632
- const task = await resourceManagementApi.getTask(taskId);
2633
- const target = (Array.isArray(task.userTasks) ? task.userTasks : []).find((item) => item.id === userTaskId);
2634
- expectedVersion = typeof target?.taskVersion === "number" ? target.taskVersion : 0;
2635
- }
2636
- await resourceManagementApi.decideTask({
2637
- taskId,
2638
- userTaskId,
2639
- decision: action,
2640
- comment: decision.comment,
2641
- expectedVersion,
2642
- idempotencyKey: decision.idempotency_key
2643
- });
2644
- results.push({
2645
- taskId,
2646
- userTaskId,
2647
- decision: action,
2648
- ok: true
2649
- });
2650
- } catch (error) {
2651
- results.push({
2652
- taskId,
2653
- userTaskId,
2654
- decision: action,
2655
- ok: false,
2656
- error: error instanceof Error ? error.message : String(error)
2657
- });
2658
- }
2659
- }
2660
- audit("dataops_resource_approval_decide", exec, {
2661
- count: results.length,
2662
- ok: results.filter((item) => item.ok === true).length
2663
- });
2664
- return { results };
2665
- }
2666
- })
2667
- },
2668
- {
2669
- name: "dataops_resource_grant_revoke",
2670
- definition: defineTool({
2671
- name: "dataops_resource_grant_revoke",
2672
- description: "Batch revoke access grants from one DataOps resource by target type and target id. Administrator only; resource.manage capability must be on. DataOps audits the resulting grant replacement.",
2673
- parameters: {
2674
- resource_id: {
2675
- type: "number",
2676
- required: true,
2677
- description: "DataOps resource id."
2678
- },
2679
- targets: {
2680
- type: "array",
2681
- required: true,
2682
- description: "Targets to revoke.",
2683
- items: {
2684
- type: "object",
2685
- properties: {
2686
- targetType: {
2687
- type: "string",
2688
- description: "USER, ROLE, DEPARTMENT or APPLICATION."
2689
- },
2690
- targetId: {
2691
- type: "string",
2692
- description: "Target id/code."
2693
- }
2694
- },
2695
- additionalProperties: false
2696
- }
2697
- }
2698
- },
2699
- output: {
2700
- schema: OPEN_OBJECT_SCHEMA,
2701
- render: renderJson
2702
- },
2703
- execute: async (args, exec) => {
2704
- if (!Number.isSafeInteger(args.resource_id) || args.resource_id <= 0) throw new Error("resource_id must be a positive integer");
2705
- if (!Array.isArray(args.targets) || args.targets.length === 0) throw new Error("targets must be a non-empty array");
2706
- const existing = await resourceManagementApi.listGrants(args.resource_id);
2707
- const keys = new Set(args.targets.map((target) => String(target.targetType).toUpperCase() + ":" + String(target.targetId)));
2708
- let appId = existing.map((g) => Number(g.applicationId)).find((id) => Number.isSafeInteger(id) && id > 0);
2709
- if (appId === void 0) appId = (await resourceManagementApi.listApplications()).map((app) => Number(app.id)).find((id) => Number.isSafeInteger(id) && id > 0);
2710
- if (appId === void 0) throw new Error("no application is available for access grants");
2711
- const remaining = existing.filter((grant) => !keys.has(String(grant.targetType).toUpperCase() + ":" + String(grant.targetId))).map((grant) => ({
2712
- targetType: String(grant.targetType),
2713
- targetId: String(grant.targetId),
2714
- permission: String(grant.permission ?? "READ"),
2715
- grantType: String(grant.grantType ?? "REGULAR"),
2716
- applicationId: Number(grant.applicationId) || appId
2717
- }));
2718
- const removed = existing.length - remaining.length;
2719
- if (removed === 0) throw new Error("no matching grant to revoke");
2720
- await resourceManagementApi.replaceGrants(args.resource_id, remaining);
2721
- audit("dataops_resource_grant_revoke", exec, {
2722
- resourceId: args.resource_id,
2723
- removed
2724
- });
2725
- return {
2726
- resourceId: args.resource_id,
2727
- removed,
2728
- remaining,
2729
- count: remaining.length
2730
- };
2731
- }
2732
- })
2733
- }
2734
- ];
2735
- }
2736
- //#endregion
2737
- //#region src/tool-manager.ts
2738
- /**
2739
- * Reconcile the managed tools with the current DataOps scope.
2740
- *
2741
- * Construct once per plugin activation. `refresh` is idempotent and coalesces concurrent calls;
2742
- * the constructor also subscribes to the credential observation so an expired session removes
2743
- * the tools without waiting for another explicit sync.
2744
- */
2745
- var AiToolManager = class {
2746
- ctx;
2747
- reviewApi;
2748
- collectHub;
2749
- definitions;
2750
- registrations = /* @__PURE__ */ new Map();
2751
- unsubscribeExpiry;
2752
- disposeViewer;
2753
- scope;
2754
- connectorState;
2755
- revision = 0;
2756
- inflight;
2757
- disposed = false;
2758
- constructor(ctx, reviewApi, collectHub) {
2759
- this.ctx = ctx;
2760
- this.reviewApi = reviewApi;
2761
- this.collectHub = collectHub;
2762
- this.definitions = new Map(buildAiManagementTools(ctx, reviewApi, () => this.scope, this.collectHub).map((tool) => [tool.name, tool.definition]));
2763
- this.unsubscribeExpiry = onAuthStateChange((state) => {
2764
- if (state === "expired") this.clear();
2765
- });
2766
- }
2767
- /** The scope the current registration set was derived from, when one has been read. */
2768
- currentScope() {
2769
- return this.scope;
2770
- }
2771
- /** The tool names currently registered, for diagnostics and tests. */
2772
- registeredToolNames() {
2773
- return AI_TOOL_NAMES.filter((name) => this.registrations.has(name));
2774
- }
2775
- /**
2776
- * Re-read the workspace's DataOps scope and reconcile the tool list.
2777
- *
2778
- * Definitive denials clear the list; transient failures (network, 5xx) keep what the last good
2779
- * observation produced. The method never throws: sync happens in the background of a browser
2780
- * request and must not fail that request.
2781
- * @param force - Start a new read even when one is already in flight. Credential adoption uses
2782
- * this because an older read may have captured the previous token; its answer must not win
2783
- * over the scope the new token produces.
2784
- */
2785
- async refresh(force = false) {
2786
- if (this.disposed) return;
2787
- if (this.inflight !== void 0 && !force) return this.inflight;
2788
- const revision = ++this.revision;
2789
- const run = this.loadScope(revision).catch((error) => {
2790
- this.ctx.logger.warn("dataops-managed: tool disclosure refresh failed");
2791
- this.ctx.logger.warn(error);
2792
- }).finally(() => {
2793
- if (this.inflight === run) this.inflight = void 0;
2794
- });
2795
- this.inflight = run;
2796
- return run;
2797
- }
2798
- /**
2799
- * Apply a context answer already fetched by a same-origin route.
2800
- *
2801
- * The review-context route is how the UI learns about a role change, so its answer is also the
2802
- * freshest scope this plugin will see. Reusing it avoids a second fetch on a page that polls.
2803
- * @param result - The upstream status and parsed body.
2804
- */
2805
- observeContext(result) {
2806
- if (result.status === 200) {
2807
- this.applyContext(result.body);
2808
- return;
2809
- }
2810
- if (result.status === 401 || result.status === 403 || result.status === 404 || result.status === 503) this.clear();
2811
- }
2812
- /**
2813
- * Apply one parsed context body without contacting DataOps.
2814
- * @param body - Parsed `/api/ai/review/context` body.
2815
- */
2816
- applyContext(body) {
2817
- if (this.disposed) return;
2818
- this.revision += 1;
2819
- const scope = normalizeScope(body);
2820
- this.applyScope(scope);
2821
- }
2822
- /** Drop every managed tool because no usable DataOps scope is known. */
2823
- clear() {
2824
- if (this.disposed) return;
2825
- this.revision += 1;
2826
- this.applyScope(void 0);
2827
- }
2828
- /** Dispose every tool this manager registered and stop observing auth state. */
2829
- dispose() {
2830
- if (this.disposed) return;
2831
- this.disposed = true;
2832
- this.revision += 1;
2833
- this.unsubscribeExpiry();
2834
- this.disposeRegistrations();
2835
- this.disposeViewer?.();
2836
- this.disposeViewer = void 0;
2837
- this.scope = void 0;
2838
- }
2839
- /**
2840
- * Read the connector state that gates capability-owned tools.
2841
- *
2842
- * A missing or unreadable state file is not a permission decision: it means the connector has
2843
- * never been enabled in this workspace, so capability-gated tools stay unregistered.
2844
- * @returns The persisted connector state, or a disabled placeholder when it cannot be read.
2845
- */
2846
- async readConnectorState() {
2847
- try {
2848
- return await readConnectorState();
2849
- } catch (error) {
2850
- this.ctx.logger.warn("dataops-managed: connector state could not be read for tool disclosure");
2851
- this.ctx.logger.warn(error);
2852
- return {
2853
- enabled: false,
2854
- capabilities: {}
2855
- };
2856
- }
2857
- }
2858
- /**
2859
- * Re-reconcile after the connector's capability switches changed.
2860
- *
2861
- * The skill center writes the connector state; calling this keeps the registered tool set in
2862
- * step with it without waiting for the next credential or role sync.
2863
- */
2864
- async refreshCapabilities() {
2865
- if (this.disposed) return;
2866
- const connectorState = await this.readConnectorState();
2867
- if (this.disposed) return;
2868
- this.applyScope(this.scope, connectorState);
2869
- }
2870
- async loadScope(revision) {
2871
- let result;
2872
- try {
2873
- result = await this.reviewApi.request("/api/ai/review/context");
2874
- } catch (error) {
2875
- this.ctx.logger.warn("dataops-managed: tool disclosure could not read the DataOps scope");
2876
- this.ctx.logger.warn(error);
2877
- return;
2878
- }
2879
- if (this.disposed || revision !== this.revision) return;
2880
- const connectorState = await this.readConnectorState();
2881
- if (this.disposed || revision !== this.revision) return;
2882
- if (result.status === 200) {
2883
- this.applyScope(normalizeScope(result.body), connectorState);
2884
- return;
2885
- }
2886
- if (result.status === 401 || result.status === 403 || result.status === 404 || result.status === 503) {
2887
- this.applyScope(void 0, connectorState);
2888
- return;
2889
- }
2890
- this.ctx.logger.warn("dataops-managed: tool disclosure scope read failed with HTTP " + result.status.toString());
2891
- }
2892
- /** Store the scope and make the registry match it. */
2893
- applyScope(scope, connectorState) {
2894
- this.scope = scope;
2895
- if (connectorState !== void 0) this.connectorState = connectorState;
2896
- if (this.disposed) return;
2897
- this.applyViewer(scope);
2898
- const capabilities = this.connectorState ?? {
2899
- enabled: false,
2900
- capabilities: {}
2901
- };
2902
- const desired = new Set(scope === void 0 ? [] : AI_TOOL_NAMES.filter((name) => isToolVisible(name, scope) && isToolCapabilityEnabled(name, capabilities)));
2903
- for (const [name, registration] of this.registrations) {
2904
- if (desired.has(name)) continue;
2905
- this.disposeRegistration(name, registration);
2906
- }
2907
- for (const name of AI_TOOL_NAMES) {
2908
- if (!desired.has(name) || this.registrations.has(name)) continue;
2909
- const definition = this.definitions.get(name);
2910
- if (definition === void 0) continue;
2911
- try {
2912
- const dispose = this.ctx.tools.register(definition);
2913
- this.registrations.set(name, { dispose });
2914
- } catch (error) {
2915
- this.ctx.logger.warn("dataops-managed: could not register tool " + name);
2916
- this.ctx.logger.warn(error);
2917
- }
2918
- }
2919
- }
2920
- /** Map one DataOps scope to the skill registry's audience filter. */
2921
- applyViewer(scope) {
2922
- this.disposeViewer?.();
2923
- this.disposeViewer = void 0;
2924
- const viewer = scope === void 0 ? {
2925
- role: "user",
2926
- permissions: []
2927
- } : {
2928
- role: isSuperAdmin(scope) ? "super-admin" : isAdmin(scope) || isDepartmentAdmin(scope) ? "admin" : "user",
2929
- permissions: [...scope.permissions ?? scope.permissionKeys ?? []]
2930
- };
2931
- try {
2932
- const skills = this.ctx.skills;
2933
- if (typeof skills.useViewer !== "function") return;
2934
- this.disposeViewer = skills.useViewer(viewer);
2935
- } catch (error) {
2936
- this.ctx.logger.warn("dataops-managed: could not apply the skill viewer");
2937
- this.ctx.logger.warn(error);
2938
- }
2939
- }
2940
- /** Dispose one registration, tolerating a disposer that has already run. */
2941
- disposeRegistration(name, registration) {
2942
- this.registrations.delete(name);
2943
- try {
2944
- registration.dispose();
2945
- } catch (error) {
2946
- this.ctx.logger.warn("dataops-managed: could not dispose tool " + name);
2947
- this.ctx.logger.warn(error);
2948
- }
2949
- }
2950
- /** Dispose the whole current set. */
2951
- disposeRegistrations() {
2952
- for (const [name, registration] of [...this.registrations]) this.disposeRegistration(name, registration);
2953
- }
2954
- };
2955
- //#endregion
2956
- //#region src/resource-tab.ts
2957
- /** SSE route the client subscribes to. */
2958
- const OPEN_RESOURCE_EVENTS_PATH = "/integrations/dataops/open-resource/events";
2959
- /** Same-origin route the client uses to learn where the DataOps frontend lives. */
2960
- const RESOURCE_TAB_CONFIG_PATH = "/integrations/dataops/resource-tab/config";
2961
- /** Browser tab type registered by the client half. */
2962
- const RESOURCE_TAB_TYPE = "dataops-resources";
2963
- /**
2964
- * Fan-out registry for the workspace's live SSE subscribers.
2965
- *
2966
- * A workspace has one browser in the normal case, but a reconnect can briefly leave the
2967
- * previous response open. Broadcasting to the current set makes the new connection and the
2968
- * stale one harmless: the browser keeps one tab, and the client dedupes by resource tab id.
2969
- */
2970
- var OpenResourceHub = class {
2971
- logger;
2972
- clients = /* @__PURE__ */ new Set();
2973
- heartbeat;
2974
- constructor(logger) {
2975
- this.logger = logger;
2976
- }
2977
- /** Accept one SSE subscription and own its response until the client disconnects. */
2978
- subscribe(request, response) {
2979
- response.writeHead(200, {
2980
- "content-type": "text/event-stream; charset=utf-8",
2981
- "cache-control": "no-cache, no-transform",
2982
- connection: "keep-alive",
2983
- "x-accel-buffering": "no"
2984
- });
2985
- response.write(": connected\n\n");
2986
- this.clients.add(response);
2987
- this.ensureHeartbeat();
2988
- const remove = () => {
2989
- this.clients.delete(response);
2990
- if (this.clients.size === 0 && this.heartbeat !== void 0) {
2991
- clearInterval(this.heartbeat);
2992
- this.heartbeat = void 0;
2993
- }
2994
- };
2995
- request.on("close", remove);
2996
- request.on("aborted", remove);
2997
- response.on("error", (error) => {
2998
- this.logger.warn("dataops-managed: resource tab SSE response failed: " + String(error));
2999
- remove();
3000
- });
3001
- }
3002
- /** Send one navigation event to every connected client. */
3003
- broadcast(event) {
3004
- const payload = {
3005
- type: "open_resource",
3006
- requestId: event.requestId ?? randomUUID(),
3007
- resourceId: event.resourceId,
3008
- resourceName: event.resourceName,
3009
- mode: event.mode,
3010
- nonce: event.nonce
3011
- };
3012
- const frame = "event: dataops-open-resource\ndata: " + JSON.stringify(payload) + "\n\n";
3013
- for (const client of this.clients) try {
3014
- client.write(frame);
3015
- } catch (error) {
3016
- this.clients.delete(client);
3017
- this.logger.warn("dataops-managed: resource tab SSE write failed: " + String(error));
3018
- }
3019
- return payload;
3020
- }
3021
- /** Number of live subscribers, used by the tool result to explain a missing browser. */
3022
- size() {
3023
- return this.clients.size;
3024
- }
3025
- /** Close every subscriber; called by the plugin disposer. */
3026
- dispose() {
3027
- if (this.heartbeat !== void 0) clearInterval(this.heartbeat);
3028
- this.heartbeat = void 0;
3029
- for (const client of this.clients) try {
3030
- client.end();
3031
- } catch {}
3032
- this.clients.clear();
3033
- }
3034
- ensureHeartbeat() {
3035
- if (this.heartbeat !== void 0) return;
3036
- this.heartbeat = setInterval(() => {
3037
- for (const client of this.clients) try {
3038
- client.write(": keep-alive\n\n");
3039
- } catch {
3040
- this.clients.delete(client);
3041
- }
3042
- }, 25e3);
3043
- this.heartbeat.unref?.();
3044
- }
3045
- };
3046
- /** Resolve the browser-facing DataOps origin for the iframe. */
3047
- const resolveResourceTabConfig = (request, configuredWebBaseUrl) => {
3048
- const header = (name) => {
3049
- const value = request.headers[name];
3050
- return Array.isArray(value) ? value[0] : value;
3051
- };
3052
- const forwardedProto = header("x-forwarded-proto")?.split(",")[0]?.trim();
3053
- const host = header("x-forwarded-host")?.split(",")[0]?.trim() || header("host") || "";
3054
- const requestOrigin = host ? `${forwardedProto || "http"}://${host}` : "";
3055
- const embedBaseUrl = configuredWebBaseUrl?.trim() || requestOrigin || "http://127.0.0.1:8080";
3056
- let sameOrigin = false;
3057
- try {
3058
- sameOrigin = new URL(embedBaseUrl).origin === requestOrigin;
3059
- } catch {
3060
- sameOrigin = false;
3061
- }
3062
- return {
3063
- embedBaseUrl,
3064
- sameOrigin,
3065
- tabType: RESOURCE_TAB_TYPE
3066
- };
3067
- };
3068
- //#endregion
3069
- //#region src/workspace-limits.ts
3070
- /** Narrow a value to a plain object. */
3071
- function asRecord(value) {
3072
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
3073
- }
3074
- /** Narrow a value to a positive integer. */
3075
- function asByteCount(value) {
3076
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
3077
- }
3078
- /**
3079
- * A rejection DataOps answered with, carrying its status and message.
3080
- *
3081
- * Without this the caller can only tell that something failed, and a value DataOps refused —
3082
- * which the user can correct — is indistinguishable from a fault in the request path.
3083
- */
3084
- var WorkspaceLimitsRejection = class extends Error {
3085
- status;
3086
- constructor(status, message) {
3087
- super(message);
3088
- this.status = status;
3089
- this.name = "WorkspaceLimitsRejection";
3090
- }
3091
- };
3092
- /** Read DataOps' own explanation from a failed response, falling back to the status line. */
3093
- async function rejectionMessage(response, fallback) {
3094
- try {
3095
- const message = asRecord(await response.json())?.message;
3096
- if (typeof message === "string" && message.trim() !== "") return message;
3097
- if (Array.isArray(message) && typeof message[0] === "string") return message[0];
3098
- } catch {}
3099
- return `${fallback} with HTTP ${String(response.status)}`;
3100
- }
3101
- /**
3102
- * The workspace limits an administrator sets in DataOps.
3103
- *
3104
- * The plugin holds the DataOps JWT, so the browser cannot read these itself; this class is the
3105
- * only path from the Settings panel to that document.
3106
- */
3107
- var WorkspaceLimits = class {
3108
- ctx;
3109
- config;
3110
- constructor(ctx, config) {
3111
- this.ctx = ctx;
3112
- this.config = config;
3113
- }
3114
- /**
3115
- * Read the DataOps JWT this workspace is currently authorized with.
3116
- * @returns The token, or undefined when the workspace has no session yet.
3117
- */
3118
- async token() {
3119
- return (await this.ctx.credentials.resolve(credentialRef(this.config.credentialRef)))?.value;
3120
- }
3121
- /** The DataOps API origin this workspace reports to. */
3122
- apiBase() {
3123
- return new URL(this.config.baseUrl).origin;
3124
- }
3125
- /**
3126
- * Read the current ceilings.
3127
- * @returns The status, or undefined when the workspace is not authorized.
3128
- */
3129
- async status() {
3130
- const token = await this.token();
3131
- if (token === void 0) return void 0;
3132
- const response = await fetch(new URL("/api/ai/attachment-settings", this.apiBase()), { headers: { authorization: `Bearer ${token}` } });
3133
- if (response.status === 401) {
3134
- noteExpired();
3135
- return;
3136
- }
3137
- noteAccepted();
3138
- if (!response.ok) throw new WorkspaceLimitsRejection(response.status, await rejectionMessage(response, "Workspace limits read failed"));
3139
- const body = asRecord(await response.json());
3140
- const settings = body === null ? null : asRecord(body.settings);
3141
- const size = settings === null ? null : asRecord(settings.workspaceSize);
3142
- const fileReadMaxBytes = size === null ? null : asByteCount(size.fileReadMaxBytes);
3143
- const uploadMaxBytes = size === null ? null : asByteCount(size.uploadMaxBytes);
3144
- if (fileReadMaxBytes === null || uploadMaxBytes === null) throw new Error("Workspace limits read returned an unrecognized document");
3145
- return {
3146
- limits: {
3147
- fileReadMaxBytes,
3148
- uploadMaxBytes
3149
- },
3150
- canWrite: true,
3151
- readOnlyReason: null
3152
- };
3153
- }
3154
- /**
3155
- * Write new ceilings.
3156
- * @param limits - The ceilings to store.
3157
- * @returns The stored status.
3158
- */
3159
- async save(limits) {
3160
- const token = await this.token();
3161
- if (token === void 0) return void 0;
3162
- const response = await fetch(new URL("/api/ai/attachment-settings", this.apiBase()), {
3163
- method: "PATCH",
3164
- headers: {
3165
- authorization: `Bearer ${token}`,
3166
- "content-type": "application/json"
3167
- },
3168
- body: JSON.stringify({ workspaceSize: limits })
3169
- });
3170
- if (response.status === 401) {
3171
- noteExpired();
3172
- return;
3173
- }
3174
- noteAccepted();
3175
- if (!response.ok) throw new WorkspaceLimitsRejection(response.status, await rejectionMessage(response, "Workspace limits write failed"));
3176
- return this.status();
3177
- }
3178
- };
3179
- /** The live instance, so the Settings route can act on it after activation. */
3180
- let limitsRef;
3181
- /** @param next - Instance to publish, or undefined to clear. */
3182
- function setWorkspaceLimits(next) {
3183
- limitsRef = next;
3184
- }
3185
- /** @returns The live workspace-limits instance, when the plugin activated. */
3186
- function currentWorkspaceLimits() {
3187
- return limitsRef;
3188
- }
3189
- /** Directory used by this plugin below the DSH home. */
3190
- const WORKSPACE_UPGRADE_STATE_DIR = "dataops-managed";
3191
- /** Name of the hand-off file. */
3192
- const WORKSPACE_UPGRADE_STATE_FILE = "workspace-upgrade.json";
3193
- /**
3194
- * Resolve the persistent DSH home used by this workspace.
3195
- *
3196
- * The companion currently starts with `DSH_HOME=/workspace/.dataops/dsh`; the fallback
3197
- * keeps tests and a manually launched host deterministic without reaching outside the
3198
- * mounted workspace.
3199
- * @param dshHome - override for tests.
3200
- * @returns the state directory path.
3201
- */
3202
- function workspaceUpgradeStatePath(dshHome = process.env.DSH_HOME ?? "/workspace/.dataops/dsh") {
3203
- return join(dshHome, WORKSPACE_UPGRADE_STATE_DIR, WORKSPACE_UPGRADE_STATE_FILE);
3204
- }
3205
- /** Validate one persisted session entry. */
3206
- function asSession(value) {
3207
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
3208
- const record = value;
3209
- if (typeof record.sessionId !== "string" || record.sessionId.trim() === "") return null;
3210
- return {
3211
- sessionId: record.sessionId.trim(),
3212
- ...typeof record.title === "string" && record.title.trim() !== "" ? { title: record.title.trim() } : {},
3213
- ...typeof record.cwd === "string" && record.cwd.trim() !== "" ? { cwd: record.cwd.trim() } : {}
3214
- };
3215
- }
3216
- /** Validate a parsed state document. */
3217
- function asWorkspaceUpgradeState(value) {
3218
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
3219
- const record = value;
3220
- if (record.version !== 1) return null;
3221
- if (typeof record.upgradeId !== "string" || record.upgradeId.trim() === "") return null;
3222
- if (typeof record.targetImage !== "string" || record.targetImage.trim() === "") return null;
3223
- if (!Array.isArray(record.sessions)) return null;
3224
- const sessions = record.sessions.map(asSession).filter((session) => session !== null);
3225
- return {
3226
- version: 1,
3227
- upgradeId: record.upgradeId.trim(),
3228
- targetImage: record.targetImage.trim(),
3229
- sessions,
3230
- createdAt: typeof record.createdAt === "string" ? record.createdAt : (/* @__PURE__ */ new Date()).toISOString()
3231
- };
3232
- }
3233
- /**
3234
- * Read the pending hand-off record.
3235
- * @param file - state file path.
3236
- * @returns the record, or null when none exists or it cannot be parsed.
3237
- */
3238
- async function readWorkspaceUpgradeState(file = workspaceUpgradeStatePath()) {
3239
- try {
3240
- return asWorkspaceUpgradeState(JSON.parse(await readFile(file, "utf8")));
3241
- } catch {
3242
- return null;
3243
- }
3244
- }
3245
- /**
3246
- * Persist the hand-off record atomically.
3247
- *
3248
- * A partially written JSON file would be indistinguishable from "no upgrade pending",
3249
- * which would silently skip recovery. The temporary file is renamed into place only
3250
- * after the content is complete.
3251
- * @param state - record to persist.
3252
- * @param file - state file path.
3253
- */
3254
- async function writeWorkspaceUpgradeState(state, file = workspaceUpgradeStatePath()) {
3255
- await mkdir(dirname(file), { recursive: true });
3256
- const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
3257
- await writeFile(temporary, JSON.stringify(state, null, 2) + "\n", "utf8");
3258
- await rename(temporary, file);
3259
- }
3260
- /**
3261
- * Remove the hand-off record after recovery has been attempted.
3262
- * @param file - state file path.
3263
- */
3264
- async function clearWorkspaceUpgradeState(file = workspaceUpgradeStatePath()) {
3265
- await rm(file, { force: true });
3266
- }
3267
- //#endregion
3268
- //#region src/workspace-upgrade.ts
3269
- /**
3270
- * Workspace image upgrade orchestration.
3271
- *
3272
- * DataOps owns the Docker image comparison and the container restart. This plugin owns
3273
- * the two facts DSH alone can know: which sessions are running right now, and how to
3274
- * bring those sessions back after the container has been recreated. A small JSON file
3275
- * on the shared workspace volume carries that hand-off across the restart.
3276
- *
3277
- * @module workspace-upgrade
3278
- */
3279
- /** A refusal or transport failure from the DataOps API. */
3280
- var WorkspaceUpgradeError = class extends Error {
3281
- status;
3282
- constructor(status, message) {
3283
- super(message);
3284
- this.status = status;
3285
- this.name = "WorkspaceUpgradeError";
3286
- }
3287
- };
3288
- /** Create the user-message value `agent.followup` accepts. */
3289
- function userMessage(text) {
3290
- return {
3291
- id: randomUUID(),
3292
- role: "user",
3293
- content: [{
3294
- type: "text",
3295
- text
3296
- }],
3297
- source: { kind: "user" }
3298
- };
3299
- }
3300
- /** Extract a useful message from a DataOps error body. */
3301
- async function responseMessage(response, fallback) {
3302
- try {
3303
- const message = (await response.json()).message;
3304
- if (typeof message === "string" && message.trim() !== "") return message;
3305
- if (Array.isArray(message) && typeof message[0] === "string") return message[0];
3306
- } catch {}
3307
- return `${fallback} (HTTP ${String(response.status)})`;
3308
- }
3309
- /** Owns DataOps preview/restart calls and the DSH session hand-off. */
3310
- var WorkspaceUpgrade = class {
3311
- ctx;
3312
- config;
3313
- statePath;
3314
- constructor(ctx, config, statePath = workspaceUpgradeStatePath()) {
3315
- this.ctx = ctx;
3316
- this.config = config;
3317
- this.statePath = statePath;
3318
- }
3319
- /** Resolve the injected DSH agents service, if the profile provides one. */
3320
- agents() {
3321
- return this.ctx.agents;
3322
- }
3323
- /** Read the current DataOps credential. */
3324
- async token() {
3325
- return (await this.ctx.credentials.resolve(credentialRef(this.config.credentialRef)))?.value;
3326
- }
3327
- /** DataOps origin used by this workspace. */
3328
- apiBase() {
3329
- return new URL(this.config.baseUrl).origin;
3330
- }
3331
- /** Call one DataOps API path with the workspace JWT. */
3332
- async request(path, init) {
3333
- const token = await this.token();
3334
- if (token === void 0) throw new WorkspaceUpgradeError(401, "workspace is not signed in to DataOps");
3335
- let response;
3336
- try {
3337
- response = await fetch(new URL(path, this.apiBase()), {
3338
- ...init,
3339
- headers: {
3340
- authorization: `Bearer ${token}`,
3341
- ...init?.body === void 0 ? {} : { "content-type": "application/json" },
3342
- ...init?.headers ?? {}
3343
- }
3344
- });
3345
- } catch (error) {
3346
- throw new WorkspaceUpgradeError(502, error instanceof Error ? error.message : String(error));
3347
- }
3348
- if (response.status === 401) {
3349
- noteExpired();
3350
- throw new WorkspaceUpgradeError(401, "DataOps session has ended");
3351
- }
3352
- noteAccepted();
3353
- return response;
3354
- }
3355
- /** Read the DataOps restart preview plus this host's running-session snapshot. */
3356
- async preview() {
3357
- const response = await this.request("/api/ai/workspace/restart-preview");
3358
- if (!response.ok) throw new WorkspaceUpgradeError(response.status, await responseMessage(response, "workspace preview failed"));
3359
- const body = await response.json();
3360
- const imageStatus = body.workspace?.imageStatus;
3361
- if (imageStatus !== "CURRENT" && imageStatus !== "UPDATE_AVAILABLE" && imageStatus !== "NOT_RUNNING" && imageStatus !== "UNKNOWN") throw new WorkspaceUpgradeError(502, "workspace preview returned an unrecognized image status");
3362
- return {
3363
- imageStatus,
3364
- configuredImage: typeof body.workspace?.configuredImage === "string" ? body.workspace.configuredImage : "",
3365
- activeSessions: this.runningSessions()
3366
- };
3367
- }
3368
- /** Snapshot sessions that are executing a turn right now. */
3369
- runningSessions() {
3370
- const agents = this.agents();
3371
- if (agents === void 0) return [];
3372
- return agents.list().filter((agent) => agent.status === "running").map((agent) => ({
3373
- sessionId: agent.session.id,
3374
- ...agent.session.header?.title ? { title: agent.session.header.title } : {},
3375
- ...agent.session.header?.cwd ? { cwd: agent.session.header.cwd } : {}
3376
- }));
3377
- }
3378
- /** Restart DataOps' workspace container; force is required when sessions are snapshot. */
3379
- async restart() {
3380
- const response = await this.request("/api/ai/workspace/restart", {
3381
- method: "POST",
3382
- body: JSON.stringify({ force: true })
3383
- });
3384
- if (!response.ok) throw new WorkspaceUpgradeError(response.status, await responseMessage(response, "workspace restart failed"));
3385
- }
3386
- /**
3387
- * Persist the running-session snapshot and ask DataOps to recreate the container.
3388
- * @returns the accepted hand-off record.
3389
- */
3390
- async upgrade() {
3391
- const preview = await this.preview();
3392
- if (preview.imageStatus !== "UPDATE_AVAILABLE") throw new WorkspaceUpgradeError(409, "workspace image is already current or not running");
3393
- const state = {
3394
- version: 1,
3395
- upgradeId: randomUUID(),
3396
- targetImage: preview.configuredImage,
3397
- sessions: preview.activeSessions,
3398
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
3399
- };
3400
- await writeWorkspaceUpgradeState(state, this.statePath);
3401
- try {
3402
- await this.restart();
3403
- } catch (error) {
3404
- await clearWorkspaceUpgradeState(this.statePath);
3405
- throw error;
3406
- }
3407
- return state;
3408
- }
3409
- /**
3410
- * Resume every snapshotted session and send one "继续".
3411
- *
3412
- * The method deliberately does not wait for an answer: the user's workspace should
3413
- * become usable immediately, and an in-flight tool call cannot be replayed safely.
3414
- * `recoverWorkspaceUpgradeAfterBoot` removes the hand-off file after this attempt.
3415
- */
3416
- async recover() {
3417
- const state = await readWorkspaceUpgradeState(this.statePath);
3418
- if (state === null) return {
3419
- recovered: 0,
3420
- skipped: 0
3421
- };
3422
- if (this.agents() === void 0) throw new Error("DSH agents service is not ready");
3423
- let recovered = 0;
3424
- let skipped = 0;
3425
- for (const session of state.sessions) try {
3426
- const agent = await this.ensureAgent(session.sessionId);
3427
- if (agent === void 0) {
3428
- skipped += 1;
3429
- continue;
3430
- }
3431
- agent.followup(userMessage("继续"));
3432
- recovered += 1;
3433
- } catch (error) {
3434
- skipped += 1;
3435
- this.ctx.logger.warn(`dataops-managed: could not resume session ${session.sessionId}: ${error instanceof Error ? error.message : String(error)}`);
3436
- }
3437
- return {
3438
- recovered,
3439
- skipped
3440
- };
3441
- }
3442
- /** Remove the hand-off record once recovery has been attempted. */
3443
- async clearRecoveryState() {
3444
- await clearWorkspaceUpgradeState(this.statePath);
3445
- }
3446
- /** Find a live session or resume it from persisted state. */
3447
- async ensureAgent(sessionId) {
3448
- const agents = this.agents();
3449
- if (agents === void 0) return void 0;
3450
- const live = agents.get(sessionId);
3451
- if (live !== void 0) return live;
3452
- return (await agents.resume({ resumeSessionId: sessionId }))?.agent;
3453
- }
3454
- };
3455
- /** Delay helper for boot-time recovery without keeping the plugin apply() pending. */
3456
- const sleep = (ms) => new Promise((resolve) => {
3457
- setTimeout(resolve, ms);
3458
- });
3459
- /**
3460
- * Run recovery after the DSH host and its session persistence have had time to boot.
3461
- *
3462
- * `apply()` runs before a persisted session necessarily has its live agent; resuming
3463
- * eagerly can race that boot. A short bounded retry is enough, and a failed attempt
3464
- * still removes the hand-off file so the next page load cannot send "继续" forever.
3465
- * @param upgrade - upgrade service.
3466
- */
3467
- async function recoverWorkspaceUpgradeAfterBoot(upgrade) {
3468
- let lastState = null;
3469
- for (let attempt = 0; attempt < 10; attempt += 1) {
3470
- const state = await readWorkspaceUpgradeState(upgrade.statePath);
3471
- if (state === null) return;
3472
- lastState = state;
3473
- if (attempt > 0) await sleep(1500);
3474
- try {
3475
- if ((await upgrade.recover()).recovered > 0 || state.sessions.length === 0) {
3476
- await upgrade.clearRecoveryState();
3477
- return;
3478
- }
3479
- } catch (error) {
3480
- console.warn("[dataops-managed] workspace upgrade recovery failed:", error);
3481
- }
3482
- }
3483
- if (lastState !== null) await upgrade.clearRecoveryState();
3484
- }
3485
- //#endregion
3486
- //#region src/index.ts
3487
- /** Cordis plugin name for the DataOps-managed integration. */
3488
- const name = "dataops-managed";
3489
- /** Host services required by managed JWT and MCP ownership. */
3490
- const inject = [
3491
- "credentials",
3492
- "webServer",
3493
- "tools",
3494
- "settings",
3495
- "skills",
3496
- "approval"
3497
- ];
3498
- const MANAGED_AUTH_PATH = "/integrations/dataops/managed-auth";
3499
- /** This plugin's profile entry id, which owns its Config and sync state. */
3500
- const MANAGED_PLUGIN_ID = "dataops-managed";
3501
- /** Same-origin route the workspace settings pages use to read and change model sharing. */
3502
- const MODEL_SYNC_PATH = "/integrations/dataops/model-sync";
3503
- /** Same-origin route the skill center uses to read and change plaza sharing. */
3504
- const SKILL_PLAZA_PATH = "/integrations/dataops/skill-plaza";
3505
- /** Caller role and review capability. */
3506
- const REVIEW_CONTEXT_PATH = "/integrations/dataops/review-context";
3507
- /** Notification inbox and read receipts. */
3508
- const REVIEW_NOTIFICATIONS_PATH = "/integrations/dataops/review-notifications";
3509
- /** AI scan and the administrator's decision. */
3510
- const REVIEW_ACTION_PATH = "/integrations/dataops/review";
3511
- /** Permission-centre reads and writes. */
3512
- const RBAC_PATH = "/integrations/dataops/rbac";
3513
- /** The three plaza-review switches. */
3514
- const REVIEW_SETTINGS_PATH = "/integrations/dataops/review-settings";
3515
- /** Department CRUD bridge (task-67). */
3516
- const DEPARTMENTS_PATH = "/integrations/dataops/departments";
3517
- /** Same-origin route the Settings panel uses to read and change this workspace's limits. */
3518
- const WORKSPACE_LIMITS_PATH = "/integrations/dataops/workspace-limits";
3519
- /** Same-origin route the Settings panel uses to read and change the tool-call timeout. */
3520
- const TOOL_TIMEOUT_PATH = "/integrations/dataops/tool-timeout";
3521
- /** Same-origin route reporting what the last DataOps answer said about the credential. */
3522
- const AUTH_STATE_PATH = "/integrations/dataops/auth-state";
3523
- /** Same-origin route the DSH page uses to detect and start a workspace image upgrade. */
3524
- const WORKSPACE_UPGRADE_PATH = "/integrations/dataops/workspace-upgrade";
3525
- /** The ends a tool-call timeout may take, in whole seconds. */
3526
- const TOOL_TIMEOUT_MIN_SECONDS = 1;
3527
- const TOOL_TIMEOUT_MAX_SECONDS = 3600;
3528
- /** The live sync instance, so the settings routes can act on it after activation. */
3529
- let modelSyncRef;
3530
- /** The live plaza instance, so the skill center routes can act on it after activation. */
3531
- let skillPlazaRef;
3532
- /** The live review API, once this plugin activated. */
3533
- let reviewApiRef;
3534
- /** The live skill plaza, once this plugin activated. */
3535
- function currentSkillPlaza() {
3536
- return skillPlazaRef;
3537
- }
3538
- /** The live model-sync instance, once this plugin activated. */
3539
- function currentModelSync() {
3540
- return modelSyncRef;
3541
- }
3542
- /** The live settings-sync instance, once this plugin activated. */
3543
- let settingsSyncRef;
3544
- /** @returns The live instance, or undefined before this plugin activated. */
3545
- function currentSettingsSync() {
3546
- return settingsSyncRef;
3547
- }
3548
- /**
3549
- * Read the value behind a possibly-volatile field.
3550
- *
3551
- * A volatile field always arrives as a reference, but the plain shape is accepted too so a
3552
- * caller that validated the config without a settings service still reads its value.
3553
- * @param field - The config field as the runtime supplied it.
3554
- * @param fallback - Value to use when nothing is stored yet.
3555
- * @returns The current value.
3556
- */
3557
- function volatileValue(field, fallback) {
3558
- if (field === void 0) return fallback;
3559
- if (typeof field === "object" && field !== null && "get" in field && typeof field.get === "function") return field.get() ?? fallback;
3560
- return field;
3561
- }
3562
- /**
3563
- * Per-tool-call timeout a workspace starts with.
3564
- *
3565
- * Named rather than inlined so the schema default and the read fallback cannot drift: the field is
3566
- * volatile, so a workspace that never changed it reads no value at all and both places have to
3567
- * answer the same number.
3568
- */
3569
- const DEFAULT_TOOL_CALL_TIMEOUT_MS = 3e5;
3570
- /** Default sync state before this workspace stored anything. */
3571
- const MODEL_SYNC_DEFAULT = {
3572
- detached: false,
3573
- adoptedModelIds: [],
3574
- privateModelIds: []
3575
- };
3576
- /** Schemastery parser for managed DataOps configuration. */
3577
- const Config = z.object({
3578
- baseUrl: z.string().default("http://host.docker.internal:3101"),
3579
- webBaseUrl: z.string().default(""),
3580
- serverName: z.string().default("dataops"),
3581
- credentialRef: z.string().role("credential-ref").default("DATAOPS_ACCESS_TOKEN"),
3582
- /**
3583
- * Volatile so the settings service persists it in this workspace's document: the timeout an
3584
- * operator needs depends on the query behind a tool, which is deployment knowledge the profile
3585
- * that mounts this plugin does not have.
3586
- *
3587
- * `z.any()` like the sync state above, and for the same reason: a volatile field is delivered
3588
- * to `apply` as a reference rather than a value, so a narrowed schema would describe a shape
3589
- * the runtime does not pass. The range is enforced where the value is read.
3590
- */
3591
- toolCallTimeoutMs: z.any().default(DEFAULT_TOOL_CALL_TIMEOUT_MS).volatile(),
3592
- /**
3593
- * Volatile so the settings service persists it in this workspace's document. The shape is
3594
- * left open because the sync state is this plugin's own record, not user configuration.
3595
- */
3596
- modelSync: z.any().default(MODEL_SYNC_DEFAULT).volatile(),
3597
- /** Volatile for the same reason as `modelSync`: it is this plugin's own record. */
3598
- settingsSync: z.any().default(SECTION_SYNC_DEFAULT).volatile(),
3599
- /**
3600
- * Namespaces offered in a publication. Validated as strings so a malformed profile entry fails
3601
- * at load rather than producing a publication no reader can apply.
3602
- */
3603
- distributedSettingsNamespaces: z.array(z.string()).default([]).description("Settings namespaces offered to other workspaces when this one publishes.")
3604
- });
3605
- function bearerToken(request) {
3606
- const authorization = request.headers.authorization?.trim() ?? "";
3607
- if (!authorization.startsWith("Bearer ")) return null;
3608
- const token = authorization.slice(7).trim();
3609
- return token === "" ? null : token;
3610
- }
3611
- /**
3612
- * Adopt the JWT the browser gateway attached to one request.
3613
- *
3614
- * Every browser request reaches this workspace through the DataOps gateway, which resolves the
3615
- * caller's session and forwards a fresh `authorization: Bearer <jwt>` — so the current credential
3616
- * arrives continuously, without any push, handshake or refresh protocol. The routes below are
3617
- * the only place this plugin can see that header, and reading it here is what keeps the stored
3618
- * credential from going stale: the value in it was captured once, while the caller's session is
3619
- * renewed by DataOps for as long as they stay signed in.
3620
- *
3621
- * A request without the header is normal rather than an error (same-origin fetches from inside
3622
- * the workspace do carry it, but a probe or a health check may not), so this only ever improves
3623
- * the stored value and never rejects the request.
3624
- *
3625
- * @param request - the incoming request, whose headers the gateway filled in.
3626
- * @returns once the credential has been updated, or immediately when there is nothing to adopt.
3627
- */
3628
- function adoptRequestJwt(ctx, accessRef, request) {
3629
- const token = bearerToken(request);
3630
- if (token === null) return Promise.resolve();
3631
- return (async () => {
3632
- if ((await ctx.credentials.resolve(accessRef))?.value === token) {
3633
- resetAuthState();
3634
- return;
3635
- }
3636
- await ctx.credentials.set(accessRef, token);
3637
- resetAuthState();
3638
- })().catch((error) => {
3639
- ctx.logger.warn("dataops-managed: request JWT could not be adopted");
3640
- ctx.logger.warn(error);
3641
- });
3642
- }
3643
- /** The skill this plugin contributes: how to answer a DataOps data question. */
3644
- const QUERY_SKILL_NAME = "dataops-query";
3645
- /** Location of the skill document inside the published package. */
3646
- const QUERY_SKILL_FILE = new URL("../skills/dataops-query/SKILL.md", import.meta.url);
3647
- /**
3648
- * Describe the query skill to the catalog without reading it.
3649
- *
3650
- * The description repeats what the skill file declares, because a catalog listing must
3651
- * answer whether the skill applies before its content is loaded.
3652
- */
3653
- const QUERY_SKILL = {
3654
- name: QUERY_SKILL_NAME,
3655
- description: "用户问数、取数、查数据、要报表时使用。包含选表策略(优先总表;有地域区分时先大后小)、取数前与用户确认资源清单、以及超时时主动分批次。",
3656
- invocation: {
3657
- modelInvocable: true,
3658
- userInvocable: true
3659
- },
3660
- provider: QUERY_SKILL_NAME,
3661
- source: "bundled",
3662
- resourceBase: {
3663
- kind: "directory",
3664
- path: fileURLToPath(new URL("../", import.meta.url))
3665
- },
3666
- rank: BUNDLED_SKILL_RANK,
3667
- locator: QUERY_SKILL_FILE
3668
- };
3669
- /** Serve the query skill to the catalog. */
3670
- const querySkillProvider = {
3671
- name: QUERY_SKILL_NAME,
3672
- list: () => Promise.resolve([QUERY_SKILL]),
3673
- async get() {
3674
- return {
3675
- ...QUERY_SKILL,
3676
- content: await readFile(QUERY_SKILL_FILE, "utf8")
3677
- };
3678
- }
3679
- };
3680
- /** The skill this plugin contributes: turn one spreadsheet into a queryable resource. */
3681
- const COLLECT_SKILL_NAME = "dataops-collect";
3682
- /** Location of the collection skill document inside the published package. */
3683
- const COLLECT_SKILL_FILE = new URL("../skills/dataops-collect/SKILL.md", import.meta.url);
3684
- /**
3685
- * Describe the collection skill to the catalog without reading it.
3686
- *
3687
- * The description carries the natural-language triggers so a request like "把这份表格建成
3688
- * 能问数的资源" selects this skill before the model sees the body.
3689
- */
3690
- const COLLECT_SKILL = {
3691
- name: COLLECT_SKILL_NAME,
3692
- description: "把表格 / Excel / CSV 建成可问数的数据资源,或把新表格追加到已有资源时使用。包含新建与追加的分岔、计划确认、建表写入、权限入口和结果汇报;确认计划前绝不建表。",
3693
- invocation: {
3694
- modelInvocable: true,
3695
- userInvocable: true
3696
- },
3697
- provider: COLLECT_SKILL_NAME,
3698
- source: "bundled",
3699
- resourceBase: {
3700
- kind: "directory",
3701
- path: fileURLToPath(new URL("../", import.meta.url))
3702
- },
3703
- rank: BUNDLED_SKILL_RANK,
3704
- locator: COLLECT_SKILL_FILE
3705
- };
3706
- /** Connector authoring skill: only superadmins hold `data:connector:authoring`. */
3707
- const CONNECTOR_SKILL_NAME = "api-connector-authoring";
3708
- const CONNECTOR_SKILL_FILE = new URL("../skills/api-connector-authoring/SKILL.md", import.meta.url);
3709
- const CONNECTOR_SKILL_ROOT = fileURLToPath(new URL("../", import.meta.url));
3710
- /** 该技能的门禁:只有持有 `data:connector:authoring` 的超管能看到(只对超管授权)。 */
3711
- const CONNECTOR_SKILL_PERMISSION = "data:connector:authoring";
3712
- const CONNECTOR_SKILL = {
3713
- name: CONNECTOR_SKILL_NAME,
3714
- metadata: { permissions: [CONNECTOR_SKILL_PERMISSION] },
3715
- description: "从接口文档(OpenAPI / Swagger / 接口说明)创建 API Connector 并导入为接口资源时使用。包含文档解析、导入粒度判断、资源命名与目录治理、GenUI 预览和用户确认后才导入的流程。",
3716
- invocation: {
3717
- modelInvocable: true,
3718
- userInvocable: true
3719
- },
3720
- provider: CONNECTOR_SKILL_NAME,
3721
- source: "bundled",
3722
- resourceBase: {
3723
- kind: "directory",
3724
- path: CONNECTOR_SKILL_ROOT
3725
- },
3726
- rank: BUNDLED_SKILL_RANK,
3727
- locator: CONNECTOR_SKILL_FILE
3728
- };
3729
- /**
3730
- * 当前 DataOps 身份是否允许看到连接器作者技能。
3731
- *
3732
- * 核心层对 provider 的列表是 fail-open 的:不认识的技能一律展示。所以门禁必须在这里做——
3733
- * 没有权限时返回空列表,`get` 也拒绝,避免只靠 SKILL.md 里的 frontmatter 声明。
3734
- */
3735
- let connectorSkillAllowed = () => false;
3736
- const connectorSkillProvider = {
3737
- name: CONNECTOR_SKILL_NAME,
3738
- list: () => Promise.resolve(connectorSkillAllowed() ? [CONNECTOR_SKILL] : []),
3739
- async get() {
3740
- if (!connectorSkillAllowed()) throw new Error("connector skill is not available for this account");
3741
- return {
3742
- ...CONNECTOR_SKILL,
3743
- content: await readFile(CONNECTOR_SKILL_FILE, "utf8")
3744
- };
3745
- }
3746
- };
3747
- /** Serve the collection skill to the catalog. */
3748
- const collectSkillProvider = {
3749
- name: COLLECT_SKILL_NAME,
3750
- list: () => Promise.resolve([COLLECT_SKILL]),
3751
- async get() {
3752
- return {
3753
- ...COLLECT_SKILL,
3754
- content: await readFile(COLLECT_SKILL_FILE, "utf8")
3755
- };
3756
- }
3757
- };
3758
- /**
3759
- * Accept the current DataOps JWT and expose DataOps MCP tools through its credential.
3760
- * @param ctx - DSH Host context with credentials, Web routes, and tools.
3761
- * @param config - Managed DataOps origin and MCP settings.
3762
- * @returns Startup readiness after an existing JWT is connected when present.
3763
- */
3764
- async function apply(ctx, config) {
3765
- const baseUrl = new URL(config.baseUrl).origin;
3766
- const accessRef = credentialRef(config.credentialRef);
3767
- let mcpFiber;
3768
- ctx.skills.registerProvider(() => querySkillProvider);
3769
- ctx.skills.registerProvider(() => collectSkillProvider);
3770
- ctx.skills.registerProvider(() => connectorSkillProvider);
3771
- const ensureMcp = async () => {
3772
- if (mcpFiber !== void 0 && mcpFiber.uid !== null) return;
3773
- const fiber = ctx.plugin(McpClient, {
3774
- transport: "streamable-http",
3775
- serverName: config.serverName,
3776
- url: `${baseUrl}/api/ai/data-query/mcp`,
3777
- headers: {},
3778
- bearerTokenRef: config.credentialRef,
3779
- toolCallTimeoutMs: volatileValue(config.toolCallTimeoutMs, DEFAULT_TOOL_CALL_TIMEOUT_MS)
3780
- });
3781
- mcpFiber = fiber;
3782
- try {
3783
- await fiber.await();
3784
- } catch (error) {
3785
- if (mcpFiber === fiber) mcpFiber = void 0;
3786
- await fiber.dispose();
3787
- throw error;
3788
- }
3789
- };
3790
- ctx.effect(() => async () => {
3791
- const fiber = mcpFiber;
3792
- mcpFiber = void 0;
3793
- if (fiber !== void 0 && fiber.uid !== null) await fiber.dispose();
3794
- }, "dataops-managed: MCP lifecycle");
3795
- /**
3796
- * Connect the MCP client when a JWT is already stored.
3797
- *
3798
- * A connect can fail for reasons this plugin does not own — the stored JWT may have expired,
3799
- * or DataOps may be unreachable at this moment — and those are states the settings routes
3800
- * report and recover from. Awaiting it here would abort activation, leaving the plugin with
3801
- * no routes at all: the panel then cannot read the very state that explains the failure, and
3802
- * the browser reports a connection error instead. The routes below are registered first, and
3803
- * a failed connect is reported rather than thrown.
3804
- */
3805
- const connectExisting = async () => {
3806
- if (await ctx.credentials.resolve(accessRef) === void 0) {
3807
- aiTools.clear();
3808
- return;
3809
- }
3810
- aiTools.refresh();
3811
- try {
3812
- await ensureMcp();
3813
- } catch (error) {
3814
- ctx.logger.warn("dataops-managed: connecting the DataOps MCP server failed; the settings routes stay up so a new JWT can be connected");
3815
- ctx.logger.warn(error);
3816
- }
3817
- };
3818
- /**
3819
- * The sync state lives in this plugin's own Config, so the settings service persists it in
3820
- * the workspace document and it survives a restart.
3821
- */
3822
- const syncStore = {
3823
- read: () => {
3824
- const state = volatileValue(config.modelSync, MODEL_SYNC_DEFAULT);
3825
- return {
3826
- detached: state?.detached === true,
3827
- adoptedModelIds: Array.isArray(state?.adoptedModelIds) ? state.adoptedModelIds : [],
3828
- privateModelIds: Array.isArray(state?.privateModelIds) ? state.privateModelIds : []
3829
- };
3830
- },
3831
- write: async (next) => {
3832
- await ctx.settings.update(MANAGED_PLUGIN_ID, { modelSync: next });
3833
- }
3834
- };
3835
- const settingsSync = new SettingsSync(ctx, {
3836
- read: () => {
3837
- const state = volatileValue(config.settingsSync, SECTION_SYNC_DEFAULT);
3838
- return { sections: typeof state?.sections === "object" && state.sections !== null ? state.sections : {} };
3839
- },
3840
- write: async (next) => {
3841
- await ctx.settings.update(MANAGED_PLUGIN_ID, { settingsSync: next });
3842
- }
3843
- });
3844
- settingsSyncRef = settingsSync;
3845
- /**
3846
- * The namespaces this deployment distributes.
3847
- *
3848
- * Listed here rather than inside the sync because what a deployment offers is its own choice:
3849
- * the sync knows how to carry a section, and this decides which ones travel.
3850
- */
3851
- const distributedNamespaces = () => {
3852
- const configured = config.distributedSettingsNamespaces;
3853
- return Array.isArray(configured) ? configured.filter((ns) => typeof ns === "string" && ns !== "") : [];
3854
- };
3855
- /**
3856
- * Read the sections this workspace would publish.
3857
- *
3858
- * A namespace no plugin owns is skipped: publishing a section this deployment cannot apply
3859
- * would offer readers values nothing on their side reads.
3860
- */
3861
- const collectSections = async () => {
3862
- const collected = [];
3863
- for (const ns of distributedNamespaces()) {
3864
- const descriptor = ctx.settings.describe().find((entry) => entry.ns === ns);
3865
- if (descriptor === void 0) continue;
3866
- const value = descriptor.value;
3867
- if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
3868
- collected.push({
3869
- ns,
3870
- value
3871
- });
3872
- }
3873
- return collected;
3874
- };
3875
- const modelSync = new ModelSync(ctx, {
3876
- baseUrl,
3877
- credentialRef: config.credentialRef,
3878
- collectSections
3879
- }, syncStore);
3880
- modelSyncRef = modelSync;
3881
- skillPlazaRef = new SkillPlaza(ctx, {
3882
- baseUrl,
3883
- credentialRef: config.credentialRef
3884
- });
3885
- const reviewApi = new ReviewApi(ctx, {
3886
- baseUrl,
3887
- credentialRef: config.credentialRef
3888
- });
3889
- reviewApiRef = reviewApi;
3890
- const resourceTabHub = new OpenResourceHub(ctx.logger);
3891
- ctx.effect(() => () => resourceTabHub.dispose(), "dataops-managed: resource tab SSE clients");
3892
- ctx.effect(() => ctx.webServer.register({
3893
- kind: "exact",
3894
- path: OPEN_RESOURCE_EVENTS_PATH,
3895
- handler: (request, response) => resourceTabHub.subscribe(request, response)
3896
- }), "dataops-managed: resource tab SSE route");
3897
- ctx.effect(() => ctx.webServer.register({
3898
- kind: "exact",
3899
- path: RESOURCE_TAB_CONFIG_PATH,
3900
- handler: async (request, response) => {
3901
- const payload = resolveResourceTabConfig(request, config.webBaseUrl);
3902
- let token;
3903
- try {
3904
- token = (await ctx.credentials.resolve(accessRef))?.value;
3905
- } catch {
3906
- token = void 0;
3907
- }
3908
- response.writeHead(200, {
3909
- "content-type": "application/json; charset=utf-8",
3910
- "cache-control": "no-store"
3911
- });
3912
- response.end(JSON.stringify(token === void 0 ? payload : {
3913
- ...payload,
3914
- token
3915
- }));
3916
- }
3917
- }), "dataops-managed: resource tab config route");
3918
- /**
3919
- * Same-origin resource reads for the tab's native fallback.
3920
- *
3921
- * A DSH page served from its own origin (for example the workspace port) cannot open the
3922
- * portal's `/embed/resources` iframe with a session: that document is cross-origin and its
3923
- * sessionStorage token is unreachable. The tab then renders the list in React and reads the
3924
- * same DataOps resources through this route, where the Host still owns the JWT.
3925
- */
3926
- ctx.effect(() => ctx.webServer.register({
3927
- kind: "prefix",
3928
- path: "/integrations/dataops/resources",
3929
- handler: async (request, response) => {
3930
- const method = (request.method ?? "GET").toUpperCase();
3931
- const url = new URL(request.url ?? "/", "http://dsh.internal");
3932
- const rest = url.pathname.slice(31).replace(/^\/+/u, "").replace(/\/+$/u, "");
3933
- const preferenceWrite = /^\d+\/(?:favorite|pin)$/u.test(rest);
3934
- if (method !== "GET" && !(preferenceWrite && (method === "PUT" || method === "DELETE"))) {
3935
- response.writeHead(405, {
3936
- allow: "GET, PUT, DELETE",
3937
- "content-length": "0"
3938
- });
3939
- response.end();
3940
- return;
3941
- }
3942
- const target = rest === "" ? "/api/resources" + (url.search || "") : "/api/resources/" + encodeURIComponent(rest) + (url.search || "");
3943
- const result = await reviewApi.request(target, { method });
3944
- writeJson(response, result.status, result.body);
3945
- }
3946
- }), "dataops-managed: resource list bridge");
3947
- /**
3948
- * The managed tool list follows the workspace's DataOps scope.
3949
- *
3950
- * `AiToolManager` registers only the skill/review tools the current principal can use and
3951
- * disposes them when the role changes. The credential event below is the existing auth-sync
3952
- * path: JWT adoption and the managed-auth route both go through `credentials.set`, which
3953
- * publishes this event after the write commits. The manager also observes the review-context
3954
- * route's answer, because a role edit does not change the JWT but does change the scope.
3955
- */
3956
- const aiTools = new AiToolManager(ctx, reviewApi, resourceTabHub);
3957
- connectorSkillAllowed = () => {
3958
- const scope = aiTools.currentScope();
3959
- if (scope === void 0) return false;
3960
- return (scope.permissions ?? scope.permissionKeys ?? []).includes(CONNECTOR_SKILL_PERMISSION);
3961
- };
3962
- ctx.effect(() => () => aiTools.dispose(), "dataops-managed: skill and review tool disclosure");
3963
- ctx.effect(() => ctx.on("credentials/reference-updated", (ref) => {
3964
- if (String(ref) !== config.credentialRef) return;
3965
- aiTools.refresh(true);
3966
- }), "dataops-managed: tool disclosure follows the DataOps credential");
3967
- setWorkspaceLimits(new WorkspaceLimits(ctx, {
3968
- baseUrl,
3969
- credentialRef: config.credentialRef
3970
- }));
3971
- const workspaceUpgrade = new WorkspaceUpgrade(ctx, {
3972
- baseUrl,
3973
- credentialRef: config.credentialRef
3974
- });
3975
- /**
3976
- * Adopt the publisher's models once the workspace has a session.
3977
- *
3978
- * Adoption waits for the JWT because the publication is read with it; a workspace that has
3979
- * not been authorized yet simply tries again when its session arrives.
3980
- */
3981
- const adoptNow = async () => {
3982
- try {
3983
- await modelSync.adopt();
3984
- } catch (error) {
3985
- ctx.logger.warn("dataops-managed: model sync could not adopt the published models");
3986
- ctx.logger.warn(error);
3987
- }
3988
- try {
3989
- const published = await modelSync.readPublishedSections();
3990
- if (published.length > 0) await settingsSync.adopt(published);
3991
- } catch (error) {
3992
- ctx.logger.warn("dataops-managed: distributed settings could not be adopted");
3993
- ctx.logger.warn(error);
3994
- }
3995
- };
3996
- if (await ctx.credentials.resolve(accessRef) !== void 0) adoptNow();
3997
- ctx.effect(() => ctx.webServer.register({
3998
- kind: "exact",
3999
- path: MANAGED_AUTH_PATH,
4000
- handler: async (request, response) => {
4001
- if (request.method !== "POST") {
4002
- response.writeHead(405, {
4003
- allow: "POST",
4004
- "content-length": "0"
4005
- });
4006
- response.end();
4007
- return;
4008
- }
4009
- await adoptRequestJwt(ctx, accessRef, request);
4010
- const token = bearerToken(request);
4011
- if (token === null) {
4012
- response.writeHead(401, { "content-length": "0" });
4013
- response.end();
4014
- return;
4015
- }
4016
- await ctx.credentials.set(accessRef, token);
4017
- resetAuthState();
4018
- aiTools.refresh(true);
4019
- await ensureMcp();
4020
- await adoptNow();
4021
- response.writeHead(204, { "cache-control": "no-store" });
4022
- response.end();
4023
- }
4024
- }), "dataops-managed: JWT intake route");
4025
- /**
4026
- * The settings surface the workspace's own pages read and write.
4027
- *
4028
- * Same-origin only: the browser reaches these through the gateway that already authenticated
4029
- * it, and the DataOps JWT they act with is the one this plugin holds, never a value the page
4030
- * supplies.
4031
- */
4032
- ctx.effect(() => ctx.webServer.register({
4033
- kind: "exact",
4034
- path: MODEL_SYNC_PATH,
4035
- handler: async (request, response) => {
4036
- const sync = currentModelSync();
4037
- if (sync === void 0) {
4038
- writeJson(response, 503, { error: "model sync is not active" });
4039
- return;
4040
- }
4041
- try {
4042
- if (request.method === "GET") {
4043
- writeJson(response, 200, {
4044
- ...await sync.status(),
4045
- sections: settingsSyncRef === void 0 ? [] : settingsSyncRef.status(distributedNamespaces())
4046
- });
4047
- return;
4048
- }
4049
- if (request.method !== "POST") {
4050
- response.writeHead(405, {
4051
- allow: "GET, POST",
4052
- "content-length": "0"
4053
- });
4054
- response.end();
4055
- return;
4056
- }
4057
- const body = await readJson(request);
4058
- const action = typeof body?.action === "string" ? body.action : "";
4059
- if (action === "publish") {
4060
- const sharingEnabled = body?.sharingEnabled === true;
4061
- await sync.publish(sharingEnabled);
4062
- writeJson(response, 200, await sync.status());
4063
- return;
4064
- }
4065
- if (action === "publish-defaults") {
4066
- await sync.publish(true);
4067
- writeJson(response, 200, {
4068
- ...await sync.status(),
4069
- sections: settingsSyncRef === void 0 ? [] : settingsSyncRef.status(distributedNamespaces())
4070
- });
4071
- return;
4072
- }
4073
- if (action === "detach") {
4074
- await sync.detach();
4075
- writeJson(response, 200, await sync.status());
4076
- return;
4077
- }
4078
- if (action === "detach-section") {
4079
- const ns = typeof body?.ns === "string" ? body.ns.trim() : "";
4080
- if (ns === "") {
4081
- writeJson(response, 400, { error: "detach-section needs a namespace" });
4082
- return;
4083
- }
4084
- await settingsSyncRef?.detach(ns);
4085
- writeJson(response, 200, {
4086
- ...await sync.status(),
4087
- sections: settingsSyncRef === void 0 ? [] : settingsSyncRef.status(distributedNamespaces())
4088
- });
4089
- return;
4090
- }
4091
- if (action === "resume") {
4092
- await sync.resumeFollowing();
4093
- await sync.adopt();
4094
- writeJson(response, 200, await sync.status());
4095
- return;
4096
- }
4097
- if (action === "private-models") {
4098
- const ids = Array.isArray(body?.privateModelIds) ? body.privateModelIds.filter((id) => typeof id === "string") : [];
4099
- await sync.setPrivateModels(ids, body?.sharingEnabled === true);
4100
- writeJson(response, 200, await sync.status());
4101
- return;
4102
- }
4103
- writeJson(response, 400, { error: "unknown action" });
4104
- } catch (error) {
4105
- ctx.logger.warn("dataops-managed: model sync request failed");
4106
- ctx.logger.warn(error);
4107
- writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
4108
- }
4109
- }
4110
- }), "dataops-managed: model sync routes");
4111
- /**
4112
- * The skill plaza surface the workspace's skill center reads and writes.
4113
- *
4114
- * Same-origin only, like the model routes: the browser reaches these through the gateway
4115
- * that already authenticated it, and the DataOps JWT they act with is the one this plugin
4116
- * holds rather than a value the page supplies.
4117
- */
4118
- ctx.effect(() => ctx.webServer.register({
4119
- kind: "exact",
4120
- path: SKILL_PLAZA_PATH,
4121
- handler: async (request, response) => {
4122
- const plaza = currentSkillPlaza();
4123
- if (plaza === void 0) {
4124
- writeJson(response, 503, { error: "skill plaza is not active" });
4125
- return;
4126
- }
4127
- try {
4128
- if (request.method === "GET") {
4129
- const url = new URL(request.url ?? "/", "http://localhost");
4130
- const mine = url.searchParams.get("mine") === "1";
4131
- const page = await plaza.listPage({
4132
- tag: url.searchParams.get("tag") ?? void 0,
4133
- query: url.searchParams.get("q") ?? void 0,
4134
- status: url.searchParams.get("status") ?? void 0,
4135
- scope: mine ? "mine" : url.searchParams.get("scope") ?? void 0,
4136
- departmentCode: url.searchParams.get("departmentCode") ?? void 0
4137
- });
4138
- writeJson(response, 200, {
4139
- skills: mine ? page.skills.filter((skill) => skill.sharedByMe) : page.skills,
4140
- tags: mine ? [] : await plaza.tags(),
4141
- ...page.counts === void 0 ? {} : { counts: page.counts }
4142
- });
4143
- return;
4144
- }
4145
- if (request.method !== "POST") {
4146
- response.writeHead(405, {
4147
- allow: "GET, POST",
4148
- "content-length": "0"
4149
- });
4150
- response.end();
4151
- return;
4152
- }
4153
- const body = await readJson(request);
4154
- const action = typeof body?.action === "string" ? body.action : "";
4155
- if (action === "local-skills") {
4156
- writeJson(response, 200, { skills: await readLocalSkills(ctx) });
4157
- return;
4158
- }
4159
- if (action === "share" || action === "submit") {
4160
- const name = typeof body?.name === "string" ? body.name : "";
4161
- const instruction = typeof body?.instruction === "string" ? body.instruction : "";
4162
- const description = typeof body?.description === "string" ? body.description : void 0;
4163
- const tags = Array.isArray(body?.tags) ? body.tags.filter((tag) => typeof tag === "string") : [];
4164
- if (name.trim() === "" || instruction.trim() === "") {
4165
- writeJson(response, 400, { error: "name and instruction are required" });
4166
- return;
4167
- }
4168
- writeJson(response, 200, {
4169
- ok: true,
4170
- skill: await plaza.share({
4171
- name,
4172
- description,
4173
- instruction,
4174
- tags
4175
- })
4176
- });
4177
- return;
4178
- }
4179
- if (action === "review") {
4180
- const api = reviewApiRef;
4181
- if (api === void 0) {
4182
- writeJson(response, 503, { error: "review api is not active" });
4183
- return;
4184
- }
4185
- const id = typeof body?.id === "number" ? body.id : void 0;
4186
- const decision = body?.decision === "reject" ? "reject" : body?.decision === "approve" ? "approve" : null;
4187
- if (id === void 0 || decision === null) {
4188
- writeJson(response, 400, { error: "id and decision are required" });
4189
- return;
4190
- }
4191
- const result = await api.request("/api/ai/review/decide", {
4192
- method: "POST",
4193
- body: JSON.stringify({
4194
- skills: [id],
4195
- workflows: [],
4196
- decision,
4197
- note: typeof body?.note === "string" ? body.note : "",
4198
- authorization: {
4199
- confirmed: true,
4200
- reason: "skill-plaza-review"
4201
- }
4202
- })
4203
- });
4204
- writeJson(response, result.status, result.body);
4205
- return;
4206
- }
4207
- if (action === "unshare") {
4208
- if (typeof body?.id === "number") await plaza.unshare(body.id);
4209
- writeJson(response, 200, { success: true });
4210
- return;
4211
- }
4212
- if (action === "install") {
4213
- writeJson(response, 200, (typeof body?.id === "number" ? await plaza.install(body.id) : null) ?? {
4214
- installed: false,
4215
- skillKey: null,
4216
- keptLocal: false
4217
- });
4218
- return;
4219
- }
4220
- writeJson(response, 400, { error: "unknown action" });
4221
- } catch (error) {
4222
- ctx.logger.warn("dataops-managed: skill plaza request failed");
4223
- ctx.logger.warn(error);
4224
- writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
4225
- }
4226
- }
4227
- }), "dataops-managed: skill plaza routes");
4228
- /**
4229
- * Review context, notifications, AI scan/decide, the permission centre and review settings.
4230
- *
4231
- * These are thin same-origin bridges: DataOps owns identity, authorization, the state machine
4232
- * and the audit trail; this route only attaches the workspace JWT and forwards answers so the
4233
- * browser can show a precise waiting/refused state instead of flattening both to "empty".
4234
- */
4235
- ctx.effect(() => ctx.webServer.register({
4236
- kind: "exact",
4237
- path: REVIEW_CONTEXT_PATH,
4238
- handler: async (request, response) => {
4239
- if (request.method !== "GET") {
4240
- response.writeHead(405, {
4241
- allow: "GET",
4242
- "content-length": "0"
4243
- });
4244
- response.end();
4245
- return;
4246
- }
4247
- const api = reviewApiRef;
4248
- if (api === void 0) {
4249
- writeJson(response, 503, { error: "review api is not active" });
4250
- return;
4251
- }
4252
- try {
4253
- const result = await api.request("/api/ai/review/context");
4254
- aiTools.observeContext(result);
4255
- writeJson(response, result.status, result.body);
4256
- } catch (error) {
4257
- ctx.logger.warn("dataops-managed: review context failed");
4258
- writeJson(response, 502, { error: error instanceof Error ? error.message : String(error) });
4259
- }
4260
- }
4261
- }), "dataops-managed: review context route");
4262
- ctx.effect(() => ctx.webServer.register({
4263
- kind: "exact",
4264
- path: REVIEW_NOTIFICATIONS_PATH,
4265
- handler: async (request, response) => {
4266
- const api = reviewApiRef;
4267
- if (api === void 0) {
4268
- writeJson(response, 503, { error: "review api is not active" });
4269
- return;
4270
- }
4271
- try {
4272
- if (request.method === "GET") {
4273
- const url = new URL(request.url ?? "/", "http://localhost");
4274
- const params = new URLSearchParams();
4275
- if (url.searchParams.get("unreadOnly") === "true") params.set("unreadOnly", "true");
4276
- if (url.searchParams.get("limit") !== null) params.set("limit", url.searchParams.get("limit"));
4277
- const result = await api.request("/api/ai/review-notifications" + (params.size === 0 ? "" : "?" + params.toString()));
4278
- writeJson(response, result.status, result.body);
4279
- return;
4280
- }
4281
- if (request.method !== "POST") {
4282
- response.writeHead(405, {
4283
- allow: "GET, POST",
4284
- "content-length": "0"
4285
- });
4286
- response.end();
4287
- return;
4288
- }
4289
- const body = await readJson(request);
4290
- const result = await api.request("/api/ai/review-notifications/read", {
4291
- method: "POST",
4292
- body: JSON.stringify(body ?? {})
4293
- });
4294
- writeJson(response, result.status, result.body);
4295
- } catch (error) {
4296
- ctx.logger.warn("dataops-managed: review notifications failed");
4297
- writeJson(response, 502, { error: error instanceof Error ? error.message : String(error) });
4298
- }
4299
- }
4300
- }), "dataops-managed: review notifications route");
4301
- ctx.effect(() => ctx.webServer.register({
4302
- kind: "exact",
4303
- path: REVIEW_ACTION_PATH,
4304
- handler: async (request, response) => {
4305
- if (request.method !== "POST") {
4306
- response.writeHead(405, {
4307
- allow: "POST",
4308
- "content-length": "0"
4309
- });
4310
- response.end();
4311
- return;
4312
- }
4313
- const api = reviewApiRef;
4314
- if (api === void 0) {
4315
- writeJson(response, 503, { error: "review api is not active" });
4316
- return;
4317
- }
4318
- try {
4319
- const body = await readJson(request);
4320
- const action = typeof body?.action === "string" ? body.action : "";
4321
- const skills = Array.isArray(body?.skills) ? body.skills : [];
4322
- const workflows = Array.isArray(body?.workflows) ? body.workflows : [];
4323
- if (action === "scan") {
4324
- const result = await api.request("/api/ai/review/scan", {
4325
- method: "POST",
4326
- body: JSON.stringify({
4327
- skills,
4328
- workflows
4329
- })
4330
- });
4331
- writeJson(response, result.status, result.body);
4332
- return;
4333
- }
4334
- if (action === "decide") {
4335
- const result = await api.request("/api/ai/review/decide", {
4336
- method: "POST",
4337
- body: JSON.stringify({
4338
- skills,
4339
- workflows,
4340
- decision: body?.decision,
4341
- note: body?.note,
4342
- authorization: body?.authorization
4343
- })
4344
- });
4345
- writeJson(response, result.status, result.body);
4346
- return;
4347
- }
4348
- writeJson(response, 400, { error: "unknown review action" });
4349
- } catch (error) {
4350
- ctx.logger.warn("dataops-managed: review action failed");
4351
- writeJson(response, 502, { error: error instanceof Error ? error.message : String(error) });
4352
- }
4353
- }
4354
- }), "dataops-managed: review action route");
4355
- ctx.effect(() => ctx.webServer.register({
4356
- kind: "exact",
4357
- path: RBAC_PATH,
4358
- handler: async (request, response) => {
4359
- const api = reviewApiRef;
4360
- if (api === void 0) {
4361
- writeJson(response, 503, { error: "review api is not active" });
4362
- return;
4363
- }
4364
- try {
4365
- if (request.method === "GET") {
4366
- const url = new URL(request.url ?? "/", "http://localhost");
4367
- const section = url.searchParams.get("section") ?? "matrix";
4368
- const suffix = section === "members" ? "?q=" + encodeURIComponent(url.searchParams.get("q") ?? "") + "&departmentCode=" + encodeURIComponent(url.searchParams.get("departmentCode") ?? "") : section === "resources" ? "?kind=" + encodeURIComponent(url.searchParams.get("kind") ?? "") : "";
4369
- const target = section === "members" ? "/api/system/permission-center/members" + suffix : section === "departments" ? "/api/system/permission-center/departments" : section === "resources" ? "/api/system/permission-center/resources" + suffix : "/api/system/permission-center/matrix" + (url.searchParams.get("scope") === "dsh" ? "?scope=dsh" : "");
4370
- const result = await api.request(target);
4371
- writeJson(response, result.status, result.body);
4372
- return;
4373
- }
4374
- if (request.method !== "PUT") {
4375
- response.writeHead(405, {
4376
- allow: "GET, PUT",
4377
- "content-length": "0"
4378
- });
4379
- response.end();
4380
- return;
4381
- }
4382
- const body = await readJson(request);
4383
- const section = typeof body?.section === "string" ? body.section : "";
4384
- const value = typeof body?.value === "object" && body.value !== null ? body.value : {};
4385
- if (section === "roles") {
4386
- const result = await api.request("/api/system/permission-center/matrix", {
4387
- method: "PUT",
4388
- body: JSON.stringify(value)
4389
- });
4390
- writeJson(response, result.status, result.body);
4391
- return;
4392
- }
4393
- if (section === "members" && typeof value.userId === "string") {
4394
- const result = await api.request("/api/system/permission-center/members/" + encodeURIComponent(value.userId) + "/roles", {
4395
- method: "PUT",
4396
- body: JSON.stringify({ roleCodes: value.roleCodes })
4397
- });
4398
- writeJson(response, result.status, result.body);
4399
- return;
4400
- }
4401
- if (section === "departments" && typeof value.code === "string") {
4402
- const result = await api.request("/api/system/permission-center/departments/" + encodeURIComponent(value.code) + "/admin", {
4403
- method: "PUT",
4404
- body: JSON.stringify({ userIds: value.userIds })
4405
- });
4406
- writeJson(response, result.status, result.body);
4407
- return;
4408
- }
4409
- if (section === "resources" && typeof value.kind === "string" && value.id !== void 0) {
4410
- const result = await api.request("/api/system/permission-center/resources/" + encodeURIComponent(value.kind) + "/" + encodeURIComponent(String(value.id)) + "/scope", {
4411
- method: "PUT",
4412
- body: JSON.stringify({
4413
- departmentCode: value.departmentCode,
4414
- visibility: value.visibility,
4415
- ownerId: value.ownerId
4416
- })
4417
- });
4418
- writeJson(response, result.status, result.body);
4419
- return;
4420
- }
4421
- writeJson(response, 400, { error: "unknown rbac section" });
4422
- } catch (error) {
4423
- ctx.logger.warn("dataops-managed: permission centre failed");
4424
- writeJson(response, 502, { error: error instanceof Error ? error.message : String(error) });
4425
- }
4426
- }
4427
- }), "dataops-managed: permission centre route");
4428
- ctx.effect(() => ctx.webServer.register({
4429
- kind: "exact",
4430
- path: DEPARTMENTS_PATH,
4431
- handler: async (request, response) => {
4432
- const api = reviewApiRef;
4433
- if (api === void 0) {
4434
- writeJson(response, 503, { error: "review api is not active" });
4435
- return;
4436
- }
4437
- try {
4438
- const body = await readJson(request);
4439
- if (request.method === "POST") {
4440
- const result = await api.request("/api/system/departments", {
4441
- method: "POST",
4442
- body: JSON.stringify(body ?? {})
4443
- });
4444
- writeJson(response, result.status, result.body);
4445
- return;
4446
- }
4447
- if (request.method !== "PATCH" && request.method !== "DELETE") {
4448
- response.writeHead(405, {
4449
- allow: "POST, PATCH, DELETE",
4450
- "content-length": "0"
4451
- });
4452
- response.end();
4453
- return;
4454
- }
4455
- const code = typeof body?.code === "string" ? body.code : "";
4456
- if (code === "") {
4457
- writeJson(response, 400, { error: "department code is required" });
4458
- return;
4459
- }
4460
- const current = await api.request("/api/system/departments/" + encodeURIComponent(code));
4461
- const record = typeof current.body === "object" && current.body !== null ? current.body : {};
4462
- const department = typeof record.department === "object" && record.department !== null ? record.department : {};
4463
- const updatedAt = typeof body?.updatedAt === "string" ? body.updatedAt : department.updatedAt;
4464
- if (typeof updatedAt !== "string") {
4465
- writeJson(response, current.status === 200 ? 409 : current.status, { error: "department not found" });
4466
- return;
4467
- }
4468
- if (request.method === "PATCH") {
4469
- const result = await api.request("/api/system/departments/" + encodeURIComponent(code), {
4470
- method: "PATCH",
4471
- body: JSON.stringify({
4472
- updatedAt,
4473
- name: body?.name,
4474
- parentCode: body?.parentCode,
4475
- description: body?.description,
4476
- owner: body?.owner,
4477
- enabled: body?.enabled
4478
- })
4479
- });
4480
- writeJson(response, result.status, result.body);
4481
- return;
4482
- }
4483
- const result = await api.request("/api/system/departments/" + encodeURIComponent(code), {
4484
- method: "DELETE",
4485
- body: JSON.stringify({ updatedAt })
4486
- });
4487
- writeJson(response, result.status, result.body);
4488
- } catch (error) {
4489
- ctx.logger.warn("dataops-managed: department bridge failed");
4490
- writeJson(response, 502, { error: error instanceof Error ? error.message : String(error) });
4491
- }
4492
- }
4493
- }), "dataops-managed: department CRUD bridge");
4494
- ctx.effect(() => ctx.webServer.register({
4495
- kind: "exact",
4496
- path: REVIEW_SETTINGS_PATH,
4497
- handler: async (request, response) => {
4498
- const api = reviewApiRef;
4499
- if (api === void 0) {
4500
- writeJson(response, 503, { error: "review api is not active" });
4501
- return;
4502
- }
4503
- try {
4504
- if (request.method === "GET") {
4505
- const result = await api.request("/api/integrations/dataops/review-settings");
4506
- writeJson(response, result.status, result.body);
4507
- return;
4508
- }
4509
- if (request.method !== "PUT" && request.method !== "POST") {
4510
- response.writeHead(405, {
4511
- allow: "GET, POST, PUT",
4512
- "content-length": "0"
4513
- });
4514
- response.end();
4515
- return;
4516
- }
4517
- const body = await readJson(request);
4518
- const result = await api.request("/api/integrations/dataops/review-settings", {
4519
- method: "POST",
4520
- body: JSON.stringify(body ?? {})
4521
- });
4522
- writeJson(response, result.status, result.body);
4523
- } catch (error) {
4524
- ctx.logger.warn("dataops-managed: review settings failed");
4525
- writeJson(response, 502, { error: error instanceof Error ? error.message : String(error) });
4526
- }
4527
- }
4528
- }), "dataops-managed: review settings route");
4529
- /**
4530
- * The workspace limits an administrator sets in DataOps.
4531
- *
4532
- * Read through the plugin because it holds the DataOps JWT; the page cannot reach those settings
4533
- * itself. Same-origin only, like its neighbours.
4534
- */
4535
- ctx.effect(() => ctx.webServer.register({
4536
- kind: "exact",
4537
- path: WORKSPACE_LIMITS_PATH,
4538
- handler: async (request, response) => {
4539
- const limits = currentWorkspaceLimits();
4540
- if (limits === void 0) {
4541
- writeJson(response, 503, { error: "workspace limits are not active" });
4542
- return;
4543
- }
4544
- try {
4545
- if (request.method === "GET") {
4546
- const status = await limits.status();
4547
- if (status === void 0) {
4548
- writeJson(response, 503, { error: "workspace limits are not active" });
4549
- return;
4550
- }
4551
- writeJson(response, 200, status);
4552
- return;
4553
- }
4554
- if (request.method !== "POST") {
4555
- response.writeHead(405, {
4556
- allow: "GET, POST",
4557
- "content-length": "0"
4558
- });
4559
- response.end();
4560
- return;
4561
- }
4562
- const body = await readJson(request);
4563
- const fileReadMaxBytes = body?.fileReadMaxBytes;
4564
- const uploadMaxBytes = body?.uploadMaxBytes;
4565
- if (typeof fileReadMaxBytes !== "number" || typeof uploadMaxBytes !== "number") {
4566
- writeJson(response, 400, { error: "both byte ceilings are required" });
4567
- return;
4568
- }
4569
- const status = await limits.save({
4570
- fileReadMaxBytes,
4571
- uploadMaxBytes
4572
- });
4573
- if (status === void 0) {
4574
- writeJson(response, 503, { error: "workspace limits are not active" });
4575
- return;
4576
- }
4577
- writeJson(response, 200, status);
4578
- } catch (error) {
4579
- if (error instanceof WorkspaceLimitsRejection) {
4580
- writeJson(response, error.status, { error: error.message });
4581
- return;
4582
- }
4583
- ctx.logger.warn("dataops-managed: workspace limits request failed");
4584
- ctx.logger.warn(error);
4585
- writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
4586
- }
4587
- }
4588
- }), "dataops-managed: workspace limits route");
4589
- /**
4590
- * The tool-call timeout, stored in this plugin's own Config.
4591
- *
4592
- * The settings service keeps the value in this workspace's document and updates the volatile
4593
- * reference in place, so a change takes effect on the next connection without a restart. The
4594
- * profile therefore does not have to anticipate how long a deployment's queries take.
4595
- */
4596
- ctx.effect(() => ctx.webServer.register({
4597
- kind: "exact",
4598
- path: TOOL_TIMEOUT_PATH,
4599
- handler: async (request, response) => {
4600
- const read = () => volatileValue(config.toolCallTimeoutMs, DEFAULT_TOOL_CALL_TIMEOUT_MS);
4601
- if (request.method === "GET") {
4602
- writeJson(response, 200, { toolCallTimeoutMs: read() });
4603
- return;
4604
- }
4605
- if (request.method !== "POST") {
4606
- response.writeHead(405, {
4607
- allow: "GET, POST",
4608
- "content-length": "0"
4609
- });
4610
- response.end();
4611
- return;
4612
- }
4613
- try {
4614
- const milliseconds = (await readJson(request))?.toolCallTimeoutMs;
4615
- if (typeof milliseconds !== "number" || !Number.isSafeInteger(milliseconds)) {
4616
- writeJson(response, 400, { error: "toolCallTimeoutMs must be a whole number of milliseconds" });
4617
- return;
4618
- }
4619
- const seconds = milliseconds / 1e3;
4620
- if (seconds < 1 || seconds > 3600) {
4621
- writeJson(response, 400, { error: "the timeout must be between " + String(1) + " and " + String(TOOL_TIMEOUT_MAX_SECONDS) + " seconds" });
4622
- return;
4623
- }
4624
- await ctx.settings.update(MANAGED_PLUGIN_ID, { toolCallTimeoutMs: milliseconds });
4625
- writeJson(response, 200, { toolCallTimeoutMs: milliseconds });
4626
- } catch (error) {
4627
- ctx.logger.warn("dataops-managed: tool timeout request failed");
4628
- ctx.logger.warn(error);
4629
- writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
4630
- }
4631
- }
4632
- }), "dataops-managed: tool timeout route");
4633
- /**
4634
- * Workspace image upgrade: DataOps owns the image comparison and restart; this
4635
- * plugin adds the DSH-side running-session snapshot and post-restart recovery.
4636
- */
4637
- ctx.effect(() => ctx.webServer.register({
4638
- kind: "exact",
4639
- path: WORKSPACE_UPGRADE_PATH,
4640
- handler: async (request, response) => {
4641
- try {
4642
- if (request.method === "GET") {
4643
- const preview = await workspaceUpgrade.preview();
4644
- writeJson(response, 200, {
4645
- imageStatus: preview.imageStatus,
4646
- configuredImage: preview.configuredImage,
4647
- activeSessions: preview.activeSessions
4648
- });
4649
- return;
4650
- }
4651
- if (request.method !== "POST") {
4652
- response.writeHead(405, {
4653
- allow: "GET, POST",
4654
- "content-length": "0"
4655
- });
4656
- response.end();
4657
- return;
4658
- }
4659
- const state = await workspaceUpgrade.upgrade();
4660
- writeJson(response, 202, {
4661
- accepted: true,
4662
- upgradeId: state.upgradeId,
4663
- sessions: state.sessions.length
4664
- });
4665
- } catch (error) {
4666
- writeJson(response, error instanceof WorkspaceUpgradeError ? error.status : 502, { error: error instanceof Error ? error.message : String(error) });
4667
- }
4668
- }
4669
- }), "dataops-managed: workspace upgrade route");
4670
- recoverWorkspaceUpgradeAfterBoot(workspaceUpgrade);
4671
- /**
4672
- * What the last DataOps answer said about this workspace's credential.
4673
- *
4674
- * The settings surfaces need this because a 401 is handled deep inside a call that degrades to
4675
- * "no data", so the panel renders as if the workspace simply has nothing to show. Reading this
4676
- * route is how the interface learns the reason is an ended session rather than an empty one.
4677
- * The recorded state is an observation, never an authority: DataOps still decides.
4678
- */
4679
- ctx.effect(() => ctx.webServer.register({
4680
- kind: "exact",
4681
- path: AUTH_STATE_PATH,
4682
- handler: async (request, response) => {
4683
- if (request.method === "POST") {
4684
- const body = await readJson(request).catch(() => null);
4685
- if (body?.state === "expired") noteExpired();
4686
- else if (body?.state === "valid") noteAccepted();
4687
- else {
4688
- response.writeHead(400, { "content-length": "0" });
4689
- response.end();
4690
- return;
4691
- }
4692
- response.writeHead(204, { "cache-control": "no-store" });
4693
- response.end();
4694
- return;
4695
- }
4696
- if (request.method !== "GET") {
4697
- response.writeHead(405, {
4698
- allow: "GET, POST",
4699
- "content-length": "0"
4700
- });
4701
- response.end();
4702
- return;
4703
- }
4704
- await adoptRequestJwt(ctx, accessRef, request);
4705
- writeJson(response, 200, { state: currentAuthState() });
4706
- }
4707
- }), "dataops-managed: auth state route");
4708
- /**
4709
- * The skill center's connector tab. The route is a same-origin presentation bridge: reads
4710
- * return only capabilities the current scope can use, and writes persist the connector's own
4711
- * enable state. It never substitutes for a DataOps authorization decision.
4712
- */
4713
- ctx.effect(() => ctx.webServer.register({
4714
- kind: "exact",
4715
- path: CONNECTORS_PATH,
4716
- handler: async (request, response) => {
4717
- try {
4718
- if (request.method === "GET") {
4719
- if (aiTools.currentScope() === void 0) await aiTools.refresh();
4720
- const state = await readConnectorState();
4721
- writeJson(response, 200, { connectors: [buildConnectorView(aiTools.currentScope(), state)] });
4722
- return;
4723
- }
4724
- if (request.method === "POST") {
4725
- const body = await readJson(request);
4726
- if (body === null) {
4727
- writeJson(response, 400, { error: "connector state requires a JSON body" });
4728
- return;
4729
- }
4730
- if (body.connectorId !== "dataops-managed") {
4731
- writeJson(response, 404, { error: "unknown connector" });
4732
- return;
4733
- }
4734
- const state = await readConnectorState();
4735
- const capabilityId = typeof body.capabilityId === "string" ? body.capabilityId : void 0;
4736
- if (capabilityId !== void 0) {
4737
- if (!hasCapability(capabilityId)) {
4738
- writeJson(response, 400, { error: "unknown capability" });
4739
- return;
4740
- }
4741
- if (!buildConnectorView(aiTools.currentScope(), state).capabilities.some((row) => row.id === capabilityId)) {
4742
- writeJson(response, 403, { error: "capability is not available to this account" });
4743
- return;
4744
- }
4745
- if (typeof body.enabled !== "boolean") {
4746
- writeJson(response, 400, { error: "capability state requires enabled:boolean" });
4747
- return;
4748
- }
4749
- state.capabilities[capabilityId] = body.enabled;
4750
- } else {
4751
- if (typeof body.enabled !== "boolean") {
4752
- writeJson(response, 400, { error: "connector state requires enabled:boolean" });
4753
- return;
4754
- }
4755
- state.enabled = body.enabled;
4756
- }
4757
- await writeConnectorState(state);
4758
- await aiTools.refreshCapabilities();
4759
- writeJson(response, 200, { connectors: [buildConnectorView(aiTools.currentScope(), state)] });
4760
- return;
4761
- }
4762
- response.writeHead(405, {
4763
- allow: "GET, POST",
4764
- "content-length": "0"
4765
- });
4766
- response.end();
4767
- } catch (error) {
4768
- ctx.logger.warn("dataops-managed: connector catalogue route failed");
4769
- ctx.logger.warn(error);
4770
- writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
4771
- }
4772
- }
4773
- }), "dataops-managed: skill-center connector catalogue");
4774
- await connectExisting();
4775
- }
4776
- /** Read and parse a JSON request body, tolerating an absent one. */
4777
- async function readJson(request) {
4778
- const chunks = [];
4779
- for await (const chunk of request) chunks.push(chunk);
4780
- if (chunks.length === 0) return null;
4781
- try {
4782
- const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
4783
- return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
4784
- } catch {
4785
- return null;
4786
- }
4787
- }
4788
- /** Answer one settings request as JSON. */
4789
- function writeJson(response, status, body) {
4790
- const payload = JSON.stringify(body);
4791
- response.writeHead(status, {
4792
- "content-type": "application/json",
4793
- "cache-control": "no-store"
4794
- });
4795
- response.end(payload);
4796
- }
4797
- //#endregion
4798
- export { AUTH_STATE_PATH, Config, DEFAULT_TOOL_CALL_TIMEOUT_MS, DEPARTMENTS_PATH, MANAGED_AUTH_PATH, MANAGED_PLUGIN_ID, MODEL_SYNC_PATH, RBAC_PATH, REVIEW_ACTION_PATH, REVIEW_CONTEXT_PATH, REVIEW_NOTIFICATIONS_PATH, REVIEW_SETTINGS_PATH, SKILL_PLAZA_PATH, TOOL_TIMEOUT_MAX_SECONDS, TOOL_TIMEOUT_MIN_SECONDS, TOOL_TIMEOUT_PATH, WORKSPACE_LIMITS_PATH, WORKSPACE_UPGRADE_PATH, adoptRequestJwt, apply, currentModelSync, currentSettingsSync, currentSkillPlaza, currentWorkspaceLimits, inject, name };