@voxslopuli/teamdynamix-mcp 0.5.0 → 0.5.2
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/index.js +1453 -297
- package/index.js.map +1 -1
- package/package.json +10 -5
- package/sweep.d.ts +1 -0
- package/sweep.js +1076 -0
- package/sweep.js.map +1 -0
package/sweep.js
ADDED
|
@@ -0,0 +1,1076 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/client/sdk-client.factory.ts
|
|
4
|
+
import { existsSync } from "fs";
|
|
5
|
+
import { createRequire } from "module";
|
|
6
|
+
import { dirname, resolve } from "path";
|
|
7
|
+
import { fileURLToPath } from "url";
|
|
8
|
+
import { createTeamDynamixClient, loginWithPassword, loginWithServiceAccount } from "@voxslopuli/teamdynamix-ts";
|
|
9
|
+
var cachedSpecPath;
|
|
10
|
+
function resolveSdkSpecPath() {
|
|
11
|
+
const override = process.env["TEAMDYNAMIX_SPEC_PATH"]?.trim();
|
|
12
|
+
if (override) return override;
|
|
13
|
+
if (cachedSpecPath) return cachedSpecPath;
|
|
14
|
+
try {
|
|
15
|
+
const require2 = createRequire(fileURLToPath(import.meta.url));
|
|
16
|
+
const entryPath = require2.resolve("@voxslopuli/teamdynamix-ts");
|
|
17
|
+
const pkgRoot = dirname(entryPath);
|
|
18
|
+
const candidates = [
|
|
19
|
+
resolve(pkgRoot, "dist/generated/openapi.json"),
|
|
20
|
+
resolve(pkgRoot, "generated/openapi.json"),
|
|
21
|
+
resolve(pkgRoot, "src/generated/openapi.json")
|
|
22
|
+
];
|
|
23
|
+
cachedSpecPath = candidates.find((p) => existsSync(p));
|
|
24
|
+
return cachedSpecPath;
|
|
25
|
+
} catch {
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function createTokenProvider(config, tenant) {
|
|
30
|
+
if (config.authMode === "admin") {
|
|
31
|
+
if (!config.beid || !config.webServicesKey) {
|
|
32
|
+
throw new Error("BEID and WebServicesKey are required for admin authentication");
|
|
33
|
+
}
|
|
34
|
+
return loginWithServiceAccount({
|
|
35
|
+
tenant,
|
|
36
|
+
baseUrl: config.baseUrl,
|
|
37
|
+
beid: config.beid,
|
|
38
|
+
webServicesKey: config.webServicesKey
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
if (!config.username || !config.password) {
|
|
42
|
+
throw new Error("Username and password are required for standard authentication");
|
|
43
|
+
}
|
|
44
|
+
return loginWithPassword({
|
|
45
|
+
tenant,
|
|
46
|
+
baseUrl: config.baseUrl,
|
|
47
|
+
username: config.username,
|
|
48
|
+
password: config.password
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function extractTenant(baseUrl) {
|
|
52
|
+
const normalized = baseUrl.replace(/\/+$/, "").replace(/\/TDWebApi$/, "");
|
|
53
|
+
const withoutProtocol = normalized.replace(/^https?:\/\//, "");
|
|
54
|
+
const parts = withoutProtocol.split("/");
|
|
55
|
+
return parts[0] ?? "";
|
|
56
|
+
}
|
|
57
|
+
function buildSdkConfig(config, tenant, tokenProvider) {
|
|
58
|
+
return {
|
|
59
|
+
tenant,
|
|
60
|
+
tokenProvider,
|
|
61
|
+
environment: config.baseUrl?.includes("sandbox") ? "sandbox" : "production",
|
|
62
|
+
baseUrl: config.baseUrl,
|
|
63
|
+
timeoutMs: config.timeoutMs,
|
|
64
|
+
runtimeValidationMode: "fail-open",
|
|
65
|
+
...resolveSdkSpecPath() ? { specPath: resolveSdkSpecPath() } : {},
|
|
66
|
+
retryPolicy: {
|
|
67
|
+
maxRetries: config.maxRetries
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
async function createMcpSdkClient(config) {
|
|
72
|
+
const tenant = extractTenant(config.baseUrl ?? "");
|
|
73
|
+
const tokenProvider = createTokenProvider(config, tenant);
|
|
74
|
+
const sdkConfig = buildSdkConfig(config, tenant, tokenProvider);
|
|
75
|
+
const { client } = await createTeamDynamixClient(sdkConfig);
|
|
76
|
+
return client;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/config.ts
|
|
80
|
+
import { z } from "zod";
|
|
81
|
+
|
|
82
|
+
// package.json
|
|
83
|
+
var package_default = {
|
|
84
|
+
name: "@voxslopuli/teamdynamix-mcp",
|
|
85
|
+
version: "0.5.2",
|
|
86
|
+
private: false,
|
|
87
|
+
description: "A production-ready TypeScript MCP server for TeamDynamix",
|
|
88
|
+
keywords: [
|
|
89
|
+
"mcp",
|
|
90
|
+
"model context protocol",
|
|
91
|
+
"server",
|
|
92
|
+
"tdx",
|
|
93
|
+
"teamdynamix",
|
|
94
|
+
"typescript"
|
|
95
|
+
],
|
|
96
|
+
homepage: "https://github.com/voxslopuli/teamdynamix-mcp",
|
|
97
|
+
bugs: {
|
|
98
|
+
url: "https://github.com/voxslopuli/teamdynamix-mcp/issues"
|
|
99
|
+
},
|
|
100
|
+
license: "MIT",
|
|
101
|
+
author: "Grand Slopulissimo <slopulissimo@voxslopuli.org>",
|
|
102
|
+
repository: {
|
|
103
|
+
type: "git",
|
|
104
|
+
url: "git+https://github.com/voxslopuli/teamdynamix-mcp.git"
|
|
105
|
+
},
|
|
106
|
+
bin: {
|
|
107
|
+
"tdx-watch-sweep": "dist/sweep.js",
|
|
108
|
+
"teamdynamix-mcp": "dist/index.js"
|
|
109
|
+
},
|
|
110
|
+
type: "module",
|
|
111
|
+
main: "dist/index.js",
|
|
112
|
+
scripts: {
|
|
113
|
+
build: "tsup",
|
|
114
|
+
postbuild: "node scripts/write-dist-package.js",
|
|
115
|
+
dev: "tsx watch src/index.ts",
|
|
116
|
+
"docs:build": "node scripts/prepare-docs-public.js && vitepress build docs",
|
|
117
|
+
"docs:dev": "vitepress dev docs",
|
|
118
|
+
"docs:preview": "vitepress preview docs",
|
|
119
|
+
format: "oxfmt . --write",
|
|
120
|
+
"format:check": "oxfmt . --check",
|
|
121
|
+
lint: "oxlint .",
|
|
122
|
+
"lint:fix": "oxlint . --fix",
|
|
123
|
+
prepare: "husky",
|
|
124
|
+
start: "node dist/index.js",
|
|
125
|
+
test: "vitest run",
|
|
126
|
+
"test:coverage": "vitest run --coverage",
|
|
127
|
+
typecheck: "tsc --noEmit"
|
|
128
|
+
},
|
|
129
|
+
dependencies: {
|
|
130
|
+
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
131
|
+
"@voxslopuli/teamdynamix-ts": "^0.3.0",
|
|
132
|
+
tablemark: "^4.1.0",
|
|
133
|
+
zod: "^4.6.2"
|
|
134
|
+
},
|
|
135
|
+
devDependencies: {
|
|
136
|
+
"@octokit/rest": "^22.0.1",
|
|
137
|
+
"@types/node": "25.9.2",
|
|
138
|
+
"@vitest/coverage-v8": "^5.0.0",
|
|
139
|
+
husky: "^9.1.7",
|
|
140
|
+
"lint-staged": "^17.5.1",
|
|
141
|
+
ora: "^9.4.1",
|
|
142
|
+
oxfmt: "^0.67.0",
|
|
143
|
+
oxlint: "^1.82.0",
|
|
144
|
+
tsup: "^8.5.1",
|
|
145
|
+
tsx: "^4.23.13",
|
|
146
|
+
typescript: "6.0.3",
|
|
147
|
+
vite: "8.3.0",
|
|
148
|
+
vitepress: "^1.6.4",
|
|
149
|
+
vitest: "5.0.0",
|
|
150
|
+
zx: "^8.8.5"
|
|
151
|
+
},
|
|
152
|
+
"lint-staged": {
|
|
153
|
+
"*.{ts,mts,cts,js,mjs,cjs}": [
|
|
154
|
+
"oxlint --fix --no-error-on-unmatched-pattern",
|
|
155
|
+
"oxfmt --no-error-on-unmatched-pattern --write"
|
|
156
|
+
],
|
|
157
|
+
"*.{json,yaml,yml,md}": [
|
|
158
|
+
"oxfmt --no-error-on-unmatched-pattern --write"
|
|
159
|
+
]
|
|
160
|
+
},
|
|
161
|
+
packageManager: "pnpm@10.32.1",
|
|
162
|
+
pnpm: {
|
|
163
|
+
overrides: {
|
|
164
|
+
hono: ">=4.12.18",
|
|
165
|
+
"@hono/node-server": ">=1.19.13"
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
mcpName: "io.github.selfagency/teamdynamix-mcp"
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
// src/constants.ts
|
|
172
|
+
var SERVER_VERSION = package_default.version;
|
|
173
|
+
var TEAMDYNAMIX_DEFAULT_TIMEOUT_MS = 3e4;
|
|
174
|
+
var TEAMDYNAMIX_DEFAULT_MAX_RETRIES = 2;
|
|
175
|
+
var TEAMDYNAMIX_MAX_RETRY_ATTEMPTS = 5;
|
|
176
|
+
|
|
177
|
+
// src/config.ts
|
|
178
|
+
var SERVER_NAME_OVERRIDE = process.env["MCP_SERVER_NAME"]?.trim() || void 0;
|
|
179
|
+
var SERVER_VERSION_OVERRIDE = process.env["MCP_SERVER_VERSION"]?.trim() || void 0;
|
|
180
|
+
var validLogLevels = ["debug", "info", "warn", "error"];
|
|
181
|
+
var logLevelSchema = z.enum(validLogLevels);
|
|
182
|
+
var parsedLogLevel = logLevelSchema.safeParse(process.env["MCP_LOG_LEVEL"]?.trim());
|
|
183
|
+
var LOG_LEVEL = parsedLogLevel.success ? parsedLogLevel.data : "info";
|
|
184
|
+
function normalizeOptionalString(value) {
|
|
185
|
+
const normalized = value?.trim();
|
|
186
|
+
return normalized ? normalized : void 0;
|
|
187
|
+
}
|
|
188
|
+
function normalizeOptionalNumber(value) {
|
|
189
|
+
if (!value?.trim()) {
|
|
190
|
+
return void 0;
|
|
191
|
+
}
|
|
192
|
+
const parsed = Number.parseInt(value, 10);
|
|
193
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
|
|
194
|
+
}
|
|
195
|
+
function normalizeBoolean(value, defaultValue) {
|
|
196
|
+
if (!value) {
|
|
197
|
+
return defaultValue;
|
|
198
|
+
}
|
|
199
|
+
const normalized = value.trim().toLowerCase();
|
|
200
|
+
if (normalized === "true") return true;
|
|
201
|
+
if (normalized === "false") return false;
|
|
202
|
+
return defaultValue;
|
|
203
|
+
}
|
|
204
|
+
function normalizeNumberWithDefault(value, defaultValue, minimum) {
|
|
205
|
+
if (!value?.trim()) {
|
|
206
|
+
return defaultValue;
|
|
207
|
+
}
|
|
208
|
+
const parsed = Number.parseInt(value, 10);
|
|
209
|
+
return Number.isFinite(parsed) && parsed >= minimum ? parsed : defaultValue;
|
|
210
|
+
}
|
|
211
|
+
function normalizeTeamDynamixBaseUrl(value) {
|
|
212
|
+
const normalized = normalizeOptionalString(value);
|
|
213
|
+
return normalized ? normalized.replace(/\/+$/, "") : void 0;
|
|
214
|
+
}
|
|
215
|
+
function validateHttpsBaseUrl(value) {
|
|
216
|
+
if (!value) return void 0;
|
|
217
|
+
const schema = z.string().url().refine((url) => url.startsWith("https://"), {
|
|
218
|
+
message: "TEAMDYNAMIX_BASE_URL must be an https URL."
|
|
219
|
+
});
|
|
220
|
+
const parsed = schema.safeParse(value);
|
|
221
|
+
if (!parsed.success) {
|
|
222
|
+
throw new Error(parsed.error.issues[0]?.message ?? "Invalid TEAMDYNAMIX_BASE_URL.");
|
|
223
|
+
}
|
|
224
|
+
return value;
|
|
225
|
+
}
|
|
226
|
+
function normalizeTeamDynamixAuthMode(value) {
|
|
227
|
+
return value?.trim().toLowerCase() === "admin" ? "admin" : "standard";
|
|
228
|
+
}
|
|
229
|
+
function getTeamDynamixConfig() {
|
|
230
|
+
const baseUrl = validateHttpsBaseUrl(normalizeTeamDynamixBaseUrl(process.env["TEAMDYNAMIX_BASE_URL"]));
|
|
231
|
+
const maxRetries = normalizeNumberWithDefault(
|
|
232
|
+
process.env["TEAMDYNAMIX_MAX_RETRIES"],
|
|
233
|
+
TEAMDYNAMIX_DEFAULT_MAX_RETRIES,
|
|
234
|
+
0
|
|
235
|
+
);
|
|
236
|
+
if (maxRetries > 5) {
|
|
237
|
+
throw new Error(`TEAMDYNAMIX_MAX_RETRIES must be between 0 and ${TEAMDYNAMIX_MAX_RETRY_ATTEMPTS}.`);
|
|
238
|
+
}
|
|
239
|
+
return {
|
|
240
|
+
baseUrl,
|
|
241
|
+
authMode: normalizeTeamDynamixAuthMode(process.env["TEAMDYNAMIX_AUTH_MODE"]),
|
|
242
|
+
username: normalizeOptionalString(process.env["TEAMDYNAMIX_USERNAME"]),
|
|
243
|
+
password: normalizeOptionalString(process.env["TEAMDYNAMIX_PASSWORD"]),
|
|
244
|
+
beid: normalizeOptionalString(process.env["TEAMDYNAMIX_BEID"]),
|
|
245
|
+
webServicesKey: normalizeOptionalString(process.env["TEAMDYNAMIX_WEB_SERVICES_KEY"]),
|
|
246
|
+
defaultTicketAppId: normalizeOptionalNumber(process.env["TEAMDYNAMIX_DEFAULT_TICKET_APP_ID"]),
|
|
247
|
+
defaultAssetAppId: normalizeOptionalNumber(process.env["TEAMDYNAMIX_DEFAULT_ASSET_APP_ID"]),
|
|
248
|
+
defaultKnowledgeBaseAppId: normalizeOptionalNumber(process.env["TEAMDYNAMIX_DEFAULT_KB_APP_ID"]),
|
|
249
|
+
timeoutMs: normalizeNumberWithDefault(process.env["TEAMDYNAMIX_TIMEOUT_MS"], TEAMDYNAMIX_DEFAULT_TIMEOUT_MS, 1e3),
|
|
250
|
+
maxRetries,
|
|
251
|
+
enableWriteTools: normalizeBoolean(process.env["TEAMDYNAMIX_ENABLE_WRITE_TOOLS"], false),
|
|
252
|
+
enableAdminTools: normalizeBoolean(process.env["TEAMDYNAMIX_ENABLE_ADMIN_TOOLS"], false),
|
|
253
|
+
enableDeleteTools: normalizeBoolean(process.env["TEAMDYNAMIX_ENABLE_DELETE_TOOLS"], false)
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// src/services/teamdynamix/client.factory.ts
|
|
258
|
+
var TICKET_SEARCH_FIELD_MAP = {
|
|
259
|
+
ResponsibleGroupIDs: "ResponsibilityGroupIDs",
|
|
260
|
+
ResponsibleGroupID: "ResponsibilityGroupID",
|
|
261
|
+
ResponsibleGroups: "ResponsibilityGroupIDs"
|
|
262
|
+
};
|
|
263
|
+
function mapTicketSearchBody(body) {
|
|
264
|
+
const mapped = {};
|
|
265
|
+
for (const [key, value] of Object.entries(body)) {
|
|
266
|
+
if (value === void 0) continue;
|
|
267
|
+
mapped[TICKET_SEARCH_FIELD_MAP[key] ?? key] = value;
|
|
268
|
+
}
|
|
269
|
+
return mapped;
|
|
270
|
+
}
|
|
271
|
+
function parseIdListEnv(raw) {
|
|
272
|
+
return (raw ?? "").split(/[;,\s]+/).map(Number).filter((n) => Number.isFinite(n) && n > 0);
|
|
273
|
+
}
|
|
274
|
+
var USER_SEARCH_KEYS = /* @__PURE__ */ new Set([
|
|
275
|
+
"AccountIDs",
|
|
276
|
+
"AlternateID",
|
|
277
|
+
"AppName",
|
|
278
|
+
"AuthenticationUserName",
|
|
279
|
+
"ExternalID",
|
|
280
|
+
"IsActive",
|
|
281
|
+
"IsConfidential",
|
|
282
|
+
"IsEmployee",
|
|
283
|
+
"MaxResults",
|
|
284
|
+
"PhoneNumber",
|
|
285
|
+
"ReferenceIDs",
|
|
286
|
+
"SearchText",
|
|
287
|
+
"SecurityRoleID",
|
|
288
|
+
"UserName"
|
|
289
|
+
]);
|
|
290
|
+
var GROUP_SEARCH_KEYS = /* @__PURE__ */ new Set(["AssociatedAppID", "HasAppID", "HasSystemAppName", "IsActive", "NameLike"]);
|
|
291
|
+
var ARTICLE_SEARCH_KEYS = /* @__PURE__ */ new Set([
|
|
292
|
+
"AuthorUID",
|
|
293
|
+
"CategoryID",
|
|
294
|
+
"CustomAttributes",
|
|
295
|
+
"IncludeArticleBodies",
|
|
296
|
+
"IncludeShortcuts",
|
|
297
|
+
"IsPublic",
|
|
298
|
+
"IsPublished",
|
|
299
|
+
"ReturnCount",
|
|
300
|
+
"SearchText",
|
|
301
|
+
"Status"
|
|
302
|
+
]);
|
|
303
|
+
function sanitizeTo(body, allowed) {
|
|
304
|
+
const out = {};
|
|
305
|
+
for (const [key, value] of Object.entries(body)) {
|
|
306
|
+
if (allowed.has(key) && value !== void 0) out[key] = value;
|
|
307
|
+
}
|
|
308
|
+
return out;
|
|
309
|
+
}
|
|
310
|
+
var UnifiedTeamDynamixClient = class _UnifiedTeamDynamixClient {
|
|
311
|
+
constructor(config) {
|
|
312
|
+
this.config = config;
|
|
313
|
+
}
|
|
314
|
+
config;
|
|
315
|
+
sdkPromise = null;
|
|
316
|
+
sdk() {
|
|
317
|
+
this.sdkPromise ??= createMcpSdkClient(this.config);
|
|
318
|
+
return this.sdkPromise;
|
|
319
|
+
}
|
|
320
|
+
//
|
|
321
|
+
// Discovery
|
|
322
|
+
//
|
|
323
|
+
getCurrentUser() {
|
|
324
|
+
return this.sdk().then((s) => s.discovery.authGetuser());
|
|
325
|
+
}
|
|
326
|
+
listApplications() {
|
|
327
|
+
return this.sdk().then((s) => s.discovery.applications());
|
|
328
|
+
}
|
|
329
|
+
//
|
|
330
|
+
// Tickets
|
|
331
|
+
//
|
|
332
|
+
getTicket(appId, ticketId) {
|
|
333
|
+
return this.sdk().then((s) => s.tickets.appIdTicketsId({ params: { path: { appId, id: ticketId } } }));
|
|
334
|
+
}
|
|
335
|
+
searchTickets(appId, body) {
|
|
336
|
+
return this.sdk().then(async (s) => {
|
|
337
|
+
const { data, error } = await s.tickets.appIdTicketsSearch({
|
|
338
|
+
params: { path: { appId } },
|
|
339
|
+
body: mapTicketSearchBody(body)
|
|
340
|
+
});
|
|
341
|
+
if (error) {
|
|
342
|
+
throw new Error(`Ticket search failed: ${JSON.stringify(error)}`);
|
|
343
|
+
}
|
|
344
|
+
const results = Array.isArray(data) ? data : [];
|
|
345
|
+
const groupFilter = parseIdListEnv(process.env["TEAMDYNAMIX_TICKET_GROUP_IDS"]);
|
|
346
|
+
if (groupFilter.length === 0) return results;
|
|
347
|
+
return results.filter((item) => {
|
|
348
|
+
if (typeof item !== "object" || item === null) return false;
|
|
349
|
+
const gid = Number(item["ResponsibleGroupID"]);
|
|
350
|
+
return groupFilter.includes(gid);
|
|
351
|
+
});
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
listTicketTypes(appId) {
|
|
355
|
+
return this.sdk().then((s) => s.tickets.appIdTicketsTypes({ params: { path: { appId } } }));
|
|
356
|
+
}
|
|
357
|
+
listTicketPriorities(appId) {
|
|
358
|
+
return this.sdk().then((s) => s.tickets.appIdTicketsPriorities({ params: { path: { appId } } }));
|
|
359
|
+
}
|
|
360
|
+
listTicketUrgencies(appId) {
|
|
361
|
+
return this.sdk().then((s) => s.tickets.appIdTicketsUrgencies({ params: { path: { appId } } }));
|
|
362
|
+
}
|
|
363
|
+
listTicketImpacts(appId) {
|
|
364
|
+
return this.sdk().then((s) => s.tickets.appIdTicketsImpacts({ params: { path: { appId } } }));
|
|
365
|
+
}
|
|
366
|
+
listTicketSources(appId) {
|
|
367
|
+
return this.sdk().then((s) => s.tickets.appIdTicketsSources({ params: { path: { appId } } }));
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Upper bound on feed entries we'll fetch replies for. The TDX API allows 60
|
|
371
|
+
* requests/60s; the feed call itself plus one fetch per entry must stay under it.
|
|
372
|
+
*/
|
|
373
|
+
static DEFAULT_REPLIES_ENTRY_LIMIT = 10;
|
|
374
|
+
async getTicketFeed(appId, ticketId, opts = {}) {
|
|
375
|
+
const s = await this.sdk();
|
|
376
|
+
const feed = await s.tickets.appIdTicketsIdFeed({ params: { path: { appId, id: ticketId } } });
|
|
377
|
+
const entries = Array.isArray(feed) ? feed : [];
|
|
378
|
+
const limit = opts.repliesEntryLimit ?? _UnifiedTeamDynamixClient.DEFAULT_REPLIES_ENTRY_LIMIT;
|
|
379
|
+
const missing = entries.filter(
|
|
380
|
+
(e) => typeof e.RepliesCount === "number" && e.RepliesCount > 0 && (!Array.isArray(e.Replies) || e.Replies.length === 0) && typeof e.ID !== "undefined"
|
|
381
|
+
);
|
|
382
|
+
for (const entry of missing.slice(0, limit)) {
|
|
383
|
+
const target = entry;
|
|
384
|
+
const { data, error } = await s.GET(`/api/feed/${target.ID}`, {
|
|
385
|
+
params: { path: { id: target.ID } }
|
|
386
|
+
});
|
|
387
|
+
if (error) {
|
|
388
|
+
const detail = typeof error === "string" ? error : JSON.stringify(error);
|
|
389
|
+
throw new Error(`Failed to fetch replies for feed entry ${target.ID} (GET /api/feed/{id}): ${detail}`);
|
|
390
|
+
}
|
|
391
|
+
if (data && Array.isArray(data.Replies)) {
|
|
392
|
+
target.Replies = data.Replies;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
return entries;
|
|
396
|
+
}
|
|
397
|
+
//
|
|
398
|
+
// Ticket Relationships
|
|
399
|
+
//
|
|
400
|
+
getTicketTasks(appId, ticketId) {
|
|
401
|
+
return this.sdk().then(
|
|
402
|
+
(s) => s.ticketRelationships.appIdTicketsTicketIdTasks({ params: { path: { appId, ticketId } } })
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
createTicketTask(appId, ticketId, body) {
|
|
406
|
+
return this.sdk().then((s) => s.ticketRelationships.createTicketTask({ appId, ticketId, body }));
|
|
407
|
+
}
|
|
408
|
+
listTicketAssets(appId, ticketId) {
|
|
409
|
+
return this.sdk().then(
|
|
410
|
+
(s) => s.ticketRelationships.appIdTicketsIdAssets({ params: { path: { appId, id: ticketId } } })
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
addTicketAsset(appId, ticketId, assetId) {
|
|
414
|
+
return this.sdk().then((s) => s.ticketRelationships.addTicketAsset({ appId, ticketId, assetId }));
|
|
415
|
+
}
|
|
416
|
+
removeTicketAsset(appId, ticketId, assetId) {
|
|
417
|
+
return this.sdk().then((s) => {
|
|
418
|
+
s.ticketRelationships.removeTicketAsset({ appId, ticketId, assetId, confirm: true });
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
getTicketContacts(appId, ticketId) {
|
|
422
|
+
return this.sdk().then(
|
|
423
|
+
(s) => s.ticketRelationships.appIdTicketsIdContacts({ params: { path: { appId, id: ticketId } } })
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
addTicketContact(appId, ticketId, contactUid) {
|
|
427
|
+
return this.sdk().then((s) => s.ticketRelationships.addTicketContact({ appId, ticketId, contactUid }));
|
|
428
|
+
}
|
|
429
|
+
removeTicketContact(appId, ticketId, contactUid) {
|
|
430
|
+
return this.sdk().then((s) => {
|
|
431
|
+
s.ticketRelationships.removeTicketContact({ appId, ticketId, contactUid, confirm: true });
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
//
|
|
435
|
+
// People
|
|
436
|
+
//
|
|
437
|
+
getUser(uid) {
|
|
438
|
+
return this.sdk().then((s) => s.people.peopleUid({ params: { path: { uid } } }));
|
|
439
|
+
}
|
|
440
|
+
searchUsers(body) {
|
|
441
|
+
return this.sdk().then((s) => s.people.postPeopleSearch({ body: sanitizeTo(body, USER_SEARCH_KEYS) }));
|
|
442
|
+
}
|
|
443
|
+
getGroup(groupId) {
|
|
444
|
+
return this.sdk().then((s) => s.people.groupsId({ params: { path: { id: groupId } } }));
|
|
445
|
+
}
|
|
446
|
+
searchGroups(body) {
|
|
447
|
+
return this.sdk().then((s) => s.people.searchGroups({ body: sanitizeTo(body, GROUP_SEARCH_KEYS) }));
|
|
448
|
+
}
|
|
449
|
+
getGroupMembers(groupId) {
|
|
450
|
+
return this.sdk().then((s) => s.people.groupsIdMembers({ params: { path: { id: groupId } } }));
|
|
451
|
+
}
|
|
452
|
+
//
|
|
453
|
+
// Knowledge Base
|
|
454
|
+
//
|
|
455
|
+
getKbArticle(appId, articleId) {
|
|
456
|
+
return this.sdk().then((s) => s.knowledgeBase.appIdKnowledgebaseId({ params: { path: { appId, id: articleId } } }));
|
|
457
|
+
}
|
|
458
|
+
searchKbArticles(appId, body) {
|
|
459
|
+
return this.sdk().then(async (s) => {
|
|
460
|
+
const { data, error } = await s.referenceData.appIdKnowledgebaseSearch({
|
|
461
|
+
params: { path: { appId } },
|
|
462
|
+
body: sanitizeTo(body, ARTICLE_SEARCH_KEYS)
|
|
463
|
+
});
|
|
464
|
+
if (error) {
|
|
465
|
+
throw new Error(`KB search failed: ${JSON.stringify(error)}`);
|
|
466
|
+
}
|
|
467
|
+
return Array.isArray(data) ? data : [];
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
listKbCategories(appId) {
|
|
471
|
+
return this.sdk().then(
|
|
472
|
+
(s) => s.knowledgeBase.appIdKnowledgebaseCategories({ params: { path: { appId } } })
|
|
473
|
+
);
|
|
474
|
+
}
|
|
475
|
+
//
|
|
476
|
+
// Assets
|
|
477
|
+
//
|
|
478
|
+
getAsset(appId, assetId) {
|
|
479
|
+
return this.sdk().then((s) => s.assets.appIdAssetsId({ params: { path: { appId, id: assetId } } }));
|
|
480
|
+
}
|
|
481
|
+
searchAssets(appId, _body) {
|
|
482
|
+
return this.sdk().then((s) => s.assets.appIdAssetsFeed({ params: { path: { appId } } }));
|
|
483
|
+
}
|
|
484
|
+
listAssetStatuses(appId) {
|
|
485
|
+
return this.sdk().then((s) => s.assets.appIdAssetsStatuses({ params: { path: { appId } } }));
|
|
486
|
+
}
|
|
487
|
+
listProductModels(appId) {
|
|
488
|
+
return this.sdk().then((s) => s.assets.appIdAssetsModels({ params: { path: { appId } } }));
|
|
489
|
+
}
|
|
490
|
+
listVendors(appId) {
|
|
491
|
+
return this.sdk().then((s) => s.cmdb.appIdAssetsVendors({ params: { path: { appId } } }));
|
|
492
|
+
}
|
|
493
|
+
//
|
|
494
|
+
// CMDB
|
|
495
|
+
//
|
|
496
|
+
getConfigurationItem(appId, ciId) {
|
|
497
|
+
return this.sdk().then((s) => s.cmdb.appIdCmdbId({ params: { path: { appId, id: ciId } } }));
|
|
498
|
+
}
|
|
499
|
+
searchConfigurationItems(appId, _body) {
|
|
500
|
+
return this.sdk().then((s) => s.cmdb.appIdCmdbSearches({ params: { path: { appId } } }));
|
|
501
|
+
}
|
|
502
|
+
listCiTypes(appId) {
|
|
503
|
+
return this.sdk().then((s) => s.cmdb.appIdCmdbTypes({ params: { path: { appId } } }));
|
|
504
|
+
}
|
|
505
|
+
listCiRelationshipTypes() {
|
|
506
|
+
return this.sdk().then((s) => s.cmdb.appIdCmdbRelationshiptypes());
|
|
507
|
+
}
|
|
508
|
+
//
|
|
509
|
+
// Services
|
|
510
|
+
//
|
|
511
|
+
listServiceCatalog(appId) {
|
|
512
|
+
return this.sdk().then((s) => s.services.appIdServices({ params: { path: { appId } } }));
|
|
513
|
+
}
|
|
514
|
+
getService(appId, serviceId) {
|
|
515
|
+
return this.sdk().then((s) => s.services.appIdServicesId({ params: { path: { appId, id: serviceId } } }));
|
|
516
|
+
}
|
|
517
|
+
searchServices(appId, body) {
|
|
518
|
+
const keyword = typeof body["Keyword"] === "string" ? body["Keyword"] : "";
|
|
519
|
+
return this.sdk().then((s) => s.services.appIdServices({ params: { path: { appId } } })).then((r) => {
|
|
520
|
+
if (!Array.isArray(r)) return [];
|
|
521
|
+
if (!keyword) return r;
|
|
522
|
+
const lower = keyword.toLowerCase();
|
|
523
|
+
return r.filter((item) => {
|
|
524
|
+
const text = typeof item === "object" && item !== null ? JSON.stringify(item).toLowerCase() : "";
|
|
525
|
+
return text.includes(lower);
|
|
526
|
+
});
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
listServiceCategories(appId) {
|
|
530
|
+
return this.sdk().then((s) => s.services.appIdServicesCategories({ params: { path: { appId } } }));
|
|
531
|
+
}
|
|
532
|
+
//
|
|
533
|
+
// Projects
|
|
534
|
+
//
|
|
535
|
+
getProject(projectId) {
|
|
536
|
+
return this.sdk().then((s) => s.projects.projectsId({ params: { path: { id: projectId } } }));
|
|
537
|
+
}
|
|
538
|
+
searchProjects(_body) {
|
|
539
|
+
return this.sdk().then((s) => s.projects.projectsFeed());
|
|
540
|
+
}
|
|
541
|
+
listProjectTypes() {
|
|
542
|
+
return this.sdk().then((s) => s.projects.projectsTypes());
|
|
543
|
+
}
|
|
544
|
+
getProjectPlans(projectId) {
|
|
545
|
+
return this.sdk().then(
|
|
546
|
+
(s) => s.projects.projectsProjectIDPlansPlanID({ params: { path: { id: projectId } } })
|
|
547
|
+
);
|
|
548
|
+
}
|
|
549
|
+
getProjectIssues(projectId) {
|
|
550
|
+
return this.sdk().then(
|
|
551
|
+
(s) => s.projects.projectsProjectIdIssuesCategories({ params: { path: { id: projectId } } })
|
|
552
|
+
);
|
|
553
|
+
}
|
|
554
|
+
getProjectRisks(projectId) {
|
|
555
|
+
return this.sdk().then(
|
|
556
|
+
(s) => s.projects.projectsProjectIdRisksCategories({ params: { path: { id: projectId } } })
|
|
557
|
+
);
|
|
558
|
+
}
|
|
559
|
+
//
|
|
560
|
+
// Time
|
|
561
|
+
//
|
|
562
|
+
listTimeTypes() {
|
|
563
|
+
return this.sdk().then((s) => s.time.timeTypes());
|
|
564
|
+
}
|
|
565
|
+
getMyTimeEntries(_startDate, _endDate) {
|
|
566
|
+
return this.sdk().then((s) => s.time.timeId({ params: { path: { id: 0 } } }));
|
|
567
|
+
}
|
|
568
|
+
//
|
|
569
|
+
// Reference Data
|
|
570
|
+
//
|
|
571
|
+
listAccounts(_appId) {
|
|
572
|
+
return this.sdk().then((s) => s.referenceData.accounts());
|
|
573
|
+
}
|
|
574
|
+
getAccount(accountId) {
|
|
575
|
+
return this.sdk().then((s) => s.referenceData.accountsId({ params: { path: { id: accountId } } }));
|
|
576
|
+
}
|
|
577
|
+
listLocations() {
|
|
578
|
+
return this.sdk().then((s) => s.referenceData.locations());
|
|
579
|
+
}
|
|
580
|
+
listFunctionalRoles() {
|
|
581
|
+
return this.sdk().then((s) => s.referenceData.securityrolesPermissions());
|
|
582
|
+
}
|
|
583
|
+
listCustomAttributes(_componentId, _appId, _associatedTypeId) {
|
|
584
|
+
return this.sdk().then((s) => s.referenceData.attributesCustom());
|
|
585
|
+
}
|
|
586
|
+
listTicketStatuses(appId) {
|
|
587
|
+
return this.sdk().then((s) => s.referenceData.appIdTicketsStatuses({ params: { path: { appId } } }));
|
|
588
|
+
}
|
|
589
|
+
//
|
|
590
|
+
// Mutations
|
|
591
|
+
//
|
|
592
|
+
createTicket(appId, body, _notifyRequestor, _notifyResponsible) {
|
|
593
|
+
return this.sdk().then((s) => s.tickets.createTicket({ appId, body }));
|
|
594
|
+
}
|
|
595
|
+
updateTicket(appId, ticketId, body, _notifyRequestor, _notifyResponsible, _comments, _isPrivate) {
|
|
596
|
+
return this.sdk().then((s) => s.tickets.updateTicket({ appId, ticketId, body }));
|
|
597
|
+
}
|
|
598
|
+
addTicketComment(appId, ticketId, body, _isPrivate, _notifyRequestor, _notifyResponsible) {
|
|
599
|
+
return this.sdk().then((s) => s.tickets.addTicketComment({ appId, ticketId, body: { Body: body } }));
|
|
600
|
+
}
|
|
601
|
+
createKbArticle(appId, body) {
|
|
602
|
+
return this.sdk().then((s) => s.knowledgeBase.createArticle({ appId, body }));
|
|
603
|
+
}
|
|
604
|
+
updateKbArticle(appId, articleId, body) {
|
|
605
|
+
return this.sdk().then((s) => s.knowledgeBase.updateArticle({ appId, articleId, body }));
|
|
606
|
+
}
|
|
607
|
+
createProjectIssue(_projectId, body) {
|
|
608
|
+
return this.sdk().then((s) => s.projects.createIssue({ body }));
|
|
609
|
+
}
|
|
610
|
+
createProjectRisk(_projectId, body) {
|
|
611
|
+
return this.sdk().then((s) => s.projects.createRisk({ body }));
|
|
612
|
+
}
|
|
613
|
+
//
|
|
614
|
+
// Delete mutations (confirm:true required for all)
|
|
615
|
+
//
|
|
616
|
+
deleteAsset(appId, assetId) {
|
|
617
|
+
return this.sdk().then((s) => s.assets.deleteAsset({ appId, assetId, confirm: true }));
|
|
618
|
+
}
|
|
619
|
+
deleteConfigurationItem(appId, ciId) {
|
|
620
|
+
return this.sdk().then((s) => s.cmdb.deleteConfigurationItem({ appId, configurationItemId: ciId, confirm: true }));
|
|
621
|
+
}
|
|
622
|
+
deleteService(appId, serviceId) {
|
|
623
|
+
return this.sdk().then((s) => s.services.deleteService({ appId, serviceId, confirm: true }));
|
|
624
|
+
}
|
|
625
|
+
deleteServiceCategory(appId, categoryId) {
|
|
626
|
+
return this.sdk().then((s) => s.services.deleteServiceCategory({ appId, categoryId, confirm: true }));
|
|
627
|
+
}
|
|
628
|
+
deleteTimeEntry(timeEntryId) {
|
|
629
|
+
return this.sdk().then((s) => s.time.deleteTimeEntry({ timeEntryId, confirm: true }));
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
function createConfiguredTeamDynamixClient() {
|
|
633
|
+
return new UnifiedTeamDynamixClient(getTeamDynamixConfig());
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// src/services/teamdynamix/watch.store.ts
|
|
637
|
+
import { promises as fs } from "fs";
|
|
638
|
+
import path from "path";
|
|
639
|
+
var LEDGER_VERSION = 1;
|
|
640
|
+
var MAX_NOTE_LENGTH = 4e3;
|
|
641
|
+
var MAX_OBSERVATIONS = 20;
|
|
642
|
+
var LedgerCorruptError = class extends Error {
|
|
643
|
+
constructor(path2, cause) {
|
|
644
|
+
super(
|
|
645
|
+
`Watch ledger at ${path2} is corrupt or unreadable; refusing to read or write it. Fix or remove the file manually (state preservation is deliberate). Cause: ${String(cause)}`
|
|
646
|
+
);
|
|
647
|
+
this.name = "LedgerCorruptError";
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
function defaultLedgerPath() {
|
|
651
|
+
return process.env["TDX_WATCH_LEDGER"] ?? path.join(process.cwd(), ".tdx-watch-ledger.json");
|
|
652
|
+
}
|
|
653
|
+
async function loadLedger(filePath) {
|
|
654
|
+
let raw;
|
|
655
|
+
try {
|
|
656
|
+
raw = await fs.readFile(filePath, "utf8");
|
|
657
|
+
} catch (cause) {
|
|
658
|
+
throw cause instanceof Error ? cause : new Error(String(cause));
|
|
659
|
+
}
|
|
660
|
+
try {
|
|
661
|
+
const parsed = JSON.parse(raw);
|
|
662
|
+
if (!Array.isArray(parsed.active) || !Array.isArray(parsed.archived)) {
|
|
663
|
+
throw new Error("missing active/archived arrays");
|
|
664
|
+
}
|
|
665
|
+
parsed.pendingTriage ??= [];
|
|
666
|
+
return parsed;
|
|
667
|
+
} catch (cause) {
|
|
668
|
+
throw new LedgerCorruptError(filePath, cause);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
async function saveLedger(filePath, ledger2) {
|
|
672
|
+
try {
|
|
673
|
+
await fs.access(filePath);
|
|
674
|
+
await loadLedger(filePath);
|
|
675
|
+
} catch (cause) {
|
|
676
|
+
if (cause instanceof LedgerCorruptError) throw cause;
|
|
677
|
+
}
|
|
678
|
+
ledger2.version = LEDGER_VERSION;
|
|
679
|
+
const dir = path.dirname(filePath);
|
|
680
|
+
await fs.mkdir(dir, { recursive: true });
|
|
681
|
+
const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
682
|
+
await fs.writeFile(tmp, `${JSON.stringify(ledger2, null, 2)}
|
|
683
|
+
`, "utf8");
|
|
684
|
+
await fs.rename(tmp, filePath);
|
|
685
|
+
}
|
|
686
|
+
function emptyLedger() {
|
|
687
|
+
return { active: [], archived: [], pendingTriage: [], sweepMeta: {} };
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// src/services/teamdynamix/watch.service.ts
|
|
691
|
+
var REPORT_MAX_CHARS = 8e3;
|
|
692
|
+
var TITLE_MAX_CHARS = 200;
|
|
693
|
+
var US_UIDS_ENV = "TEAMDYNAMIX_US_UIDS";
|
|
694
|
+
var GROUP_IDS_ENV = "TEAMDYNAMIX_TICKET_GROUP_IDS";
|
|
695
|
+
var STATUS_IDS_ENV = "TEAMDYNAMIX_WATCH_STATUS_IDS";
|
|
696
|
+
var DEFAULT_MAX_PENDING = 25;
|
|
697
|
+
var UNASSIGNED_SENTINELS = /* @__PURE__ */ new Set(["", "unassigned"]);
|
|
698
|
+
function redact(text) {
|
|
699
|
+
return text.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g, "[redacted-email]").replace(/\b(?:\d{3}[-.\s]?){2}\d{4}\b/g, "[redacted-phone]");
|
|
700
|
+
}
|
|
701
|
+
function cap(text, max) {
|
|
702
|
+
if (text.length <= max) return text;
|
|
703
|
+
return `${text.slice(0, Math.max(0, max - 1))}\u2026`;
|
|
704
|
+
}
|
|
705
|
+
function sanitizeForReport(value) {
|
|
706
|
+
if (typeof value === "string") return cap(redact(value), TITLE_MAX_CHARS);
|
|
707
|
+
return value;
|
|
708
|
+
}
|
|
709
|
+
function computeHash(entries) {
|
|
710
|
+
const perEntryReplies = {};
|
|
711
|
+
let replyCount = 0;
|
|
712
|
+
let lastEntryId = 0;
|
|
713
|
+
for (const e of entries) {
|
|
714
|
+
const id = e.ID ?? 0;
|
|
715
|
+
const rc = e.RepliesCount ?? 0;
|
|
716
|
+
perEntryReplies[String(id)] = rc;
|
|
717
|
+
replyCount += rc;
|
|
718
|
+
lastEntryId = Math.max(lastEntryId, id);
|
|
719
|
+
}
|
|
720
|
+
return { lastEntryId, entryCount: entries.length, replyCount, perEntryReplies };
|
|
721
|
+
}
|
|
722
|
+
function hashGrewHiddenReplies(prev, entries) {
|
|
723
|
+
for (const e of entries) {
|
|
724
|
+
const id = String(e.ID ?? 0);
|
|
725
|
+
const now = e.RepliesCount ?? 0;
|
|
726
|
+
const before = prev.perEntryReplies[id];
|
|
727
|
+
if (before !== void 0 && now > before) return true;
|
|
728
|
+
}
|
|
729
|
+
return false;
|
|
730
|
+
}
|
|
731
|
+
var WorkspaceWatchService = class {
|
|
732
|
+
constructor(ledger2, ledgerPath2, client, opts = {}) {
|
|
733
|
+
this.ledger = ledger2;
|
|
734
|
+
this.ledgerPath = ledgerPath2;
|
|
735
|
+
this.client = client;
|
|
736
|
+
const envUids = (process.env[US_UIDS_ENV] ?? "").split(/[,\s]+/).filter(Boolean);
|
|
737
|
+
this.usUids = /* @__PURE__ */ new Set([...envUids, ...opts.usUids ?? []]);
|
|
738
|
+
this.autoObserve = opts.autoObserve ?? process.env["TEAMDYNAMIX_AUTO_OBSERVE"] === "true";
|
|
739
|
+
}
|
|
740
|
+
ledger;
|
|
741
|
+
client;
|
|
742
|
+
ledgerPath;
|
|
743
|
+
usUids;
|
|
744
|
+
autoObserve;
|
|
745
|
+
usUidsFor() {
|
|
746
|
+
const ledgerUids = this.ledger.sweepMeta.usUids ?? [];
|
|
747
|
+
return /* @__PURE__ */ new Set([...this.usUids, ...ledgerUids]);
|
|
748
|
+
}
|
|
749
|
+
groupIds() {
|
|
750
|
+
return this.ledger.sweepMeta.groupIds ?? parseIdListEnv(process.env[GROUP_IDS_ENV]);
|
|
751
|
+
}
|
|
752
|
+
statusIds() {
|
|
753
|
+
return this.ledger.sweepMeta.statusIds ?? parseIdListEnv(process.env[STATUS_IDS_ENV]);
|
|
754
|
+
}
|
|
755
|
+
maxPending() {
|
|
756
|
+
return this.ledger.sweepMeta.maxPending ?? DEFAULT_MAX_PENDING;
|
|
757
|
+
}
|
|
758
|
+
pushPending(item) {
|
|
759
|
+
const queue = this.ledger.pendingTriage ??= [];
|
|
760
|
+
if (queue.some((p) => p.ticketId === item.ticketId)) return "deduped";
|
|
761
|
+
if (queue.length >= this.maxPending()) return "full";
|
|
762
|
+
queue.push(item);
|
|
763
|
+
return "queued";
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* Cheap sweep (stage 1 only): one queue search per app, client-side team
|
|
767
|
+
* filtering (GroupIDs is not applied server-side on queue searches), stateHash
|
|
768
|
+
* freshness, new-unassigned detection, and pendingTriage queue maintenance.
|
|
769
|
+
* Deep fetches / reply expansion are the agent's job via check() / triage.
|
|
770
|
+
*/
|
|
771
|
+
async sweep() {
|
|
772
|
+
const result = {
|
|
773
|
+
swept: 0,
|
|
774
|
+
changedQueued: 0,
|
|
775
|
+
newUnassignedQueued: 0,
|
|
776
|
+
deduped: 0,
|
|
777
|
+
queueFull: 0,
|
|
778
|
+
unassigned: []
|
|
779
|
+
};
|
|
780
|
+
const rows = this.ledger.active;
|
|
781
|
+
const byApp = /* @__PURE__ */ new Map();
|
|
782
|
+
for (const row of rows) {
|
|
783
|
+
const list = byApp.get(row.appId) ?? [];
|
|
784
|
+
list.push(row);
|
|
785
|
+
byApp.set(row.appId, list);
|
|
786
|
+
}
|
|
787
|
+
const appIds = /* @__PURE__ */ new Set([...byApp.keys(), ...parseIdListEnv(process.env["TEAMDYNAMIX_WATCH_APP_IDS"])]);
|
|
788
|
+
const groupFilter = this.groupIds();
|
|
789
|
+
const statusFilter = this.statusIds();
|
|
790
|
+
const queue = this.ledger.pendingTriage ??= [];
|
|
791
|
+
const ledgeredIds = new Set(rows.map((r) => r.id));
|
|
792
|
+
for (const appId of appIds) {
|
|
793
|
+
const appRows = byApp.get(appId) ?? [];
|
|
794
|
+
let page;
|
|
795
|
+
try {
|
|
796
|
+
page = await this.client.searchTickets(appId, { MaxResults: 500 });
|
|
797
|
+
} catch {
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
for (const t of page) {
|
|
801
|
+
const id = Number(t["ID"]);
|
|
802
|
+
if (!Number.isFinite(id)) continue;
|
|
803
|
+
if (groupFilter.length > 0) {
|
|
804
|
+
const gid = Number(t["ResponsibleGroupID"]);
|
|
805
|
+
if (!groupFilter.includes(gid)) continue;
|
|
806
|
+
}
|
|
807
|
+
if (statusFilter.length > 0 && !statusFilter.includes(Number(t["StatusID"]))) continue;
|
|
808
|
+
result.swept += 1;
|
|
809
|
+
const row = appRows.find((r) => r.id === id);
|
|
810
|
+
const modified = String(t["ModifiedDate"] ?? "");
|
|
811
|
+
if (row && row.stateHash.modified !== "" && modified !== row.stateHash.modified) {
|
|
812
|
+
const outcome = this.pushPending({ ticketId: id, appId, reason: "changed", at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
813
|
+
if (outcome === "queued") result.changedQueued += 1;
|
|
814
|
+
else if (outcome === "deduped") result.deduped += 1;
|
|
815
|
+
else result.queueFull += 1;
|
|
816
|
+
}
|
|
817
|
+
if (!ledgeredIds.has(id)) {
|
|
818
|
+
const responsible = String(t["ResponsibleUid"] ?? "").trim();
|
|
819
|
+
if (UNASSIGNED_SENTINELS.has(responsible.toLowerCase())) {
|
|
820
|
+
result.unassigned.push(id);
|
|
821
|
+
const outcome = this.pushPending({
|
|
822
|
+
ticketId: id,
|
|
823
|
+
appId,
|
|
824
|
+
reason: "new-unassigned",
|
|
825
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
826
|
+
detail: `group=${String(t["ResponsibleGroupName"] ?? "")}`
|
|
827
|
+
});
|
|
828
|
+
if (outcome === "queued") result.newUnassignedQueued += 1;
|
|
829
|
+
else if (outcome === "deduped") result.deduped += 1;
|
|
830
|
+
else result.queueFull += 1;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
for (const row of appRows) {
|
|
835
|
+
const t = page.find((x) => Number(x["ID"]) === row.id);
|
|
836
|
+
if (t) row.stateHash.modified = String(t["ModifiedDate"] ?? row.stateHash.modified);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
this.ledger.sweepMeta.lastSweep = (/* @__PURE__ */ new Date()).toISOString();
|
|
840
|
+
await this.persist();
|
|
841
|
+
return result;
|
|
842
|
+
}
|
|
843
|
+
pendingTriage() {
|
|
844
|
+
return this.ledger.pendingTriage ?? [];
|
|
845
|
+
}
|
|
846
|
+
async markTriaged(ticketId) {
|
|
847
|
+
const queue = this.ledger.pendingTriage ?? [];
|
|
848
|
+
const before = queue.length;
|
|
849
|
+
this.ledger.pendingTriage = queue.filter((p) => p.ticketId !== ticketId);
|
|
850
|
+
await this.persist();
|
|
851
|
+
return { removed: this.ledger.pendingTriage.length < before };
|
|
852
|
+
}
|
|
853
|
+
async persist() {
|
|
854
|
+
await saveLedger(this.ledgerPath, this.ledger);
|
|
855
|
+
this.ledger = await loadLedger(this.ledgerPath);
|
|
856
|
+
}
|
|
857
|
+
findRow(id) {
|
|
858
|
+
return this.ledger.active.find((r) => r.id === id);
|
|
859
|
+
}
|
|
860
|
+
async register(input) {
|
|
861
|
+
const existing = this.findRow(input.id);
|
|
862
|
+
if (existing) {
|
|
863
|
+
existing.kind = input.kind;
|
|
864
|
+
if (input.title !== void 0) existing.title = cap(redact(input.title), TITLE_MAX_CHARS);
|
|
865
|
+
if (input.district !== void 0) existing.district = input.district;
|
|
866
|
+
if (input.nextAction !== void 0) existing.nextAction = input.nextAction;
|
|
867
|
+
if (input.ball !== void 0) {
|
|
868
|
+
existing.ball = input.ball;
|
|
869
|
+
existing.ballSource = "manual";
|
|
870
|
+
}
|
|
871
|
+
await this.persist();
|
|
872
|
+
return existing;
|
|
873
|
+
}
|
|
874
|
+
const row = {
|
|
875
|
+
id: input.id,
|
|
876
|
+
appId: input.appId,
|
|
877
|
+
title: cap(redact(input.title ?? ""), TITLE_MAX_CHARS),
|
|
878
|
+
district: input.district ?? "",
|
|
879
|
+
kind: input.kind,
|
|
880
|
+
status: "",
|
|
881
|
+
stateHash: { modified: "", lastEntryId: 0, entryCount: 0, replyCount: 0, perEntryReplies: {} },
|
|
882
|
+
ball: input.ball ?? "us",
|
|
883
|
+
ballSource: input.ball !== void 0 ? "manual" : "auto",
|
|
884
|
+
nextAction: input.nextAction ?? "",
|
|
885
|
+
lastChecked: "",
|
|
886
|
+
memory: { notes: [], observations: [] }
|
|
887
|
+
};
|
|
888
|
+
this.ledger.active.push(row);
|
|
889
|
+
await this.persist();
|
|
890
|
+
return row;
|
|
891
|
+
}
|
|
892
|
+
async archive(input) {
|
|
893
|
+
const idx = this.ledger.active.findIndex((r) => r.id === input.id);
|
|
894
|
+
if (idx === -1) return { archived: false };
|
|
895
|
+
const [row] = this.ledger.active.splice(idx, 1);
|
|
896
|
+
this.ledger.archived.push({ ...row, outcome: input.outcome });
|
|
897
|
+
await this.persist();
|
|
898
|
+
return { archived: true };
|
|
899
|
+
}
|
|
900
|
+
async status() {
|
|
901
|
+
const active = this.ledger.active;
|
|
902
|
+
const oldestChecked = active.map((r) => r.lastChecked).filter(Boolean).sort()[0] ?? "";
|
|
903
|
+
return {
|
|
904
|
+
activeCount: active.length,
|
|
905
|
+
archivedCount: this.ledger.archived.length,
|
|
906
|
+
ballUs: active.filter((r) => r.ball === "us").length,
|
|
907
|
+
ballThem: active.filter((r) => r.ball === "them").length,
|
|
908
|
+
oldestChecked
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
async check(input = {}) {
|
|
912
|
+
const report = { checked: 0, deltas: [], errors: [] };
|
|
913
|
+
const rows = this.ledger.active.filter((r) => input.tickets ? input.tickets.includes(r.id) : true);
|
|
914
|
+
const byApp = /* @__PURE__ */ new Map();
|
|
915
|
+
for (const row of rows) {
|
|
916
|
+
const list = byApp.get(row.appId) ?? [];
|
|
917
|
+
list.push(row);
|
|
918
|
+
byApp.set(row.appId, list);
|
|
919
|
+
}
|
|
920
|
+
for (const [appId, appRows] of byApp) {
|
|
921
|
+
let sweep;
|
|
922
|
+
try {
|
|
923
|
+
sweep = await this.client.searchTickets(appId, { MaxResults: 500 });
|
|
924
|
+
} catch (cause) {
|
|
925
|
+
report.errors.push(`sweep failed for appId ${appId}: ${String(cause)}`);
|
|
926
|
+
continue;
|
|
927
|
+
}
|
|
928
|
+
const sweepById = new Map(sweep.map((t) => [Number(t["ID"]), t]));
|
|
929
|
+
for (const row of appRows) {
|
|
930
|
+
report.checked += 1;
|
|
931
|
+
const sweepTicket = sweepById.get(row.id);
|
|
932
|
+
const sweepModified = sweepTicket ? String(sweepTicket["ModifiedDate"] ?? "") : "";
|
|
933
|
+
const seeded = row.stateHash.modified !== "";
|
|
934
|
+
const needsDeep = !seeded || sweepModified !== row.stateHash.modified;
|
|
935
|
+
if (seeded && !needsDeep) continue;
|
|
936
|
+
const classes = /* @__PURE__ */ new Set();
|
|
937
|
+
try {
|
|
938
|
+
const t = sweepTicket ?? await this.client.getTicket(appId, row.id);
|
|
939
|
+
const feed = await this.client.getTicketFeed(appId, row.id);
|
|
940
|
+
const modified = String(t["ModifiedDate"] ?? "");
|
|
941
|
+
const status = String(t["Status"] ?? t["StatusID"] ?? "");
|
|
942
|
+
const isOnHold = Boolean(t["IsOnHold"]);
|
|
943
|
+
if (seeded && status !== row.status) classes.add("status");
|
|
944
|
+
if (seeded && Boolean(t["IsOnHold"]) !== row.status.startsWith("hold:")) {
|
|
945
|
+
}
|
|
946
|
+
if (seeded && modified !== row.stateHash.modified) classes.add("new-entry");
|
|
947
|
+
const prevHash = row.stateHash;
|
|
948
|
+
const newHash = { modified, ...computeHash(feed) };
|
|
949
|
+
if (seeded && hashGrewHiddenReplies(prevHash, feed)) classes.add("hidden-reply");
|
|
950
|
+
if (seeded && newHash.entryCount > prevHash.entryCount) classes.add("new-entry");
|
|
951
|
+
if (seeded && isOnHold !== row.wasOnHold) {
|
|
952
|
+
classes.add("hold-window");
|
|
953
|
+
}
|
|
954
|
+
const slaDate = t["SlaCompleteByDate"];
|
|
955
|
+
if (seeded && typeof slaDate === "string" && slaDate !== row.slaDate) {
|
|
956
|
+
classes.add("sla");
|
|
957
|
+
row.slaDate = slaDate;
|
|
958
|
+
}
|
|
959
|
+
row.wasOnHold = isOnHold;
|
|
960
|
+
if (row.ballSource === "auto" && feed.length > 0) {
|
|
961
|
+
const last = feed[0];
|
|
962
|
+
const author = String(last?.CreatedUid ?? "");
|
|
963
|
+
if (author) row.ball = this.usUidsFor().has(author) ? "them" : "us";
|
|
964
|
+
}
|
|
965
|
+
row.stateHash = newHash;
|
|
966
|
+
row.status = status;
|
|
967
|
+
if (typeof t["Title"] === "string" && row.title === "") {
|
|
968
|
+
row.title = cap(redact(t["Title"]), TITLE_MAX_CHARS);
|
|
969
|
+
}
|
|
970
|
+
row.lastChecked = (/* @__PURE__ */ new Date()).toISOString();
|
|
971
|
+
if (this.autoObserve) {
|
|
972
|
+
row.memory.observations.push({ at: row.lastChecked, seen: { status, modified } });
|
|
973
|
+
if (row.memory.observations.length > MAX_OBSERVATIONS) {
|
|
974
|
+
row.memory.observations = row.memory.observations.slice(-MAX_OBSERVATIONS);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
if (classes.size > 0) {
|
|
978
|
+
report.deltas.push({
|
|
979
|
+
id: row.id,
|
|
980
|
+
appId,
|
|
981
|
+
classes: [...classes],
|
|
982
|
+
status: sanitizeForReport(status),
|
|
983
|
+
modified,
|
|
984
|
+
ball: row.ball
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
} catch (cause) {
|
|
988
|
+
report.errors.push(`deep fetch failed for ticket ${row.id}: ${String(cause)}`);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
this.ledger.sweepMeta.lastSweep = (/* @__PURE__ */ new Date()).toISOString();
|
|
993
|
+
await this.persist();
|
|
994
|
+
return this.capReport(report);
|
|
995
|
+
}
|
|
996
|
+
capReport(report) {
|
|
997
|
+
let json = JSON.stringify(report);
|
|
998
|
+
if (json.length > REPORT_MAX_CHARS) {
|
|
999
|
+
report.deltas = report.deltas.slice(0, Math.max(1, Math.floor(report.deltas.length / 2)));
|
|
1000
|
+
json = JSON.stringify(report);
|
|
1001
|
+
if (json.length > REPORT_MAX_CHARS) report.deltas = [];
|
|
1002
|
+
}
|
|
1003
|
+
return report;
|
|
1004
|
+
}
|
|
1005
|
+
//
|
|
1006
|
+
// Notes (local-only memory; never written to TDX)
|
|
1007
|
+
//
|
|
1008
|
+
async notesAdd(input) {
|
|
1009
|
+
const row = this.rowForNote(input.appId, input.ticketId);
|
|
1010
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1011
|
+
const note = {
|
|
1012
|
+
id: `n-${now}-${Math.random().toString(36).slice(2, 8)}`,
|
|
1013
|
+
text: cap(redact(input.text), MAX_NOTE_LENGTH),
|
|
1014
|
+
createdAt: now,
|
|
1015
|
+
updatedAt: now
|
|
1016
|
+
};
|
|
1017
|
+
row.memory.notes.unshift(note);
|
|
1018
|
+
await this.persist();
|
|
1019
|
+
return note;
|
|
1020
|
+
}
|
|
1021
|
+
async notesUpdate(input) {
|
|
1022
|
+
const { row, note } = this.noteById(input.noteId);
|
|
1023
|
+
note.text = cap(redact(input.text), MAX_NOTE_LENGTH);
|
|
1024
|
+
note.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1025
|
+
await this.persist();
|
|
1026
|
+
return note;
|
|
1027
|
+
}
|
|
1028
|
+
async notesDelete(input) {
|
|
1029
|
+
const { row } = this.noteById(input.noteId);
|
|
1030
|
+
row.memory.notes = row.memory.notes.filter((n) => n.id !== input.noteId);
|
|
1031
|
+
await this.persist();
|
|
1032
|
+
return { deleted: true };
|
|
1033
|
+
}
|
|
1034
|
+
async notesList(input) {
|
|
1035
|
+
const rows = this.ledger.active.filter(
|
|
1036
|
+
(r) => (input.appId === void 0 || r.appId === input.appId) && (input.ticketId === void 0 || r.id === input.ticketId)
|
|
1037
|
+
);
|
|
1038
|
+
return rows.flatMap((r) => r.memory.notes);
|
|
1039
|
+
}
|
|
1040
|
+
rowForNote(appId, ticketId) {
|
|
1041
|
+
const row = this.ledger.active.find((r) => r.id === ticketId && r.appId === appId);
|
|
1042
|
+
if (!row) throw new Error(`No active watch row for ticket ${ticketId} in app ${appId}; register it first.`);
|
|
1043
|
+
return row;
|
|
1044
|
+
}
|
|
1045
|
+
noteById(noteId) {
|
|
1046
|
+
for (const row of [...this.ledger.active, ...this.ledger.archived]) {
|
|
1047
|
+
const note = row.memory.notes.find((n) => n.id === noteId);
|
|
1048
|
+
if (note) return { row, note };
|
|
1049
|
+
}
|
|
1050
|
+
throw new Error(`Note ${noteId} not found.`);
|
|
1051
|
+
}
|
|
1052
|
+
};
|
|
1053
|
+
|
|
1054
|
+
// src/sweep.ts
|
|
1055
|
+
var ledgerPath = defaultLedgerPath();
|
|
1056
|
+
var ledger;
|
|
1057
|
+
try {
|
|
1058
|
+
ledger = await loadLedger(ledgerPath);
|
|
1059
|
+
} catch (cause) {
|
|
1060
|
+
if (cause instanceof LedgerCorruptError) {
|
|
1061
|
+
console.error(String(cause.message));
|
|
1062
|
+
process.exit(1);
|
|
1063
|
+
}
|
|
1064
|
+
ledger = emptyLedger();
|
|
1065
|
+
}
|
|
1066
|
+
try {
|
|
1067
|
+
const client = await createConfiguredTeamDynamixClient();
|
|
1068
|
+
const svc = new WorkspaceWatchService(ledger, ledgerPath, client);
|
|
1069
|
+
const result = await svc.sweep();
|
|
1070
|
+
const pending = svc.pendingTriage();
|
|
1071
|
+
console.log(JSON.stringify({ ledgerPath, ...result, pendingCount: pending.length }, null, 2));
|
|
1072
|
+
} catch (cause) {
|
|
1073
|
+
console.error(`Sweep failed: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
1074
|
+
process.exit(1);
|
|
1075
|
+
}
|
|
1076
|
+
//# sourceMappingURL=sweep.js.map
|