@renanlido/tia-openness-mcp 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1736 -1238
- package/package.json +6 -1
package/dist/index.js
CHANGED
|
@@ -8,7 +8,11 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
|
8
8
|
var __getProtoOf = Object.getPrototypeOf;
|
|
9
9
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
10
10
|
var __commonJS = (cb, mod) => function __require() {
|
|
11
|
-
|
|
11
|
+
try {
|
|
12
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
13
|
+
} catch (e) {
|
|
14
|
+
throw mod = 0, e;
|
|
15
|
+
}
|
|
12
16
|
};
|
|
13
17
|
var __export = (target, all) => {
|
|
14
18
|
for (var name in all)
|
|
@@ -3107,9 +3111,28 @@ var require_utils = __commonJS({
|
|
|
3107
3111
|
"use strict";
|
|
3108
3112
|
var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
|
|
3109
3113
|
var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
|
|
3114
|
+
var isPort = RegExp.prototype.test.bind(/^\d*$/u);
|
|
3110
3115
|
var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
|
|
3111
3116
|
var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);
|
|
3112
|
-
var isPathCharacter = RegExp.prototype.test.bind(/^[
|
|
3117
|
+
var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u);
|
|
3118
|
+
var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u);
|
|
3119
|
+
var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u);
|
|
3120
|
+
var BYTE_HEX = new Array(256);
|
|
3121
|
+
{
|
|
3122
|
+
const HEX_DIGITS = "0123456789ABCDEF";
|
|
3123
|
+
for (let i = 0; i < 256; i++) {
|
|
3124
|
+
BYTE_HEX[i] = "%" + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 15];
|
|
3125
|
+
}
|
|
3126
|
+
}
|
|
3127
|
+
function percentEncodeNonAscii(cp) {
|
|
3128
|
+
if (cp < 2048) {
|
|
3129
|
+
return BYTE_HEX[192 | cp >> 6] + BYTE_HEX[128 | cp & 63];
|
|
3130
|
+
}
|
|
3131
|
+
if (cp < 65536) {
|
|
3132
|
+
return BYTE_HEX[224 | cp >> 12] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63];
|
|
3133
|
+
}
|
|
3134
|
+
return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63];
|
|
3135
|
+
}
|
|
3113
3136
|
function stringArrayToHexStripped(input) {
|
|
3114
3137
|
let acc = "";
|
|
3115
3138
|
let code = 0;
|
|
@@ -3134,91 +3157,105 @@ var require_utils = __commonJS({
|
|
|
3134
3157
|
}
|
|
3135
3158
|
return acc;
|
|
3136
3159
|
}
|
|
3160
|
+
var isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/);
|
|
3161
|
+
var isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/);
|
|
3162
|
+
var isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/);
|
|
3137
3163
|
var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
|
|
3138
|
-
function
|
|
3139
|
-
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
if (hex3 !== "") {
|
|
3146
|
-
address.push(hex3);
|
|
3147
|
-
} else {
|
|
3148
|
-
output.error = true;
|
|
3149
|
-
return false;
|
|
3164
|
+
function isZoneIdentifier(zone) {
|
|
3165
|
+
if (zone.length === 0) return false;
|
|
3166
|
+
for (let i = 0; i < zone.length; i++) {
|
|
3167
|
+
if (isZoneCharacter(zone[i])) continue;
|
|
3168
|
+
if (zone[i] === "%" && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) {
|
|
3169
|
+
i += 2;
|
|
3170
|
+
continue;
|
|
3150
3171
|
}
|
|
3151
|
-
|
|
3172
|
+
return false;
|
|
3152
3173
|
}
|
|
3153
3174
|
return true;
|
|
3154
3175
|
}
|
|
3155
|
-
function
|
|
3156
|
-
let
|
|
3157
|
-
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
let
|
|
3161
|
-
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
}
|
|
3168
|
-
if (cursor === ":") {
|
|
3169
|
-
if (endipv6Encountered === true) {
|
|
3170
|
-
endIpv6 = true;
|
|
3171
|
-
}
|
|
3172
|
-
if (!consume(buffer, address, output)) {
|
|
3173
|
-
break;
|
|
3174
|
-
}
|
|
3175
|
-
if (++tokenCount > 7) {
|
|
3176
|
-
output.error = true;
|
|
3177
|
-
break;
|
|
3178
|
-
}
|
|
3179
|
-
if (i > 0 && input[i - 1] === ":") {
|
|
3180
|
-
endipv6Encountered = true;
|
|
3181
|
-
}
|
|
3182
|
-
address.push(":");
|
|
3183
|
-
continue;
|
|
3184
|
-
} else if (cursor === "%") {
|
|
3185
|
-
if (!consume(buffer, address, output)) {
|
|
3186
|
-
break;
|
|
3176
|
+
function compressIPv6ZeroRun(hextets) {
|
|
3177
|
+
let bestStart = -1;
|
|
3178
|
+
let bestLength = 0;
|
|
3179
|
+
let runStart = -1;
|
|
3180
|
+
let runLength = 0;
|
|
3181
|
+
for (let i = 0; i < hextets.length; i++) {
|
|
3182
|
+
if (hextets[i] === "0") {
|
|
3183
|
+
if (runStart === -1) runStart = i;
|
|
3184
|
+
runLength++;
|
|
3185
|
+
if (runLength > bestLength) {
|
|
3186
|
+
bestLength = runLength;
|
|
3187
|
+
bestStart = runStart;
|
|
3187
3188
|
}
|
|
3188
|
-
consume = consumeIsZone;
|
|
3189
3189
|
} else {
|
|
3190
|
-
|
|
3190
|
+
runStart = -1;
|
|
3191
|
+
runLength = 0;
|
|
3192
|
+
}
|
|
3193
|
+
}
|
|
3194
|
+
if (bestLength < 2) return hextets.join(":");
|
|
3195
|
+
const head = hextets.slice(0, bestStart).join(":");
|
|
3196
|
+
const tail = hextets.slice(bestStart + bestLength).join(":");
|
|
3197
|
+
return head + "::" + tail;
|
|
3198
|
+
}
|
|
3199
|
+
function normalizeIPv6Address(input) {
|
|
3200
|
+
const compression = input.indexOf("::");
|
|
3201
|
+
if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0;
|
|
3202
|
+
const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":");
|
|
3203
|
+
const right = compression === -1 ? [] : input.slice(compression + 2).split(":");
|
|
3204
|
+
if (compression !== -1) {
|
|
3205
|
+
if (left.length === 1 && left[0] === "") left.length = 0;
|
|
3206
|
+
if (right.length === 1 && right[0] === "") right.length = 0;
|
|
3207
|
+
}
|
|
3208
|
+
const parts = left.concat(right);
|
|
3209
|
+
let hextetCount = 0;
|
|
3210
|
+
for (let i = 0; i < parts.length; i++) {
|
|
3211
|
+
const part = parts[i];
|
|
3212
|
+
if (part === "") return void 0;
|
|
3213
|
+
if (part.indexOf(".") !== -1) {
|
|
3214
|
+
if (i !== parts.length - 1 || compression !== -1 && right.length === 0 || !isIPv4(part)) return void 0;
|
|
3215
|
+
hextetCount += 2;
|
|
3191
3216
|
continue;
|
|
3192
3217
|
}
|
|
3218
|
+
if (!isHextet(part)) return void 0;
|
|
3219
|
+
parts[i] = parseInt(part, 16).toString(16);
|
|
3220
|
+
hextetCount++;
|
|
3193
3221
|
}
|
|
3194
|
-
if (
|
|
3195
|
-
if (
|
|
3196
|
-
|
|
3197
|
-
} else if (endIpv6) {
|
|
3198
|
-
address.push(buffer.join(""));
|
|
3199
|
-
} else {
|
|
3200
|
-
address.push(stringArrayToHexStripped(buffer));
|
|
3201
|
-
}
|
|
3222
|
+
if (compression === -1) {
|
|
3223
|
+
if (hextetCount !== 8) return void 0;
|
|
3224
|
+
return compressIPv6ZeroRun(parts);
|
|
3202
3225
|
}
|
|
3203
|
-
|
|
3204
|
-
|
|
3226
|
+
if (hextetCount >= 8) return void 0;
|
|
3227
|
+
const expanded = parts.slice(0, left.length);
|
|
3228
|
+
for (let i = hextetCount; i < 8; i++) expanded.push("0");
|
|
3229
|
+
for (let i = left.length; i < parts.length; i++) expanded.push(parts[i]);
|
|
3230
|
+
return compressIPv6ZeroRun(expanded);
|
|
3205
3231
|
}
|
|
3206
3232
|
function normalizeIPv6(host) {
|
|
3207
|
-
|
|
3208
|
-
|
|
3209
|
-
}
|
|
3210
|
-
|
|
3211
|
-
if (
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
3233
|
+
const bracketed = host[0] === "[" && host[host.length - 1] === "]";
|
|
3234
|
+
const hasBracket = host[0] === "[" || host[host.length - 1] === "]";
|
|
3235
|
+
if (hasBracket && !bracketed) return { host, isIPV6: false, error: true };
|
|
3236
|
+
let input = bracketed ? host.slice(1, -1) : host;
|
|
3237
|
+
if (bracketed && isIPvFuture(input)) {
|
|
3238
|
+
input = input.toLowerCase();
|
|
3239
|
+
return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true };
|
|
3240
|
+
}
|
|
3241
|
+
if (findToken(input, ":") < 2) {
|
|
3242
|
+
return { host, isIPV6: false, error: bracketed };
|
|
3243
|
+
}
|
|
3244
|
+
let zoneIdentifier = "";
|
|
3245
|
+
const zoneSeparator = input.indexOf("%");
|
|
3246
|
+
if (zoneSeparator !== -1) {
|
|
3247
|
+
const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1;
|
|
3248
|
+
zoneIdentifier = input.slice(zoneSeparator + separatorLength);
|
|
3249
|
+
if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true };
|
|
3250
|
+
input = input.slice(0, zoneSeparator);
|
|
3251
|
+
}
|
|
3252
|
+
const address = normalizeIPv6Address(input);
|
|
3253
|
+
if (address === void 0) return { host, isIPV6: false, error: true };
|
|
3254
|
+
return {
|
|
3255
|
+
host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""),
|
|
3256
|
+
escapedHost: address + (zoneIdentifier ? "%25" + zoneIdentifier : ""),
|
|
3257
|
+
isIPV6: true
|
|
3258
|
+
};
|
|
3222
3259
|
}
|
|
3223
3260
|
function findToken(str, token) {
|
|
3224
3261
|
let ind = 0;
|
|
@@ -3337,7 +3374,8 @@ var require_utils = __commonJS({
|
|
|
3337
3374
|
function normalizePathEncoding(input) {
|
|
3338
3375
|
let output = "";
|
|
3339
3376
|
for (let i = 0; i < input.length; i++) {
|
|
3340
|
-
|
|
3377
|
+
const ch = input[i];
|
|
3378
|
+
if (ch === "%" && i + 2 < input.length) {
|
|
3341
3379
|
const hex3 = input.slice(i + 1, i + 3);
|
|
3342
3380
|
if (isHexPair(hex3)) {
|
|
3343
3381
|
const normalizedHex = hex3.toUpperCase();
|
|
@@ -3351,10 +3389,152 @@ var require_utils = __commonJS({
|
|
|
3351
3389
|
continue;
|
|
3352
3390
|
}
|
|
3353
3391
|
}
|
|
3354
|
-
if (isPathCharacter(
|
|
3355
|
-
output +=
|
|
3392
|
+
if (isPathCharacter(ch)) {
|
|
3393
|
+
output += ch;
|
|
3394
|
+
} else {
|
|
3395
|
+
const code = input.charCodeAt(i);
|
|
3396
|
+
if (code < 128) {
|
|
3397
|
+
output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
|
|
3398
|
+
} else if (code < 55296 || code > 57343) {
|
|
3399
|
+
output += percentEncodeNonAscii(code);
|
|
3400
|
+
} else if (code <= 56319 && i + 1 < input.length) {
|
|
3401
|
+
const low = input.charCodeAt(i + 1);
|
|
3402
|
+
if (low >= 56320 && low <= 57343) {
|
|
3403
|
+
output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
|
|
3404
|
+
i++;
|
|
3405
|
+
} else {
|
|
3406
|
+
output += percentEncodeNonAscii(65533);
|
|
3407
|
+
}
|
|
3408
|
+
} else {
|
|
3409
|
+
output += percentEncodeNonAscii(65533);
|
|
3410
|
+
}
|
|
3411
|
+
}
|
|
3412
|
+
}
|
|
3413
|
+
return output;
|
|
3414
|
+
}
|
|
3415
|
+
function serializePathEncoding(input, pathNoScheme = false) {
|
|
3416
|
+
let output = "";
|
|
3417
|
+
let firstSegment = pathNoScheme && input[0] !== "/";
|
|
3418
|
+
for (let i = 0; i < input.length; i++) {
|
|
3419
|
+
const ch = input[i];
|
|
3420
|
+
if (ch === "%" && i + 2 < input.length) {
|
|
3421
|
+
const hex3 = input.slice(i + 1, i + 3);
|
|
3422
|
+
if (isHexPair(hex3)) {
|
|
3423
|
+
output += "%" + hex3.toUpperCase();
|
|
3424
|
+
i += 2;
|
|
3425
|
+
continue;
|
|
3426
|
+
}
|
|
3427
|
+
}
|
|
3428
|
+
if (ch === "/") {
|
|
3429
|
+
firstSegment = false;
|
|
3430
|
+
}
|
|
3431
|
+
if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) {
|
|
3432
|
+
output += ch;
|
|
3433
|
+
} else {
|
|
3434
|
+
const code = input.charCodeAt(i);
|
|
3435
|
+
if (code < 128) {
|
|
3436
|
+
output += BYTE_HEX[code];
|
|
3437
|
+
} else if (code < 55296 || code > 57343) {
|
|
3438
|
+
output += percentEncodeNonAscii(code);
|
|
3439
|
+
} else if (code <= 56319 && i + 1 < input.length) {
|
|
3440
|
+
const low = input.charCodeAt(i + 1);
|
|
3441
|
+
if (low >= 56320 && low <= 57343) {
|
|
3442
|
+
output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
|
|
3443
|
+
i++;
|
|
3444
|
+
} else {
|
|
3445
|
+
output += percentEncodeNonAscii(65533);
|
|
3446
|
+
}
|
|
3447
|
+
} else {
|
|
3448
|
+
output += percentEncodeNonAscii(65533);
|
|
3449
|
+
}
|
|
3450
|
+
}
|
|
3451
|
+
}
|
|
3452
|
+
return output;
|
|
3453
|
+
}
|
|
3454
|
+
function encodeComponent(input, isAllowed) {
|
|
3455
|
+
let output = "";
|
|
3456
|
+
for (let i = 0; i < input.length; i++) {
|
|
3457
|
+
const ch = input[i];
|
|
3458
|
+
if (ch === "%" && i + 2 < input.length) {
|
|
3459
|
+
const hex3 = input.slice(i + 1, i + 3);
|
|
3460
|
+
if (isHexPair(hex3)) {
|
|
3461
|
+
output += "%" + hex3.toUpperCase();
|
|
3462
|
+
i += 2;
|
|
3463
|
+
continue;
|
|
3464
|
+
}
|
|
3465
|
+
}
|
|
3466
|
+
if (isAllowed(ch)) {
|
|
3467
|
+
output += ch;
|
|
3468
|
+
} else {
|
|
3469
|
+
const code = input.charCodeAt(i);
|
|
3470
|
+
if (code < 128) {
|
|
3471
|
+
output += BYTE_HEX[code];
|
|
3472
|
+
} else if (code < 55296 || code > 57343) {
|
|
3473
|
+
output += percentEncodeNonAscii(code);
|
|
3474
|
+
} else if (code <= 56319 && i + 1 < input.length) {
|
|
3475
|
+
const low = input.charCodeAt(i + 1);
|
|
3476
|
+
if (low >= 56320 && low <= 57343) {
|
|
3477
|
+
output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
|
|
3478
|
+
i++;
|
|
3479
|
+
} else {
|
|
3480
|
+
output += percentEncodeNonAscii(65533);
|
|
3481
|
+
}
|
|
3482
|
+
} else {
|
|
3483
|
+
output += percentEncodeNonAscii(65533);
|
|
3484
|
+
}
|
|
3485
|
+
}
|
|
3486
|
+
}
|
|
3487
|
+
return output;
|
|
3488
|
+
}
|
|
3489
|
+
function encodeUserinfo(input) {
|
|
3490
|
+
return encodeComponent(input, isUserinfoCharacter);
|
|
3491
|
+
}
|
|
3492
|
+
function encodeQuery(input) {
|
|
3493
|
+
return encodeComponent(input, isQueryFragmentCharacter);
|
|
3494
|
+
}
|
|
3495
|
+
function encodeFragment(input) {
|
|
3496
|
+
return encodeComponent(input, isQueryFragmentCharacter);
|
|
3497
|
+
}
|
|
3498
|
+
function isEscapeSafe(cp) {
|
|
3499
|
+
return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95;
|
|
3500
|
+
}
|
|
3501
|
+
function normalizeQueryFragmentEncoding(input) {
|
|
3502
|
+
let output = "";
|
|
3503
|
+
for (let i = 0; i < input.length; i++) {
|
|
3504
|
+
const ch = input[i];
|
|
3505
|
+
if (ch === "%" && i + 2 < input.length) {
|
|
3506
|
+
const hex3 = input.slice(i + 1, i + 3);
|
|
3507
|
+
if (isHexPair(hex3)) {
|
|
3508
|
+
const normalizedHex = hex3.toUpperCase();
|
|
3509
|
+
const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
|
|
3510
|
+
if (isUnreserved(decoded)) {
|
|
3511
|
+
output += decoded;
|
|
3512
|
+
} else {
|
|
3513
|
+
output += "%" + normalizedHex;
|
|
3514
|
+
}
|
|
3515
|
+
i += 2;
|
|
3516
|
+
continue;
|
|
3517
|
+
}
|
|
3518
|
+
}
|
|
3519
|
+
if (isQueryFragmentCharacter(ch)) {
|
|
3520
|
+
output += ch;
|
|
3356
3521
|
} else {
|
|
3357
|
-
|
|
3522
|
+
const code = input.charCodeAt(i);
|
|
3523
|
+
if (code < 128) {
|
|
3524
|
+
output += isEscapeSafe(code) ? ch : BYTE_HEX[code];
|
|
3525
|
+
} else if (code < 55296 || code > 57343) {
|
|
3526
|
+
output += percentEncodeNonAscii(code);
|
|
3527
|
+
} else if (code <= 56319 && i + 1 < input.length) {
|
|
3528
|
+
const low = input.charCodeAt(i + 1);
|
|
3529
|
+
if (low >= 56320 && low <= 57343) {
|
|
3530
|
+
output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320));
|
|
3531
|
+
i++;
|
|
3532
|
+
} else {
|
|
3533
|
+
output += percentEncodeNonAscii(65533);
|
|
3534
|
+
}
|
|
3535
|
+
} else {
|
|
3536
|
+
output += percentEncodeNonAscii(65533);
|
|
3537
|
+
}
|
|
3358
3538
|
}
|
|
3359
3539
|
}
|
|
3360
3540
|
return output;
|
|
@@ -3377,14 +3557,18 @@ var require_utils = __commonJS({
|
|
|
3377
3557
|
function recomposeAuthority(component) {
|
|
3378
3558
|
const uriTokens = [];
|
|
3379
3559
|
if (component.userinfo !== void 0) {
|
|
3380
|
-
uriTokens.push(component.userinfo);
|
|
3560
|
+
uriTokens.push(encodeUserinfo(component.userinfo));
|
|
3381
3561
|
uriTokens.push("@");
|
|
3382
3562
|
}
|
|
3383
3563
|
if (component.host !== void 0) {
|
|
3384
|
-
let host =
|
|
3564
|
+
let host = component.host;
|
|
3385
3565
|
if (!isIPv4(host)) {
|
|
3386
|
-
|
|
3387
|
-
if (ipV6res.isIPV6
|
|
3566
|
+
let ipV6res = normalizeIPv6(host);
|
|
3567
|
+
if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) {
|
|
3568
|
+
host = normalizePercentEncoding(host, true);
|
|
3569
|
+
ipV6res = normalizeIPv6(host);
|
|
3570
|
+
}
|
|
3571
|
+
if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) {
|
|
3388
3572
|
host = `[${ipV6res.escapedHost}]`;
|
|
3389
3573
|
} else {
|
|
3390
3574
|
host = reescapeHostDelimiters(host, false);
|
|
@@ -3393,8 +3577,12 @@ var require_utils = __commonJS({
|
|
|
3393
3577
|
uriTokens.push(host);
|
|
3394
3578
|
}
|
|
3395
3579
|
if (typeof component.port === "number" || typeof component.port === "string") {
|
|
3580
|
+
const port = String(component.port);
|
|
3581
|
+
if (!isPort(port)) {
|
|
3582
|
+
throw new TypeError("URI port is malformed.");
|
|
3583
|
+
}
|
|
3396
3584
|
uriTokens.push(":");
|
|
3397
|
-
uriTokens.push(
|
|
3585
|
+
uriTokens.push(port);
|
|
3398
3586
|
}
|
|
3399
3587
|
return uriTokens.length ? uriTokens.join("") : void 0;
|
|
3400
3588
|
}
|
|
@@ -3404,6 +3592,11 @@ var require_utils = __commonJS({
|
|
|
3404
3592
|
reescapeHostDelimiters,
|
|
3405
3593
|
normalizePercentEncoding,
|
|
3406
3594
|
normalizePathEncoding,
|
|
3595
|
+
serializePathEncoding,
|
|
3596
|
+
normalizeQueryFragmentEncoding,
|
|
3597
|
+
encodeUserinfo,
|
|
3598
|
+
encodeQuery,
|
|
3599
|
+
encodeFragment,
|
|
3407
3600
|
escapePreservingEscapes,
|
|
3408
3601
|
removeDotSegments,
|
|
3409
3602
|
isIPv4,
|
|
@@ -3419,7 +3612,7 @@ var require_schemes = __commonJS({
|
|
|
3419
3612
|
"node_modules/fast-uri/lib/schemes.js"(exports, module) {
|
|
3420
3613
|
"use strict";
|
|
3421
3614
|
var { isUUID } = require_utils();
|
|
3422
|
-
var URN_REG =
|
|
3615
|
+
var URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu;
|
|
3423
3616
|
var supportedSchemeNames = (
|
|
3424
3617
|
/** @type {const} */
|
|
3425
3618
|
[
|
|
@@ -3480,9 +3673,10 @@ var require_schemes = __commonJS({
|
|
|
3480
3673
|
wsComponent.secure = void 0;
|
|
3481
3674
|
}
|
|
3482
3675
|
if (wsComponent.resourceName) {
|
|
3483
|
-
const
|
|
3676
|
+
const queryIndex = wsComponent.resourceName.indexOf("?");
|
|
3677
|
+
const path = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
|
|
3484
3678
|
wsComponent.path = path && path !== "/" ? path : void 0;
|
|
3485
|
-
wsComponent.query =
|
|
3679
|
+
wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
|
|
3486
3680
|
wsComponent.resourceName = void 0;
|
|
3487
3681
|
}
|
|
3488
3682
|
wsComponent.fragment = void 0;
|
|
@@ -3494,7 +3688,7 @@ var require_schemes = __commonJS({
|
|
|
3494
3688
|
return urnComponent;
|
|
3495
3689
|
}
|
|
3496
3690
|
const matches = urnComponent.path.match(URN_REG);
|
|
3497
|
-
if (matches) {
|
|
3691
|
+
if (matches && matches[0] === urnComponent.path) {
|
|
3498
3692
|
const scheme = options.scheme || urnComponent.scheme || "urn";
|
|
3499
3693
|
urnComponent.nid = matches[1].toLowerCase();
|
|
3500
3694
|
urnComponent.nss = matches[2];
|
|
@@ -3628,8 +3822,17 @@ var require_schemes = __commonJS({
|
|
|
3628
3822
|
var require_fast_uri = __commonJS({
|
|
3629
3823
|
"node_modules/fast-uri/index.js"(exports, module) {
|
|
3630
3824
|
"use strict";
|
|
3631
|
-
var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding,
|
|
3825
|
+
var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();
|
|
3632
3826
|
var { SCHEMES, getSchemeHandler } = require_schemes();
|
|
3827
|
+
var VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u;
|
|
3828
|
+
var MALFORMED_SCHEME_ERROR = "URI scheme is malformed.";
|
|
3829
|
+
function decodeValidScheme(scheme) {
|
|
3830
|
+
const decodedScheme = unescape(String(scheme));
|
|
3831
|
+
if (!VALID_SCHEME.test(decodedScheme)) {
|
|
3832
|
+
throw new TypeError(MALFORMED_SCHEME_ERROR);
|
|
3833
|
+
}
|
|
3834
|
+
return decodedScheme;
|
|
3835
|
+
}
|
|
3633
3836
|
function normalize(uri, options) {
|
|
3634
3837
|
if (typeof uri === "string") {
|
|
3635
3838
|
uri = /** @type {T} */
|
|
@@ -3642,7 +3845,34 @@ var require_fast_uri = __commonJS({
|
|
|
3642
3845
|
}
|
|
3643
3846
|
function resolve(baseURI, relativeURI, options) {
|
|
3644
3847
|
const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
|
|
3645
|
-
const
|
|
3848
|
+
const {
|
|
3849
|
+
parsed: baseParsed,
|
|
3850
|
+
malformedAuthorityOrPort: baseMalformed,
|
|
3851
|
+
malformedPercentEncoding: baseMalformedPercentEncoding,
|
|
3852
|
+
malformedSchemeSpecific: baseMalformedSchemeSpecific,
|
|
3853
|
+
malformedHost: baseMalformedHost,
|
|
3854
|
+
malformedScheme: baseMalformedScheme
|
|
3855
|
+
} = parseWithStatus(baseURI, schemelessOptions);
|
|
3856
|
+
const {
|
|
3857
|
+
parsed: relativeParsed,
|
|
3858
|
+
malformedAuthorityOrPort: relativeMalformed,
|
|
3859
|
+
malformedPercentEncoding: relativeMalformedPercentEncoding,
|
|
3860
|
+
malformedSchemeSpecific: relativeMalformedSchemeSpecific,
|
|
3861
|
+
malformedHost: relativeMalformedHost,
|
|
3862
|
+
malformedScheme: relativeMalformedScheme
|
|
3863
|
+
} = parseWithStatus(relativeURI, schemelessOptions);
|
|
3864
|
+
if (baseMalformed || relativeMalformed || baseMalformedPercentEncoding || relativeMalformedPercentEncoding || baseMalformedSchemeSpecific || relativeMalformedSchemeSpecific || baseMalformedHost || relativeMalformedHost || baseMalformedScheme || relativeMalformedScheme) {
|
|
3865
|
+
throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed.");
|
|
3866
|
+
}
|
|
3867
|
+
const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
|
|
3868
|
+
const resolvedSchemeHandler = getSchemeHandler(options && options.scheme || resolved.scheme);
|
|
3869
|
+
const resolvedHost = resolved.host;
|
|
3870
|
+
const resolvedHostIsIP = resolvedHost !== void 0 && resolvedHost !== "" && (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6);
|
|
3871
|
+
canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP);
|
|
3872
|
+
const encodedASCIIHost = resolvedHost && resolvedHost.indexOf("%") !== -1 && !new RegExp("\\P{ASCII}", "u").test(resolvedHost);
|
|
3873
|
+
if (resolved.error && !encodedASCIIHost) {
|
|
3874
|
+
throw new Error(resolved.error);
|
|
3875
|
+
}
|
|
3646
3876
|
schemelessOptions.skipEscape = true;
|
|
3647
3877
|
return serialize(resolved, schemelessOptions);
|
|
3648
3878
|
}
|
|
@@ -3702,7 +3932,7 @@ var require_fast_uri = __commonJS({
|
|
|
3702
3932
|
function equal(uriA, uriB, options) {
|
|
3703
3933
|
const normalizedA = normalizeComparableURI(uriA, options);
|
|
3704
3934
|
const normalizedB = normalizeComparableURI(uriB, options);
|
|
3705
|
-
return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA
|
|
3935
|
+
return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA === normalizedB;
|
|
3706
3936
|
}
|
|
3707
3937
|
function serialize(cmpts, opts) {
|
|
3708
3938
|
const component = {
|
|
@@ -3723,19 +3953,22 @@ var require_fast_uri = __commonJS({
|
|
|
3723
3953
|
};
|
|
3724
3954
|
const options = Object.assign({}, opts);
|
|
3725
3955
|
const uriTokens = [];
|
|
3956
|
+
if (component.scheme) {
|
|
3957
|
+
component.scheme = decodeValidScheme(component.scheme);
|
|
3958
|
+
}
|
|
3726
3959
|
const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
|
|
3727
3960
|
if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
|
|
3961
|
+
const hasAuthority = component.userinfo !== void 0 || component.host !== void 0 || component.port !== void 0;
|
|
3962
|
+
const pathNoScheme = !options.skipEscape && component.scheme === void 0 && !hasAuthority;
|
|
3728
3963
|
if (component.path !== void 0) {
|
|
3729
3964
|
if (!options.skipEscape) {
|
|
3730
|
-
component.path =
|
|
3731
|
-
if (component.scheme !== void 0) {
|
|
3732
|
-
component.path = component.path.split("%3A").join(":");
|
|
3733
|
-
}
|
|
3965
|
+
component.path = serializePathEncoding(component.path, pathNoScheme);
|
|
3734
3966
|
} else {
|
|
3735
3967
|
component.path = normalizePercentEncoding(component.path);
|
|
3736
3968
|
}
|
|
3737
3969
|
}
|
|
3738
3970
|
if (options.reference !== "suffix" && component.scheme) {
|
|
3971
|
+
component.scheme = decodeValidScheme(component.scheme);
|
|
3739
3972
|
uriTokens.push(component.scheme, ":");
|
|
3740
3973
|
}
|
|
3741
3974
|
const authority = recomposeAuthority(component);
|
|
@@ -3753,20 +3986,25 @@ var require_fast_uri = __commonJS({
|
|
|
3753
3986
|
if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
|
|
3754
3987
|
s = removeDotSegments(s);
|
|
3755
3988
|
}
|
|
3989
|
+
if (pathNoScheme) {
|
|
3990
|
+
s = serializePathEncoding(s, true);
|
|
3991
|
+
}
|
|
3756
3992
|
if (authority === void 0 && s[0] === "/" && s[1] === "/") {
|
|
3757
3993
|
s = "/%2F" + s.slice(2);
|
|
3758
3994
|
}
|
|
3759
3995
|
uriTokens.push(s);
|
|
3760
3996
|
}
|
|
3761
3997
|
if (component.query !== void 0) {
|
|
3762
|
-
uriTokens.push("?", component.query);
|
|
3998
|
+
uriTokens.push("?", encodeQuery(component.query));
|
|
3763
3999
|
}
|
|
3764
4000
|
if (component.fragment !== void 0) {
|
|
3765
|
-
uriTokens.push("#", component.fragment);
|
|
4001
|
+
uriTokens.push("#", encodeFragment(component.fragment));
|
|
3766
4002
|
}
|
|
3767
4003
|
return uriTokens.join("");
|
|
3768
4004
|
}
|
|
3769
4005
|
var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
|
|
4006
|
+
var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;
|
|
4007
|
+
var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;
|
|
3770
4008
|
function getParseError(parsed, matches) {
|
|
3771
4009
|
if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") {
|
|
3772
4010
|
return 'URI path must start with "/" when authority is present.';
|
|
@@ -3776,6 +4014,35 @@ var require_fast_uri = __commonJS({
|
|
|
3776
4014
|
}
|
|
3777
4015
|
return void 0;
|
|
3778
4016
|
}
|
|
4017
|
+
function hasMalformedPercentEncoding(component) {
|
|
4018
|
+
if (component === void 0) return false;
|
|
4019
|
+
let percent = component.indexOf("%");
|
|
4020
|
+
while (percent !== -1) {
|
|
4021
|
+
if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) {
|
|
4022
|
+
return true;
|
|
4023
|
+
}
|
|
4024
|
+
percent = component.indexOf("%", percent + 3);
|
|
4025
|
+
}
|
|
4026
|
+
return false;
|
|
4027
|
+
}
|
|
4028
|
+
function isIPLiteral(host) {
|
|
4029
|
+
return host[0] === "[" && host[host.length - 1] === "]";
|
|
4030
|
+
}
|
|
4031
|
+
function hasMalformedComponentPercentEncoding(matches) {
|
|
4032
|
+
const host = matches[4];
|
|
4033
|
+
return hasMalformedPercentEncoding(matches[3]) || host !== void 0 && !isIPLiteral(host) && hasMalformedPercentEncoding(host) || hasMalformedPercentEncoding(matches[6]) || hasMalformedPercentEncoding(matches[7]) || hasMalformedPercentEncoding(matches[8]);
|
|
4034
|
+
}
|
|
4035
|
+
function canonicalizeHost(parsed, options, schemeHandler, isIP) {
|
|
4036
|
+
if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
|
|
4037
|
+
try {
|
|
4038
|
+
parsed.host = new URL("http://" + parsed.host).hostname;
|
|
4039
|
+
} catch (e) {
|
|
4040
|
+
parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
|
|
4041
|
+
return true;
|
|
4042
|
+
}
|
|
4043
|
+
}
|
|
4044
|
+
return false;
|
|
4045
|
+
}
|
|
3779
4046
|
function parseWithStatus(uri, opts) {
|
|
3780
4047
|
const options = Object.assign({}, opts);
|
|
3781
4048
|
const parsed = {
|
|
@@ -3788,6 +4055,11 @@ var require_fast_uri = __commonJS({
|
|
|
3788
4055
|
fragment: void 0
|
|
3789
4056
|
};
|
|
3790
4057
|
let malformedAuthorityOrPort = false;
|
|
4058
|
+
let malformedPercentEncoding = false;
|
|
4059
|
+
let malformedSchemeSpecific = false;
|
|
4060
|
+
let malformedHost = false;
|
|
4061
|
+
let malformedIPLiteral = false;
|
|
4062
|
+
let malformedScheme = false;
|
|
3791
4063
|
let isIP = false;
|
|
3792
4064
|
if (options.reference === "suffix") {
|
|
3793
4065
|
if (options.scheme) {
|
|
@@ -3796,6 +4068,25 @@ var require_fast_uri = __commonJS({
|
|
|
3796
4068
|
uri = "//" + uri;
|
|
3797
4069
|
}
|
|
3798
4070
|
}
|
|
4071
|
+
const authorityMatch = uri.match(AUTHORITY_PREFIX);
|
|
4072
|
+
if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) {
|
|
4073
|
+
parsed.error = "URI authority must not contain a literal backslash.";
|
|
4074
|
+
malformedAuthorityOrPort = true;
|
|
4075
|
+
}
|
|
4076
|
+
const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION);
|
|
4077
|
+
if (introducerMatch !== null) {
|
|
4078
|
+
const region = introducerMatch[1];
|
|
4079
|
+
const normalizedRegion = region.replace(/[\t\n\r]/g, "");
|
|
4080
|
+
if (normalizedRegion.length >= 2) {
|
|
4081
|
+
if (normalizedRegion.slice(0, 2) !== "//") {
|
|
4082
|
+
parsed.error = parsed.error || "URI authority must not contain a literal backslash.";
|
|
4083
|
+
malformedAuthorityOrPort = true;
|
|
4084
|
+
} else if (region.length !== normalizedRegion.length) {
|
|
4085
|
+
parsed.error = parsed.error || "URI authority introducer must not contain whitespace.";
|
|
4086
|
+
malformedAuthorityOrPort = true;
|
|
4087
|
+
}
|
|
4088
|
+
}
|
|
4089
|
+
}
|
|
3799
4090
|
const matches = uri.match(URI_PARSE);
|
|
3800
4091
|
if (matches) {
|
|
3801
4092
|
parsed.scheme = matches[1];
|
|
@@ -3805,6 +4096,19 @@ var require_fast_uri = __commonJS({
|
|
|
3805
4096
|
parsed.path = matches[6] || "";
|
|
3806
4097
|
parsed.query = matches[7];
|
|
3807
4098
|
parsed.fragment = matches[8];
|
|
4099
|
+
if (parsed.scheme !== void 0) {
|
|
4100
|
+
const decodedScheme = unescape(parsed.scheme);
|
|
4101
|
+
if (VALID_SCHEME.test(decodedScheme)) {
|
|
4102
|
+
parsed.scheme = decodedScheme.toLowerCase();
|
|
4103
|
+
} else {
|
|
4104
|
+
parsed.error = parsed.error || MALFORMED_SCHEME_ERROR;
|
|
4105
|
+
malformedScheme = true;
|
|
4106
|
+
}
|
|
4107
|
+
}
|
|
4108
|
+
malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches);
|
|
4109
|
+
if (malformedPercentEncoding) {
|
|
4110
|
+
parsed.error = parsed.error || "URI contains malformed percent-encoding.";
|
|
4111
|
+
}
|
|
3808
4112
|
if (isNaN(parsed.port)) {
|
|
3809
4113
|
parsed.port = matches[5];
|
|
3810
4114
|
}
|
|
@@ -3816,9 +4120,16 @@ var require_fast_uri = __commonJS({
|
|
|
3816
4120
|
if (parsed.host) {
|
|
3817
4121
|
const ipv4result = isIPv4(parsed.host);
|
|
3818
4122
|
if (ipv4result === false) {
|
|
4123
|
+
const bracketedIPLiteral = isIPLiteral(parsed.host);
|
|
4124
|
+
const hasIPLiteralBracket = parsed.host.indexOf("[") !== -1 || parsed.host.indexOf("]") !== -1;
|
|
3819
4125
|
const ipv6result = normalizeIPv6(parsed.host);
|
|
3820
|
-
|
|
3821
|
-
|
|
4126
|
+
isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true;
|
|
4127
|
+
malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true);
|
|
4128
|
+
parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase();
|
|
4129
|
+
if (malformedIPLiteral) {
|
|
4130
|
+
parsed.error = parsed.error || "URI host is malformed.";
|
|
4131
|
+
malformedAuthorityOrPort = true;
|
|
4132
|
+
}
|
|
3822
4133
|
} else {
|
|
3823
4134
|
isIP = true;
|
|
3824
4135
|
}
|
|
@@ -3836,42 +4147,37 @@ var require_fast_uri = __commonJS({
|
|
|
3836
4147
|
parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
|
|
3837
4148
|
}
|
|
3838
4149
|
const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
|
|
3839
|
-
if (!
|
|
3840
|
-
|
|
3841
|
-
|
|
3842
|
-
|
|
3843
|
-
|
|
3844
|
-
|
|
3845
|
-
|
|
4150
|
+
if (!malformedIPLiteral) {
|
|
4151
|
+
malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP);
|
|
4152
|
+
}
|
|
4153
|
+
if (uri.indexOf("%") !== -1 && parsed.host !== void 0 && !malformedIPLiteral) {
|
|
4154
|
+
let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true);
|
|
4155
|
+
if (!isIP) {
|
|
4156
|
+
host = normalizePercentEncoding(host.toLowerCase());
|
|
3846
4157
|
}
|
|
4158
|
+
parsed.host = reescapeHostDelimiters(host, isIP);
|
|
3847
4159
|
}
|
|
3848
4160
|
if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
|
|
3849
|
-
if (uri.indexOf("%") !== -1) {
|
|
3850
|
-
if (parsed.scheme !== void 0) {
|
|
3851
|
-
parsed.scheme = unescape(parsed.scheme);
|
|
3852
|
-
}
|
|
3853
|
-
if (parsed.host !== void 0) {
|
|
3854
|
-
parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP);
|
|
3855
|
-
}
|
|
3856
|
-
}
|
|
3857
4161
|
if (parsed.path) {
|
|
3858
4162
|
parsed.path = normalizePathEncoding(parsed.path);
|
|
3859
4163
|
}
|
|
4164
|
+
if (parsed.query) {
|
|
4165
|
+
parsed.query = normalizeQueryFragmentEncoding(parsed.query);
|
|
4166
|
+
}
|
|
3860
4167
|
if (parsed.fragment) {
|
|
3861
|
-
|
|
3862
|
-
parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
|
|
3863
|
-
} catch {
|
|
3864
|
-
parsed.error = parsed.error || "URI malformed";
|
|
3865
|
-
}
|
|
4168
|
+
parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment);
|
|
3866
4169
|
}
|
|
3867
4170
|
}
|
|
3868
4171
|
if (schemeHandler && schemeHandler.parse) {
|
|
3869
4172
|
schemeHandler.parse(parsed, options);
|
|
4173
|
+
if (schemeHandler === SCHEMES.urn && parsed.nid === void 0) {
|
|
4174
|
+
malformedSchemeSpecific = true;
|
|
4175
|
+
}
|
|
3870
4176
|
}
|
|
3871
4177
|
} else {
|
|
3872
4178
|
parsed.error = parsed.error || "URI can not be parsed.";
|
|
3873
4179
|
}
|
|
3874
|
-
return { parsed, malformedAuthorityOrPort };
|
|
4180
|
+
return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme };
|
|
3875
4181
|
}
|
|
3876
4182
|
function parse3(uri, opts) {
|
|
3877
4183
|
return parseWithStatus(uri, opts).parsed;
|
|
@@ -3880,20 +4186,28 @@ var require_fast_uri = __commonJS({
|
|
|
3880
4186
|
return normalizeStringWithStatus(uri, opts).normalized;
|
|
3881
4187
|
}
|
|
3882
4188
|
function normalizeStringWithStatus(uri, opts) {
|
|
3883
|
-
const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts);
|
|
4189
|
+
const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts);
|
|
3884
4190
|
return {
|
|
3885
|
-
normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts),
|
|
3886
|
-
malformedAuthorityOrPort
|
|
4191
|
+
normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts),
|
|
4192
|
+
malformedAuthorityOrPort,
|
|
4193
|
+
malformedPercentEncoding,
|
|
4194
|
+
malformedSchemeSpecific,
|
|
4195
|
+
malformedHost,
|
|
4196
|
+
malformedScheme
|
|
3887
4197
|
};
|
|
3888
4198
|
}
|
|
3889
4199
|
function normalizeComparableURI(uri, opts) {
|
|
3890
|
-
if (typeof uri
|
|
3891
|
-
|
|
3892
|
-
return malformedAuthorityOrPort ? void 0 : normalized;
|
|
4200
|
+
if (typeof uri !== "string" && typeof uri !== "object") {
|
|
4201
|
+
return void 0;
|
|
3893
4202
|
}
|
|
3894
|
-
|
|
3895
|
-
|
|
4203
|
+
let value;
|
|
4204
|
+
try {
|
|
4205
|
+
value = typeof uri === "string" ? uri : serialize(uri, opts);
|
|
4206
|
+
} catch {
|
|
4207
|
+
return void 0;
|
|
3896
4208
|
}
|
|
4209
|
+
const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts);
|
|
4210
|
+
return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? void 0 : normalized;
|
|
3897
4211
|
}
|
|
3898
4212
|
var fastUri = {
|
|
3899
4213
|
SCHEMES,
|
|
@@ -4321,8 +4635,8 @@ var require_core = __commonJS({
|
|
|
4321
4635
|
for (const jsonPointer of keywordsJsonPointers) {
|
|
4322
4636
|
const segments = jsonPointer.split("/").slice(1);
|
|
4323
4637
|
let keywords = metaSchema;
|
|
4324
|
-
for (const
|
|
4325
|
-
keywords = keywords[
|
|
4638
|
+
for (const seg2 of segments)
|
|
4639
|
+
keywords = keywords[seg2];
|
|
4326
4640
|
for (const key in rules) {
|
|
4327
4641
|
const rule = rules[key];
|
|
4328
4642
|
if (typeof rule != "object")
|
|
@@ -11927,18 +12241,18 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
|
|
|
11927
12241
|
}
|
|
11928
12242
|
function toDotPath(_path) {
|
|
11929
12243
|
const segs = [];
|
|
11930
|
-
const path = _path.map((
|
|
11931
|
-
for (const
|
|
11932
|
-
if (typeof
|
|
11933
|
-
segs.push(`[${
|
|
11934
|
-
else if (typeof
|
|
11935
|
-
segs.push(`[${JSON.stringify(String(
|
|
11936
|
-
else if (/[^\w$]/.test(
|
|
11937
|
-
segs.push(`[${JSON.stringify(
|
|
12244
|
+
const path = _path.map((seg2) => typeof seg2 === "object" ? seg2.key : seg2);
|
|
12245
|
+
for (const seg2 of path) {
|
|
12246
|
+
if (typeof seg2 === "number")
|
|
12247
|
+
segs.push(`[${seg2}]`);
|
|
12248
|
+
else if (typeof seg2 === "symbol")
|
|
12249
|
+
segs.push(`[${JSON.stringify(String(seg2))}]`);
|
|
12250
|
+
else if (/[^\w$]/.test(seg2))
|
|
12251
|
+
segs.push(`[${JSON.stringify(seg2)}]`);
|
|
11938
12252
|
else {
|
|
11939
12253
|
if (segs.length)
|
|
11940
12254
|
segs.push(".");
|
|
11941
|
-
segs.push(
|
|
12255
|
+
segs.push(seg2);
|
|
11942
12256
|
}
|
|
11943
12257
|
}
|
|
11944
12258
|
return segs.join("");
|
|
@@ -23040,17 +23354,33 @@ function normalizeObjectSchema(schema) {
|
|
|
23040
23354
|
}
|
|
23041
23355
|
return void 0;
|
|
23042
23356
|
}
|
|
23357
|
+
function getDotPath(path) {
|
|
23358
|
+
if (path.length === 0) {
|
|
23359
|
+
return "object root";
|
|
23360
|
+
}
|
|
23361
|
+
return path.reduce((acc, seg2, index) => {
|
|
23362
|
+
if (index === 0) {
|
|
23363
|
+
return String(seg2);
|
|
23364
|
+
}
|
|
23365
|
+
if (typeof seg2 === "number") {
|
|
23366
|
+
return `${acc}[${seg2}]`;
|
|
23367
|
+
}
|
|
23368
|
+
return `${acc}.${seg2}`;
|
|
23369
|
+
}, "");
|
|
23370
|
+
}
|
|
23043
23371
|
function getParseErrorMessage(error51) {
|
|
23044
23372
|
if (error51 && typeof error51 === "object") {
|
|
23373
|
+
if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
|
|
23374
|
+
return error51.issues.map((i) => {
|
|
23375
|
+
if (!i.path?.length) {
|
|
23376
|
+
return i.message;
|
|
23377
|
+
}
|
|
23378
|
+
return `${i.message} at ${getDotPath(i.path)}`;
|
|
23379
|
+
}).join("\n");
|
|
23380
|
+
}
|
|
23045
23381
|
if ("message" in error51 && typeof error51.message === "string") {
|
|
23046
23382
|
return error51.message;
|
|
23047
23383
|
}
|
|
23048
|
-
if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
|
|
23049
|
-
const firstIssue = error51.issues[0];
|
|
23050
|
-
if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) {
|
|
23051
|
-
return String(firstIssue.message);
|
|
23052
|
-
}
|
|
23053
|
-
}
|
|
23054
23384
|
try {
|
|
23055
23385
|
return JSON.stringify(error51);
|
|
23056
23386
|
} catch {
|
|
@@ -28370,6 +28700,9 @@ var Protocol = class {
|
|
|
28370
28700
|
this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
|
|
28371
28701
|
const handleTaskResult = async () => {
|
|
28372
28702
|
const taskId = request.params.taskId;
|
|
28703
|
+
if (!await this._taskStore.getTask(taskId, extra.sessionId)) {
|
|
28704
|
+
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
|
|
28705
|
+
}
|
|
28373
28706
|
if (this._taskMessageQueue) {
|
|
28374
28707
|
let queuedMessage;
|
|
28375
28708
|
while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
|
|
@@ -28400,12 +28733,12 @@ var Protocol = class {
|
|
|
28400
28733
|
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
|
|
28401
28734
|
}
|
|
28402
28735
|
if (!isTerminal(task.status)) {
|
|
28403
|
-
await this._waitForTaskUpdate(taskId, extra.signal);
|
|
28736
|
+
await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId);
|
|
28404
28737
|
return await handleTaskResult();
|
|
28405
28738
|
}
|
|
28406
28739
|
if (isTerminal(task.status)) {
|
|
28407
28740
|
const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
|
|
28408
|
-
this._clearTaskQueue(taskId);
|
|
28741
|
+
this._clearTaskQueue(taskId, extra.sessionId);
|
|
28409
28742
|
return {
|
|
28410
28743
|
...result,
|
|
28411
28744
|
_meta: {
|
|
@@ -28442,7 +28775,7 @@ var Protocol = class {
|
|
|
28442
28775
|
throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
|
|
28443
28776
|
}
|
|
28444
28777
|
await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
|
|
28445
|
-
this._clearTaskQueue(request.params.taskId);
|
|
28778
|
+
this._clearTaskQueue(request.params.taskId, extra.sessionId);
|
|
28446
28779
|
const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
|
|
28447
28780
|
if (!cancelledTask) {
|
|
28448
28781
|
throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
|
|
@@ -28570,6 +28903,19 @@ var Protocol = class {
|
|
|
28570
28903
|
const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
|
|
28571
28904
|
const capturedTransport = this._transport;
|
|
28572
28905
|
const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
|
|
28906
|
+
const sessionId = capturedTransport?.sessionId;
|
|
28907
|
+
const store = this._taskStore;
|
|
28908
|
+
let relatedTaskFound = true;
|
|
28909
|
+
let relatedTaskLookup;
|
|
28910
|
+
if (relatedTaskId && store && this._taskMessageQueue && sessionId !== void 0) {
|
|
28911
|
+
relatedTaskFound = false;
|
|
28912
|
+
relatedTaskLookup = (async () => {
|
|
28913
|
+
if (!await store.getTask(relatedTaskId, sessionId)) {
|
|
28914
|
+
throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`);
|
|
28915
|
+
}
|
|
28916
|
+
relatedTaskFound = true;
|
|
28917
|
+
})();
|
|
28918
|
+
}
|
|
28573
28919
|
if (handler === void 0) {
|
|
28574
28920
|
const errorResponse = {
|
|
28575
28921
|
jsonrpc: "2.0",
|
|
@@ -28579,7 +28925,10 @@ var Protocol = class {
|
|
|
28579
28925
|
message: "Method not found"
|
|
28580
28926
|
}
|
|
28581
28927
|
};
|
|
28582
|
-
if (relatedTaskId &&
|
|
28928
|
+
if (relatedTaskId && relatedTaskLookup) {
|
|
28929
|
+
const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() };
|
|
28930
|
+
relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error51) => this._onerror(new Error(`Failed to send an error response: ${error51}`)));
|
|
28931
|
+
} else if (relatedTaskId && this._taskMessageQueue) {
|
|
28583
28932
|
this._enqueueTaskMessage(relatedTaskId, {
|
|
28584
28933
|
type: "error",
|
|
28585
28934
|
message: errorResponse,
|
|
@@ -28630,7 +28979,10 @@ var Protocol = class {
|
|
|
28630
28979
|
closeSSEStream: extra?.closeSSEStream,
|
|
28631
28980
|
closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
|
|
28632
28981
|
};
|
|
28633
|
-
Promise.resolve().then(() => {
|
|
28982
|
+
(relatedTaskLookup ?? Promise.resolve()).then(() => {
|
|
28983
|
+
if (relatedTaskLookup && abortController.signal.aborted) {
|
|
28984
|
+
throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
|
|
28985
|
+
}
|
|
28634
28986
|
if (taskCreationParams) {
|
|
28635
28987
|
this.assertTaskHandlerCapability(request.method);
|
|
28636
28988
|
}
|
|
@@ -28665,7 +29017,7 @@ var Protocol = class {
|
|
|
28665
29017
|
...error51["data"] !== void 0 && { data: error51["data"] }
|
|
28666
29018
|
}
|
|
28667
29019
|
};
|
|
28668
|
-
if (relatedTaskId && this._taskMessageQueue) {
|
|
29020
|
+
if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) {
|
|
28669
29021
|
await this._enqueueTaskMessage(relatedTaskId, {
|
|
28670
29022
|
type: "error",
|
|
28671
29023
|
message: errorResponse,
|
|
@@ -29145,7 +29497,7 @@ var Protocol = class {
|
|
|
29145
29497
|
throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
|
|
29146
29498
|
}
|
|
29147
29499
|
const maxQueueSize = this._options?.maxTaskQueueSize;
|
|
29148
|
-
await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
|
|
29500
|
+
await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize);
|
|
29149
29501
|
}
|
|
29150
29502
|
/**
|
|
29151
29503
|
* Clears the message queue for a task and rejects any pending request resolvers.
|
|
@@ -29174,12 +29526,13 @@ var Protocol = class {
|
|
|
29174
29526
|
* Uses polling to check for updates at the task's configured poll interval.
|
|
29175
29527
|
* @param taskId The task ID to wait for
|
|
29176
29528
|
* @param signal Abort signal to cancel the wait
|
|
29529
|
+
* @param sessionId Session of the request that waits, passed to the task store
|
|
29177
29530
|
* @returns Promise that resolves when an update occurs or rejects if aborted
|
|
29178
29531
|
*/
|
|
29179
|
-
async _waitForTaskUpdate(taskId, signal) {
|
|
29532
|
+
async _waitForTaskUpdate(taskId, signal, sessionId) {
|
|
29180
29533
|
let interval = this._options?.defaultTaskPollInterval ?? 1e3;
|
|
29181
29534
|
try {
|
|
29182
|
-
const task = await this._taskStore?.getTask(taskId);
|
|
29535
|
+
const task = await this._taskStore?.getTask(taskId, sessionId);
|
|
29183
29536
|
if (task?.pollInterval) {
|
|
29184
29537
|
interval = task.pollInterval;
|
|
29185
29538
|
}
|
|
@@ -29665,16 +30018,7 @@ var Server = class extends Protocol {
|
|
|
29665
30018
|
if (!methodSchema) {
|
|
29666
30019
|
throw new Error("Schema is missing a method literal");
|
|
29667
30020
|
}
|
|
29668
|
-
|
|
29669
|
-
if (isZ4Schema(methodSchema)) {
|
|
29670
|
-
const v4Schema = methodSchema;
|
|
29671
|
-
const v4Def = v4Schema._zod?.def;
|
|
29672
|
-
methodValue = v4Def?.value ?? v4Schema.value;
|
|
29673
|
-
} else {
|
|
29674
|
-
const v3Schema = methodSchema;
|
|
29675
|
-
const legacyDef = v3Schema._def;
|
|
29676
|
-
methodValue = legacyDef?.value ?? v3Schema.value;
|
|
29677
|
-
}
|
|
30021
|
+
const methodValue = getLiteralValue(methodSchema);
|
|
29678
30022
|
if (typeof methodValue !== "string") {
|
|
29679
30023
|
throw new Error("Schema method literal must be a string");
|
|
29680
30024
|
}
|
|
@@ -30067,6 +30411,42 @@ var ExperimentalMcpServerTasks = class {
|
|
|
30067
30411
|
};
|
|
30068
30412
|
|
|
30069
30413
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
|
|
30414
|
+
function toolInputElementCount(value, max) {
|
|
30415
|
+
let count = 0;
|
|
30416
|
+
const stack = [value];
|
|
30417
|
+
while (stack.length > 0) {
|
|
30418
|
+
const node = stack.pop();
|
|
30419
|
+
if (node === null || typeof node !== "object")
|
|
30420
|
+
continue;
|
|
30421
|
+
if (Array.isArray(node)) {
|
|
30422
|
+
for (const child of node) {
|
|
30423
|
+
if (++count > max)
|
|
30424
|
+
return count;
|
|
30425
|
+
if (child !== null && typeof child === "object")
|
|
30426
|
+
stack.push(child);
|
|
30427
|
+
}
|
|
30428
|
+
} else {
|
|
30429
|
+
for (const key in node) {
|
|
30430
|
+
if (!Object.prototype.hasOwnProperty.call(node, key))
|
|
30431
|
+
continue;
|
|
30432
|
+
if (++count > max)
|
|
30433
|
+
return count;
|
|
30434
|
+
const child = node[key];
|
|
30435
|
+
if (child !== null && typeof child === "object")
|
|
30436
|
+
stack.push(child);
|
|
30437
|
+
}
|
|
30438
|
+
}
|
|
30439
|
+
}
|
|
30440
|
+
return count;
|
|
30441
|
+
}
|
|
30442
|
+
function resolveMaxToolInputElements(value) {
|
|
30443
|
+
if (value === void 0 || value === Infinity)
|
|
30444
|
+
return void 0;
|
|
30445
|
+
if (typeof value !== "number" || Number.isNaN(value) || value < 1) {
|
|
30446
|
+
throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`);
|
|
30447
|
+
}
|
|
30448
|
+
return value;
|
|
30449
|
+
}
|
|
30070
30450
|
var McpServer = class {
|
|
30071
30451
|
constructor(serverInfo, options) {
|
|
30072
30452
|
this._registeredResources = {};
|
|
@@ -30078,6 +30458,7 @@ var McpServer = class {
|
|
|
30078
30458
|
this._resourceHandlersInitialized = false;
|
|
30079
30459
|
this._promptHandlersInitialized = false;
|
|
30080
30460
|
this.server = new Server(serverInfo, options);
|
|
30461
|
+
this._maxToolInputElements = resolveMaxToolInputElements(options?.maxToolInputElements);
|
|
30081
30462
|
}
|
|
30082
30463
|
/**
|
|
30083
30464
|
* Access experimental features.
|
|
@@ -30208,12 +30589,15 @@ var McpServer = class {
|
|
|
30208
30589
|
* Validates tool input arguments against the tool's input schema.
|
|
30209
30590
|
*/
|
|
30210
30591
|
async validateToolInput(tool, args, toolName) {
|
|
30592
|
+
if (this._maxToolInputElements !== void 0 && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) {
|
|
30593
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);
|
|
30594
|
+
}
|
|
30211
30595
|
if (!tool.inputSchema) {
|
|
30212
30596
|
return void 0;
|
|
30213
30597
|
}
|
|
30214
30598
|
const inputObj = normalizeObjectSchema(tool.inputSchema);
|
|
30215
30599
|
const schemaToParse = inputObj ?? tool.inputSchema;
|
|
30216
|
-
const parseResult = await safeParseAsync2(schemaToParse, args);
|
|
30600
|
+
const parseResult = await safeParseAsync2(schemaToParse, args ?? {});
|
|
30217
30601
|
if (!parseResult.success) {
|
|
30218
30602
|
const error51 = "error" in parseResult ? parseResult.error : "Unknown error";
|
|
30219
30603
|
const errorMessage = getParseErrorMessage(error51);
|
|
@@ -30451,7 +30835,7 @@ var McpServer = class {
|
|
|
30451
30835
|
}
|
|
30452
30836
|
if (prompt.argsSchema) {
|
|
30453
30837
|
const argsObj = normalizeObjectSchema(prompt.argsSchema);
|
|
30454
|
-
const parseResult = await safeParseAsync2(argsObj, request.params.arguments);
|
|
30838
|
+
const parseResult = await safeParseAsync2(argsObj, request.params.arguments ?? {});
|
|
30455
30839
|
if (!parseResult.success) {
|
|
30456
30840
|
const error51 = "error" in parseResult ? parseResult.error : "Unknown error";
|
|
30457
30841
|
const errorMessage = getParseErrorMessage(error51);
|
|
@@ -30862,8 +31246,17 @@ var EMPTY_COMPLETION_RESULT = {
|
|
|
30862
31246
|
import process3 from "node:process";
|
|
30863
31247
|
|
|
30864
31248
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
|
|
31249
|
+
var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
|
|
30865
31250
|
var ReadBuffer = class {
|
|
31251
|
+
constructor(options) {
|
|
31252
|
+
this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;
|
|
31253
|
+
}
|
|
30866
31254
|
append(chunk) {
|
|
31255
|
+
const newSize = (this._buffer?.length ?? 0) + chunk.length;
|
|
31256
|
+
if (newSize > this._maxBufferSize) {
|
|
31257
|
+
this.clear();
|
|
31258
|
+
throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);
|
|
31259
|
+
}
|
|
30867
31260
|
this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
|
|
30868
31261
|
}
|
|
30869
31262
|
readMessage() {
|
|
@@ -30891,18 +31284,24 @@ function serializeMessage(message) {
|
|
|
30891
31284
|
|
|
30892
31285
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
|
|
30893
31286
|
var StdioServerTransport = class {
|
|
30894
|
-
constructor(_stdin = process3.stdin, _stdout = process3.stdout) {
|
|
31287
|
+
constructor(_stdin = process3.stdin, _stdout = process3.stdout, options) {
|
|
30895
31288
|
this._stdin = _stdin;
|
|
30896
31289
|
this._stdout = _stdout;
|
|
30897
|
-
this._readBuffer = new ReadBuffer();
|
|
30898
31290
|
this._started = false;
|
|
30899
31291
|
this._ondata = (chunk) => {
|
|
30900
|
-
|
|
30901
|
-
|
|
31292
|
+
try {
|
|
31293
|
+
this._readBuffer.append(chunk);
|
|
31294
|
+
this.processReadBuffer();
|
|
31295
|
+
} catch (error51) {
|
|
31296
|
+
this.onerror?.(error51);
|
|
31297
|
+
this.close().catch(() => {
|
|
31298
|
+
});
|
|
31299
|
+
}
|
|
30902
31300
|
};
|
|
30903
31301
|
this._onerror = (error51) => {
|
|
30904
31302
|
this.onerror?.(error51);
|
|
30905
31303
|
};
|
|
31304
|
+
this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });
|
|
30906
31305
|
}
|
|
30907
31306
|
/**
|
|
30908
31307
|
* Starts listening for messages on stdin.
|
|
@@ -30954,11 +31353,14 @@ var StdioServerTransport = class {
|
|
|
30954
31353
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
30955
31354
|
import { createHash, randomBytes } from "node:crypto";
|
|
30956
31355
|
var SOFT_DEADLINE_CAP_MS = 25e3;
|
|
30957
|
-
function
|
|
30958
|
-
if (raw === void 0) return
|
|
31356
|
+
function parsePositiveInt(raw, fallback) {
|
|
31357
|
+
if (raw === void 0 || !/^\d+$/.test(raw)) return fallback;
|
|
30959
31358
|
const n = Number(raw);
|
|
30960
|
-
if (!Number.isSafeInteger(n) || n <= 0) return
|
|
30961
|
-
return
|
|
31359
|
+
if (!Number.isSafeInteger(n) || n <= 0 || n > 2147483647) return fallback;
|
|
31360
|
+
return n;
|
|
31361
|
+
}
|
|
31362
|
+
function parseSoftDeadline(raw) {
|
|
31363
|
+
return Math.min(parsePositiveInt(raw, 2e4), SOFT_DEADLINE_CAP_MS);
|
|
30962
31364
|
}
|
|
30963
31365
|
var SOFT_DEADLINE_MS = parseSoftDeadline(process.env.TIA_SOFT_DEADLINE_MS);
|
|
30964
31366
|
var MAX_STATUS_WAIT_MS = 25e3;
|
|
@@ -31186,9 +31588,9 @@ var jobs = new JobRunner();
|
|
|
31186
31588
|
|
|
31187
31589
|
// src/client.ts
|
|
31188
31590
|
var BASE = (process.env.TIA_API_BASE ?? "http://localhost:5000").replace(/\/+$/, "");
|
|
31189
|
-
var TIMEOUT_MS =
|
|
31190
|
-
var CONNECT_TIMEOUT_MS =
|
|
31191
|
-
var SLOW_TIMEOUT_MS =
|
|
31591
|
+
var TIMEOUT_MS = parsePositiveInt(process.env.TIA_API_TIMEOUT_MS, 15e3);
|
|
31592
|
+
var CONNECT_TIMEOUT_MS = parsePositiveInt(process.env.TIA_CONNECT_TIMEOUT_MS, 18e4);
|
|
31593
|
+
var SLOW_TIMEOUT_MS = parsePositiveInt(process.env.TIA_SLOW_TIMEOUT_MS, 12e4);
|
|
31192
31594
|
var TiaApiError = class extends Error {
|
|
31193
31595
|
status;
|
|
31194
31596
|
kind;
|
|
@@ -31260,6 +31662,7 @@ async function tiaFetch(path, init = {}, opts = {}) {
|
|
|
31260
31662
|
}
|
|
31261
31663
|
return body;
|
|
31262
31664
|
}
|
|
31665
|
+
var INSTALLING_HINT = "The serve host is installing a TIAOpenness app update: this call was refused BEFORE any operation ran (nothing changed). Wait until the update finishes, then retry the same call (GET /status stays available while draining \u2014 retry once it reports draining:false).";
|
|
31263
31666
|
function hintFor(err) {
|
|
31264
31667
|
switch (err.kind) {
|
|
31265
31668
|
case "timeout":
|
|
@@ -31284,28 +31687,145 @@ function hintFor(err) {
|
|
|
31284
31687
|
return "Update the TIAOpenness app (serve) on the host to v1.6.0 or later; this MCP refuses unverified downloads.";
|
|
31285
31688
|
case "route_not_found":
|
|
31286
31689
|
return "This serve does not know this route \u2014 update the TIAOpenness app on the host to the version the tool requires.";
|
|
31690
|
+
case "installing":
|
|
31691
|
+
return INSTALLING_HINT;
|
|
31287
31692
|
}
|
|
31288
31693
|
if (err.status === 403) return "Server not activated \u2014 configure the license in the TIAOpenness GUI.";
|
|
31289
31694
|
return null;
|
|
31290
31695
|
}
|
|
31291
|
-
function textResult(payload, isError = false) {
|
|
31292
|
-
return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }], isError };
|
|
31293
|
-
}
|
|
31294
31696
|
function asTiaError(e) {
|
|
31295
31697
|
return e instanceof TiaApiError ? e : new TiaApiError(String(e));
|
|
31296
31698
|
}
|
|
31297
31699
|
|
|
31298
|
-
// src/tools/
|
|
31700
|
+
// src/tools/results.ts
|
|
31701
|
+
function textResult(payload, isError = false) {
|
|
31702
|
+
return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }], isError };
|
|
31703
|
+
}
|
|
31704
|
+
var seg = (v) => encodeURIComponent(v);
|
|
31705
|
+
var JSON_HEADERS = { "Content-Type": "application/json; charset=utf-8" };
|
|
31706
|
+
function jsonBody(obj) {
|
|
31707
|
+
const out = {};
|
|
31708
|
+
for (const [k, v] of Object.entries(obj)) if (v !== void 0 && v !== null) out[k] = v;
|
|
31709
|
+
return out;
|
|
31710
|
+
}
|
|
31711
|
+
var isObject2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
31712
|
+
function isInstallingError(err) {
|
|
31713
|
+
return err.kind === "installing";
|
|
31714
|
+
}
|
|
31715
|
+
function installingResult(err, hintOverride) {
|
|
31716
|
+
return textResult(
|
|
31717
|
+
{
|
|
31718
|
+
error: "The serve host is installing a TIAOpenness app update (draining): this call was refused BEFORE any operation ran \u2014 nothing changed. Wait until the update finishes, then retry the same call.",
|
|
31719
|
+
kind: err.kind,
|
|
31720
|
+
status: err.status,
|
|
31721
|
+
type: err.type,
|
|
31722
|
+
inner: err.inner ?? null,
|
|
31723
|
+
details: err.details ?? null,
|
|
31724
|
+
hint: hintOverride ?? hintFor(err)
|
|
31725
|
+
},
|
|
31726
|
+
true
|
|
31727
|
+
);
|
|
31728
|
+
}
|
|
31729
|
+
function errorResult(err, hintOverride) {
|
|
31730
|
+
if (isInstallingError(err)) return installingResult(err, hintOverride);
|
|
31731
|
+
return textResult(
|
|
31732
|
+
{ error: err.message, kind: err.kind, status: err.status, type: err.type, inner: err.inner ?? null, details: err.details ?? null, hint: hintOverride ?? hintFor(err) },
|
|
31733
|
+
true
|
|
31734
|
+
);
|
|
31735
|
+
}
|
|
31299
31736
|
async function getResult(path, timeoutMs) {
|
|
31300
31737
|
try {
|
|
31301
31738
|
const data = await tiaFetch(path, {}, { timeoutMs });
|
|
31302
31739
|
return textResult(data);
|
|
31740
|
+
} catch (e) {
|
|
31741
|
+
return errorResult(asTiaError(e));
|
|
31742
|
+
}
|
|
31743
|
+
}
|
|
31744
|
+
async function postResult(path, body, opts) {
|
|
31745
|
+
try {
|
|
31746
|
+
const data = await tiaFetch(
|
|
31747
|
+
path,
|
|
31748
|
+
{ method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body ?? {}) },
|
|
31749
|
+
{ timeoutMs: opts?.timeoutMs ?? SLOW_TIMEOUT_MS }
|
|
31750
|
+
);
|
|
31751
|
+
return textResult(data);
|
|
31303
31752
|
} catch (e) {
|
|
31304
31753
|
const err = asTiaError(e);
|
|
31305
|
-
|
|
31754
|
+
if (opts?.mapError) return opts.mapError(err);
|
|
31755
|
+
return errorResult(err);
|
|
31306
31756
|
}
|
|
31307
31757
|
}
|
|
31308
|
-
|
|
31758
|
+
async function send(method, path, body, timeoutMs) {
|
|
31759
|
+
try {
|
|
31760
|
+
const init = { method, headers: JSON_HEADERS };
|
|
31761
|
+
if (body !== void 0) init.body = JSON.stringify(body);
|
|
31762
|
+
return textResult(await tiaFetch(path, init, { timeoutMs: timeoutMs ?? SLOW_TIMEOUT_MS }));
|
|
31763
|
+
} catch (e) {
|
|
31764
|
+
return errorResult(asTiaError(e));
|
|
31765
|
+
}
|
|
31766
|
+
}
|
|
31767
|
+
|
|
31768
|
+
// src/tools/diagnostics.ts
|
|
31769
|
+
function registerDiagnosticTools(server2) {
|
|
31770
|
+
server2.registerTool(
|
|
31771
|
+
"tia_ping",
|
|
31772
|
+
{
|
|
31773
|
+
title: "TIA \u2014 connection diagnostics",
|
|
31774
|
+
description: "Diagnoses connectivity to the TIA Openness `serve` API and whether the server is ACTIVATED. Tests GET /health (reachability) and GET /readiness (license activation). Ideal for the MCP-on-Mac-pointing-at-a-`serve`-on-a-Windows-VM scenario. Read-only. Returns { base, reachable, activated, latencyMs, hint }.",
|
|
31775
|
+
inputSchema: {}
|
|
31776
|
+
},
|
|
31777
|
+
async () => {
|
|
31778
|
+
const report = {
|
|
31779
|
+
base: BASE,
|
|
31780
|
+
timeoutMs: TIMEOUT_MS,
|
|
31781
|
+
reachable: false,
|
|
31782
|
+
activated: null,
|
|
31783
|
+
latencyMs: null,
|
|
31784
|
+
detail: null,
|
|
31785
|
+
hint: null
|
|
31786
|
+
};
|
|
31787
|
+
const start = Date.now();
|
|
31788
|
+
try {
|
|
31789
|
+
await tiaFetch("/health");
|
|
31790
|
+
report.reachable = true;
|
|
31791
|
+
report.latencyMs = Date.now() - start;
|
|
31792
|
+
} catch (e) {
|
|
31793
|
+
const err = asTiaError(e);
|
|
31794
|
+
report.detail = err.message;
|
|
31795
|
+
report.hint = hintFor(err);
|
|
31796
|
+
return textResult(report);
|
|
31797
|
+
}
|
|
31798
|
+
try {
|
|
31799
|
+
await tiaFetch("/readiness");
|
|
31800
|
+
report.activated = true;
|
|
31801
|
+
} catch (e) {
|
|
31802
|
+
const err = asTiaError(e);
|
|
31803
|
+
report.activated = err.kind === "license_required" || err.status === 403 ? false : null;
|
|
31804
|
+
report.detail = err.message;
|
|
31805
|
+
report.hint = hintFor(err);
|
|
31806
|
+
}
|
|
31807
|
+
return textResult(report);
|
|
31808
|
+
}
|
|
31809
|
+
);
|
|
31810
|
+
server2.registerTool(
|
|
31811
|
+
"tia_readiness",
|
|
31812
|
+
{
|
|
31813
|
+
title: "TIA \u2014 environment readiness",
|
|
31814
|
+
description: "Readiness diagnostic for the TIA Openness V21 environment ON THE SERVE HOST (x64 process, Windows 'Siemens TIA Openness' group, PublicAPI, 21.0 registry key, and TIA instances). Call BEFORE connecting. Maps to GET /readiness. Read-only (class R). Returns { ready, checks:[{ name, status, detail, remediation }] }.",
|
|
31815
|
+
inputSchema: {}
|
|
31816
|
+
},
|
|
31817
|
+
async () => {
|
|
31818
|
+
try {
|
|
31819
|
+
const data = await tiaFetch("/readiness");
|
|
31820
|
+
return textResult(data);
|
|
31821
|
+
} catch (e) {
|
|
31822
|
+
return errorResult(asTiaError(e));
|
|
31823
|
+
}
|
|
31824
|
+
}
|
|
31825
|
+
);
|
|
31826
|
+
}
|
|
31827
|
+
|
|
31828
|
+
// src/tools/readonly.ts
|
|
31309
31829
|
async function pgInterfacesFlow(plc) {
|
|
31310
31830
|
return getResult(`/plcs/${seg(plc)}/pginterfaces`);
|
|
31311
31831
|
}
|
|
@@ -31577,13 +32097,6 @@ function registerJobTools(server2) {
|
|
|
31577
32097
|
}
|
|
31578
32098
|
|
|
31579
32099
|
// src/tools/lifecycle.ts
|
|
31580
|
-
function jsonBody(obj) {
|
|
31581
|
-
const out = {};
|
|
31582
|
-
for (const [k, v] of Object.entries(obj)) {
|
|
31583
|
-
if (v !== void 0 && v !== null) out[k] = v;
|
|
31584
|
-
}
|
|
31585
|
-
return out;
|
|
31586
|
-
}
|
|
31587
32100
|
function startToolNextSteps(tool) {
|
|
31588
32101
|
if (tool === "tia_project_create") {
|
|
31589
32102
|
return [
|
|
@@ -31598,33 +32111,18 @@ function startToolNextSteps(tool) {
|
|
|
31598
32111
|
`3. Re-call ${tool} with the SAME arguments after the human confirms.`
|
|
31599
32112
|
];
|
|
31600
32113
|
}
|
|
31601
|
-
async function
|
|
31602
|
-
|
|
31603
|
-
|
|
31604
|
-
|
|
31605
|
-
|
|
31606
|
-
|
|
31607
|
-
|
|
31608
|
-
|
|
31609
|
-
}
|
|
31610
|
-
|
|
31611
|
-
);
|
|
31612
|
-
return textResult(data);
|
|
31613
|
-
} catch (e) {
|
|
31614
|
-
const err = asTiaError(e);
|
|
31615
|
-
if (err.kind === "tia_start_failed") return tiaStartFailedResult(err, opts?.trustDeniedTool ?? path);
|
|
31616
|
-
const tool = opts?.trustDeniedTool;
|
|
31617
|
-
if (tool !== void 0 && err.kind === "timeout" && await serveAlive()) {
|
|
31618
|
-
return waitingForTrustHandoff(tool, tool, startToolNextSteps(tool), err);
|
|
32114
|
+
async function postResult2(path, body, opts) {
|
|
32115
|
+
return postResult(path, body, {
|
|
32116
|
+
timeoutMs: opts?.timeoutMs,
|
|
32117
|
+
mapError: async (err) => {
|
|
32118
|
+
if (err.kind === "tia_start_failed") return tiaStartFailedResult(err, opts?.trustDeniedTool ?? path);
|
|
32119
|
+
const tool = opts?.trustDeniedTool;
|
|
32120
|
+
if (tool !== void 0 && err.kind === "timeout" && await serveAlive()) {
|
|
32121
|
+
return waitingForTrustHandoff(tool, tool, startToolNextSteps(tool), err);
|
|
32122
|
+
}
|
|
32123
|
+
return errorResult(err);
|
|
31619
32124
|
}
|
|
31620
|
-
|
|
31621
|
-
}
|
|
31622
|
-
}
|
|
31623
|
-
function errorResult(err) {
|
|
31624
|
-
return textResult(
|
|
31625
|
-
{ error: err.message, kind: err.kind, status: err.status, type: err.type, details: err.details ?? null, hint: hintFor(err) },
|
|
31626
|
-
true
|
|
31627
|
-
);
|
|
32125
|
+
});
|
|
31628
32126
|
}
|
|
31629
32127
|
function looksLikeTrustGate(err) {
|
|
31630
32128
|
if (err.type === "EngineeringSecurityException") return true;
|
|
@@ -31711,12 +32209,13 @@ async function connectFlow(args) {
|
|
|
31711
32209
|
try {
|
|
31712
32210
|
const data = await tiaFetch(
|
|
31713
32211
|
"/connect",
|
|
31714
|
-
{ method: "POST", headers:
|
|
32212
|
+
{ method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body) },
|
|
31715
32213
|
{ timeoutMs: CONNECT_TIMEOUT_MS }
|
|
31716
32214
|
);
|
|
31717
32215
|
return textResult(resumeToken ? { resumed: true, project: data } : data);
|
|
31718
32216
|
} catch (e) {
|
|
31719
32217
|
const err = asTiaError(e);
|
|
32218
|
+
if (isInstallingError(err)) return errorResult(err);
|
|
31720
32219
|
if (err.kind === "tia_start_failed") return tiaStartFailedResult(err, `connect ${projectPath}`);
|
|
31721
32220
|
if (looksLikeTrustGate(err)) return trustHandoff(projectPath, err);
|
|
31722
32221
|
if (err.kind === "timeout" && await serveAlive()) return trustHandoff(projectPath, err);
|
|
@@ -31733,7 +32232,7 @@ function registerLifecycleTools(server2) {
|
|
|
31733
32232
|
headless: external_exports.boolean().optional().describe("true = no window (fast offline authoring); false (default) = with window. Only when creating a new instance.")
|
|
31734
32233
|
}
|
|
31735
32234
|
},
|
|
31736
|
-
async ({ headless }) => jobs.run("tia_start", { headless }, () =>
|
|
32235
|
+
async ({ headless }) => jobs.run("tia_start", { headless }, () => postResult2("/tia/start", jsonBody({ headless }), { timeoutMs: CONNECT_TIMEOUT_MS, trustDeniedTool: "tia_start" }))
|
|
31737
32236
|
);
|
|
31738
32237
|
server2.registerTool(
|
|
31739
32238
|
"tia_show_ui",
|
|
@@ -31743,7 +32242,7 @@ function registerLifecycleTools(server2) {
|
|
|
31743
32242
|
inputSchema: {}
|
|
31744
32243
|
},
|
|
31745
32244
|
// Sem args: chave de dedupe = {} literal (nunca o `extra` do SDK, que muda a cada chamada).
|
|
31746
|
-
async () => jobs.run("tia_show_ui", {}, () =>
|
|
32245
|
+
async () => jobs.run("tia_show_ui", {}, () => postResult2("/tia/show-ui", void 0, { timeoutMs: CONNECT_TIMEOUT_MS, trustDeniedTool: "tia_show_ui" }))
|
|
31747
32246
|
);
|
|
31748
32247
|
server2.registerTool(
|
|
31749
32248
|
"tia_connect",
|
|
@@ -31769,7 +32268,7 @@ function registerLifecycleTools(server2) {
|
|
|
31769
32268
|
description: "Disconnects from TIA. This is the explicit teardown for the TIA instance the serve itself created (an instance we merely ATTACHED to is only detached, never killed) \u2014 but not the only path that can end an owned instance: tia_show_ui (relaunch visible), tia_project_create, and a tia_connect needing a fresh connect also end/replace it. WARNING (Gd3): on an ATTACHED instance, /disconnect does NOT close the project \u2014 to RELEASE the project lock while KEEPING the TIA process alive (so the next tia_connect reuses it) use tia_project_close instead. Maps to POST /disconnect.",
|
|
31770
32269
|
inputSchema: {}
|
|
31771
32270
|
},
|
|
31772
|
-
async () =>
|
|
32271
|
+
async () => postResult2("/disconnect")
|
|
31773
32272
|
);
|
|
31774
32273
|
server2.registerTool(
|
|
31775
32274
|
"tia_project_create",
|
|
@@ -31785,7 +32284,7 @@ function registerLifecycleTools(server2) {
|
|
|
31785
32284
|
async ({ directory, name, withUserInterface }) => jobs.run(
|
|
31786
32285
|
"tia_project_create",
|
|
31787
32286
|
{ directory, name, withUserInterface },
|
|
31788
|
-
() =>
|
|
32287
|
+
() => postResult2("/project/create", jsonBody({ directory, name, withUserInterface }), { timeoutMs: CONNECT_TIMEOUT_MS, trustDeniedTool: "tia_project_create" })
|
|
31789
32288
|
)
|
|
31790
32289
|
);
|
|
31791
32290
|
server2.registerTool(
|
|
@@ -31795,7 +32294,7 @@ function registerLifecycleTools(server2) {
|
|
|
31795
32294
|
description: `Saves the open project. Maps to POST /project/save. ${LONG_OPERATION_NOTE}`,
|
|
31796
32295
|
inputSchema: {}
|
|
31797
32296
|
},
|
|
31798
|
-
async () => jobs.run("tia_project_save", {}, () =>
|
|
32297
|
+
async () => jobs.run("tia_project_save", {}, () => postResult2("/project/save"))
|
|
31799
32298
|
);
|
|
31800
32299
|
server2.registerTool(
|
|
31801
32300
|
"tia_project_saveas",
|
|
@@ -31806,7 +32305,7 @@ function registerLifecycleTools(server2) {
|
|
|
31806
32305
|
directory: external_exports.string().optional().describe("target directory for 'save as'")
|
|
31807
32306
|
}
|
|
31808
32307
|
},
|
|
31809
|
-
async ({ directory }) =>
|
|
32308
|
+
async ({ directory }) => postResult2("/project/saveas", jsonBody({ directory }))
|
|
31810
32309
|
);
|
|
31811
32310
|
server2.registerTool(
|
|
31812
32311
|
"tia_project_close",
|
|
@@ -31815,7 +32314,7 @@ function registerLifecycleTools(server2) {
|
|
|
31815
32314
|
description: "Closes the open project and RELEASES the lock (Gd3: use this, not tia_disconnect, to release the project). KEEPS the TIA process alive (response `portalKept`/`pid`) \u2014 the next tia_connect reuses it instead of paying the 40-80s cold start. Nothing is saved: call tia_project_save first if needed. Maps to POST /project/close. " + LONG_OPERATION_NOTE,
|
|
31816
32315
|
inputSchema: {}
|
|
31817
32316
|
},
|
|
31818
|
-
async () => jobs.run("tia_project_close", {}, () =>
|
|
32317
|
+
async () => jobs.run("tia_project_close", {}, () => postResult2("/project/close"))
|
|
31819
32318
|
);
|
|
31820
32319
|
server2.registerTool(
|
|
31821
32320
|
"tia_project_archive",
|
|
@@ -31828,197 +32327,11 @@ function registerLifecycleTools(server2) {
|
|
|
31828
32327
|
mode: external_exports.string().optional().describe("archive mode (e.g., Compressed)")
|
|
31829
32328
|
}
|
|
31830
32329
|
},
|
|
31831
|
-
async ({ directory, name, mode }) => jobs.run("tia_project_archive", { directory, name, mode }, () =>
|
|
32330
|
+
async ({ directory, name, mode }) => jobs.run("tia_project_archive", { directory, name, mode }, () => postResult2("/project/archive", jsonBody({ directory, name, mode })))
|
|
31832
32331
|
);
|
|
31833
32332
|
}
|
|
31834
32333
|
|
|
31835
|
-
// src/
|
|
31836
|
-
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
31837
|
-
var PLAN_TTL_MS = Number.parseInt(process.env.TIA_PLAN_TTL_MS ?? "900000", 10) || 9e5;
|
|
31838
|
-
function canonicalPlan(plan) {
|
|
31839
|
-
for (const [k, v] of Object.entries(plan)) {
|
|
31840
|
-
if (v !== null && typeof v === "object") {
|
|
31841
|
-
throw new Error(`canonicalPlan: nested value at key '${k}' is not allowed (the G3 plan must be flat)`);
|
|
31842
|
-
}
|
|
31843
|
-
}
|
|
31844
|
-
return JSON.stringify(plan, Object.keys(plan).sort());
|
|
31845
|
-
}
|
|
31846
|
-
var PlanStore = class {
|
|
31847
|
-
constructor(ttlMs = PLAN_TTL_MS, now = Date.now, prefix = "g3_") {
|
|
31848
|
-
this.ttlMs = ttlMs;
|
|
31849
|
-
this.now = now;
|
|
31850
|
-
this.prefix = prefix;
|
|
31851
|
-
}
|
|
31852
|
-
ttlMs;
|
|
31853
|
-
now;
|
|
31854
|
-
prefix;
|
|
31855
|
-
issued = /* @__PURE__ */ new Map();
|
|
31856
|
-
consumed = /* @__PURE__ */ new Set();
|
|
31857
|
-
issue(plan, fingerprint) {
|
|
31858
|
-
if (!fingerprint) throw new Error("planStore.issue: fingerprint is required");
|
|
31859
|
-
canonicalPlan(plan);
|
|
31860
|
-
const t = this.now();
|
|
31861
|
-
const entry = {
|
|
31862
|
-
token: `${this.prefix}${randomBytes2(12).toString("base64url")}`,
|
|
31863
|
-
plan: { ...plan },
|
|
31864
|
-
fingerprint,
|
|
31865
|
-
issuedAt: t,
|
|
31866
|
-
expiresAt: t + this.ttlMs
|
|
31867
|
-
};
|
|
31868
|
-
this.issued.set(entry.token, entry);
|
|
31869
|
-
return entry;
|
|
31870
|
-
}
|
|
31871
|
-
check(token, plan) {
|
|
31872
|
-
if (!token) return { ok: false, reason: "unknown" };
|
|
31873
|
-
if (this.consumed.has(token)) return { ok: false, reason: "consumed" };
|
|
31874
|
-
const entry = this.issued.get(token);
|
|
31875
|
-
if (!entry) return { ok: false, reason: "unknown" };
|
|
31876
|
-
if (this.now() > entry.expiresAt) return { ok: false, reason: "expired" };
|
|
31877
|
-
if (canonicalPlan(entry.plan) !== canonicalPlan(plan)) return { ok: false, reason: "plan_mismatch" };
|
|
31878
|
-
return { ok: true, issued: entry };
|
|
31879
|
-
}
|
|
31880
|
-
/** Marca como usado ANTES de chamar o serve: um retry após timeout do cliente é recusado (sem download duplicado). */
|
|
31881
|
-
consume(token) {
|
|
31882
|
-
this.issued.delete(token);
|
|
31883
|
-
this.consumed.add(token);
|
|
31884
|
-
}
|
|
31885
|
-
};
|
|
31886
|
-
var planStore = new PlanStore();
|
|
31887
|
-
var uploadPlanStore = new PlanStore(PLAN_TTL_MS, Date.now, "g4_");
|
|
31888
|
-
|
|
31889
|
-
// src/tools/verification.ts
|
|
31890
|
-
var seg2 = (v) => encodeURIComponent(v);
|
|
31891
|
-
var JSON_HEADERS = { "Content-Type": "application/json; charset=utf-8" };
|
|
31892
|
-
function jsonBody2(obj) {
|
|
31893
|
-
const out = {};
|
|
31894
|
-
for (const [k, v] of Object.entries(obj)) if (v !== void 0 && v !== null) out[k] = v;
|
|
31895
|
-
return out;
|
|
31896
|
-
}
|
|
31897
|
-
function errorResult2(err, hintOverride) {
|
|
31898
|
-
return textResult(
|
|
31899
|
-
{ error: err.message, kind: err.kind, status: err.status, type: err.type, details: err.details ?? null, hint: hintOverride ?? hintFor(err) },
|
|
31900
|
-
true
|
|
31901
|
-
);
|
|
31902
|
-
}
|
|
31903
|
-
async function send(method, path, body, timeoutMs) {
|
|
31904
|
-
try {
|
|
31905
|
-
const init = { method, headers: JSON_HEADERS };
|
|
31906
|
-
if (body !== void 0) init.body = JSON.stringify(body);
|
|
31907
|
-
return textResult(await tiaFetch(path, init, { timeoutMs: timeoutMs ?? SLOW_TIMEOUT_MS }));
|
|
31908
|
-
} catch (e) {
|
|
31909
|
-
return errorResult2(asTiaError(e));
|
|
31910
|
-
}
|
|
31911
|
-
}
|
|
31912
|
-
var GATE_INSTRUCTION = {
|
|
31913
|
-
download_approval: "A human must APPROVE the download: it STOPS the physical CPU (StopAll), OVERWRITES system data, and RESTARTS the CPU. Review the plan AND its software fingerprint (what exactly goes to the CPU). The serve auto-confirms Stop/Reset(DeleteAll, when the loaded program is replaced)/Overwrite/Consistent-blocks/Start (listed in 'configurations' after the download).",
|
|
31914
|
-
go_online: "Going ONLINE connects to the PHYSICAL PLC over the network. Confirm with a human that it is safe to connect to the target machine.",
|
|
31915
|
-
station_upload: "GATE G4: a station upload goes ONLINE to the PHYSICAL CPU and reads its hardware configuration and program into the OPEN project as a new station (it reads the CPU and does not write or stop it \u2014 observed on hardware: the CPU stayed in RUN). Confirm with a human that it is safe to connect to this machine AND that the open project shown here is a dedicated backup project \u2014 never the working project.",
|
|
31916
|
-
upload_password: "GATE G6: the CPU is read-protected. Ask the human for its read-access password \u2014 NEVER invent, guess or reuse one. The approval token is spent: call tia_upload without confirm for a fresh confirmation, then confirm:true with the new planHash and the password.",
|
|
31917
|
-
net_scan: "A network scan (accessible devices) probes the local network via the PG/PC adapter. Confirm before scanning."
|
|
31918
|
-
};
|
|
31919
|
-
var DOWNLOAD_REASON = {
|
|
31920
|
-
not_approved: "No human approval yet: the real download needs approved:true plus the planHash of a reviewed dryRun.",
|
|
31921
|
-
unknown: "No valid approval token: this planHash was not issued by this MCP process (or the MCP restarted). Approval tokens are random, single-use and live only in the MCP process that issued them.",
|
|
31922
|
-
expired: "This planHash expired (TIA_PLAN_TTL_MS). Approvals do not carry over to later sessions.",
|
|
31923
|
-
consumed: "This planHash was already used (single-use). If the previous call timed out, check the CPU and tia_job_status BEFORE anything else \u2014 the download may have happened.",
|
|
31924
|
-
plan_mismatch: "The parameters differ from the approved plan (plc / interface / options / allowUpgradeTargetDevice). The approval covers exactly the reviewed plan.",
|
|
31925
|
-
// P3 fix round 1 (#1): cause-neutral on purpose — this same reason now covers transport failures (a network or
|
|
31926
|
-
// timeout issue) AND a serve error (5xx/403/404/409 not_connected/etc.) AND an unreadable response, so the
|
|
31927
|
-
// text must not single out one cause (the old text named only "a network/timeout error", which read as if it
|
|
31928
|
-
// ruled out the other causes — deliberately NOT reusing that exact joined phrase here).
|
|
31929
|
-
outcome_unknown: "The /download call did not return a usable answer (a network or timeout issue, a serve error, or an unreadable response) AFTER the single-use token was already consumed \u2014 the token is SPENT and cannot be reused. The download may still be running on the CPU, or it may already have completed. Check the CPU state directly and tia_status (and tia_job_status if a job id is known) BEFORE requesting a new plan. Do NOT retry this same call \u2014 the token is gone and a retry cannot resume it."
|
|
31930
|
-
};
|
|
31931
|
-
function downloadResumeSteps(reason) {
|
|
31932
|
-
if (reason === "outcome_unknown") {
|
|
31933
|
-
return [
|
|
31934
|
-
"1. The approval token is SPENT and cannot be used again \u2014 do NOT call tia_download with approved:true and this same planHash.",
|
|
31935
|
-
"2. Check the CPU state directly, then tia_status (and tia_job_status if a job id is known), BEFORE anything else.",
|
|
31936
|
-
"3. Only once the real outcome is known, run tia_download with dryRun:true for a FRESH plan and a NEW token.",
|
|
31937
|
-
"4. Get a new explicit human approval before calling tia_download with approved:true again."
|
|
31938
|
-
];
|
|
31939
|
-
}
|
|
31940
|
-
if (reason === "consumed") {
|
|
31941
|
-
return [
|
|
31942
|
-
"1. This planHash was already used (single-use) \u2014 do NOT call tia_download with approved:true and this same planHash again.",
|
|
31943
|
-
"2. Check the CPU state directly, then tia_status (and tia_job_status if a job id is known), BEFORE anything else \u2014 the download may already have happened.",
|
|
31944
|
-
"3. Only once the real outcome is known, run tia_download with dryRun:true for a FRESH plan and a NEW token.",
|
|
31945
|
-
"4. Get a new explicit human approval before calling tia_download with approved:true again."
|
|
31946
|
-
];
|
|
31947
|
-
}
|
|
31948
|
-
return [
|
|
31949
|
-
"1. Run tia_download with dryRun:true to get a FRESH plan, its software fingerprint and a new single-use planHash.",
|
|
31950
|
-
"2. Show the plan + fingerprint to the line's responsible person and get an explicit yes.",
|
|
31951
|
-
"3. Re-call with approved:true and that NEW planHash, before it expires."
|
|
31952
|
-
];
|
|
31953
|
-
}
|
|
31954
|
-
var UPLOAD_REASON = {
|
|
31955
|
-
unknown: "No valid approval token: this planHash was not issued by this MCP process (or the MCP restarted). Approval tokens are random, single-use and live only in the MCP process that issued them. Call tia_upload without confirm for a fresh plan.",
|
|
31956
|
-
expired: "This planHash expired (TIA_PLAN_TTL_MS). Approvals do not carry over to later sessions.",
|
|
31957
|
-
consumed: "This planHash was already used (single-use). If the previous call timed out, check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the station may already have been added.",
|
|
31958
|
-
plan_mismatch: "The parameters differ from the approved plan (ip / connection). The approval covers exactly the reviewed plan.",
|
|
31959
|
-
outcome_unknown: "The /stations/upload call did not return a usable answer (a network or timeout issue, a serve error, or an unreadable response) AFTER the single-use token was already consumed \u2014 the token is SPENT and cannot be reused. The station may still be uploading or may already have been added as a new station. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE requesting a new plan. Do NOT repeat this call \u2014 the token is gone and a retry cannot resume it.",
|
|
31960
|
-
password_required: "The CPU is read-protected and no accepted password was provided (G6): the approval token is SPENT. Ask the human for the read-access password \u2014 never invent one \u2014 then call tia_upload without confirm for a fresh confirmation and confirm:true with the new planHash and the password.",
|
|
31961
|
-
password_rejected: "The CPU rejected the provided read-access password (G6): the approval token is SPENT. Confirm the password with the human \u2014 never invent one \u2014 then call tia_upload without confirm for a fresh confirmation and confirm:true with the new planHash and the corrected password."
|
|
31962
|
-
};
|
|
31963
|
-
function uploadResumeSteps(reason) {
|
|
31964
|
-
if (reason === "outcome_unknown") {
|
|
31965
|
-
return [
|
|
31966
|
-
"1. The approval token is SPENT and cannot be used again \u2014 do NOT call tia_upload with confirm:true and this same planHash.",
|
|
31967
|
-
"2. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else.",
|
|
31968
|
-
"3. Only once the real outcome is known, run tia_upload without confirm for a FRESH plan and a NEW token.",
|
|
31969
|
-
"4. Get a new explicit human approval before calling tia_upload with confirm:true again."
|
|
31970
|
-
];
|
|
31971
|
-
}
|
|
31972
|
-
if (reason === "password_required" || reason === "password_rejected") {
|
|
31973
|
-
return [
|
|
31974
|
-
"1. Ask the human for the CPU read-access password (G6 \u2014 never invent, guess or reuse one).",
|
|
31975
|
-
"2. Run tia_upload without confirm for a FRESH plan and a NEW token (the old token is SPENT).",
|
|
31976
|
-
"3. Show the plan to the human and get an explicit yes.",
|
|
31977
|
-
"4. Re-call with confirm:true, that NEW planHash and the human-provided password, before it expires."
|
|
31978
|
-
];
|
|
31979
|
-
}
|
|
31980
|
-
if (reason === "consumed") {
|
|
31981
|
-
return [
|
|
31982
|
-
"1. This planHash was already used (single-use) \u2014 do NOT call tia_upload with confirm:true and this same planHash again.",
|
|
31983
|
-
"2. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the station may already have been added.",
|
|
31984
|
-
"3. Only once the real outcome is known, run tia_upload without confirm for a FRESH plan and a NEW token.",
|
|
31985
|
-
"4. Get a new explicit human approval before calling tia_upload with confirm:true again."
|
|
31986
|
-
];
|
|
31987
|
-
}
|
|
31988
|
-
if (reason) {
|
|
31989
|
-
return [
|
|
31990
|
-
"1. Run tia_upload without confirm to get a FRESH plan and a new single-use planHash.",
|
|
31991
|
-
"2. Show the plan to the human and get an explicit yes.",
|
|
31992
|
-
"3. Re-call with confirm:true and that NEW planHash, before it expires."
|
|
31993
|
-
];
|
|
31994
|
-
}
|
|
31995
|
-
return [
|
|
31996
|
-
"1. Show the plan + project to the human and get an explicit yes.",
|
|
31997
|
-
"2. Re-call tia_upload with confirm:true and this SAME planHash, before it expires."
|
|
31998
|
-
];
|
|
31999
|
-
}
|
|
32000
|
-
var YOUMUSTDO_OUTCOME_UNKNOWN = "Check the CPU state directly (and tia_status / tia_job_status) BEFORE anything else \u2014 the approval token is ALREADY SPENT. Do NOT repeat this call: get a fresh dryRun plan and a new human approval only once the real outcome is known.";
|
|
32001
|
-
var YOUMUSTDO_UPLOAD_OUTCOME_UNKNOWN = "Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the approval token is ALREADY SPENT. Do NOT repeat this call: get a fresh plan and a new human approval only once the real outcome is known.";
|
|
32002
|
-
function gateHandoff(gate, ctx) {
|
|
32003
|
-
const reasonTable = gate === "download_approval" ? DOWNLOAD_REASON : UPLOAD_REASON;
|
|
32004
|
-
const resume = gate === "download_approval" ? downloadResumeSteps(ctx.reason) : uploadResumeSteps(ctx.reason);
|
|
32005
|
-
const youMustDo = ctx.youMustDo !== void 0 ? ctx.youMustDo : gate === "download_approval" && ctx.reason === "outcome_unknown" ? YOUMUSTDO_OUTCOME_UNKNOWN : gate === "station_upload" && ctx.reason === "outcome_unknown" ? YOUMUSTDO_UPLOAD_OUTCOME_UNKNOWN : GATE_INSTRUCTION[gate] ?? "Human confirmation required.";
|
|
32006
|
-
return textResult(
|
|
32007
|
-
{
|
|
32008
|
-
status: "requires_human_action",
|
|
32009
|
-
gate,
|
|
32010
|
-
canDo: ctx.plc ? `${gate} on ${ctx.plc}` : gate,
|
|
32011
|
-
youMustDo,
|
|
32012
|
-
reasonCode: ctx.reason ?? null,
|
|
32013
|
-
reason: ctx.reason ? reasonTable[ctx.reason] ?? ctx.reason : null,
|
|
32014
|
-
plan: ctx.plan ?? null,
|
|
32015
|
-
planHash: ctx.planHash ?? null,
|
|
32016
|
-
...ctx.extra ?? {},
|
|
32017
|
-
nextSteps: resume
|
|
32018
|
-
},
|
|
32019
|
-
false
|
|
32020
|
-
);
|
|
32021
|
-
}
|
|
32334
|
+
// src/tools/compile.ts
|
|
32022
32335
|
var COMPILE_GUI_GATE_SIGNATURES = [
|
|
32023
32336
|
{
|
|
32024
32337
|
contains: "OPC UA license is not sufficient",
|
|
@@ -32112,7 +32425,7 @@ function summarizeCompile(compileDto) {
|
|
|
32112
32425
|
}
|
|
32113
32426
|
async function compileFlow(plc) {
|
|
32114
32427
|
try {
|
|
32115
|
-
const data = await tiaFetch(`/plcs/${
|
|
32428
|
+
const data = await tiaFetch(`/plcs/${seg(plc)}/compile`, { method: "POST", headers: JSON_HEADERS, body: "{}" }, { timeoutMs: 12e4 });
|
|
32116
32429
|
const d = data ?? {};
|
|
32117
32430
|
const errors = typeof d.errors === "number" ? d.errors : null;
|
|
32118
32431
|
const clean = errors !== null ? errors === 0 : d.state === "Success";
|
|
@@ -32128,684 +32441,154 @@ async function compileFlow(plc) {
|
|
|
32128
32441
|
...located.length > 0 ? { located } : {}
|
|
32129
32442
|
});
|
|
32130
32443
|
} catch (e) {
|
|
32131
|
-
return
|
|
32444
|
+
return errorResult(asTiaError(e));
|
|
32132
32445
|
}
|
|
32133
32446
|
}
|
|
32134
|
-
|
|
32135
|
-
|
|
32136
|
-
|
|
32137
|
-
|
|
32138
|
-
|
|
32139
|
-
|
|
32140
|
-
|
|
32141
|
-
|
|
32142
|
-
|
|
32143
|
-
|
|
32144
|
-
// Sempre booleano: ausente ≡ false, para "ausente" e "false" nunca darem plan_mismatch.
|
|
32145
|
-
allowUpgradeTargetDevice: args.allowUpgradeTargetDevice === true
|
|
32146
|
-
};
|
|
32447
|
+
function registerCompileTools(server2) {
|
|
32448
|
+
server2.registerTool(
|
|
32449
|
+
"tia_compile",
|
|
32450
|
+
{
|
|
32451
|
+
title: "TIA \u2014 compile (verifier)",
|
|
32452
|
+
description: "Compiles the PLC and returns the message tree + a verification summary (Gd8: only ERROR blocks, warnings don't) and nextHints. This is the offline VERIFIER: a clean compile is a precondition (Gd9) for download/S7. Maps to POST /plcs/{plc}/compile. M-off. " + LONG_OPERATION_NOTE,
|
|
32453
|
+
inputSchema: { plc: external_exports.string().describe("PLC name") }
|
|
32454
|
+
},
|
|
32455
|
+
async ({ plc }) => jobs.run("tia_compile", { plc }, () => compileFlow(plc))
|
|
32456
|
+
);
|
|
32147
32457
|
}
|
|
32148
|
-
|
|
32149
|
-
|
|
32150
|
-
|
|
32151
|
-
|
|
32152
|
-
|
|
32153
|
-
|
|
32154
|
-
|
|
32155
|
-
|
|
32156
|
-
|
|
32458
|
+
|
|
32459
|
+
// src/simaticml.ts
|
|
32460
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
32461
|
+
var LEADING_BOM = /^/;
|
|
32462
|
+
var IGNORED_ALWAYS = [
|
|
32463
|
+
"leading UTF-8 BOM (U+FEFF)",
|
|
32464
|
+
"line-ending style (CRLF vs LF)",
|
|
32465
|
+
"indentation and blank lines (also inside multi-line <Text> comments, via a per-line trim)",
|
|
32466
|
+
"<Created> (export timestamp)",
|
|
32467
|
+
"<InstalledProducts> (TIA hotfix level and installed option packages)",
|
|
32468
|
+
"UId attributes (renumbered by Openness on every export/re-import)"
|
|
32469
|
+
];
|
|
32470
|
+
var IGNORED_FORMATTING = "<NewLine/> and <Blank/> structured-text formatting tokens";
|
|
32471
|
+
function ignoredList(opts) {
|
|
32472
|
+
const list = [...IGNORED_ALWAYS];
|
|
32473
|
+
if (opts.ignoreFormatting ?? true) list.push(IGNORED_FORMATTING);
|
|
32474
|
+
return list;
|
|
32157
32475
|
}
|
|
32158
|
-
function
|
|
32159
|
-
|
|
32160
|
-
return {
|
|
32161
|
-
...jsonBody2({
|
|
32162
|
-
connectionMode: plan.connectionMode,
|
|
32163
|
-
pcInterfaceName: plan.pcInterfaceName,
|
|
32164
|
-
pcInterfaceNumber: plan.pcInterfaceNumber,
|
|
32165
|
-
targetInterfaceName: plan.targetInterfaceName,
|
|
32166
|
-
hardware: plan.hardware,
|
|
32167
|
-
software: plan.software
|
|
32168
|
-
}),
|
|
32169
|
-
expectedFingerprint: issued.fingerprint,
|
|
32170
|
-
allowUpgradeTargetDevice: plan.allowUpgradeTargetDevice === true
|
|
32171
|
-
};
|
|
32476
|
+
function sha256Utf8(text) {
|
|
32477
|
+
return createHash2("sha256").update(text.replace(LEADING_BOM, ""), "utf8").digest("hex");
|
|
32172
32478
|
}
|
|
32173
|
-
|
|
32174
|
-
let
|
|
32175
|
-
|
|
32176
|
-
|
|
32177
|
-
|
|
32178
|
-
|
|
32179
|
-
|
|
32180
|
-
|
|
32181
|
-
|
|
32182
|
-
|
|
32183
|
-
|
|
32184
|
-
|
|
32185
|
-
|
|
32186
|
-
|
|
32187
|
-
|
|
32188
|
-
|
|
32189
|
-
|
|
32479
|
+
function normalizeSimaticMl(xml, opts = {}) {
|
|
32480
|
+
let s = xml.replace(LEADING_BOM, "").replace(/\r\n?/g, "\n");
|
|
32481
|
+
s = s.replace(/<Created>[^<]*<\/Created>/g, "");
|
|
32482
|
+
s = s.replace(/<InstalledProducts>[\s\S]*?<\/InstalledProducts>/g, "");
|
|
32483
|
+
s = s.replace(/<InstalledProducts\s*\/>/g, "");
|
|
32484
|
+
s = s.replace(/\s+UId="[^"]*"/g, "");
|
|
32485
|
+
if (opts.ignoreFormatting ?? true) s = s.replace(/<(?:NewLine|Blank)\b[^>]*\/>/g, "");
|
|
32486
|
+
s = s.replace(/>\s+</g, ">\n<");
|
|
32487
|
+
return s.split("\n").map((l) => l.trim()).filter((l) => l.length > 0).join("\n");
|
|
32488
|
+
}
|
|
32489
|
+
function compareSimaticMl(left, right, opts = {}) {
|
|
32490
|
+
const a = normalizeSimaticMl(left, opts).split("\n");
|
|
32491
|
+
const b = normalizeSimaticMl(right, opts).split("\n");
|
|
32492
|
+
const ignored = ignoredList(opts);
|
|
32493
|
+
const n = Math.max(a.length, b.length);
|
|
32494
|
+
for (let i = 0; i < n; i++) {
|
|
32495
|
+
if (a[i] !== b[i]) {
|
|
32496
|
+
return {
|
|
32497
|
+
equal: false,
|
|
32498
|
+
leftLines: a.length,
|
|
32499
|
+
rightLines: b.length,
|
|
32500
|
+
firstDifference: {
|
|
32501
|
+
line: i + 1,
|
|
32502
|
+
left: a[i] ?? null,
|
|
32503
|
+
right: b[i] ?? null,
|
|
32504
|
+
context: a.slice(Math.max(0, i - 3), i)
|
|
32505
|
+
},
|
|
32506
|
+
ignored
|
|
32507
|
+
};
|
|
32190
32508
|
}
|
|
32191
|
-
return errorResult2(err);
|
|
32192
32509
|
}
|
|
32193
|
-
|
|
32194
|
-
|
|
32195
|
-
|
|
32196
|
-
|
|
32197
|
-
|
|
32198
|
-
|
|
32199
|
-
|
|
32200
|
-
|
|
32201
|
-
|
|
32510
|
+
return { equal: true, leftLines: a.length, rightLines: b.length, firstDifference: null, ignored };
|
|
32511
|
+
}
|
|
32512
|
+
|
|
32513
|
+
// src/tools/authoring.ts
|
|
32514
|
+
function gd5Violation(typeIdentifier) {
|
|
32515
|
+
if (!typeIdentifier) return null;
|
|
32516
|
+
if (/:V\d/.test(typeIdentifier)) {
|
|
32517
|
+
return `Gd5: the typeIdentifier uses ':V' (drift form) before the firmware version. Use '/V' (slash) \u2014 e.g.: "OrderNumber:6ES7 511-1AK02-0AB0/V2.9". Resolve the exact value with tia_catalog.`;
|
|
32518
|
+
}
|
|
32519
|
+
return null;
|
|
32520
|
+
}
|
|
32521
|
+
function guardError(guard, message, context) {
|
|
32522
|
+
return textResult(
|
|
32523
|
+
{
|
|
32524
|
+
error: message,
|
|
32525
|
+
kind: "guard_violation",
|
|
32526
|
+
guard,
|
|
32527
|
+
blockedBeforeOpenness: true,
|
|
32528
|
+
context,
|
|
32529
|
+
hint: "Fix the input and try again \u2014 nothing was changed in the project."
|
|
32530
|
+
},
|
|
32531
|
+
true
|
|
32532
|
+
);
|
|
32533
|
+
}
|
|
32534
|
+
async function mutate(method, path, body, opts) {
|
|
32535
|
+
if (opts.dryRun) {
|
|
32202
32536
|
return textResult(
|
|
32203
32537
|
{
|
|
32204
32538
|
dryRun: true,
|
|
32205
|
-
status: "
|
|
32206
|
-
|
|
32207
|
-
|
|
32208
|
-
|
|
32209
|
-
|
|
32210
|
-
connection: data.connection ?? null,
|
|
32211
|
-
note: fingerprintMissing ? "NO approval token was issued: serve reported ready but returned no software fingerprint, and this MCP never approves a download it cannot verify. Update the TIAOpenness app (serve) to v1.6.0 or later and run dryRun again." : "NO approval token was issued. Fix the blockers (compile errors \u2192 tia_compile; interface \u2192 tia_pg_interfaces) and run dryRun again."
|
|
32539
|
+
status: "plan_ok",
|
|
32540
|
+
action: `${method} ${path}`,
|
|
32541
|
+
summary: opts.summary,
|
|
32542
|
+
body: body ?? null,
|
|
32543
|
+
note: "Plan validated (guards OK). NOTHING was changed. Run again with dryRun:false to apply."
|
|
32212
32544
|
},
|
|
32213
32545
|
false
|
|
32214
32546
|
);
|
|
32215
32547
|
}
|
|
32216
|
-
const issued = store.issue(plan, fingerprint);
|
|
32217
|
-
return textResult(
|
|
32218
|
-
{
|
|
32219
|
-
dryRun: true,
|
|
32220
|
-
status: "plan_ok",
|
|
32221
|
-
gate: "download_approval",
|
|
32222
|
-
plan,
|
|
32223
|
-
planHash: issued.token,
|
|
32224
|
-
expiresAt: new Date(issued.expiresAt).toISOString(),
|
|
32225
|
-
fingerprint,
|
|
32226
|
-
fingerprintItems: data.fingerprintItems ?? [],
|
|
32227
|
-
coverage: data.coverage ?? null,
|
|
32228
|
-
warnings: data.warnings ?? [],
|
|
32229
|
-
compile,
|
|
32230
|
-
connection: data.connection ?? null,
|
|
32231
|
-
loadPreview: {
|
|
32232
|
-
// Emenda #4: espelha TODAS as auto-confirmações reais de PlcDeployService.cs (PreDownload/PostDownload),
|
|
32233
|
-
// não só as 3 mais óbvias — inclusive as que não param/reiniciam a CPU, mas ainda alteram o conteúdo dela.
|
|
32234
|
-
willConfirm: [
|
|
32235
|
-
"StopModules = StopAll \u2014 STOPS the physical CPU (pre phase)",
|
|
32236
|
-
"ResetModule = DeleteAll \u2014 if the CPU already holds a DIFFERENT program, it is deleted before this one loads (pre and/or post phase)",
|
|
32237
|
-
"OverwriteSystemData = Overwrite \u2014 overwrites system data (pre phase for a hardware download, and again in the post phase)",
|
|
32238
|
-
"ConsistentBlocksDownload = ConsistentDownload \u2014 downloads all blocks consistently (pre phase)",
|
|
32239
|
-
"AlarmTextLibrariesDownload = ConsistentDownload \u2014 downloads alarm text libraries consistently (pre phase)",
|
|
32240
|
-
"StartModules = StartModule \u2014 RESTARTS the CPU at the end (post phase)",
|
|
32241
|
-
plan.allowUpgradeTargetDevice ? "UpgradeTargetDevice = Checked \u2014 upgrades the target device (explicitly allowed)" : "UpgradeTargetDevice = NOT confirmed unless allowUpgradeTargetDevice:true \u2014 if the CPU requires it the download is refused, but the CPU may already have been stopped.",
|
|
32242
|
-
"Any OTHER configuration dialog serve does not recognize is left UNTOUCHED, which can abort the load."
|
|
32243
|
-
],
|
|
32244
|
-
note: "Openness has no preview-without-downloading; these are the selections serve's delegates will make. The real download returns 'configurations' with what was actually confirmed."
|
|
32245
|
-
},
|
|
32246
|
-
note: "Plan verified by serve. NOTHING was downloaded. After a human approves THIS plan and fingerprint, call tia_download with approved:true and this planHash (single-use, expires at expiresAt)."
|
|
32247
|
-
},
|
|
32248
|
-
false
|
|
32249
|
-
);
|
|
32250
|
-
}
|
|
32251
|
-
async function downloadFlow(args, store = planStore) {
|
|
32252
|
-
const plan = buildPlan(args);
|
|
32253
|
-
if (args.dryRun) return planDownload(args, plan, store);
|
|
32254
|
-
if (args.approved !== true) return gateHandoff("download_approval", { plc: args.plc, plan, reason: "not_approved" });
|
|
32255
|
-
const check2 = store.check(args.planHash, plan);
|
|
32256
|
-
if (!check2.ok) return gateHandoff("download_approval", { plc: args.plc, plan, reason: check2.reason });
|
|
32257
|
-
store.consume(check2.issued.token);
|
|
32258
|
-
let raw;
|
|
32259
32548
|
try {
|
|
32260
|
-
|
|
32261
|
-
|
|
32262
|
-
|
|
32263
|
-
|
|
32264
|
-
);
|
|
32549
|
+
const init = { method, headers: { "Content-Type": "application/json; charset=utf-8" } };
|
|
32550
|
+
if (body !== void 0) init.body = JSON.stringify(body);
|
|
32551
|
+
const data = await tiaFetch(path, init, { timeoutMs: SLOW_TIMEOUT_MS });
|
|
32552
|
+
return textResult(data);
|
|
32265
32553
|
} catch (e) {
|
|
32266
|
-
|
|
32267
|
-
const knownRefusal = err.status === 409 && (err.kind === "plan_stale" || err.kind === "upgrade_target_device_required");
|
|
32268
|
-
if (knownRefusal) return errorResult2(err);
|
|
32269
|
-
const isTransport = err.kind === "timeout" || err.kind === "connection_refused";
|
|
32270
|
-
return gateHandoff("download_approval", {
|
|
32271
|
-
plc: args.plc,
|
|
32272
|
-
plan,
|
|
32273
|
-
reason: "outcome_unknown",
|
|
32274
|
-
extra: {
|
|
32275
|
-
approvedPlanHash: check2.issued.token,
|
|
32276
|
-
...isTransport ? { transportKind: err.kind, transportDiagnostics: err.message } : {
|
|
32277
|
-
serveErrorStatus: err.status,
|
|
32278
|
-
serveErrorKind: err.kind,
|
|
32279
|
-
serveErrorType: err.type ?? null,
|
|
32280
|
-
serveErrorInner: err.inner ?? null,
|
|
32281
|
-
serveErrorDetails: err.details ?? null,
|
|
32282
|
-
serveErrorDiagnostics: err.message
|
|
32283
|
-
}
|
|
32284
|
-
}
|
|
32285
|
-
});
|
|
32286
|
-
}
|
|
32287
|
-
const data = isObject2(raw) ? raw : {};
|
|
32288
|
-
const state = typeof data.state === "string" ? data.state : null;
|
|
32289
|
-
const errors = typeof data.errors === "number" ? data.errors : null;
|
|
32290
|
-
const stateLower = state !== null ? state.toLowerCase() : null;
|
|
32291
|
-
const cleanErrors = errors === 0;
|
|
32292
|
-
const loadOutcome = stateLower === "success" && cleanErrors ? "success" : (stateLower === "warning" || stateLower === "information") && cleanErrors ? "success_with_warnings" : "failed";
|
|
32293
|
-
const downloaded = loadOutcome !== "failed";
|
|
32294
|
-
const fingerprintVerified = data.fingerprintVerified === true;
|
|
32295
|
-
const warnings = [];
|
|
32296
|
-
if (loadOutcome === "failed") {
|
|
32297
|
-
warnings.push(
|
|
32298
|
-
`serve answered the download call, but did not report a clean load (state='${state ?? "unknown"}', errors=${errors ?? "unknown"}). Check 'result.messages' for what happened \u2014 the CPU may be in a partial or unexpected state. Do not treat this as a confirmed successful deploy.`
|
|
32299
|
-
);
|
|
32300
|
-
}
|
|
32301
|
-
if (!fingerprintVerified) {
|
|
32302
|
-
warnings.push(
|
|
32303
|
-
"serve did NOT confirm the software fingerprint check (fingerprintVerified is not true): it is NOT proven that the CPU received exactly the approved software. The serve may be older than v1.6.0 and have ignored expectedFingerprint. Tell the human and check the CPU before relying on it."
|
|
32304
|
-
);
|
|
32554
|
+
return errorResult(asTiaError(e));
|
|
32305
32555
|
}
|
|
32306
|
-
|
|
32307
|
-
|
|
32308
|
-
|
|
32309
|
-
|
|
32310
|
-
|
|
32311
|
-
|
|
32312
|
-
|
|
32313
|
-
errors,
|
|
32314
|
-
...loadOutcome === "success_with_warnings" ? { note: "The load completed with warnings \u2014 read result.messages." } : {},
|
|
32315
|
-
...warnings.length > 0 ? { warning: warnings.join(" ") } : {},
|
|
32316
|
-
result: raw ?? null
|
|
32556
|
+
}
|
|
32557
|
+
async function deviceCreateFlow(args) {
|
|
32558
|
+
const bad = gd5Violation(args.typeIdentifier);
|
|
32559
|
+
if (bad) return guardError("Gd5", bad, { typeIdentifier: args.typeIdentifier });
|
|
32560
|
+
return mutate("POST", "/devices", jsonBody({ typeIdentifier: args.typeIdentifier, deviceItemName: args.deviceItemName, deviceName: args.deviceName }), {
|
|
32561
|
+
dryRun: args.dryRun,
|
|
32562
|
+
summary: `create device "${args.deviceName ?? args.deviceItemName ?? "?"}" (${args.typeIdentifier})`
|
|
32317
32563
|
});
|
|
32318
32564
|
}
|
|
32319
|
-
var
|
|
32320
|
-
function
|
|
32321
|
-
|
|
32322
|
-
|
|
32323
|
-
|
|
32324
|
-
|
|
32325
|
-
|
|
32326
|
-
};
|
|
32565
|
+
var FW_CHANGE_RESET_WARNING = `DeviceItem.ChangeType RESETS GUI-gated comm settings on the CPU (runtime-validated): OPC UA server activation goes false and the OPC UA runtime-license selection is cleared (the server interface and PUT/GET survive). Archive FIRST (tia_project_archive). Afterwards: re-set OpcUaServer:true via tia_obj_set_attributes on the 'OPC UA' device-item (scriptable), re-select the license in the GUI (GUI-only), and recompile \u2014 the change marks blocks isConsistent:false. Same-version ChangeType is rejected by TIA. Details: tia_guide {"topic":"gui-gates"}.`;
|
|
32566
|
+
async function deviceChangeVersionFlow(args) {
|
|
32567
|
+
const bad = gd5Violation(args.typeIdentifier);
|
|
32568
|
+
if (bad) return guardError("Gd5", bad, { typeIdentifier: args.typeIdentifier });
|
|
32569
|
+
const r = await mutate("POST", `/plcs/${seg(args.plc)}/device/changeversion`, jsonBody({ typeIdentifier: args.typeIdentifier, dryRun: args.dryRun }), {
|
|
32570
|
+
dryRun: args.dryRun,
|
|
32571
|
+
summary: `change firmware of CPU "${args.plc}" to ${args.typeIdentifier}`
|
|
32572
|
+
});
|
|
32573
|
+
if (r.isError) return r;
|
|
32574
|
+
const data = JSON.parse(r.content[0].text);
|
|
32575
|
+
return textResult({ ...data, fwChangeReset: FW_CHANGE_RESET_WARNING });
|
|
32327
32576
|
}
|
|
32328
|
-
function
|
|
32329
|
-
const
|
|
32330
|
-
|
|
32331
|
-
|
|
32332
|
-
|
|
32333
|
-
|
|
32334
|
-
|
|
32335
|
-
|
|
32336
|
-
|
|
32337
|
-
|
|
32338
|
-
|
|
32339
|
-
};
|
|
32340
|
-
}
|
|
32341
|
-
async function planUpload(args, plan, store) {
|
|
32342
|
-
let raw;
|
|
32343
|
-
try {
|
|
32344
|
-
raw = await tiaFetch(
|
|
32345
|
-
"/stations/upload/plan",
|
|
32346
|
-
{
|
|
32347
|
-
method: "POST",
|
|
32348
|
-
headers: JSON_HEADERS,
|
|
32349
|
-
body: JSON.stringify(
|
|
32350
|
-
jsonBody2({
|
|
32351
|
-
connectionMode: args.connectionMode,
|
|
32352
|
-
pcInterfaceName: args.pcInterfaceName,
|
|
32353
|
-
pcInterfaceNumber: args.pcInterfaceNumber,
|
|
32354
|
-
ip: args.ip
|
|
32355
|
-
})
|
|
32356
|
-
)
|
|
32357
|
-
},
|
|
32358
|
-
{ timeoutMs: SLOW_TIMEOUT_MS }
|
|
32359
|
-
);
|
|
32360
|
-
} catch (e) {
|
|
32361
|
-
const err = asTiaError(e);
|
|
32362
|
-
if (err.status === 404 && err.kind === "route_not_found") {
|
|
32363
|
-
return errorResult2(
|
|
32364
|
-
new TiaApiError(
|
|
32365
|
-
"This serve does not support station-upload plans (POST /stations/upload/plan \u2192 404). Update the TIAOpenness app to v1.6.0 or later. Nothing was uploaded.",
|
|
32366
|
-
{ status: 404, kind: "serve_too_old" }
|
|
32367
|
-
),
|
|
32368
|
-
"Update the TIAOpenness app to v1.6.0 or later. Nothing was uploaded."
|
|
32369
|
-
);
|
|
32370
|
-
}
|
|
32371
|
-
return errorResult2(err);
|
|
32372
|
-
}
|
|
32373
|
-
const data = isObject2(raw) ? raw : {};
|
|
32374
|
-
const project = isObject2(data.project) ? data.project : {};
|
|
32375
|
-
const projectPath = typeof project.path === "string" ? project.path : "";
|
|
32376
|
-
const projectName = typeof project.name === "string" ? project.name : "(unnamed)";
|
|
32377
|
-
const devices = Array.isArray(data.devices) ? [...data.devices] : [];
|
|
32378
|
-
if (data.ready !== true || projectPath.trim().length === 0) {
|
|
32379
|
-
const blockers = Array.isArray(data.blockers) ? [...data.blockers] : [];
|
|
32380
|
-
if (!isObject2(raw)) blockers.push("invalid_plan_response");
|
|
32381
|
-
if (data.ready === true) blockers.push("project_path_missing");
|
|
32382
|
-
return textResult(
|
|
32383
|
-
{
|
|
32384
|
-
status: "plan_blocked",
|
|
32385
|
-
gate: "station_upload",
|
|
32386
|
-
plan,
|
|
32387
|
-
blockers,
|
|
32388
|
-
connection: data.connection ?? null,
|
|
32389
|
-
project: data.project ?? null,
|
|
32390
|
-
devices,
|
|
32391
|
-
note: typeof data.note === "string" ? data.note : null
|
|
32392
|
-
},
|
|
32393
|
-
false
|
|
32394
|
-
);
|
|
32395
|
-
}
|
|
32396
|
-
const issued = store.issue(plan, projectPath);
|
|
32397
|
-
const warning = devices.length > 0 ? `The open project already has ${devices.length} device(s); a backup belongs in a dedicated EMPTY project (tia.backup).` : void 0;
|
|
32398
|
-
const youMustDo = `GATE G4: upload (read) the hardware configuration and program of the PHYSICAL CPU at ${String(plan.ip)} into the OPEN project "${projectName}" (${projectPath}), which currently holds ${devices.length} device(s) \u2014 it reads the CPU and does not write it. Confirm with a human that it is safe to connect to this machine AND that this is a dedicated backup project, never the working project. After an explicit yes, re-call tia_upload with confirm:true and this planHash.`;
|
|
32399
|
-
return gateHandoff("station_upload", {
|
|
32400
|
-
plan,
|
|
32401
|
-
planHash: issued.token,
|
|
32402
|
-
youMustDo,
|
|
32403
|
-
extra: {
|
|
32404
|
-
expiresAt: new Date(issued.expiresAt).toISOString(),
|
|
32405
|
-
project: data.project ?? null,
|
|
32406
|
-
devices,
|
|
32407
|
-
connection: data.connection ?? null,
|
|
32408
|
-
...warning !== void 0 ? { warning } : {}
|
|
32409
|
-
}
|
|
32410
|
-
});
|
|
32411
|
-
}
|
|
32412
|
-
async function uploadFlow(args, store = uploadPlanStore) {
|
|
32413
|
-
const plan = buildUploadPlan(args);
|
|
32414
|
-
if (args.confirm !== true) return planUpload(args, plan, store);
|
|
32415
|
-
const check2 = store.check(args.planHash, plan);
|
|
32416
|
-
if (!check2.ok) return gateHandoff("station_upload", { plan, reason: check2.reason });
|
|
32417
|
-
store.consume(check2.issued.token);
|
|
32418
|
-
let raw;
|
|
32419
|
-
try {
|
|
32420
|
-
raw = await tiaFetch(
|
|
32421
|
-
"/stations/upload",
|
|
32422
|
-
{ method: "POST", headers: JSON_HEADERS, body: JSON.stringify(uploadBodyFromApprovedPlan(check2.issued, args.password)) },
|
|
32423
|
-
{ timeoutMs: UPLOAD_TIMEOUT_MS }
|
|
32424
|
-
);
|
|
32425
|
-
} catch (e) {
|
|
32426
|
-
const err = asTiaError(e);
|
|
32427
|
-
const knownRefusal = err.status === 400 || err.status === 409 && (err.kind === "project_changed" || err.kind === "upload_provider_unavailable" || err.kind === "connection_unresolved");
|
|
32428
|
-
if (knownRefusal) {
|
|
32429
|
-
return errorResult2(
|
|
32430
|
-
new TiaApiError(`${err.message} The approval token is SPENT (single-use) and cannot be reused; nothing was uploaded.`, {
|
|
32431
|
-
status: err.status,
|
|
32432
|
-
kind: err.kind,
|
|
32433
|
-
type: err.type,
|
|
32434
|
-
inner: err.inner,
|
|
32435
|
-
details: err.details
|
|
32436
|
-
})
|
|
32437
|
-
);
|
|
32438
|
-
}
|
|
32439
|
-
if (err.status === 409 && (err.kind === "upload_password_required" || err.kind === "upload_password_rejected")) {
|
|
32440
|
-
const det = isObject2(err.details) ? err.details : {};
|
|
32441
|
-
return gateHandoff("upload_password", {
|
|
32442
|
-
plan,
|
|
32443
|
-
reason: err.kind === "upload_password_required" ? "password_required" : "password_rejected",
|
|
32444
|
-
extra: { configurations: det.configurations ?? null }
|
|
32445
|
-
});
|
|
32446
|
-
}
|
|
32447
|
-
const isTransport = err.kind === "timeout" || err.kind === "connection_refused";
|
|
32448
|
-
return gateHandoff("station_upload", {
|
|
32449
|
-
plan,
|
|
32450
|
-
reason: "outcome_unknown",
|
|
32451
|
-
extra: {
|
|
32452
|
-
approvedPlanHash: check2.issued.token,
|
|
32453
|
-
...isTransport ? { transportKind: err.kind, transportDiagnostics: err.message } : {
|
|
32454
|
-
serveErrorStatus: err.status,
|
|
32455
|
-
serveErrorKind: err.kind,
|
|
32456
|
-
serveErrorType: err.type ?? null,
|
|
32457
|
-
serveErrorInner: err.inner ?? null,
|
|
32458
|
-
serveErrorDetails: err.details ?? null,
|
|
32459
|
-
serveErrorDiagnostics: err.message
|
|
32460
|
-
}
|
|
32461
|
-
}
|
|
32462
|
-
});
|
|
32463
|
-
}
|
|
32464
|
-
if (!isObject2(raw)) {
|
|
32465
|
-
return gateHandoff("station_upload", {
|
|
32466
|
-
plan,
|
|
32467
|
-
reason: "outcome_unknown",
|
|
32468
|
-
extra: {
|
|
32469
|
-
approvedPlanHash: check2.issued.token,
|
|
32470
|
-
serveErrorStatus: null,
|
|
32471
|
-
serveErrorKind: null,
|
|
32472
|
-
serveErrorType: null,
|
|
32473
|
-
serveErrorInner: null,
|
|
32474
|
-
serveErrorDetails: null,
|
|
32475
|
-
serveErrorDiagnostics: "POST /stations/upload answered 2xx with an empty or non-JSON body AFTER the single-use token was already consumed \u2014 the upload outcome is unknown."
|
|
32476
|
-
}
|
|
32477
|
-
});
|
|
32478
|
-
}
|
|
32479
|
-
const data = raw;
|
|
32480
|
-
const state = typeof data.state === "string" ? data.state : null;
|
|
32481
|
-
const errors = typeof data.errors === "number" ? data.errors : null;
|
|
32482
|
-
const stateLower = state !== null ? state.toLowerCase() : null;
|
|
32483
|
-
const cleanErrors = errors === 0;
|
|
32484
|
-
const uploadOutcome = stateLower === "success" && cleanErrors ? "success" : (stateLower === "warning" || stateLower === "information") && cleanErrors ? "success_with_warnings" : "failed";
|
|
32485
|
-
const uploaded = uploadOutcome !== "failed";
|
|
32486
|
-
const createdDevices = Array.isArray(data.createdDevices) ? data.createdDevices : [];
|
|
32487
|
-
const warnings = [];
|
|
32488
|
-
if (uploadOutcome === "failed") {
|
|
32489
|
-
warnings.push(
|
|
32490
|
-
`serve answered the upload call, but did not report a clean upload (state='${state ?? "unknown"}', errors=${errors ?? "unknown"}). Do not treat this as a backup \u2014 read result.messages for what happened; the project may hold a partial station.`
|
|
32491
|
-
);
|
|
32492
|
-
}
|
|
32493
|
-
if (uploaded && createdDevices.length === 0) {
|
|
32494
|
-
warnings.push("serve reported success but no new device appeared; check tia_devices.");
|
|
32495
|
-
}
|
|
32496
|
-
return textResult({
|
|
32497
|
-
uploaded,
|
|
32498
|
-
uploadOutcome,
|
|
32499
|
-
approvedPlanHash: check2.issued.token,
|
|
32500
|
-
projectPath: check2.issued.fingerprint,
|
|
32501
|
-
state,
|
|
32502
|
-
errors,
|
|
32503
|
-
uploadedStation: typeof data.uploadedStation === "string" ? data.uploadedStation : null,
|
|
32504
|
-
createdDevices,
|
|
32505
|
-
configurations: data.configurations ?? null,
|
|
32506
|
-
...warnings.length > 0 ? { warning: warnings.join(" ") } : {},
|
|
32507
|
-
nextSteps: [
|
|
32508
|
-
"1. Save the project with tia_project_save.",
|
|
32509
|
-
"2. Archive it with tia_project_archive \u2014 the .zap21 is the backup (the archive name must carry the .zap21 extension).",
|
|
32510
|
-
"3. Optionally compile the new PLC with tia_compile (a GUI-gated license message is not a backup failure)."
|
|
32511
|
-
],
|
|
32512
|
-
result: raw ?? null
|
|
32513
|
-
});
|
|
32514
|
-
}
|
|
32515
|
-
function registerVerificationTools(server2) {
|
|
32516
|
-
server2.registerTool(
|
|
32517
|
-
"tia_compile",
|
|
32518
|
-
{
|
|
32519
|
-
title: "TIA \u2014 compile (verifier)",
|
|
32520
|
-
description: "Compiles the PLC and returns the message tree + a verification summary (Gd8: only ERROR blocks, warnings don't) and nextHints. This is the offline VERIFIER: a clean compile is a precondition (Gd9) for download/S7. Maps to POST /plcs/{plc}/compile. M-off. " + LONG_OPERATION_NOTE,
|
|
32521
|
-
inputSchema: { plc: external_exports.string().describe("PLC name") }
|
|
32522
|
-
},
|
|
32523
|
-
async ({ plc }) => jobs.run("tia_compile", { plc }, () => compileFlow(plc))
|
|
32524
|
-
);
|
|
32525
|
-
server2.registerTool(
|
|
32526
|
-
"tia_connection_create",
|
|
32527
|
-
{
|
|
32528
|
-
title: "TIA \u2014 create S7 connection",
|
|
32529
|
-
description: "Creates an S7 connection between two devices. Guard G2: requires \u22652 CONSISTENT CPUs (compile clean) \u2014 a bare CPU fails. On error, the envelope's 'details' carries the diagnostic (or use tia_connections_diagnose). Maps to POST /connections. M-off.",
|
|
32530
|
-
inputSchema: {
|
|
32531
|
-
localDevice: external_exports.string().describe("local device"),
|
|
32532
|
-
partnerDevice: external_exports.string().describe("partner device")
|
|
32533
|
-
}
|
|
32534
|
-
},
|
|
32535
|
-
async ({ localDevice, partnerDevice }) => send("POST", "/connections", jsonBody2({ localDevice, partnerDevice }))
|
|
32536
|
-
);
|
|
32537
|
-
server2.registerTool(
|
|
32538
|
-
"tia_download",
|
|
32539
|
-
{
|
|
32540
|
-
title: "TIA \u2014 download to the PLC (GATE G3)",
|
|
32541
|
-
description: "Downloads hardware/software to the PHYSICAL CPU (STOPS and RESTARTS the CPU). GATE G3: does NOT download without human approval. dryRun:true asks serve for a VERIFIED plan (clean compile, PG/PC interface found, software fingerprint) and returns a single-use planHash that expires (TIA_PLAN_TTL_MS, default 15 min). After a human approves that plan, call with approved:true and the SAME planHash; serve re-checks the fingerprint inside the download and refuses (plan_stale) if the project changed. Pick connectionMode/pcInterfaceName/targetInterfaceName with tia_pg_interfaces (no scan). Requires app \u2265 v1.6.0. Maps to POST /plcs/{plc}/download/plan and POST /plcs/{plc}/download. " + LONG_OPERATION_NOTE,
|
|
32542
|
-
inputSchema: {
|
|
32543
|
-
plc: external_exports.string().describe("PLC name"),
|
|
32544
|
-
connectionMode: external_exports.string().optional().describe(`connection mode (e.g., "PN/IE") \u2014 TIA's LOCALIZED name`),
|
|
32545
|
-
pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized name)"),
|
|
32546
|
-
pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
|
|
32547
|
-
targetInterfaceName: external_exports.string().optional().describe('target CPU interface (e.g., "1 X1")'),
|
|
32548
|
-
hardware: external_exports.boolean().optional().describe("download hardware (default false)"),
|
|
32549
|
-
software: external_exports.boolean().optional().describe("download software (default true)"),
|
|
32550
|
-
allowUpgradeTargetDevice: external_exports.boolean().optional().describe("confirm TIA's 'upgrade the target device' check (default false). Part of the approved plan \u2014 changing it needs a new dryRun + approval"),
|
|
32551
|
-
dryRun: external_exports.boolean().optional().describe("Gd11: returns the plan + planHash WITHOUT downloading"),
|
|
32552
|
-
approved: external_exports.boolean().optional().describe("G3: only true after explicit HUMAN APPROVAL"),
|
|
32553
|
-
planHash: external_exports.string().optional().describe("G3: the single-use approval token returned by dryRun (issued only by this MCP process; expires)")
|
|
32554
|
-
}
|
|
32555
|
-
},
|
|
32556
|
-
// Handler INTEIRO no job e args inteiros na chave (planHash/approved/conexão incluídos): um busy devolve
|
|
32557
|
-
// ANTES de downloadFlow rodar, então o token de uso único só é consumido dentro do job, antes da chamada ao serve.
|
|
32558
|
-
async (args) => jobs.run("tia_download", args, () => downloadFlow(args))
|
|
32559
|
-
);
|
|
32560
|
-
server2.registerTool(
|
|
32561
|
-
"tia_upload",
|
|
32562
|
-
{
|
|
32563
|
-
title: "TIA \u2014 station upload (GATE G4)",
|
|
32564
|
-
description: "Station upload (GATE G4): goes ONLINE to the PHYSICAL CPU at `ip` and reads its hardware configuration and program into the OPEN project as a new station \u2014 it reads the CPU and does not write or stop it (observed on hardware: the CPU stayed in RUN). Back up into a dedicated EMPTY project, never the working project (skill tia.backup). Without confirm it asks serve for an upload plan (PG/PC interface resolved, the open project's path and devices \u2014 no network access) and returns a single-use planHash bound to that project; after a human confirms, call again with confirm:true and that planHash. A read-protected CPU needs its read-access password from a HUMAN (G6 \u2014 never invented). Needs the deploy license scope (Basic \u2192 403 scope_required) and app \u2265 v1.6.0. Maps to POST /stations/upload/plan and POST /stations/upload. " + LONG_OPERATION_NOTE,
|
|
32565
|
-
inputSchema: {
|
|
32566
|
-
ip: external_exports.string().describe("IPv4 of the PHYSICAL CPU"),
|
|
32567
|
-
connectionMode: external_exports.string().optional().describe(`connection mode (e.g., "PN/IE") \u2014 TIA's LOCALIZED name`),
|
|
32568
|
-
pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized name)"),
|
|
32569
|
-
pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
|
|
32570
|
-
confirm: external_exports.boolean().optional().describe("G4: true only after explicit HUMAN confirmation"),
|
|
32571
|
-
planHash: external_exports.string().optional().describe("G4: the single-use approval token returned by the unconfirmed call (issued only by this MCP process; expires)"),
|
|
32572
|
-
password: external_exports.string().optional().describe("G6: the CPU read-access password provided by a HUMAN, never invented")
|
|
32573
|
-
}
|
|
32574
|
-
},
|
|
32575
|
-
// Handler INTEIRO no job e args inteiros na chave (como tia_download): um busy devolve ANTES de uploadFlow
|
|
32576
|
-
// rodar, então o token de uso único só é consumido dentro do job, antes da chamada ao serve. A chave é um
|
|
32577
|
-
// hash sha256 — a senha nunca aparece em texto plano no estado do job.
|
|
32578
|
-
async (args) => jobs.run("tia_upload", args, () => uploadFlow(args))
|
|
32579
|
-
);
|
|
32580
|
-
server2.registerTool(
|
|
32581
|
-
"tia_online",
|
|
32582
|
-
{
|
|
32583
|
-
title: "TIA \u2014 go online (GATE G4)",
|
|
32584
|
-
description: "Connects ONLINE to the physical PLC. GATE G4: pass confirm:true (after a human confirms it's safe to connect to the target machine); without it, returns a handoff. Maps to POST /plcs/{plc}/online.",
|
|
32585
|
-
inputSchema: {
|
|
32586
|
-
plc: external_exports.string().describe("PLC name"),
|
|
32587
|
-
connectionMode: external_exports.string().optional().describe("connection mode (localized)"),
|
|
32588
|
-
pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized)"),
|
|
32589
|
-
pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
|
|
32590
|
-
targetInterfaceName: external_exports.string().optional().describe("target CPU interface"),
|
|
32591
|
-
confirm: external_exports.boolean().optional().describe("G4: true after human confirmation")
|
|
32592
|
-
}
|
|
32593
|
-
},
|
|
32594
|
-
async ({ plc, connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName, confirm }) => {
|
|
32595
|
-
if (confirm !== true) return gateHandoff("go_online", { plc, plan: { plc, connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName } });
|
|
32596
|
-
return send("POST", `/plcs/${seg2(plc)}/online`, jsonBody2({ connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName }), 6e4);
|
|
32597
|
-
}
|
|
32598
|
-
);
|
|
32599
|
-
server2.registerTool(
|
|
32600
|
-
"tia_offline",
|
|
32601
|
-
{
|
|
32602
|
-
title: "TIA \u2014 go offline",
|
|
32603
|
-
description: "Disconnects the PLC from online mode. Maps to POST /plcs/{plc}/offline.",
|
|
32604
|
-
inputSchema: { plc: external_exports.string().describe("PLC name") }
|
|
32605
|
-
},
|
|
32606
|
-
async ({ plc }) => send("POST", `/plcs/${seg2(plc)}/offline`)
|
|
32607
|
-
);
|
|
32608
|
-
server2.registerTool(
|
|
32609
|
-
"tia_online_state",
|
|
32610
|
-
{
|
|
32611
|
-
title: "TIA \u2014 online state",
|
|
32612
|
-
description: "Reads the PLC's online state (online/offline). Read-only (class R). Maps to GET /plcs/{plc}/online/state.",
|
|
32613
|
-
inputSchema: { plc: external_exports.string().describe("PLC name") }
|
|
32614
|
-
},
|
|
32615
|
-
async ({ plc }) => {
|
|
32616
|
-
try {
|
|
32617
|
-
return textResult(await tiaFetch(`/plcs/${seg2(plc)}/online/state`));
|
|
32618
|
-
} catch (e) {
|
|
32619
|
-
return errorResult2(asTiaError(e));
|
|
32620
|
-
}
|
|
32621
|
-
}
|
|
32622
|
-
);
|
|
32623
|
-
server2.registerTool(
|
|
32624
|
-
"tia_accessible_devices",
|
|
32625
|
-
{
|
|
32626
|
-
title: "TIA \u2014 accessible devices (GATE G7)",
|
|
32627
|
-
description: "Scans the network via the PG/PC adapter and lists accessible devices \u2014 to see which devices answer on the network \u2014 to discover mode/adapter/interface names WITHOUT a scan, use tia_pg_interfaces. GATE G7 (net scan): pass confirm:true. Maps to POST /plcs/{plc}/online/accessibledevices.",
|
|
32628
|
-
inputSchema: {
|
|
32629
|
-
plc: external_exports.string().describe("PLC name"),
|
|
32630
|
-
connectionMode: external_exports.string().optional().describe("connection mode (localized)"),
|
|
32631
|
-
pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized)"),
|
|
32632
|
-
pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
|
|
32633
|
-
confirm: external_exports.boolean().optional().describe("G7: true after human confirmation")
|
|
32634
|
-
}
|
|
32635
|
-
},
|
|
32636
|
-
async ({ plc, connectionMode, pcInterfaceName, pcInterfaceNumber, confirm }) => {
|
|
32637
|
-
if (confirm !== true) return gateHandoff("net_scan", { plc, plan: { plc, connectionMode, pcInterfaceName, pcInterfaceNumber } });
|
|
32638
|
-
return send("POST", `/plcs/${seg2(plc)}/online/accessibledevices`, jsonBody2({ connectionMode, pcInterfaceName, pcInterfaceNumber }), 6e4);
|
|
32639
|
-
}
|
|
32640
|
-
);
|
|
32641
|
-
server2.registerTool(
|
|
32642
|
-
"tia_mastersecret_set",
|
|
32643
|
-
{
|
|
32644
|
-
title: "TIA \u2014 set master secret (GATE G6)",
|
|
32645
|
-
description: "Sets the master secret (password) of a protected CPU, before online/download. GATE G6: the password comes from a HUMAN (or a credential vault) \u2014 the AI NEVER makes it up. (Note: P3.7 questions sending the secret over HTTP in plain text; prefer local entry on the host.) Maps to POST /plcs/{plc}/online/mastersecret.",
|
|
32646
|
-
inputSchema: {
|
|
32647
|
-
plc: external_exports.string().describe("PLC name"),
|
|
32648
|
-
password: external_exports.string().describe("master secret provided by a human (NEVER made up by the AI)")
|
|
32649
|
-
}
|
|
32650
|
-
},
|
|
32651
|
-
async ({ plc, password }) => send("POST", `/plcs/${seg2(plc)}/online/mastersecret`, jsonBody2({ password }))
|
|
32652
|
-
);
|
|
32653
|
-
server2.registerTool(
|
|
32654
|
-
"tia_mastersecret_reset",
|
|
32655
|
-
{
|
|
32656
|
-
title: "TIA \u2014 reset master secret",
|
|
32657
|
-
description: "Removes/resets the CPU's master secret. Maps to DELETE /plcs/{plc}/online/mastersecret.",
|
|
32658
|
-
inputSchema: { plc: external_exports.string().describe("PLC name") }
|
|
32659
|
-
},
|
|
32660
|
-
async ({ plc }) => send("DELETE", `/plcs/${seg2(plc)}/online/mastersecret`)
|
|
32661
|
-
);
|
|
32662
|
-
}
|
|
32663
|
-
|
|
32664
|
-
// src/simaticml.ts
|
|
32665
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
32666
|
-
var LEADING_BOM = /^/;
|
|
32667
|
-
var IGNORED_ALWAYS = [
|
|
32668
|
-
"leading UTF-8 BOM (U+FEFF)",
|
|
32669
|
-
"line-ending style (CRLF vs LF)",
|
|
32670
|
-
"indentation and blank lines (also inside multi-line <Text> comments, via a per-line trim)",
|
|
32671
|
-
"<Created> (export timestamp)",
|
|
32672
|
-
"<InstalledProducts> (TIA hotfix level and installed option packages)",
|
|
32673
|
-
"UId attributes (renumbered by Openness on every export/re-import)"
|
|
32674
|
-
];
|
|
32675
|
-
var IGNORED_FORMATTING = "<NewLine/> and <Blank/> structured-text formatting tokens";
|
|
32676
|
-
function ignoredList(opts) {
|
|
32677
|
-
const list = [...IGNORED_ALWAYS];
|
|
32678
|
-
if (opts.ignoreFormatting ?? true) list.push(IGNORED_FORMATTING);
|
|
32679
|
-
return list;
|
|
32680
|
-
}
|
|
32681
|
-
function sha256Utf8(text) {
|
|
32682
|
-
return createHash2("sha256").update(text.replace(LEADING_BOM, ""), "utf8").digest("hex");
|
|
32683
|
-
}
|
|
32684
|
-
function normalizeSimaticMl(xml, opts = {}) {
|
|
32685
|
-
let s = xml.replace(LEADING_BOM, "").replace(/\r\n?/g, "\n");
|
|
32686
|
-
s = s.replace(/<Created>[^<]*<\/Created>/g, "");
|
|
32687
|
-
s = s.replace(/<InstalledProducts>[\s\S]*?<\/InstalledProducts>/g, "");
|
|
32688
|
-
s = s.replace(/<InstalledProducts\s*\/>/g, "");
|
|
32689
|
-
s = s.replace(/\s+UId="[^"]*"/g, "");
|
|
32690
|
-
if (opts.ignoreFormatting ?? true) s = s.replace(/<(?:NewLine|Blank)\b[^>]*\/>/g, "");
|
|
32691
|
-
s = s.replace(/>\s+</g, ">\n<");
|
|
32692
|
-
return s.split("\n").map((l) => l.trim()).filter((l) => l.length > 0).join("\n");
|
|
32693
|
-
}
|
|
32694
|
-
function compareSimaticMl(left, right, opts = {}) {
|
|
32695
|
-
const a = normalizeSimaticMl(left, opts).split("\n");
|
|
32696
|
-
const b = normalizeSimaticMl(right, opts).split("\n");
|
|
32697
|
-
const ignored = ignoredList(opts);
|
|
32698
|
-
const n = Math.max(a.length, b.length);
|
|
32699
|
-
for (let i = 0; i < n; i++) {
|
|
32700
|
-
if (a[i] !== b[i]) {
|
|
32701
|
-
return {
|
|
32702
|
-
equal: false,
|
|
32703
|
-
leftLines: a.length,
|
|
32704
|
-
rightLines: b.length,
|
|
32705
|
-
firstDifference: {
|
|
32706
|
-
line: i + 1,
|
|
32707
|
-
left: a[i] ?? null,
|
|
32708
|
-
right: b[i] ?? null,
|
|
32709
|
-
context: a.slice(Math.max(0, i - 3), i)
|
|
32710
|
-
},
|
|
32711
|
-
ignored
|
|
32712
|
-
};
|
|
32713
|
-
}
|
|
32714
|
-
}
|
|
32715
|
-
return { equal: true, leftLines: a.length, rightLines: b.length, firstDifference: null, ignored };
|
|
32716
|
-
}
|
|
32717
|
-
|
|
32718
|
-
// src/tools/authoring.ts
|
|
32719
|
-
var seg3 = (v) => encodeURIComponent(v);
|
|
32720
|
-
function jsonBody3(obj) {
|
|
32721
|
-
const out = {};
|
|
32722
|
-
for (const [k, v] of Object.entries(obj)) if (v !== void 0 && v !== null) out[k] = v;
|
|
32723
|
-
return out;
|
|
32724
|
-
}
|
|
32725
|
-
function errorResult3(err) {
|
|
32726
|
-
return textResult(
|
|
32727
|
-
{ error: err.message, kind: err.kind, status: err.status, type: err.type, details: err.details ?? null, hint: hintFor(err) },
|
|
32728
|
-
true
|
|
32729
|
-
);
|
|
32730
|
-
}
|
|
32731
|
-
function gd5Violation(typeIdentifier) {
|
|
32732
|
-
if (!typeIdentifier) return null;
|
|
32733
|
-
if (/:V\d/.test(typeIdentifier)) {
|
|
32734
|
-
return `Gd5: the typeIdentifier uses ':V' (drift form) before the firmware version. Use '/V' (slash) \u2014 e.g.: "OrderNumber:6ES7 511-1AK02-0AB0/V2.9". Resolve the exact value with tia_catalog.`;
|
|
32735
|
-
}
|
|
32736
|
-
return null;
|
|
32737
|
-
}
|
|
32738
|
-
function guardError(guard, message, context) {
|
|
32739
|
-
return textResult(
|
|
32740
|
-
{
|
|
32741
|
-
error: message,
|
|
32742
|
-
kind: "guard_violation",
|
|
32743
|
-
guard,
|
|
32744
|
-
blockedBeforeOpenness: true,
|
|
32745
|
-
context,
|
|
32746
|
-
hint: "Fix the input and try again \u2014 nothing was changed in the project."
|
|
32747
|
-
},
|
|
32748
|
-
true
|
|
32749
|
-
);
|
|
32750
|
-
}
|
|
32751
|
-
async function mutate(method, path, body, opts) {
|
|
32752
|
-
if (opts.dryRun) {
|
|
32753
|
-
return textResult(
|
|
32754
|
-
{
|
|
32755
|
-
dryRun: true,
|
|
32756
|
-
status: "plan_ok",
|
|
32757
|
-
action: `${method} ${path}`,
|
|
32758
|
-
summary: opts.summary,
|
|
32759
|
-
body: body ?? null,
|
|
32760
|
-
note: "Plan validated (guards OK). NOTHING was changed. Run again with dryRun:false to apply."
|
|
32761
|
-
},
|
|
32762
|
-
false
|
|
32763
|
-
);
|
|
32764
|
-
}
|
|
32765
|
-
try {
|
|
32766
|
-
const init = { method, headers: { "Content-Type": "application/json; charset=utf-8" } };
|
|
32767
|
-
if (body !== void 0) init.body = JSON.stringify(body);
|
|
32768
|
-
const data = await tiaFetch(path, init, { timeoutMs: SLOW_TIMEOUT_MS });
|
|
32769
|
-
return textResult(data);
|
|
32770
|
-
} catch (e) {
|
|
32771
|
-
return errorResult3(asTiaError(e));
|
|
32772
|
-
}
|
|
32773
|
-
}
|
|
32774
|
-
async function deviceCreateFlow(args) {
|
|
32775
|
-
const bad = gd5Violation(args.typeIdentifier);
|
|
32776
|
-
if (bad) return guardError("Gd5", bad, { typeIdentifier: args.typeIdentifier });
|
|
32777
|
-
return mutate("POST", "/devices", jsonBody3({ typeIdentifier: args.typeIdentifier, deviceItemName: args.deviceItemName, deviceName: args.deviceName }), {
|
|
32778
|
-
dryRun: args.dryRun,
|
|
32779
|
-
summary: `create device "${args.deviceName ?? args.deviceItemName ?? "?"}" (${args.typeIdentifier})`
|
|
32780
|
-
});
|
|
32781
|
-
}
|
|
32782
|
-
var FW_CHANGE_RESET_WARNING = `DeviceItem.ChangeType RESETS GUI-gated comm settings on the CPU (runtime-validated): OPC UA server activation goes false and the OPC UA runtime-license selection is cleared (the server interface and PUT/GET survive). Archive FIRST (tia_project_archive). Afterwards: re-set OpcUaServer:true via tia_obj_set_attributes on the 'OPC UA' device-item (scriptable), re-select the license in the GUI (GUI-only), and recompile \u2014 the change marks blocks isConsistent:false. Same-version ChangeType is rejected by TIA. Details: tia_guide {"topic":"gui-gates"}.`;
|
|
32783
|
-
async function deviceChangeVersionFlow(args) {
|
|
32784
|
-
const bad = gd5Violation(args.typeIdentifier);
|
|
32785
|
-
if (bad) return guardError("Gd5", bad, { typeIdentifier: args.typeIdentifier });
|
|
32786
|
-
const r = await mutate("POST", `/plcs/${seg3(args.plc)}/device/changeversion`, jsonBody3({ typeIdentifier: args.typeIdentifier, dryRun: args.dryRun }), {
|
|
32787
|
-
dryRun: args.dryRun,
|
|
32788
|
-
summary: `change firmware of CPU "${args.plc}" to ${args.typeIdentifier}`
|
|
32789
|
-
});
|
|
32790
|
-
if (r.isError) return r;
|
|
32791
|
-
const data = JSON.parse(r.content[0].text);
|
|
32792
|
-
return textResult({ ...data, fwChangeReset: FW_CHANGE_RESET_WARNING });
|
|
32793
|
-
}
|
|
32794
|
-
async function sourcePutFlow(args) {
|
|
32795
|
-
const r = await mutate("POST", `/plcs/${seg3(args.plc)}/source`, jsonBody3({ name: args.name, code: args.code, compile: args.compile }), {
|
|
32796
|
-
dryRun: args.dryRun,
|
|
32797
|
-
summary: `write SCL ${args.name} on ${args.plc}`
|
|
32798
|
-
});
|
|
32799
|
-
if (r.isError || args.dryRun) return r;
|
|
32800
|
-
const data = JSON.parse(r.content[0].text);
|
|
32801
|
-
const compileDto = data.compile;
|
|
32802
|
-
if (!compileDto || typeof compileDto !== "object") return r;
|
|
32803
|
-
const { located, hints } = summarizeCompile(compileDto);
|
|
32804
|
-
if (located.length === 0 && hints.length === 0) return r;
|
|
32805
|
-
return textResult({ ...data, ...located.length > 0 ? { located } : {}, ...hints.length > 0 ? { nextHints: hints } : {} });
|
|
32577
|
+
async function sourcePutFlow(args) {
|
|
32578
|
+
const r = await mutate("POST", `/plcs/${seg(args.plc)}/source`, jsonBody({ name: args.name, code: args.code, compile: args.compile }), {
|
|
32579
|
+
dryRun: args.dryRun,
|
|
32580
|
+
summary: `write SCL ${args.name} on ${args.plc}`
|
|
32581
|
+
});
|
|
32582
|
+
if (r.isError || args.dryRun) return r;
|
|
32583
|
+
const data = JSON.parse(r.content[0].text);
|
|
32584
|
+
const compileDto = data.compile;
|
|
32585
|
+
if (!compileDto || typeof compileDto !== "object") return r;
|
|
32586
|
+
const { located, hints } = summarizeCompile(compileDto);
|
|
32587
|
+
if (located.length === 0 && hints.length === 0) return r;
|
|
32588
|
+
return textResult({ ...data, ...located.length > 0 ? { located } : {}, ...hints.length > 0 ? { nextHints: hints } : {} });
|
|
32806
32589
|
}
|
|
32807
32590
|
async function importXmlFlow(args) {
|
|
32808
|
-
const r = await mutate("POST", `/plcs/${
|
|
32591
|
+
const r = await mutate("POST", `/plcs/${seg(args.plc)}/import`, jsonBody({ xml: args.xml, path: args.path, override: args.override }), {
|
|
32809
32592
|
dryRun: args.dryRun,
|
|
32810
32593
|
summary: `import XML on ${args.plc}`
|
|
32811
32594
|
});
|
|
@@ -32883,7 +32666,7 @@ function registerAuthoringTools(server2) {
|
|
|
32883
32666
|
async ({ device, typeIdentifier, name, position, host, dryRun }) => {
|
|
32884
32667
|
const bad = gd5Violation(typeIdentifier);
|
|
32885
32668
|
if (bad) return guardError("Gd5", bad, { typeIdentifier });
|
|
32886
|
-
return mutate("POST", `/devices/${
|
|
32669
|
+
return mutate("POST", `/devices/${seg(device)}/plug`, jsonBody({ typeIdentifier, name, position, host }), {
|
|
32887
32670
|
dryRun,
|
|
32888
32671
|
summary: `plug "${name ?? typeIdentifier}" into ${device}`
|
|
32889
32672
|
});
|
|
@@ -32900,7 +32683,7 @@ function registerAuthoringTools(server2) {
|
|
|
32900
32683
|
...dryRunField
|
|
32901
32684
|
}
|
|
32902
32685
|
},
|
|
32903
|
-
async ({ device, item, dryRun }) => mutate("DELETE", `/devices/${
|
|
32686
|
+
async ({ device, item, dryRun }) => mutate("DELETE", `/devices/${seg(device)}/items/${seg(item)}`, void 0, { dryRun, summary: `unplug ${item} from ${device}` })
|
|
32904
32687
|
);
|
|
32905
32688
|
server2.registerTool(
|
|
32906
32689
|
"tia_device_group_create",
|
|
@@ -32909,7 +32692,7 @@ function registerAuthoringTools(server2) {
|
|
|
32909
32692
|
description: "Creates a device group. Maps to POST /devicegroups. M-off.",
|
|
32910
32693
|
inputSchema: { name: external_exports.string().describe("group name"), ...dryRunField }
|
|
32911
32694
|
},
|
|
32912
|
-
async ({ name, dryRun }) => mutate("POST", "/devicegroups",
|
|
32695
|
+
async ({ name, dryRun }) => mutate("POST", "/devicegroups", jsonBody({ name }), { dryRun, summary: `create device group ${name}` })
|
|
32913
32696
|
);
|
|
32914
32697
|
server2.registerTool(
|
|
32915
32698
|
"tia_subnet_create",
|
|
@@ -32925,7 +32708,7 @@ function registerAuthoringTools(server2) {
|
|
|
32925
32708
|
async ({ typeIdentifier, name, dryRun }) => {
|
|
32926
32709
|
const bad = gd5Violation(typeIdentifier);
|
|
32927
32710
|
if (bad) return guardError("Gd5", bad, { typeIdentifier });
|
|
32928
|
-
return mutate("POST", "/subnets",
|
|
32711
|
+
return mutate("POST", "/subnets", jsonBody({ typeIdentifier, name }), { dryRun, summary: `create subnet ${name ?? typeIdentifier}` });
|
|
32929
32712
|
}
|
|
32930
32713
|
);
|
|
32931
32714
|
server2.registerTool(
|
|
@@ -32942,7 +32725,7 @@ function registerAuthoringTools(server2) {
|
|
|
32942
32725
|
...dryRunField
|
|
32943
32726
|
}
|
|
32944
32727
|
},
|
|
32945
|
-
async ({ device, subnet, ip, createIoSystem, ioSystemName, dryRun }) => mutate("POST", "/network/connect",
|
|
32728
|
+
async ({ device, subnet, ip, createIoSystem, ioSystemName, dryRun }) => mutate("POST", "/network/connect", jsonBody({ device, subnet, ip, createIoSystem, ioSystemName }), {
|
|
32946
32729
|
dryRun,
|
|
32947
32730
|
summary: `connect ${device} to subnet ${subnet}${ip ? " @" + ip : ""}`
|
|
32948
32731
|
})
|
|
@@ -32958,7 +32741,7 @@ function registerAuthoringTools(server2) {
|
|
|
32958
32741
|
...dryRunField
|
|
32959
32742
|
}
|
|
32960
32743
|
},
|
|
32961
|
-
async ({ device, attributes, dryRun }) => mutate("POST", "/network/address",
|
|
32744
|
+
async ({ device, attributes, dryRun }) => mutate("POST", "/network/address", jsonBody({ device, attributes }), { dryRun, summary: `address ${device}` })
|
|
32962
32745
|
);
|
|
32963
32746
|
server2.registerTool(
|
|
32964
32747
|
"tia_network_disconnect",
|
|
@@ -32967,7 +32750,7 @@ function registerAuthoringTools(server2) {
|
|
|
32967
32750
|
description: "Disconnects a device's interface from the subnet. Maps to POST /network/disconnect. M-off.",
|
|
32968
32751
|
inputSchema: { device: external_exports.string().describe("device name"), ...dryRunField }
|
|
32969
32752
|
},
|
|
32970
|
-
async ({ device, dryRun }) => mutate("POST", "/network/disconnect",
|
|
32753
|
+
async ({ device, dryRun }) => mutate("POST", "/network/disconnect", jsonBody({ device }), { dryRun, summary: `disconnect ${device} from the subnet` })
|
|
32971
32754
|
);
|
|
32972
32755
|
server2.registerTool(
|
|
32973
32756
|
"tia_tagtable_create",
|
|
@@ -32976,7 +32759,7 @@ function registerAuthoringTools(server2) {
|
|
|
32976
32759
|
description: "Creates a tag table on a PLC. Maps to POST /plcs/{plc}/tagtables. M-off.",
|
|
32977
32760
|
inputSchema: { plc: external_exports.string().describe("PLC name"), name: external_exports.string().describe("table name"), ...dryRunField }
|
|
32978
32761
|
},
|
|
32979
|
-
async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${
|
|
32762
|
+
async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/tagtables`, jsonBody({ name }), { dryRun, summary: `create tag table ${name} on ${plc}` })
|
|
32980
32763
|
);
|
|
32981
32764
|
server2.registerTool(
|
|
32982
32765
|
"tia_tag_create",
|
|
@@ -32992,7 +32775,7 @@ function registerAuthoringTools(server2) {
|
|
|
32992
32775
|
...dryRunField
|
|
32993
32776
|
}
|
|
32994
32777
|
},
|
|
32995
|
-
async ({ plc, table, name, dataType, address, dryRun }) => mutate("POST", `/plcs/${
|
|
32778
|
+
async ({ plc, table, name, dataType, address, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/tags`, jsonBody({ table, name, dataType, address }), { dryRun, summary: `create tag ${name}:${dataType} on ${plc}` })
|
|
32996
32779
|
);
|
|
32997
32780
|
server2.registerTool(
|
|
32998
32781
|
"tia_tag_delete",
|
|
@@ -33006,7 +32789,7 @@ function registerAuthoringTools(server2) {
|
|
|
33006
32789
|
...dryRunField
|
|
33007
32790
|
}
|
|
33008
32791
|
},
|
|
33009
|
-
async ({ plc, table, tag, dryRun }) => mutate("DELETE", `/plcs/${
|
|
32792
|
+
async ({ plc, table, tag, dryRun }) => mutate("DELETE", `/plcs/${seg(plc)}/tagtables/${seg(table)}/tags/${seg(tag)}`, void 0, { dryRun, summary: `delete tag ${tag}` })
|
|
33010
32793
|
);
|
|
33011
32794
|
server2.registerTool(
|
|
33012
32795
|
"tia_constant_create",
|
|
@@ -33022,7 +32805,7 @@ function registerAuthoringTools(server2) {
|
|
|
33022
32805
|
...dryRunField
|
|
33023
32806
|
}
|
|
33024
32807
|
},
|
|
33025
|
-
async ({ plc, table, name, dataType, value, dryRun }) => mutate("POST", `/plcs/${
|
|
32808
|
+
async ({ plc, table, name, dataType, value, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/constants`, jsonBody({ table, name, dataType, value }), { dryRun, summary: `create constant ${name} on ${plc}` })
|
|
33026
32809
|
);
|
|
33027
32810
|
server2.registerTool(
|
|
33028
32811
|
"tia_fb_create",
|
|
@@ -33039,7 +32822,7 @@ function registerAuthoringTools(server2) {
|
|
|
33039
32822
|
...dryRunField
|
|
33040
32823
|
}
|
|
33041
32824
|
},
|
|
33042
|
-
async ({ plc, name, language, autoNumber, number: number4, group, dryRun }) => mutate("POST", `/plcs/${
|
|
32825
|
+
async ({ plc, name, language, autoNumber, number: number4, group, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/fbs`, jsonBody({ name, language, autoNumber, number: number4, group }), { dryRun, summary: `create FB ${name} on ${plc}` })
|
|
33043
32826
|
);
|
|
33044
32827
|
server2.registerTool(
|
|
33045
32828
|
"tia_instancedb_create",
|
|
@@ -33056,7 +32839,7 @@ function registerAuthoringTools(server2) {
|
|
|
33056
32839
|
...dryRunField
|
|
33057
32840
|
}
|
|
33058
32841
|
},
|
|
33059
|
-
async ({ plc, name, instanceOf, autoNumber, number: number4, group, dryRun }) => mutate("POST", `/plcs/${
|
|
32842
|
+
async ({ plc, name, instanceOf, autoNumber, number: number4, group, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/instancedbs`, jsonBody({ name, instanceOf, autoNumber, number: number4, group }), {
|
|
33060
32843
|
dryRun,
|
|
33061
32844
|
summary: `create iDB ${name} from ${instanceOf} on ${plc}`
|
|
33062
32845
|
})
|
|
@@ -33068,7 +32851,7 @@ function registerAuthoringTools(server2) {
|
|
|
33068
32851
|
description: "Deletes a block. Maps to DELETE /plcs/{plc}/blocks/{block}. M-off.",
|
|
33069
32852
|
inputSchema: { plc: external_exports.string().describe("PLC name"), block: external_exports.string().describe("block name"), ...dryRunField }
|
|
33070
32853
|
},
|
|
33071
|
-
async ({ plc, block, dryRun }) => mutate("DELETE", `/plcs/${
|
|
32854
|
+
async ({ plc, block, dryRun }) => mutate("DELETE", `/plcs/${seg(plc)}/blocks/${seg(block)}`, void 0, { dryRun, summary: `delete block ${block}` })
|
|
33072
32855
|
);
|
|
33073
32856
|
server2.registerTool(
|
|
33074
32857
|
"tia_block_set_attribute",
|
|
@@ -33083,7 +32866,7 @@ function registerAuthoringTools(server2) {
|
|
|
33083
32866
|
...dryRunField
|
|
33084
32867
|
}
|
|
33085
32868
|
},
|
|
33086
|
-
async ({ plc, block, name, value, dryRun }) => mutate("POST", `/plcs/${
|
|
32869
|
+
async ({ plc, block, name, value, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/blocks/${seg(block)}/attributes`, jsonBody({ name, value }), {
|
|
33087
32870
|
dryRun,
|
|
33088
32871
|
summary: `set ${name} on ${block}`
|
|
33089
32872
|
})
|
|
@@ -33095,7 +32878,7 @@ function registerAuthoringTools(server2) {
|
|
|
33095
32878
|
description: "Creates a block group. Maps to POST /plcs/{plc}/blockgroups. M-off.",
|
|
33096
32879
|
inputSchema: { plc: external_exports.string().describe("PLC name"), name: external_exports.string().describe("group name"), ...dryRunField }
|
|
33097
32880
|
},
|
|
33098
|
-
async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${
|
|
32881
|
+
async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/blockgroups`, jsonBody({ name }), { dryRun, summary: `create block group ${name}` })
|
|
33099
32882
|
);
|
|
33100
32883
|
server2.registerTool(
|
|
33101
32884
|
"tia_type_group_create",
|
|
@@ -33104,7 +32887,7 @@ function registerAuthoringTools(server2) {
|
|
|
33104
32887
|
description: "Creates a type group (UDTs). Maps to POST /plcs/{plc}/typegroups. M-off.",
|
|
33105
32888
|
inputSchema: { plc: external_exports.string().describe("PLC name"), name: external_exports.string().describe("group name"), ...dryRunField }
|
|
33106
32889
|
},
|
|
33107
|
-
async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${
|
|
32890
|
+
async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/typegroups`, jsonBody({ name }), { dryRun, summary: `create type group ${name}` })
|
|
33108
32891
|
);
|
|
33109
32892
|
server2.registerTool(
|
|
33110
32893
|
"tia_type_delete",
|
|
@@ -33113,7 +32896,7 @@ function registerAuthoringTools(server2) {
|
|
|
33113
32896
|
description: "Deletes a type (UDT). Maps to DELETE /plcs/{plc}/types/{type}. M-off.",
|
|
33114
32897
|
inputSchema: { plc: external_exports.string().describe("PLC name"), type: external_exports.string().describe("type name"), ...dryRunField }
|
|
33115
32898
|
},
|
|
33116
|
-
async ({ plc, type, dryRun }) => mutate("DELETE", `/plcs/${
|
|
32899
|
+
async ({ plc, type, dryRun }) => mutate("DELETE", `/plcs/${seg(plc)}/types/${seg(type)}`, void 0, { dryRun, summary: `delete type ${type}` })
|
|
33117
32900
|
);
|
|
33118
32901
|
server2.registerTool(
|
|
33119
32902
|
"tia_source_put",
|
|
@@ -33158,7 +32941,7 @@ function registerAuthoringTools(server2) {
|
|
|
33158
32941
|
...dryRunField
|
|
33159
32942
|
}
|
|
33160
32943
|
},
|
|
33161
|
-
async ({ plc, xml, path, override, dryRun }) => mutate("POST", `/plcs/${
|
|
32944
|
+
async ({ plc, xml, path, override, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/types/import`, jsonBody({ xml, path, override }), { dryRun, summary: `import UDT on ${plc}` })
|
|
33162
32945
|
);
|
|
33163
32946
|
server2.registerTool(
|
|
33164
32947
|
"tia_export_xml",
|
|
@@ -33174,7 +32957,7 @@ function registerAuthoringTools(server2) {
|
|
|
33174
32957
|
async ({ plc, directory, dryRun }) => jobs.run(
|
|
33175
32958
|
"tia_export_xml",
|
|
33176
32959
|
{ plc, directory, dryRun },
|
|
33177
|
-
() => mutate("POST", `/plcs/${
|
|
32960
|
+
() => mutate("POST", `/plcs/${seg(plc)}/export`, jsonBody({ directory }), { dryRun, summary: `export XML from ${plc} to ${directory}` })
|
|
33178
32961
|
)
|
|
33179
32962
|
);
|
|
33180
32963
|
server2.registerTool(
|
|
@@ -33184,7 +32967,7 @@ function registerAuthoringTools(server2) {
|
|
|
33184
32967
|
description: "Creates a watch table. Maps to POST /plcs/{plc}/watchtables. M-off.",
|
|
33185
32968
|
inputSchema: { plc: external_exports.string().describe("PLC name"), name: external_exports.string().describe("watch table name"), ...dryRunField }
|
|
33186
32969
|
},
|
|
33187
|
-
async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${
|
|
32970
|
+
async ({ plc, name, dryRun }) => mutate("POST", `/plcs/${seg(plc)}/watchtables`, jsonBody({ name }), { dryRun, summary: `create watch table ${name}` })
|
|
33188
32971
|
);
|
|
33189
32972
|
server2.registerTool(
|
|
33190
32973
|
"tia_watchtable_delete",
|
|
@@ -33193,7 +32976,7 @@ function registerAuthoringTools(server2) {
|
|
|
33193
32976
|
description: "Deletes a watch table. Maps to DELETE /plcs/{plc}/watchtables/{wt}. M-off.",
|
|
33194
32977
|
inputSchema: { plc: external_exports.string().describe("PLC name"), watchtable: external_exports.string().describe("watch table name"), ...dryRunField }
|
|
33195
32978
|
},
|
|
33196
|
-
async ({ plc, watchtable, dryRun }) => mutate("DELETE", `/plcs/${
|
|
32979
|
+
async ({ plc, watchtable, dryRun }) => mutate("DELETE", `/plcs/${seg(plc)}/watchtables/${seg(watchtable)}`, void 0, { dryRun, summary: `delete watch table ${watchtable}` })
|
|
33197
32980
|
);
|
|
33198
32981
|
server2.registerTool(
|
|
33199
32982
|
"tia_obj_service",
|
|
@@ -33205,7 +32988,7 @@ function registerAuthoringTools(server2) {
|
|
|
33205
32988
|
type: external_exports.string().describe("service type name (e.g., Siemens.Engineering.HW.Features.PlcMasterSecretConfigurator)")
|
|
33206
32989
|
}
|
|
33207
32990
|
},
|
|
33208
|
-
async ({ handle, type }) => mutate("POST", `/obj/${
|
|
32991
|
+
async ({ handle, type }) => mutate("POST", `/obj/${seg(handle)}/service`, jsonBody({ type }), { summary: `acquire service ${type} from obj ${handle}` })
|
|
33209
32992
|
);
|
|
33210
32993
|
server2.registerTool(
|
|
33211
32994
|
"tia_obj_set_attributes",
|
|
@@ -33218,7 +33001,7 @@ function registerAuthoringTools(server2) {
|
|
|
33218
33001
|
...dryRunField
|
|
33219
33002
|
}
|
|
33220
33003
|
},
|
|
33221
|
-
async ({ handle, attributes, dryRun }) => mutate("POST", `/obj/${
|
|
33004
|
+
async ({ handle, attributes, dryRun }) => mutate("POST", `/obj/${seg(handle)}/attributes`, jsonBody({ ...attributes }), { dryRun, summary: `set attributes on obj ${handle}` })
|
|
33222
33005
|
);
|
|
33223
33006
|
server2.registerTool(
|
|
33224
33007
|
"tia_obj_invoke",
|
|
@@ -33232,7 +33015,7 @@ function registerAuthoringTools(server2) {
|
|
|
33232
33015
|
...dryRunField
|
|
33233
33016
|
}
|
|
33234
33017
|
},
|
|
33235
|
-
async ({ handle, name, args, dryRun }) => mutate("POST", `/obj/${
|
|
33018
|
+
async ({ handle, name, args, dryRun }) => mutate("POST", `/obj/${seg(handle)}/invoke`, jsonBody({ name, args }), { dryRun, summary: `invoke ${name}() on obj ${handle}` })
|
|
33236
33019
|
);
|
|
33237
33020
|
server2.registerTool(
|
|
33238
33021
|
"tia_obj_create",
|
|
@@ -33247,7 +33030,7 @@ function registerAuthoringTools(server2) {
|
|
|
33247
33030
|
...dryRunField
|
|
33248
33031
|
}
|
|
33249
33032
|
},
|
|
33250
|
-
async ({ handle, composition, type, parameters, dryRun }) => mutate("POST", `/obj/${
|
|
33033
|
+
async ({ handle, composition, type, parameters, dryRun }) => mutate("POST", `/obj/${seg(handle)}/create`, jsonBody({ composition, type, parameters }), {
|
|
33251
33034
|
dryRun,
|
|
33252
33035
|
summary: `create ${type} in ${composition} of obj ${handle}`
|
|
33253
33036
|
})
|
|
@@ -33255,14 +33038,9 @@ function registerAuthoringTools(server2) {
|
|
|
33255
33038
|
}
|
|
33256
33039
|
|
|
33257
33040
|
// src/tools/asCode.ts
|
|
33258
|
-
var seg4 = (v) => encodeURIComponent(v);
|
|
33259
|
-
function errorResult4(e) {
|
|
33260
|
-
const err = asTiaError(e);
|
|
33261
|
-
return textResult({ error: err.message, kind: err.kind, status: err.status, details: err.details ?? null, hint: hintFor(err) }, true);
|
|
33262
|
-
}
|
|
33263
33041
|
async function fetchBlockXml(plc, block, options) {
|
|
33264
33042
|
const q = options ? `?options=${encodeURIComponent(options)}` : "";
|
|
33265
|
-
return await tiaFetch(`/plcs/${
|
|
33043
|
+
return await tiaFetch(`/plcs/${seg(plc)}/blocks/${seg(block)}/xml${q}`, {}, { timeoutMs: SLOW_TIMEOUT_MS });
|
|
33266
33044
|
}
|
|
33267
33045
|
async function exportBlockFlow(plc, block, options) {
|
|
33268
33046
|
try {
|
|
@@ -33277,7 +33055,7 @@ async function exportBlockFlow(plc, block, options) {
|
|
|
33277
33055
|
xml: d.xml
|
|
33278
33056
|
});
|
|
33279
33057
|
} catch (e) {
|
|
33280
|
-
return
|
|
33058
|
+
return errorResult(asTiaError(e));
|
|
33281
33059
|
}
|
|
33282
33060
|
}
|
|
33283
33061
|
async function blockCompareFlow(args) {
|
|
@@ -33294,7 +33072,7 @@ async function blockCompareFlow(args) {
|
|
|
33294
33072
|
note: "left = the block exported from the project now; right = the XML you passed (e.g. the file in git)."
|
|
33295
33073
|
});
|
|
33296
33074
|
} catch (e) {
|
|
33297
|
-
return
|
|
33075
|
+
return errorResult(asTiaError(e));
|
|
33298
33076
|
}
|
|
33299
33077
|
}
|
|
33300
33078
|
function registerAsCodeTools(server2) {
|
|
@@ -33328,71 +33106,833 @@ function registerAsCodeTools(server2) {
|
|
|
33328
33106
|
);
|
|
33329
33107
|
}
|
|
33330
33108
|
|
|
33331
|
-
// src/
|
|
33332
|
-
|
|
33333
|
-
var
|
|
33334
|
-
|
|
33335
|
-
|
|
33336
|
-
|
|
33337
|
-
|
|
33338
|
-
|
|
33339
|
-
}
|
|
33340
|
-
function ipToInt(ip) {
|
|
33341
|
-
const p = ip.split(".").map((x) => Number(x));
|
|
33342
|
-
if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;
|
|
33343
|
-
return (p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]) >>> 0;
|
|
33344
|
-
}
|
|
33345
|
-
function ipInCidr(ip, cidr) {
|
|
33346
|
-
const slash = cidr.indexOf("/");
|
|
33347
|
-
if (slash < 0) return false;
|
|
33348
|
-
const bits = Number(cidr.slice(slash + 1));
|
|
33349
|
-
const ipi = ipToInt(ip);
|
|
33350
|
-
const neti = ipToInt(cidr.slice(0, slash));
|
|
33351
|
-
if (ipi === null || neti === null || !(bits >= 0 && bits <= 32)) return false;
|
|
33352
|
-
if (bits === 0) return true;
|
|
33353
|
-
const mask = bits === 32 ? 4294967295 : ~((1 << 32 - bits) - 1) >>> 0;
|
|
33354
|
-
return (ipi & mask) === (neti & mask);
|
|
33355
|
-
}
|
|
33356
|
-
function checkUnique(names, rule, what, out) {
|
|
33357
|
-
const seen = /* @__PURE__ */ new Set();
|
|
33358
|
-
for (const n of names) {
|
|
33359
|
-
if (seen.has(n)) out.push({ rule, severity: "error", detail: `duplicate ${what}: "${n}" (R-NAMES: names must be unique).` });
|
|
33360
|
-
seen.add(n);
|
|
33109
|
+
// src/planStore.ts
|
|
33110
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
33111
|
+
var PLAN_TTL_MS = parsePositiveInt(process.env.TIA_PLAN_TTL_MS, 9e5);
|
|
33112
|
+
function canonicalPlan(plan) {
|
|
33113
|
+
for (const [k, v] of Object.entries(plan)) {
|
|
33114
|
+
if (v !== null && typeof v === "object") {
|
|
33115
|
+
throw new Error(`canonicalPlan: nested value at key '${k}' is not allowed (the G3 plan must be flat)`);
|
|
33116
|
+
}
|
|
33361
33117
|
}
|
|
33118
|
+
return JSON.stringify(plan, Object.keys(plan).sort());
|
|
33362
33119
|
}
|
|
33363
|
-
|
|
33364
|
-
|
|
33365
|
-
|
|
33366
|
-
|
|
33367
|
-
|
|
33368
|
-
checkUnique(devices.map((d) => d?.name).filter(Boolean), "R-NAMES", "device", v);
|
|
33369
|
-
const subnetNames = [
|
|
33370
|
-
...spec?.network?.subnet?.name ? [spec.network.subnet.name] : [],
|
|
33371
|
-
...(Array.isArray(spec?.subnets) ? spec.subnets : []).map((s) => s?.name).filter(Boolean)
|
|
33372
|
-
];
|
|
33373
|
-
checkUnique(subnetNames, "R-NAMES", "subnet", v);
|
|
33374
|
-
checkUnique((Array.isArray(spec?.dataTypes) ? spec.dataTypes : []).map((u) => u?.name).filter(Boolean), "R-NAMES", "UDT", v);
|
|
33375
|
-
checkUnique((Array.isArray(spec?.blocks) ? spec.blocks : []).map((b) => b?.name).filter(Boolean), "R-NAMES", "block", v);
|
|
33376
|
-
const byTable = /* @__PURE__ */ new Map();
|
|
33377
|
-
for (const t of Array.isArray(spec?.tags) ? spec.tags : []) {
|
|
33378
|
-
if (!t?.table || !t?.name) continue;
|
|
33379
|
-
if (!byTable.has(t.table)) byTable.set(t.table, []);
|
|
33380
|
-
byTable.get(t.table).push(t.name);
|
|
33381
|
-
}
|
|
33382
|
-
for (const [table, names] of byTable) checkUnique(names, "R-NAMES", `tag (table ${table})`, v);
|
|
33383
|
-
for (const d of devices) {
|
|
33384
|
-
if (d?.typeIdentifier && !TYPEID_RE.test(d.typeIdentifier))
|
|
33385
|
-
v.push({ rule: "R-TYPEID", severity: "error", detail: `device "${d.name}": invalid typeIdentifier "${d.typeIdentifier}" \u2014 use OrderNumber:<MLFB>/V<fw> (slash, not ':V'). Resolve via tia_catalog.` });
|
|
33386
|
-
for (const m of Array.isArray(d?.modules) ? d.modules : []) {
|
|
33387
|
-
if (m?.order && !TYPEID_RE.test(m.order))
|
|
33388
|
-
v.push({ rule: "R-TYPEID", severity: "error", detail: `module in "${d.name}": invalid order "${m.order}" \u2014 use OrderNumber:<MLFB>/V<fw>.` });
|
|
33389
|
-
}
|
|
33120
|
+
var PlanStore = class {
|
|
33121
|
+
constructor(ttlMs = PLAN_TTL_MS, now = Date.now, prefix = "g3_") {
|
|
33122
|
+
this.ttlMs = ttlMs;
|
|
33123
|
+
this.now = now;
|
|
33124
|
+
this.prefix = prefix;
|
|
33390
33125
|
}
|
|
33391
|
-
|
|
33392
|
-
|
|
33393
|
-
|
|
33394
|
-
|
|
33395
|
-
|
|
33126
|
+
ttlMs;
|
|
33127
|
+
now;
|
|
33128
|
+
prefix;
|
|
33129
|
+
issued = /* @__PURE__ */ new Map();
|
|
33130
|
+
consumed = /* @__PURE__ */ new Set();
|
|
33131
|
+
issue(plan, fingerprint) {
|
|
33132
|
+
if (!fingerprint) throw new Error("planStore.issue: fingerprint is required");
|
|
33133
|
+
canonicalPlan(plan);
|
|
33134
|
+
const t = this.now();
|
|
33135
|
+
const entry = {
|
|
33136
|
+
token: `${this.prefix}${randomBytes2(12).toString("base64url")}`,
|
|
33137
|
+
plan: { ...plan },
|
|
33138
|
+
fingerprint,
|
|
33139
|
+
issuedAt: t,
|
|
33140
|
+
expiresAt: t + this.ttlMs
|
|
33141
|
+
};
|
|
33142
|
+
this.issued.set(entry.token, entry);
|
|
33143
|
+
return entry;
|
|
33144
|
+
}
|
|
33145
|
+
check(token, plan) {
|
|
33146
|
+
if (!token) return { ok: false, reason: "unknown" };
|
|
33147
|
+
if (this.consumed.has(token)) return { ok: false, reason: "consumed" };
|
|
33148
|
+
const entry = this.issued.get(token);
|
|
33149
|
+
if (!entry) return { ok: false, reason: "unknown" };
|
|
33150
|
+
if (this.now() > entry.expiresAt) return { ok: false, reason: "expired" };
|
|
33151
|
+
if (canonicalPlan(entry.plan) !== canonicalPlan(plan)) return { ok: false, reason: "plan_mismatch" };
|
|
33152
|
+
return { ok: true, issued: entry };
|
|
33153
|
+
}
|
|
33154
|
+
/** Marca como usado ANTES de chamar o serve: um retry após timeout do cliente é recusado (sem download duplicado). */
|
|
33155
|
+
consume(token) {
|
|
33156
|
+
this.issued.delete(token);
|
|
33157
|
+
this.consumed.add(token);
|
|
33158
|
+
}
|
|
33159
|
+
};
|
|
33160
|
+
var planStore = new PlanStore();
|
|
33161
|
+
var uploadPlanStore = new PlanStore(PLAN_TTL_MS, Date.now, "g4_");
|
|
33162
|
+
|
|
33163
|
+
// src/tools/gates.ts
|
|
33164
|
+
var GATE_INSTRUCTION = {
|
|
33165
|
+
download_approval: "A human must APPROVE the download: it STOPS the physical CPU (StopAll), OVERWRITES system data, and RESTARTS the CPU. Review the plan AND its software fingerprint (what exactly goes to the CPU). The serve auto-confirms Stop/Reset(DeleteAll, when the loaded program is replaced)/Overwrite/Consistent-blocks/Start (listed in 'configurations' after the download).",
|
|
33166
|
+
go_online: "Going ONLINE connects to the PHYSICAL PLC over the network. Confirm with a human that it is safe to connect to the target machine.",
|
|
33167
|
+
station_upload: "GATE G4: a station upload goes ONLINE to the PHYSICAL CPU and reads its hardware configuration and program into the OPEN project as a new station (it reads the CPU and does not write or stop it \u2014 observed on hardware: the CPU stayed in RUN). Confirm with a human that it is safe to connect to this machine AND that the open project shown here is a dedicated backup project \u2014 never the working project.",
|
|
33168
|
+
upload_password: "GATE G6: the CPU is read-protected. Ask the human for its read-access password \u2014 NEVER invent, guess or reuse one. The approval token is spent: call tia_upload without confirm for a fresh confirmation, then confirm:true with the new planHash and the password.",
|
|
33169
|
+
net_scan: "A network scan (accessible devices) probes the local network via the PG/PC adapter. Confirm before scanning."
|
|
33170
|
+
};
|
|
33171
|
+
var DOWNLOAD_REASON = {
|
|
33172
|
+
not_approved: "No human approval yet: the real download needs approved:true plus the planHash of a reviewed dryRun.",
|
|
33173
|
+
unknown: "No valid approval token: this planHash was not issued by this MCP process (or the MCP restarted). Approval tokens are random, single-use and live only in the MCP process that issued them.",
|
|
33174
|
+
expired: "This planHash expired (TIA_PLAN_TTL_MS). Approvals do not carry over to later sessions.",
|
|
33175
|
+
consumed: "This planHash was already used (single-use). If the previous call timed out, check the CPU and tia_job_status BEFORE anything else \u2014 the download may have happened.",
|
|
33176
|
+
plan_mismatch: "The parameters differ from the approved plan (plc / interface / options / allowUpgradeTargetDevice). The approval covers exactly the reviewed plan.",
|
|
33177
|
+
// P3 fix round 1 (#1): cause-neutral on purpose — this same reason now covers transport failures (a network or
|
|
33178
|
+
// timeout issue) AND a serve error (5xx/403/404/409 not_connected/etc.) AND an unreadable response, so the
|
|
33179
|
+
// text must not single out one cause (the old text named only "a network/timeout error", which read as if it
|
|
33180
|
+
// ruled out the other causes — deliberately NOT reusing that exact joined phrase here).
|
|
33181
|
+
outcome_unknown: "The /download call did not return a usable answer (a network or timeout issue, a serve error, or an unreadable response) AFTER the single-use token was already consumed \u2014 the token is SPENT and cannot be reused. The download may still be running on the CPU, or it may already have completed. Check the CPU state directly and tia_status (and tia_job_status if a job id is known) BEFORE requesting a new plan. Do NOT retry this same call \u2014 the token is gone and a retry cannot resume it."
|
|
33182
|
+
};
|
|
33183
|
+
function downloadResumeSteps(reason) {
|
|
33184
|
+
if (reason === "outcome_unknown") {
|
|
33185
|
+
return [
|
|
33186
|
+
"1. The approval token is SPENT and cannot be used again \u2014 do NOT call tia_download with approved:true and this same planHash.",
|
|
33187
|
+
"2. Check the CPU state directly, then tia_status (and tia_job_status if a job id is known), BEFORE anything else.",
|
|
33188
|
+
"3. Only once the real outcome is known, run tia_download with dryRun:true for a FRESH plan and a NEW token.",
|
|
33189
|
+
"4. Get a new explicit human approval before calling tia_download with approved:true again."
|
|
33190
|
+
];
|
|
33191
|
+
}
|
|
33192
|
+
if (reason === "consumed") {
|
|
33193
|
+
return [
|
|
33194
|
+
"1. This planHash was already used (single-use) \u2014 do NOT call tia_download with approved:true and this same planHash again.",
|
|
33195
|
+
"2. Check the CPU state directly, then tia_status (and tia_job_status if a job id is known), BEFORE anything else \u2014 the download may already have happened.",
|
|
33196
|
+
"3. Only once the real outcome is known, run tia_download with dryRun:true for a FRESH plan and a NEW token.",
|
|
33197
|
+
"4. Get a new explicit human approval before calling tia_download with approved:true again."
|
|
33198
|
+
];
|
|
33199
|
+
}
|
|
33200
|
+
return [
|
|
33201
|
+
"1. Run tia_download with dryRun:true to get a FRESH plan, its software fingerprint and a new single-use planHash.",
|
|
33202
|
+
"2. Show the plan + fingerprint to the line's responsible person and get an explicit yes.",
|
|
33203
|
+
"3. Re-call with approved:true and that NEW planHash, before it expires."
|
|
33204
|
+
];
|
|
33205
|
+
}
|
|
33206
|
+
var UPLOAD_REASON = {
|
|
33207
|
+
unknown: "No valid approval token: this planHash was not issued by this MCP process (or the MCP restarted). Approval tokens are random, single-use and live only in the MCP process that issued them. Call tia_upload without confirm for a fresh plan.",
|
|
33208
|
+
expired: "This planHash expired (TIA_PLAN_TTL_MS). Approvals do not carry over to later sessions.",
|
|
33209
|
+
consumed: "This planHash was already used (single-use). If the previous call timed out, check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the station may already have been added.",
|
|
33210
|
+
plan_mismatch: "The parameters differ from the approved plan (ip / connection). The approval covers exactly the reviewed plan.",
|
|
33211
|
+
outcome_unknown: "The /stations/upload call did not return a usable answer (a network or timeout issue, a serve error, or an unreadable response) AFTER the single-use token was already consumed \u2014 the token is SPENT and cannot be reused. The station may still be uploading or may already have been added as a new station. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE requesting a new plan. Do NOT repeat this call \u2014 the token is gone and a retry cannot resume it.",
|
|
33212
|
+
password_required: "The CPU is read-protected and no accepted password was provided (G6): the approval token is SPENT. Ask the human for the read-access password \u2014 never invent one \u2014 then call tia_upload without confirm for a fresh confirmation and confirm:true with the new planHash and the password.",
|
|
33213
|
+
password_rejected: "The CPU rejected the provided read-access password (G6): the approval token is SPENT. Confirm the password with the human \u2014 never invent one \u2014 then call tia_upload without confirm for a fresh confirmation and confirm:true with the new planHash and the corrected password."
|
|
33214
|
+
};
|
|
33215
|
+
function uploadResumeSteps(reason) {
|
|
33216
|
+
if (reason === "outcome_unknown") {
|
|
33217
|
+
return [
|
|
33218
|
+
"1. The approval token is SPENT and cannot be used again \u2014 do NOT call tia_upload with confirm:true and this same planHash.",
|
|
33219
|
+
"2. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else.",
|
|
33220
|
+
"3. Only once the real outcome is known, run tia_upload without confirm for a FRESH plan and a NEW token.",
|
|
33221
|
+
"4. Get a new explicit human approval before calling tia_upload with confirm:true again."
|
|
33222
|
+
];
|
|
33223
|
+
}
|
|
33224
|
+
if (reason === "password_required" || reason === "password_rejected") {
|
|
33225
|
+
return [
|
|
33226
|
+
"1. Ask the human for the CPU read-access password (G6 \u2014 never invent, guess or reuse one).",
|
|
33227
|
+
"2. Run tia_upload without confirm for a FRESH plan and a NEW token (the old token is SPENT).",
|
|
33228
|
+
"3. Show the plan to the human and get an explicit yes.",
|
|
33229
|
+
"4. Re-call with confirm:true, that NEW planHash and the human-provided password, before it expires."
|
|
33230
|
+
];
|
|
33231
|
+
}
|
|
33232
|
+
if (reason === "consumed") {
|
|
33233
|
+
return [
|
|
33234
|
+
"1. This planHash was already used (single-use) \u2014 do NOT call tia_upload with confirm:true and this same planHash again.",
|
|
33235
|
+
"2. Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the station may already have been added.",
|
|
33236
|
+
"3. Only once the real outcome is known, run tia_upload without confirm for a FRESH plan and a NEW token.",
|
|
33237
|
+
"4. Get a new explicit human approval before calling tia_upload with confirm:true again."
|
|
33238
|
+
];
|
|
33239
|
+
}
|
|
33240
|
+
if (reason) {
|
|
33241
|
+
return [
|
|
33242
|
+
"1. Run tia_upload without confirm to get a FRESH plan and a new single-use planHash.",
|
|
33243
|
+
"2. Show the plan to the human and get an explicit yes.",
|
|
33244
|
+
"3. Re-call with confirm:true and that NEW planHash, before it expires."
|
|
33245
|
+
];
|
|
33246
|
+
}
|
|
33247
|
+
return [
|
|
33248
|
+
"1. Show the plan + project to the human and get an explicit yes.",
|
|
33249
|
+
"2. Re-call tia_upload with confirm:true and this SAME planHash, before it expires."
|
|
33250
|
+
];
|
|
33251
|
+
}
|
|
33252
|
+
function goOnlineResumeSteps() {
|
|
33253
|
+
return [
|
|
33254
|
+
"1. Confirm with a human that it is safe to connect to the target machine.",
|
|
33255
|
+
"2. Re-call tia_online with confirm:true."
|
|
33256
|
+
];
|
|
33257
|
+
}
|
|
33258
|
+
function netScanResumeSteps() {
|
|
33259
|
+
return [
|
|
33260
|
+
"1. Confirm with a human that probing the local network is expected.",
|
|
33261
|
+
"2. Re-call tia_accessible_devices with confirm:true."
|
|
33262
|
+
];
|
|
33263
|
+
}
|
|
33264
|
+
var YOUMUSTDO_DOWNLOAD_CONSUMED = "This planHash was already used (single-use) \u2014 the download may already have happened. Check the CPU state directly (and tia_status / tia_job_status) BEFORE anything else; do NOT repeat the approved call. Only once the real outcome is known, run a fresh dryRun plan and get a new human approval.";
|
|
33265
|
+
var YOUMUSTDO_OUTCOME_UNKNOWN = "Check the CPU state directly (and tia_status / tia_job_status) BEFORE anything else \u2014 the approval token is ALREADY SPENT. Do NOT repeat this call: get a fresh dryRun plan and a new human approval only once the real outcome is known.";
|
|
33266
|
+
var YOUMUSTDO_UPLOAD_OUTCOME_UNKNOWN = "Check tia_devices for a NEW station (and tia_job_status if a job id is known) BEFORE anything else \u2014 the approval token is ALREADY SPENT. Do NOT repeat this call: get a fresh plan and a new human approval only once the real outcome is known.";
|
|
33267
|
+
function gateHandoff(gate, ctx) {
|
|
33268
|
+
const reasonTable = gate === "download_approval" ? DOWNLOAD_REASON : UPLOAD_REASON;
|
|
33269
|
+
const resume = gate === "download_approval" ? downloadResumeSteps(ctx.reason) : gate === "go_online" ? goOnlineResumeSteps() : gate === "net_scan" ? netScanResumeSteps() : uploadResumeSteps(ctx.reason);
|
|
33270
|
+
const youMustDo = ctx.youMustDo !== void 0 ? ctx.youMustDo : gate === "download_approval" && ctx.reason === "consumed" ? YOUMUSTDO_DOWNLOAD_CONSUMED : gate === "download_approval" && ctx.reason === "outcome_unknown" ? YOUMUSTDO_OUTCOME_UNKNOWN : gate === "station_upload" && ctx.reason === "outcome_unknown" ? YOUMUSTDO_UPLOAD_OUTCOME_UNKNOWN : GATE_INSTRUCTION[gate] ?? "Human confirmation required.";
|
|
33271
|
+
return textResult(
|
|
33272
|
+
{
|
|
33273
|
+
status: "requires_human_action",
|
|
33274
|
+
gate,
|
|
33275
|
+
canDo: ctx.plc ? `${gate} on ${ctx.plc}` : gate,
|
|
33276
|
+
youMustDo,
|
|
33277
|
+
reasonCode: ctx.reason ?? null,
|
|
33278
|
+
reason: ctx.reason ? reasonTable[ctx.reason] ?? ctx.reason : null,
|
|
33279
|
+
plan: ctx.plan ?? null,
|
|
33280
|
+
planHash: ctx.planHash ?? null,
|
|
33281
|
+
...ctx.extra ?? {},
|
|
33282
|
+
nextSteps: resume
|
|
33283
|
+
},
|
|
33284
|
+
false
|
|
33285
|
+
);
|
|
33286
|
+
}
|
|
33287
|
+
|
|
33288
|
+
// src/tools/download.ts
|
|
33289
|
+
function buildPlan(args) {
|
|
33290
|
+
return {
|
|
33291
|
+
plc: args.plc,
|
|
33292
|
+
connectionMode: args.connectionMode ?? null,
|
|
33293
|
+
pcInterfaceName: args.pcInterfaceName ?? null,
|
|
33294
|
+
pcInterfaceNumber: args.pcInterfaceNumber ?? 1,
|
|
33295
|
+
targetInterfaceName: args.targetInterfaceName ?? null,
|
|
33296
|
+
hardware: args.hardware ?? false,
|
|
33297
|
+
software: args.software ?? true,
|
|
33298
|
+
// Always boolean: absent ≡ false, so "absent" and "false" never cause plan_mismatch.
|
|
33299
|
+
allowUpgradeTargetDevice: args.allowUpgradeTargetDevice === true
|
|
33300
|
+
};
|
|
33301
|
+
}
|
|
33302
|
+
function connectionBody(args) {
|
|
33303
|
+
return jsonBody({
|
|
33304
|
+
connectionMode: args.connectionMode,
|
|
33305
|
+
pcInterfaceName: args.pcInterfaceName,
|
|
33306
|
+
pcInterfaceNumber: args.pcInterfaceNumber,
|
|
33307
|
+
targetInterfaceName: args.targetInterfaceName
|
|
33308
|
+
});
|
|
33309
|
+
}
|
|
33310
|
+
function bodyFromApprovedPlan(issued) {
|
|
33311
|
+
const plan = issued.plan;
|
|
33312
|
+
return {
|
|
33313
|
+
...jsonBody({
|
|
33314
|
+
connectionMode: plan.connectionMode,
|
|
33315
|
+
pcInterfaceName: plan.pcInterfaceName,
|
|
33316
|
+
pcInterfaceNumber: plan.pcInterfaceNumber,
|
|
33317
|
+
targetInterfaceName: plan.targetInterfaceName,
|
|
33318
|
+
hardware: plan.hardware,
|
|
33319
|
+
software: plan.software
|
|
33320
|
+
}),
|
|
33321
|
+
expectedFingerprint: issued.fingerprint,
|
|
33322
|
+
allowUpgradeTargetDevice: plan.allowUpgradeTargetDevice === true
|
|
33323
|
+
};
|
|
33324
|
+
}
|
|
33325
|
+
async function planDownload(args, plan, store) {
|
|
33326
|
+
let raw;
|
|
33327
|
+
try {
|
|
33328
|
+
raw = await tiaFetch(
|
|
33329
|
+
`/plcs/${seg(args.plc)}/download/plan`,
|
|
33330
|
+
{ method: "POST", headers: JSON_HEADERS, body: JSON.stringify(connectionBody(args)) },
|
|
33331
|
+
{ timeoutMs: SLOW_TIMEOUT_MS }
|
|
33332
|
+
);
|
|
33333
|
+
} catch (e) {
|
|
33334
|
+
const err = asTiaError(e);
|
|
33335
|
+
if (err.status === 404 && err.kind === "route_not_found") {
|
|
33336
|
+
return errorResult(
|
|
33337
|
+
new TiaApiError(
|
|
33338
|
+
"This serve does not support verified download plans (POST /plcs/{plc}/download/plan \u2192 404). Update the TIAOpenness app to v1.6.0 or later. Nothing was downloaded.",
|
|
33339
|
+
{ status: 404, kind: "serve_too_old" }
|
|
33340
|
+
)
|
|
33341
|
+
);
|
|
33342
|
+
}
|
|
33343
|
+
return errorResult(err);
|
|
33344
|
+
}
|
|
33345
|
+
const data = isObject2(raw) ? raw : {};
|
|
33346
|
+
const compile = { state: data.compile?.state ?? null, errors: data.compile?.errors ?? null, warnings: data.compile?.warnings ?? null };
|
|
33347
|
+
const fingerprint = typeof data.fingerprint === "string" ? data.fingerprint : "";
|
|
33348
|
+
const hasFingerprint = fingerprint.trim().length > 0;
|
|
33349
|
+
if (data.ready !== true || !hasFingerprint) {
|
|
33350
|
+
const blockers = Array.isArray(data.blockers) ? [...data.blockers] : [];
|
|
33351
|
+
if (!isObject2(raw)) blockers.push("invalid_plan_response");
|
|
33352
|
+
const fingerprintMissing = data.ready === true && !hasFingerprint;
|
|
33353
|
+
if (fingerprintMissing) blockers.push("fingerprint_missing");
|
|
33354
|
+
return textResult(
|
|
33355
|
+
{
|
|
33356
|
+
dryRun: true,
|
|
33357
|
+
status: "plan_blocked",
|
|
33358
|
+
gate: "download_approval",
|
|
33359
|
+
plan,
|
|
33360
|
+
blockers,
|
|
33361
|
+
compile,
|
|
33362
|
+
connection: data.connection ?? null,
|
|
33363
|
+
note: fingerprintMissing ? "NO approval token was issued: serve reported ready but returned no software fingerprint, and this MCP never approves a download it cannot verify. Update the TIAOpenness app (serve) to v1.6.0 or later and run dryRun again." : "NO approval token was issued. Fix the blockers (compile errors \u2192 tia_compile; interface \u2192 tia_pg_interfaces) and run dryRun again."
|
|
33364
|
+
},
|
|
33365
|
+
false
|
|
33366
|
+
);
|
|
33367
|
+
}
|
|
33368
|
+
const issued = store.issue(plan, fingerprint);
|
|
33369
|
+
return textResult(
|
|
33370
|
+
{
|
|
33371
|
+
dryRun: true,
|
|
33372
|
+
status: "plan_ok",
|
|
33373
|
+
gate: "download_approval",
|
|
33374
|
+
plan,
|
|
33375
|
+
planHash: issued.token,
|
|
33376
|
+
expiresAt: new Date(issued.expiresAt).toISOString(),
|
|
33377
|
+
fingerprint,
|
|
33378
|
+
fingerprintItems: data.fingerprintItems ?? [],
|
|
33379
|
+
coverage: data.coverage ?? null,
|
|
33380
|
+
warnings: data.warnings ?? [],
|
|
33381
|
+
compile,
|
|
33382
|
+
connection: data.connection ?? null,
|
|
33383
|
+
loadPreview: {
|
|
33384
|
+
// Amendment #4: mirrors EVERY real auto-confirmation of PlcDeployService.cs (PreDownload/PostDownload),
|
|
33385
|
+
// not just the 3 most obvious — including ones that don't stop/restart the CPU but still change its content.
|
|
33386
|
+
willConfirm: [
|
|
33387
|
+
"StopModules = StopAll \u2014 STOPS the physical CPU (pre phase)",
|
|
33388
|
+
"ResetModule = DeleteAll \u2014 if the CPU already holds a DIFFERENT program, it is deleted before this one loads (pre and/or post phase)",
|
|
33389
|
+
"OverwriteSystemData = Overwrite \u2014 overwrites system data (pre phase for a hardware download, and again in the post phase)",
|
|
33390
|
+
"ConsistentBlocksDownload = ConsistentDownload \u2014 downloads all blocks consistently (pre phase)",
|
|
33391
|
+
"AlarmTextLibrariesDownload = ConsistentDownload \u2014 downloads alarm text libraries consistently (pre phase)",
|
|
33392
|
+
"StartModules = StartModule \u2014 RESTARTS the CPU at the end (post phase)",
|
|
33393
|
+
plan.allowUpgradeTargetDevice ? "UpgradeTargetDevice = Checked \u2014 upgrades the target device (explicitly allowed)" : "UpgradeTargetDevice = NOT confirmed unless allowUpgradeTargetDevice:true \u2014 if the CPU requires it the download is refused, but the CPU may already have been stopped.",
|
|
33394
|
+
"Any OTHER configuration dialog serve does not recognize is left UNTOUCHED, which can abort the load."
|
|
33395
|
+
],
|
|
33396
|
+
note: "Openness has no preview-without-downloading; these are the selections serve's delegates will make. The real download returns 'configurations' with what was actually confirmed."
|
|
33397
|
+
},
|
|
33398
|
+
note: "Plan verified by serve. NOTHING was downloaded. After a human approves THIS plan and fingerprint, call tia_download with approved:true and this planHash (single-use, expires at expiresAt)."
|
|
33399
|
+
},
|
|
33400
|
+
false
|
|
33401
|
+
);
|
|
33402
|
+
}
|
|
33403
|
+
async function downloadFlow(args, store = planStore) {
|
|
33404
|
+
const plan = buildPlan(args);
|
|
33405
|
+
if (args.dryRun) return planDownload(args, plan, store);
|
|
33406
|
+
if (args.approved !== true) return gateHandoff("download_approval", { plc: args.plc, plan, reason: "not_approved" });
|
|
33407
|
+
const check2 = store.check(args.planHash, plan);
|
|
33408
|
+
if (!check2.ok) return gateHandoff("download_approval", { plc: args.plc, plan, reason: check2.reason });
|
|
33409
|
+
store.consume(check2.issued.token);
|
|
33410
|
+
let raw;
|
|
33411
|
+
try {
|
|
33412
|
+
raw = await tiaFetch(
|
|
33413
|
+
`/plcs/${seg(args.plc)}/download`,
|
|
33414
|
+
{ method: "POST", headers: JSON_HEADERS, body: JSON.stringify(bodyFromApprovedPlan(check2.issued)) },
|
|
33415
|
+
{ timeoutMs: 18e4 }
|
|
33416
|
+
);
|
|
33417
|
+
} catch (e) {
|
|
33418
|
+
const err = asTiaError(e);
|
|
33419
|
+
if (isInstallingError(err))
|
|
33420
|
+
return errorResult(
|
|
33421
|
+
err,
|
|
33422
|
+
"Serve is installing a TIAOpenness app update: nothing was downloaded (the call was refused BEFORE running, so no CPU check is needed). The single-use approval token is already spent \u2014 after the update finishes, run a fresh dryRun plan and get a new human approval. There is no background job for this call."
|
|
33423
|
+
);
|
|
33424
|
+
const knownRefusal = err.status === 409 && (err.kind === "plan_stale" || err.kind === "upgrade_target_device_required");
|
|
33425
|
+
if (knownRefusal) return errorResult(err);
|
|
33426
|
+
const isTransport = err.kind === "timeout" || err.kind === "connection_refused";
|
|
33427
|
+
return gateHandoff("download_approval", {
|
|
33428
|
+
plc: args.plc,
|
|
33429
|
+
plan,
|
|
33430
|
+
reason: "outcome_unknown",
|
|
33431
|
+
extra: {
|
|
33432
|
+
approvedPlanHash: check2.issued.token,
|
|
33433
|
+
...isTransport ? { transportKind: err.kind, transportDiagnostics: err.message } : {
|
|
33434
|
+
serveErrorStatus: err.status,
|
|
33435
|
+
serveErrorKind: err.kind,
|
|
33436
|
+
serveErrorType: err.type ?? null,
|
|
33437
|
+
serveErrorInner: err.inner ?? null,
|
|
33438
|
+
serveErrorDetails: err.details ?? null,
|
|
33439
|
+
serveErrorDiagnostics: err.message
|
|
33440
|
+
}
|
|
33441
|
+
}
|
|
33442
|
+
});
|
|
33443
|
+
}
|
|
33444
|
+
const data = isObject2(raw) ? raw : {};
|
|
33445
|
+
const state = typeof data.state === "string" ? data.state : null;
|
|
33446
|
+
const errors = typeof data.errors === "number" ? data.errors : null;
|
|
33447
|
+
const stateLower = state !== null ? state.toLowerCase() : null;
|
|
33448
|
+
const cleanErrors = errors === 0;
|
|
33449
|
+
const loadOutcome = stateLower === "success" && cleanErrors ? "success" : (stateLower === "warning" || stateLower === "information") && cleanErrors ? "success_with_warnings" : "failed";
|
|
33450
|
+
const downloaded = loadOutcome !== "failed";
|
|
33451
|
+
const fingerprintVerified = data.fingerprintVerified === true;
|
|
33452
|
+
const warnings = [];
|
|
33453
|
+
if (loadOutcome === "failed") {
|
|
33454
|
+
warnings.push(
|
|
33455
|
+
`serve answered the download call, but did not report a clean load (state='${state ?? "unknown"}', errors=${errors ?? "unknown"}). Check 'result.messages' for what happened \u2014 the CPU may be in a partial or unexpected state. Do not treat this as a confirmed successful deploy.`
|
|
33456
|
+
);
|
|
33457
|
+
}
|
|
33458
|
+
if (!fingerprintVerified) {
|
|
33459
|
+
warnings.push(
|
|
33460
|
+
"serve did NOT confirm the software fingerprint check (fingerprintVerified is not true): it is NOT proven that the CPU received exactly the approved software. The serve may be older than v1.6.0 and have ignored expectedFingerprint. Tell the human and check the CPU before relying on it."
|
|
33461
|
+
);
|
|
33462
|
+
}
|
|
33463
|
+
return textResult({
|
|
33464
|
+
downloaded,
|
|
33465
|
+
loadOutcome,
|
|
33466
|
+
approvedPlanHash: check2.issued.token,
|
|
33467
|
+
fingerprint: check2.issued.fingerprint,
|
|
33468
|
+
fingerprintVerified,
|
|
33469
|
+
state,
|
|
33470
|
+
errors,
|
|
33471
|
+
...loadOutcome === "success_with_warnings" ? { note: "The load completed with warnings \u2014 read result.messages." } : {},
|
|
33472
|
+
...warnings.length > 0 ? { warning: warnings.join(" ") } : {},
|
|
33473
|
+
result: raw ?? null
|
|
33474
|
+
});
|
|
33475
|
+
}
|
|
33476
|
+
function registerDownloadTools(server2) {
|
|
33477
|
+
server2.registerTool(
|
|
33478
|
+
"tia_download",
|
|
33479
|
+
{
|
|
33480
|
+
title: "TIA \u2014 download to the PLC (GATE G3)",
|
|
33481
|
+
description: "Downloads hardware/software to the PHYSICAL CPU (STOPS and RESTARTS the CPU). GATE G3: does NOT download without human approval. dryRun:true asks serve for a VERIFIED plan (clean compile, PG/PC interface found, software fingerprint) and returns a single-use planHash that expires (TIA_PLAN_TTL_MS, default 15 min). After a human approves that plan, call with approved:true and the SAME planHash; serve re-checks the fingerprint inside the download and refuses (plan_stale) if the project changed. Pick connectionMode/pcInterfaceName/targetInterfaceName with tia_pg_interfaces (no scan). Requires app \u2265 v1.6.0. Maps to POST /plcs/{plc}/download/plan and POST /plcs/{plc}/download. " + LONG_OPERATION_NOTE,
|
|
33482
|
+
inputSchema: {
|
|
33483
|
+
plc: external_exports.string().describe("PLC name"),
|
|
33484
|
+
connectionMode: external_exports.string().optional().describe(`connection mode (e.g., "PN/IE") \u2014 TIA's LOCALIZED name`),
|
|
33485
|
+
pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized name)"),
|
|
33486
|
+
pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
|
|
33487
|
+
targetInterfaceName: external_exports.string().optional().describe('target CPU interface (e.g., "1 X1")'),
|
|
33488
|
+
hardware: external_exports.boolean().optional().describe("download hardware (default false)"),
|
|
33489
|
+
software: external_exports.boolean().optional().describe("download software (default true)"),
|
|
33490
|
+
allowUpgradeTargetDevice: external_exports.boolean().optional().describe("confirm TIA's 'upgrade the target device' check (default false). Part of the approved plan \u2014 changing it needs a new dryRun + approval"),
|
|
33491
|
+
dryRun: external_exports.boolean().optional().describe("Gd11: returns the plan + planHash WITHOUT downloading"),
|
|
33492
|
+
approved: external_exports.boolean().optional().describe("G3: only true after explicit HUMAN APPROVAL"),
|
|
33493
|
+
planHash: external_exports.string().optional().describe("G3: the single-use approval token returned by dryRun (issued only by this MCP process; expires)")
|
|
33494
|
+
}
|
|
33495
|
+
},
|
|
33496
|
+
// ENTIRE handler in the job and ENTIRE args in the key (planHash/approved/connection included): a busy returns
|
|
33497
|
+
// BEFORE downloadFlow runs, so the single-use token is only consumed inside the job, before the serve call.
|
|
33498
|
+
async (args) => jobs.run("tia_download", args, () => downloadFlow(args))
|
|
33499
|
+
);
|
|
33500
|
+
}
|
|
33501
|
+
|
|
33502
|
+
// src/tools/upload.ts
|
|
33503
|
+
var UPLOAD_TIMEOUT_MS = 24e4;
|
|
33504
|
+
function buildUploadPlan(args) {
|
|
33505
|
+
return {
|
|
33506
|
+
ip: args.ip,
|
|
33507
|
+
connectionMode: args.connectionMode ?? null,
|
|
33508
|
+
pcInterfaceName: args.pcInterfaceName ?? null,
|
|
33509
|
+
pcInterfaceNumber: args.pcInterfaceNumber ?? 1
|
|
33510
|
+
};
|
|
33511
|
+
}
|
|
33512
|
+
function uploadBodyFromApprovedPlan(issued, password) {
|
|
33513
|
+
const plan = issued.plan;
|
|
33514
|
+
return {
|
|
33515
|
+
...jsonBody({
|
|
33516
|
+
connectionMode: plan.connectionMode,
|
|
33517
|
+
pcInterfaceName: plan.pcInterfaceName,
|
|
33518
|
+
pcInterfaceNumber: plan.pcInterfaceNumber,
|
|
33519
|
+
ip: plan.ip
|
|
33520
|
+
}),
|
|
33521
|
+
expectedProjectPath: issued.fingerprint,
|
|
33522
|
+
...password !== void 0 ? { password } : {}
|
|
33523
|
+
};
|
|
33524
|
+
}
|
|
33525
|
+
async function planUpload(args, plan, store) {
|
|
33526
|
+
let raw;
|
|
33527
|
+
try {
|
|
33528
|
+
raw = await tiaFetch(
|
|
33529
|
+
"/stations/upload/plan",
|
|
33530
|
+
{
|
|
33531
|
+
method: "POST",
|
|
33532
|
+
headers: JSON_HEADERS,
|
|
33533
|
+
body: JSON.stringify(
|
|
33534
|
+
jsonBody({
|
|
33535
|
+
connectionMode: args.connectionMode,
|
|
33536
|
+
pcInterfaceName: args.pcInterfaceName,
|
|
33537
|
+
pcInterfaceNumber: args.pcInterfaceNumber,
|
|
33538
|
+
ip: args.ip
|
|
33539
|
+
})
|
|
33540
|
+
)
|
|
33541
|
+
},
|
|
33542
|
+
{ timeoutMs: SLOW_TIMEOUT_MS }
|
|
33543
|
+
);
|
|
33544
|
+
} catch (e) {
|
|
33545
|
+
const err = asTiaError(e);
|
|
33546
|
+
if (err.status === 404 && err.kind === "route_not_found") {
|
|
33547
|
+
return errorResult(
|
|
33548
|
+
new TiaApiError(
|
|
33549
|
+
"This serve does not support station-upload plans (POST /stations/upload/plan \u2192 404). Update the TIAOpenness app to v1.6.0 or later. Nothing was uploaded.",
|
|
33550
|
+
{ status: 404, kind: "serve_too_old" }
|
|
33551
|
+
),
|
|
33552
|
+
"Update the TIAOpenness app to v1.6.0 or later. Nothing was uploaded."
|
|
33553
|
+
);
|
|
33554
|
+
}
|
|
33555
|
+
return errorResult(err);
|
|
33556
|
+
}
|
|
33557
|
+
const data = isObject2(raw) ? raw : {};
|
|
33558
|
+
const project = isObject2(data.project) ? data.project : {};
|
|
33559
|
+
const projectPath = typeof project.path === "string" ? project.path : "";
|
|
33560
|
+
const projectName = typeof project.name === "string" ? project.name : "(unnamed)";
|
|
33561
|
+
const devices = Array.isArray(data.devices) ? [...data.devices] : [];
|
|
33562
|
+
if (data.ready !== true || projectPath.trim().length === 0) {
|
|
33563
|
+
const blockers = Array.isArray(data.blockers) ? [...data.blockers] : [];
|
|
33564
|
+
if (!isObject2(raw)) blockers.push("invalid_plan_response");
|
|
33565
|
+
if (data.ready === true) blockers.push("project_path_missing");
|
|
33566
|
+
return textResult(
|
|
33567
|
+
{
|
|
33568
|
+
status: "plan_blocked",
|
|
33569
|
+
gate: "station_upload",
|
|
33570
|
+
plan,
|
|
33571
|
+
blockers,
|
|
33572
|
+
connection: data.connection ?? null,
|
|
33573
|
+
project: data.project ?? null,
|
|
33574
|
+
devices,
|
|
33575
|
+
note: typeof data.note === "string" ? data.note : null
|
|
33576
|
+
},
|
|
33577
|
+
false
|
|
33578
|
+
);
|
|
33579
|
+
}
|
|
33580
|
+
const issued = store.issue(plan, projectPath);
|
|
33581
|
+
const warning = devices.length > 0 ? `The open project already has ${devices.length} device(s); a backup belongs in a dedicated EMPTY project (tia.backup).` : void 0;
|
|
33582
|
+
const youMustDo = `GATE G4: upload (read) the hardware configuration and program of the PHYSICAL CPU at ${String(plan.ip)} into the OPEN project "${projectName}" (${projectPath}), which currently holds ${devices.length} device(s) \u2014 it reads the CPU and does not write it. Confirm with a human that it is safe to connect to this machine AND that this is a dedicated backup project, never the working project. After an explicit yes, re-call tia_upload with confirm:true and this planHash.`;
|
|
33583
|
+
return gateHandoff("station_upload", {
|
|
33584
|
+
plan,
|
|
33585
|
+
planHash: issued.token,
|
|
33586
|
+
youMustDo,
|
|
33587
|
+
extra: {
|
|
33588
|
+
expiresAt: new Date(issued.expiresAt).toISOString(),
|
|
33589
|
+
project: data.project,
|
|
33590
|
+
// no `?? null`: the plan_blocked guard above only lets a project object with a path through
|
|
33591
|
+
devices,
|
|
33592
|
+
connection: data.connection ?? null,
|
|
33593
|
+
...warning !== void 0 ? { warning } : {}
|
|
33594
|
+
}
|
|
33595
|
+
});
|
|
33596
|
+
}
|
|
33597
|
+
async function uploadFlow(args, store = uploadPlanStore) {
|
|
33598
|
+
const plan = buildUploadPlan(args);
|
|
33599
|
+
if (args.confirm !== true) return planUpload(args, plan, store);
|
|
33600
|
+
const check2 = store.check(args.planHash, plan);
|
|
33601
|
+
if (!check2.ok) return gateHandoff("station_upload", { plan, reason: check2.reason });
|
|
33602
|
+
store.consume(check2.issued.token);
|
|
33603
|
+
let raw;
|
|
33604
|
+
try {
|
|
33605
|
+
raw = await tiaFetch(
|
|
33606
|
+
"/stations/upload",
|
|
33607
|
+
{ method: "POST", headers: JSON_HEADERS, body: JSON.stringify(uploadBodyFromApprovedPlan(check2.issued, args.password)) },
|
|
33608
|
+
{ timeoutMs: UPLOAD_TIMEOUT_MS }
|
|
33609
|
+
);
|
|
33610
|
+
} catch (e) {
|
|
33611
|
+
const err = asTiaError(e);
|
|
33612
|
+
if (isInstallingError(err))
|
|
33613
|
+
return errorResult(
|
|
33614
|
+
err,
|
|
33615
|
+
"Serve is installing a TIAOpenness app update: nothing was uploaded (the call was refused BEFORE going online, so no station check is needed). The single-use approval token is already spent \u2014 after the update finishes, run a fresh plan and get a new human approval. There is no background job for this call."
|
|
33616
|
+
);
|
|
33617
|
+
const knownRefusal = err.status === 400 || err.status === 409 && (err.kind === "project_changed" || err.kind === "upload_provider_unavailable" || err.kind === "connection_unresolved");
|
|
33618
|
+
if (knownRefusal) {
|
|
33619
|
+
return errorResult(
|
|
33620
|
+
new TiaApiError(`${err.message} The approval token is SPENT (single-use) and cannot be reused; nothing was uploaded.`, {
|
|
33621
|
+
status: err.status,
|
|
33622
|
+
kind: err.kind,
|
|
33623
|
+
type: err.type,
|
|
33624
|
+
inner: err.inner,
|
|
33625
|
+
details: err.details
|
|
33626
|
+
})
|
|
33627
|
+
);
|
|
33628
|
+
}
|
|
33629
|
+
if (err.status === 409 && (err.kind === "upload_password_required" || err.kind === "upload_password_rejected")) {
|
|
33630
|
+
const det = isObject2(err.details) ? err.details : {};
|
|
33631
|
+
return gateHandoff("upload_password", {
|
|
33632
|
+
plan,
|
|
33633
|
+
reason: err.kind === "upload_password_required" ? "password_required" : "password_rejected",
|
|
33634
|
+
extra: { configurations: det.configurations ?? null }
|
|
33635
|
+
});
|
|
33636
|
+
}
|
|
33637
|
+
const isTransport = err.kind === "timeout" || err.kind === "connection_refused";
|
|
33638
|
+
return gateHandoff("station_upload", {
|
|
33639
|
+
plan,
|
|
33640
|
+
reason: "outcome_unknown",
|
|
33641
|
+
extra: {
|
|
33642
|
+
approvedPlanHash: check2.issued.token,
|
|
33643
|
+
...isTransport ? { transportKind: err.kind, transportDiagnostics: err.message } : {
|
|
33644
|
+
serveErrorStatus: err.status,
|
|
33645
|
+
serveErrorKind: err.kind,
|
|
33646
|
+
serveErrorType: err.type ?? null,
|
|
33647
|
+
serveErrorInner: err.inner ?? null,
|
|
33648
|
+
serveErrorDetails: err.details ?? null,
|
|
33649
|
+
serveErrorDiagnostics: err.message
|
|
33650
|
+
}
|
|
33651
|
+
}
|
|
33652
|
+
});
|
|
33653
|
+
}
|
|
33654
|
+
if (!isObject2(raw)) {
|
|
33655
|
+
return gateHandoff("station_upload", {
|
|
33656
|
+
plan,
|
|
33657
|
+
reason: "outcome_unknown",
|
|
33658
|
+
extra: {
|
|
33659
|
+
approvedPlanHash: check2.issued.token,
|
|
33660
|
+
serveErrorStatus: null,
|
|
33661
|
+
serveErrorKind: null,
|
|
33662
|
+
serveErrorType: null,
|
|
33663
|
+
serveErrorInner: null,
|
|
33664
|
+
serveErrorDetails: null,
|
|
33665
|
+
serveErrorDiagnostics: "POST /stations/upload answered 2xx with an empty or non-JSON body AFTER the single-use token was already consumed \u2014 the upload outcome is unknown."
|
|
33666
|
+
}
|
|
33667
|
+
});
|
|
33668
|
+
}
|
|
33669
|
+
const data = raw;
|
|
33670
|
+
const state = typeof data.state === "string" ? data.state : null;
|
|
33671
|
+
const errors = typeof data.errors === "number" ? data.errors : null;
|
|
33672
|
+
const stateLower = state !== null ? state.toLowerCase() : null;
|
|
33673
|
+
const cleanErrors = errors === 0;
|
|
33674
|
+
const uploadOutcome = stateLower === "success" && cleanErrors ? "success" : (stateLower === "warning" || stateLower === "information") && cleanErrors ? "success_with_warnings" : "failed";
|
|
33675
|
+
const uploaded = uploadOutcome !== "failed";
|
|
33676
|
+
const createdDevices = Array.isArray(data.createdDevices) ? data.createdDevices : [];
|
|
33677
|
+
const warnings = [];
|
|
33678
|
+
if (uploadOutcome === "failed") {
|
|
33679
|
+
warnings.push(
|
|
33680
|
+
`serve answered the upload call, but did not report a clean upload (state='${state ?? "unknown"}', errors=${errors ?? "unknown"}). Do not treat this as a backup \u2014 read result.messages for what happened; the project may hold a partial station.`
|
|
33681
|
+
);
|
|
33682
|
+
}
|
|
33683
|
+
if (uploaded && createdDevices.length === 0) {
|
|
33684
|
+
warnings.push("serve reported success but no new device appeared; check tia_devices.");
|
|
33685
|
+
}
|
|
33686
|
+
return textResult({
|
|
33687
|
+
uploaded,
|
|
33688
|
+
uploadOutcome,
|
|
33689
|
+
approvedPlanHash: check2.issued.token,
|
|
33690
|
+
projectPath: check2.issued.fingerprint,
|
|
33691
|
+
state,
|
|
33692
|
+
errors,
|
|
33693
|
+
uploadedStation: typeof data.uploadedStation === "string" ? data.uploadedStation : null,
|
|
33694
|
+
createdDevices,
|
|
33695
|
+
configurations: data.configurations ?? null,
|
|
33696
|
+
...warnings.length > 0 ? { warning: warnings.join(" ") } : {},
|
|
33697
|
+
nextSteps: [
|
|
33698
|
+
"1. Save the project with tia_project_save.",
|
|
33699
|
+
"2. Archive it with tia_project_archive \u2014 the .zap21 is the backup (the archive name must carry the .zap21 extension).",
|
|
33700
|
+
"3. Optionally compile the new PLC with tia_compile (a GUI-gated license message is not a backup failure)."
|
|
33701
|
+
],
|
|
33702
|
+
result: raw
|
|
33703
|
+
// no `?? null`: the outcome_unknown guard above only lets an object body through
|
|
33704
|
+
});
|
|
33705
|
+
}
|
|
33706
|
+
function registerUploadTools(server2) {
|
|
33707
|
+
server2.registerTool(
|
|
33708
|
+
"tia_upload",
|
|
33709
|
+
{
|
|
33710
|
+
title: "TIA \u2014 station upload (GATE G4)",
|
|
33711
|
+
description: "Station upload (GATE G4): goes ONLINE to the PHYSICAL CPU at `ip` and reads its hardware configuration and program into the OPEN project as a new station \u2014 it reads the CPU and does not write or stop it (observed on hardware: the CPU stayed in RUN). Back up into a dedicated EMPTY project, never the working project (skill tia.backup). Without confirm it asks serve for an upload plan (PG/PC interface resolved, the open project's path and devices \u2014 no network access) and returns a single-use planHash bound to that project; after a human confirms, call again with confirm:true and that planHash. A read-protected CPU needs its read-access password from a HUMAN (G6 \u2014 never invented). Needs the deploy license scope (Basic \u2192 403 scope_required) and app \u2265 v1.6.0. Maps to POST /stations/upload/plan and POST /stations/upload. " + LONG_OPERATION_NOTE,
|
|
33712
|
+
inputSchema: {
|
|
33713
|
+
ip: external_exports.string().describe("IPv4 of the PHYSICAL CPU"),
|
|
33714
|
+
connectionMode: external_exports.string().optional().describe(`connection mode (e.g., "PN/IE") \u2014 TIA's LOCALIZED name`),
|
|
33715
|
+
pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized name)"),
|
|
33716
|
+
pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
|
|
33717
|
+
confirm: external_exports.boolean().optional().describe("G4: true only after explicit HUMAN confirmation"),
|
|
33718
|
+
planHash: external_exports.string().optional().describe("G4: the single-use approval token returned by the unconfirmed call (issued only by this MCP process; expires)"),
|
|
33719
|
+
password: external_exports.string().optional().describe("G6: the CPU read-access password provided by a HUMAN, never invented")
|
|
33720
|
+
}
|
|
33721
|
+
},
|
|
33722
|
+
// ENTIRE handler in the job and ENTIRE args in the key (like tia_download): a busy returns BEFORE uploadFlow
|
|
33723
|
+
// runs, so the single-use token is only consumed inside the job, before the serve call. The key is a
|
|
33724
|
+
// sha256 hash — the password never appears in plain text in the job state.
|
|
33725
|
+
async (args) => jobs.run("tia_upload", args, () => uploadFlow(args))
|
|
33726
|
+
);
|
|
33727
|
+
}
|
|
33728
|
+
|
|
33729
|
+
// src/tools/online.ts
|
|
33730
|
+
function registerOnlineTools(server2) {
|
|
33731
|
+
server2.registerTool(
|
|
33732
|
+
"tia_connection_create",
|
|
33733
|
+
{
|
|
33734
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33735
|
+
title: "TIA \u2014 create S7 connection",
|
|
33736
|
+
description: (
|
|
33737
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33738
|
+
"Creates an S7 connection between two devices. Guard G2: requires \u22652 CONSISTENT CPUs (compile clean) \u2014 a bare CPU fails. On error, the envelope's 'details' carries the diagnostic (or use tia_connections_diagnose). Maps to POST /connections. M-off."
|
|
33739
|
+
),
|
|
33740
|
+
inputSchema: {
|
|
33741
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33742
|
+
localDevice: external_exports.string().describe("local device"),
|
|
33743
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33744
|
+
partnerDevice: external_exports.string().describe("partner device")
|
|
33745
|
+
}
|
|
33746
|
+
},
|
|
33747
|
+
async ({ localDevice, partnerDevice }) => send("POST", "/connections", jsonBody({ localDevice, partnerDevice }))
|
|
33748
|
+
);
|
|
33749
|
+
server2.registerTool(
|
|
33750
|
+
"tia_online",
|
|
33751
|
+
{
|
|
33752
|
+
title: "TIA \u2014 go online (GATE G4)",
|
|
33753
|
+
description: "Connects ONLINE to the physical PLC. GATE G4: pass confirm:true (after a human confirms it's safe to connect to the target machine); without it, returns a handoff. Maps to POST /plcs/{plc}/online.",
|
|
33754
|
+
inputSchema: {
|
|
33755
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33756
|
+
plc: external_exports.string().describe("PLC name"),
|
|
33757
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33758
|
+
connectionMode: external_exports.string().optional().describe("connection mode (localized)"),
|
|
33759
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33760
|
+
pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized)"),
|
|
33761
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33762
|
+
pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
|
|
33763
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33764
|
+
targetInterfaceName: external_exports.string().optional().describe("target CPU interface"),
|
|
33765
|
+
confirm: external_exports.boolean().optional().describe("G4: true after human confirmation")
|
|
33766
|
+
}
|
|
33767
|
+
},
|
|
33768
|
+
async ({ plc, connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName, confirm }) => {
|
|
33769
|
+
if (confirm !== true) return gateHandoff("go_online", { plc, plan: { plc, connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName } });
|
|
33770
|
+
return send("POST", `/plcs/${seg(plc)}/online`, jsonBody({ connectionMode, pcInterfaceName, pcInterfaceNumber, targetInterfaceName }), 6e4);
|
|
33771
|
+
}
|
|
33772
|
+
);
|
|
33773
|
+
server2.registerTool(
|
|
33774
|
+
"tia_offline",
|
|
33775
|
+
{
|
|
33776
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33777
|
+
title: "TIA \u2014 go offline",
|
|
33778
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33779
|
+
description: "Disconnects the PLC from online mode. Maps to POST /plcs/{plc}/offline.",
|
|
33780
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33781
|
+
inputSchema: { plc: external_exports.string().describe("PLC name") }
|
|
33782
|
+
},
|
|
33783
|
+
async ({ plc }) => send("POST", `/plcs/${seg(plc)}/offline`)
|
|
33784
|
+
);
|
|
33785
|
+
server2.registerTool(
|
|
33786
|
+
"tia_online_state",
|
|
33787
|
+
{
|
|
33788
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33789
|
+
title: "TIA \u2014 online state",
|
|
33790
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33791
|
+
description: "Reads the PLC's online state (online/offline). Read-only (class R). Maps to GET /plcs/{plc}/online/state.",
|
|
33792
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33793
|
+
inputSchema: { plc: external_exports.string().describe("PLC name") }
|
|
33794
|
+
},
|
|
33795
|
+
async ({ plc }) => getResult(`/plcs/${seg(plc)}/online/state`)
|
|
33796
|
+
);
|
|
33797
|
+
server2.registerTool(
|
|
33798
|
+
"tia_accessible_devices",
|
|
33799
|
+
{
|
|
33800
|
+
title: "TIA \u2014 accessible devices (GATE G7)",
|
|
33801
|
+
description: "Scans the network via the PG/PC adapter and lists accessible devices \u2014 to see which devices answer on the network \u2014 to discover mode/adapter/interface names WITHOUT a scan, use tia_pg_interfaces. GATE G7 (net scan): pass confirm:true. Maps to POST /plcs/{plc}/online/accessibledevices.",
|
|
33802
|
+
inputSchema: {
|
|
33803
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33804
|
+
plc: external_exports.string().describe("PLC name"),
|
|
33805
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33806
|
+
connectionMode: external_exports.string().optional().describe("connection mode (localized)"),
|
|
33807
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33808
|
+
pcInterfaceName: external_exports.string().optional().describe("PG/PC adapter (localized)"),
|
|
33809
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33810
|
+
pcInterfaceNumber: external_exports.number().int().optional().describe("adapter number (default 1)"),
|
|
33811
|
+
confirm: external_exports.boolean().optional().describe("G7: true after human confirmation")
|
|
33812
|
+
}
|
|
33813
|
+
},
|
|
33814
|
+
async ({ plc, connectionMode, pcInterfaceName, pcInterfaceNumber, confirm }) => {
|
|
33815
|
+
if (confirm !== true) return gateHandoff("net_scan", { plc, plan: { plc, connectionMode, pcInterfaceName, pcInterfaceNumber } });
|
|
33816
|
+
return send("POST", `/plcs/${seg(plc)}/online/accessibledevices`, jsonBody({ connectionMode, pcInterfaceName, pcInterfaceNumber }), 6e4);
|
|
33817
|
+
}
|
|
33818
|
+
);
|
|
33819
|
+
server2.registerTool(
|
|
33820
|
+
"tia_mastersecret_set",
|
|
33821
|
+
{
|
|
33822
|
+
title: "TIA \u2014 set master secret (GATE G6)",
|
|
33823
|
+
description: "Sets the master secret (password) of a protected CPU, before online/download. GATE G6: the password comes from a HUMAN (or a credential vault) \u2014 the AI NEVER makes it up. (Note: P3.7 questions sending the secret over HTTP in plain text; prefer local entry on the host.) Maps to POST /plcs/{plc}/online/mastersecret.",
|
|
33824
|
+
inputSchema: {
|
|
33825
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33826
|
+
plc: external_exports.string().describe("PLC name"),
|
|
33827
|
+
password: external_exports.string().describe("master secret provided by a human (NEVER made up by the AI)")
|
|
33828
|
+
}
|
|
33829
|
+
},
|
|
33830
|
+
async ({ plc, password }) => send("POST", `/plcs/${seg(plc)}/online/mastersecret`, jsonBody({ password }))
|
|
33831
|
+
);
|
|
33832
|
+
server2.registerTool(
|
|
33833
|
+
"tia_mastersecret_reset",
|
|
33834
|
+
{
|
|
33835
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33836
|
+
title: "TIA \u2014 reset master secret",
|
|
33837
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33838
|
+
description: "Removes/resets the CPU's master secret. Maps to DELETE /plcs/{plc}/online/mastersecret.",
|
|
33839
|
+
// Stryker disable next-line StringLiteral: handoff prose, facts are tested
|
|
33840
|
+
inputSchema: { plc: external_exports.string().describe("PLC name") }
|
|
33841
|
+
},
|
|
33842
|
+
async ({ plc }) => send("DELETE", `/plcs/${seg(plc)}/online/mastersecret`)
|
|
33843
|
+
);
|
|
33844
|
+
}
|
|
33845
|
+
|
|
33846
|
+
// src/tools/spec.ts
|
|
33847
|
+
var TYPEID_RE = /^OrderNumber:.+\/V[0-9]+\.[0-9]+$/;
|
|
33848
|
+
function ipToInt(ip) {
|
|
33849
|
+
const p = ip.split(".").map((x) => Number(x));
|
|
33850
|
+
if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;
|
|
33851
|
+
return (p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]) >>> 0;
|
|
33852
|
+
}
|
|
33853
|
+
function ipInCidr(ip, cidr) {
|
|
33854
|
+
const slash = cidr.indexOf("/");
|
|
33855
|
+
if (slash < 0) return false;
|
|
33856
|
+
const bits = Number(cidr.slice(slash + 1));
|
|
33857
|
+
const ipi = ipToInt(ip);
|
|
33858
|
+
const neti = ipToInt(cidr.slice(0, slash));
|
|
33859
|
+
if (ipi === null || neti === null || !(bits >= 0 && bits <= 32)) return false;
|
|
33860
|
+
if (bits === 0) return true;
|
|
33861
|
+
const mask = bits === 32 ? 4294967295 : ~((1 << 32 - bits) - 1) >>> 0;
|
|
33862
|
+
return (ipi & mask) === (neti & mask);
|
|
33863
|
+
}
|
|
33864
|
+
function checkUnique(names, rule, what, out) {
|
|
33865
|
+
const seen = /* @__PURE__ */ new Set();
|
|
33866
|
+
for (const n of names) {
|
|
33867
|
+
if (seen.has(n)) out.push({ rule, severity: "error", detail: `duplicate ${what}: "${n}" (R-NAMES: names must be unique).` });
|
|
33868
|
+
seen.add(n);
|
|
33869
|
+
}
|
|
33870
|
+
}
|
|
33871
|
+
function rejectNonObjects(entries, what, out) {
|
|
33872
|
+
if (!Array.isArray(entries)) return;
|
|
33873
|
+
entries.forEach((entry, i) => {
|
|
33874
|
+
if (!isObject2(entry))
|
|
33875
|
+
out.push({ rule: "SCHEMA", severity: "error", detail: `${what}[${i}] is not an object \u2014 entries must be objects.` });
|
|
33876
|
+
});
|
|
33877
|
+
}
|
|
33878
|
+
function validateSpec(spec) {
|
|
33879
|
+
const v = [];
|
|
33880
|
+
const devices = Array.isArray(spec?.devices) ? spec.devices : [];
|
|
33881
|
+
if (!spec?.project?.name) v.push({ rule: "SCHEMA", severity: "error", detail: "project.name is required." });
|
|
33882
|
+
if (devices.length === 0) v.push({ rule: "SCHEMA", severity: "error", detail: "devices must have \u22651 item." });
|
|
33883
|
+
rejectNonObjects(devices, "device", v);
|
|
33884
|
+
devices.forEach((d, i) => {
|
|
33885
|
+
if (isObject2(d)) rejectNonObjects(d.modules, `device[${i}].modules`, v);
|
|
33886
|
+
});
|
|
33887
|
+
rejectNonObjects(spec?.subnets, "subnet", v);
|
|
33888
|
+
if (spec?.network?.subnet !== void 0 && !isObject2(spec.network.subnet))
|
|
33889
|
+
v.push({ rule: "SCHEMA", severity: "error", detail: "network.subnet is not an object \u2014 it must be { name, cidr }." });
|
|
33890
|
+
rejectNonObjects(spec?.network?.nodes, "network node", v);
|
|
33891
|
+
rejectNonObjects(spec?.tagTables, "tagTable", v);
|
|
33892
|
+
rejectNonObjects(spec?.tags, "tag", v);
|
|
33893
|
+
rejectNonObjects(spec?.dataTypes, "dataType", v);
|
|
33894
|
+
rejectNonObjects(spec?.blocks, "block", v);
|
|
33895
|
+
if (Array.isArray(spec?.functionalUnits)) {
|
|
33896
|
+
rejectNonObjects(spec.functionalUnits, "functionalUnit", v);
|
|
33897
|
+
spec.functionalUnits.forEach((fu, i) => {
|
|
33898
|
+
if (!isObject2(fu)) return;
|
|
33899
|
+
rejectNonObjects(fu.equipmentModules, `functionalUnit[${i}].equipmentModules`, v);
|
|
33900
|
+
if (Array.isArray(fu.equipmentModules)) {
|
|
33901
|
+
fu.equipmentModules.forEach((em, j) => {
|
|
33902
|
+
if (!isObject2(em)) return;
|
|
33903
|
+
rejectNonObjects(em.controlModules, `functionalUnit[${i}].equipmentModules[${j}].controlModules`, v);
|
|
33904
|
+
});
|
|
33905
|
+
}
|
|
33906
|
+
});
|
|
33907
|
+
}
|
|
33908
|
+
checkUnique(devices.map((d) => d?.name).filter(Boolean), "R-NAMES", "device", v);
|
|
33909
|
+
const subnetNames = [
|
|
33910
|
+
...spec?.network?.subnet?.name ? [spec.network.subnet.name] : [],
|
|
33911
|
+
...(Array.isArray(spec?.subnets) ? spec.subnets : []).map((s) => s?.name).filter(Boolean)
|
|
33912
|
+
];
|
|
33913
|
+
checkUnique(subnetNames, "R-NAMES", "subnet", v);
|
|
33914
|
+
checkUnique((Array.isArray(spec?.dataTypes) ? spec.dataTypes : []).map((u) => u?.name).filter(Boolean), "R-NAMES", "UDT", v);
|
|
33915
|
+
checkUnique((Array.isArray(spec?.blocks) ? spec.blocks : []).map((b) => b?.name).filter(Boolean), "R-NAMES", "block", v);
|
|
33916
|
+
const byTable = /* @__PURE__ */ new Map();
|
|
33917
|
+
for (const t of Array.isArray(spec?.tags) ? spec.tags : []) {
|
|
33918
|
+
if (!t?.table || !t?.name) continue;
|
|
33919
|
+
if (!byTable.has(t.table)) byTable.set(t.table, []);
|
|
33920
|
+
byTable.get(t.table).push(t.name);
|
|
33921
|
+
}
|
|
33922
|
+
for (const [table, names] of byTable) checkUnique(names, "R-NAMES", `tag (table ${table})`, v);
|
|
33923
|
+
for (const d of devices) {
|
|
33924
|
+
if (d?.typeIdentifier && !TYPEID_RE.test(d.typeIdentifier))
|
|
33925
|
+
v.push({ rule: "R-TYPEID", severity: "error", detail: `device "${d.name}": invalid typeIdentifier "${d.typeIdentifier}" \u2014 use OrderNumber:<MLFB>/V<fw> (slash, not ':V'). Resolve via tia_catalog.` });
|
|
33926
|
+
for (const m of Array.isArray(d?.modules) ? d.modules : []) {
|
|
33927
|
+
if (m?.order && !TYPEID_RE.test(m.order))
|
|
33928
|
+
v.push({ rule: "R-TYPEID", severity: "error", detail: `module in "${d.name}": invalid order "${m.order}" \u2014 use OrderNumber:<MLFB>/V<fw>.` });
|
|
33929
|
+
}
|
|
33930
|
+
}
|
|
33931
|
+
for (const d of devices) {
|
|
33932
|
+
if (d?.family === "S7-1200") {
|
|
33933
|
+
const sm = (Array.isArray(d?.modules) ? d.modules : []).filter((m) => (m?.kind ?? "SM") === "SM").length;
|
|
33934
|
+
if (sm > 8) v.push({ rule: "R-MODLIMIT", severity: "error", detail: `device "${d.name}" (S7-1200) has ${sm} SM \u2014 above the limit (8). Confirm the exact limit for the model via tia_catalog.` });
|
|
33935
|
+
}
|
|
33396
33936
|
}
|
|
33397
33937
|
const families = new Set(devices.filter((d) => d?.role === "cpu" || /^S7-1[25]00$/.test(d?.family ?? "")).map((d) => d?.family).filter(Boolean));
|
|
33398
33938
|
const has1500 = families.has("S7-1500");
|
|
@@ -33418,8 +33958,12 @@ function validateSpec(spec) {
|
|
|
33418
33958
|
const sName = n?.subnet ?? net?.subnet?.name;
|
|
33419
33959
|
const sub = sName ? subnetByName.get(sName) : void 0;
|
|
33420
33960
|
if (!sub) v.push({ rule: "R-SUBNET", severity: "error", detail: `node "${n?.device}" references nonexistent subnet "${sName}".` });
|
|
33421
|
-
else if (n?.ip && sub?.cidr
|
|
33422
|
-
|
|
33961
|
+
else if (n?.ip && sub?.cidr) {
|
|
33962
|
+
if (typeof n.ip !== "string" || typeof sub.cidr !== "string")
|
|
33963
|
+
v.push({ rule: "R-SUBNET", severity: "error", detail: `node "${n?.device}": IP and CIDR must be strings (got IP ${typeof n.ip}, CIDR ${typeof sub.cidr}) \u2014 fix the spec before applying.` });
|
|
33964
|
+
else if (!ipInCidr(n.ip, sub.cidr))
|
|
33965
|
+
v.push({ rule: "R-SUBNET", severity: "error", detail: `node "${n?.device}": IP ${n.ip} is outside CIDR ${sub.cidr} of subnet ${sName}.` });
|
|
33966
|
+
}
|
|
33423
33967
|
if (n?.createIoSystem) {
|
|
33424
33968
|
ioSystemCount++;
|
|
33425
33969
|
ioSystemSubnet = n?.subnet ?? net?.subnet?.name ?? null;
|
|
@@ -33467,30 +34011,35 @@ function planSpec(spec) {
|
|
|
33467
34011
|
for (const s of subnets) {
|
|
33468
34012
|
if (!s?.name || subnetSeen.has(s.name)) continue;
|
|
33469
34013
|
subnetSeen.add(s.name);
|
|
33470
|
-
steps.push({ op: "subnet.create", method: "POST", path: "/subnets", body:
|
|
34014
|
+
steps.push({ op: "subnet.create", method: "POST", path: "/subnets", body: jsonBody({ typeIdentifier: s.type ?? "System:Subnet.Ethernet", name: s.name }), summary: `create subnet ${s.name}` });
|
|
33471
34015
|
}
|
|
33472
34016
|
for (const d of Array.isArray(spec?.devices) ? spec.devices : []) {
|
|
33473
|
-
|
|
34017
|
+
if (!isObject2(d)) continue;
|
|
34018
|
+
steps.push({ op: "device.create", method: "POST", path: "/devices", body: jsonBody({ typeIdentifier: d.typeIdentifier, deviceName: d.name }), summary: `create device ${d.name}` });
|
|
33474
34019
|
}
|
|
33475
34020
|
for (const d of Array.isArray(spec?.devices) ? spec.devices : []) {
|
|
34021
|
+
if (!isObject2(d)) continue;
|
|
33476
34022
|
for (const m of Array.isArray(d?.modules) ? d.modules : []) {
|
|
33477
|
-
|
|
34023
|
+
if (!isObject2(m)) continue;
|
|
34024
|
+
steps.push({ op: "device.plug", method: "POST", path: `/devices/${seg(d.name)}/plug`, body: jsonBody({ typeIdentifier: m.order, position: m.slot }), summary: `plug module into ${d.name}` });
|
|
33478
34025
|
}
|
|
33479
34026
|
}
|
|
33480
34027
|
for (const n of Array.isArray(spec?.network?.nodes) ? spec.network.nodes : []) {
|
|
34028
|
+
if (!isObject2(n)) continue;
|
|
33481
34029
|
const sName = n?.subnet ?? spec?.network?.subnet?.name;
|
|
33482
|
-
steps.push({ op: "network.connect", method: "POST", path: "/network/connect", body:
|
|
34030
|
+
steps.push({ op: "network.connect", method: "POST", path: "/network/connect", body: jsonBody({ device: n.device, subnet: sName, ip: n.ip, createIoSystem: n.createIoSystem }), summary: `connect ${n.device} @ ${n.ip} to subnet ${sName}` });
|
|
33483
34031
|
}
|
|
33484
34032
|
if (plc) {
|
|
33485
34033
|
const tableNames = /* @__PURE__ */ new Set();
|
|
33486
34034
|
for (const tt of Array.isArray(spec?.tagTables) ? spec.tagTables : []) if (tt?.name) tableNames.add(tt.name);
|
|
33487
34035
|
for (const t of Array.isArray(spec?.tags) ? spec.tags : []) if (t?.table) tableNames.add(t.table);
|
|
33488
|
-
for (const name of tableNames) steps.push({ op: "tagtable.create", method: "POST", path: `/plcs/${
|
|
34036
|
+
for (const name of tableNames) steps.push({ op: "tagtable.create", method: "POST", path: `/plcs/${seg(plc)}/tagtables`, body: { name }, summary: `create tag table ${name}` });
|
|
33489
34037
|
for (const t of Array.isArray(spec?.tags) ? spec.tags : []) {
|
|
33490
|
-
|
|
34038
|
+
if (!isObject2(t)) continue;
|
|
34039
|
+
steps.push({ op: "tag.create", method: "POST", path: `/plcs/${seg(plc)}/tags`, body: jsonBody({ table: t.table, name: t.name, dataType: t.dataType, address: t.address }), summary: `create tag ${t.name}:${t.dataType}` });
|
|
33491
34040
|
}
|
|
33492
34041
|
for (const b of Array.isArray(spec?.blocks) ? spec.blocks : []) {
|
|
33493
|
-
if (b?.kind === "FB") steps.push({ op: "fb.create", method: "POST", path: `/plcs/${
|
|
34042
|
+
if (b?.kind === "FB") steps.push({ op: "fb.create", method: "POST", path: `/plcs/${seg(plc)}/fbs`, body: jsonBody({ name: b.name, language: b.language }), summary: `create FB ${b.name} (${b.language})` });
|
|
33494
34043
|
}
|
|
33495
34044
|
const fcObDb = (Array.isArray(spec?.blocks) ? spec.blocks : []).filter((b) => b?.kind && b.kind !== "FB").map((b) => b.name);
|
|
33496
34045
|
if (fcObDb.length) assumptions.push(`OB/FC/DB blocks (${fcObDb.join(", ")}) and their logic are not included in apply \u2014 author them via tia_source_put (SCL) / tia_import_xml (graphical).`);
|
|
@@ -33499,16 +34048,17 @@ function planSpec(spec) {
|
|
|
33499
34048
|
for (const cm of Array.isArray(em?.controlModules) ? em.controlModules : []) {
|
|
33500
34049
|
if (cm?.instanceDb && cm?.libraryType) {
|
|
33501
34050
|
const fb = String(cm.libraryType).split("@")[0];
|
|
33502
|
-
steps.push({ op: "instancedb.create", method: "POST", path: `/plcs/${
|
|
34051
|
+
steps.push({ op: "instancedb.create", method: "POST", path: `/plcs/${seg(plc)}/instancedbs`, body: jsonBody({ name: cm.instanceDb, instanceOf: fb }), summary: `create iDB ${cm.instanceDb} from ${fb}` });
|
|
33503
34052
|
}
|
|
33504
34053
|
}
|
|
33505
34054
|
}
|
|
33506
34055
|
}
|
|
33507
34056
|
const ladder = Array.isArray(spec?.verification?.ladder) ? spec.verification.ladder : ["compile"];
|
|
33508
|
-
if (ladder.includes("compile")) steps.push({ op: "compile", method: "POST", path: `/plcs/${
|
|
34057
|
+
if (ladder.includes("compile")) steps.push({ op: "compile", method: "POST", path: `/plcs/${seg(plc)}/compile`, body: {}, summary: `compile ${plc} (verifier)` });
|
|
33509
34058
|
}
|
|
33510
34059
|
return { steps, assumptions };
|
|
33511
34060
|
}
|
|
34061
|
+
var SPEC_INSTALLING_HINT = "Serve is installing a TIAOpenness app update: the refused step did NOT run \u2014 but any earlier SUCCESSFUL steps in `applied` may have changed the project, so review `applied` (against a fresh dryRun plan) before doing anything else. Wait until the update finishes, then apply each remaining step individually with the matching M-off tool (or re-run the whole apply on a fresh project): this apply always restarts at step 0 and create steps are not idempotent, so it does NOT resume from the refused step. There is no background job for this call.";
|
|
33512
34062
|
async function applySpec(spec, opts = {}) {
|
|
33513
34063
|
if (spec?.safety?.required === true && spec?.autonomous === true) {
|
|
33514
34064
|
return textResult({ status: "rejected", gate: "safety_signoff", reason: "G5: safety.required && autonomous \u21D2 REJECT (IEC 61511). Selecting an F-CPU is OK; authoring/downloading F is never autonomous." }, true);
|
|
@@ -33525,19 +34075,20 @@ async function applySpec(spec, opts = {}) {
|
|
|
33525
34075
|
let compileResult = null;
|
|
33526
34076
|
for (const s of steps) {
|
|
33527
34077
|
try {
|
|
33528
|
-
const data = await tiaFetch(s.path, { method: s.method, headers:
|
|
34078
|
+
const data = await tiaFetch(s.path, { method: s.method, headers: JSON_HEADERS, body: JSON.stringify(s.body) }, { timeoutMs: SLOW_TIMEOUT_MS });
|
|
33529
34079
|
applied.push({ op: s.op, summary: s.summary, ok: true });
|
|
33530
34080
|
if (s.op === "compile") compileResult = data;
|
|
33531
34081
|
} catch (e) {
|
|
33532
34082
|
const err = asTiaError(e);
|
|
33533
34083
|
applied.push({ op: s.op, summary: s.summary, ok: false, error: err.message, kind: err.kind });
|
|
33534
34084
|
if (!opts.continueOnError) {
|
|
33535
|
-
return textResult({ status: "stopped", appliedCount: applied.length, applied, stoppedAt: s.summary, error: err.message, kind: err.kind, assumptions, note: "Stopped at the 1st error (
|
|
34085
|
+
return textResult({ status: "stopped", appliedCount: applied.length, applied, stoppedAt: s.summary, error: err.message, kind: err.kind, ...isInstallingError(err) ? { hint: SPEC_INSTALLING_HINT } : {}, assumptions, note: "Stopped at the 1st error. Review `applied` (against a fresh dryRun plan) and apply each remaining step individually with the matching M-off tool, or re-run the whole apply on a fresh project \u2014 this apply restarts at step 0 and create steps are not idempotent. Pass continueOnError:true to keep going despite errors." }, true);
|
|
33536
34086
|
}
|
|
33537
34087
|
}
|
|
33538
34088
|
}
|
|
33539
34089
|
const okAll = applied.every((a) => a.ok);
|
|
33540
|
-
|
|
34090
|
+
const failedCount = applied.filter((a) => !a.ok).length;
|
|
34091
|
+
return textResult({ status: okAll ? "applied" : "applied_with_errors", appliedCount: applied.length, applied, compile: compileResult, assumptions, ...applied.some((a) => a.kind === "installing") ? { hint: SPEC_INSTALLING_HINT } : {}, warnings: val.violations.filter((x) => x.severity === "warning"), nextHints: okAll ? ["Offline build complete. To deploy: review the compile, then tia_download (GATE G3, requires human approval)."] : [`Build incomplete: ${failedCount} step(s) failed (see \`applied\` entries with ok:false). Apply the remainder individually with the matching M-off tools \u2014 this apply restarts at step 0 and create steps are not idempotent \u2014 then review the compile before any tia_download (GATE G3, requires human approval).`] }, !okAll);
|
|
33541
34092
|
}
|
|
33542
34093
|
function registerSpecTools(server2) {
|
|
33543
34094
|
server2.registerTool(
|
|
@@ -33574,7 +34125,7 @@ function registerSpecTools(server2) {
|
|
|
33574
34125
|
inputSchema: {
|
|
33575
34126
|
spec: external_exports.record(external_exports.string(), external_exports.unknown()).describe("the project-spec"),
|
|
33576
34127
|
dryRun: external_exports.boolean().optional().describe("true \u2192 returns the plan without applying"),
|
|
33577
|
-
continueOnError: external_exports.boolean().optional().describe("true \u2192
|
|
34128
|
+
continueOnError: external_exports.boolean().optional().describe("true \u2192 keeps applying the remaining steps after an error instead of stopping at the 1st")
|
|
33578
34129
|
}
|
|
33579
34130
|
},
|
|
33580
34131
|
// dryRun é puro (não chama o serve) → fora do runner. O apply real passa pelo runner com os args inteiros.
|
|
@@ -33633,75 +34184,22 @@ function registerGuideTool(server2) {
|
|
|
33633
34184
|
|
|
33634
34185
|
// src/index.ts
|
|
33635
34186
|
var server = new McpServer(
|
|
33636
|
-
{ name: "tia-openness", version: "1.
|
|
34187
|
+
{ name: "tia-openness", version: "1.6.0" },
|
|
33637
34188
|
// Camada 1 (ambiente): o brief operacional viaja no handshake MCP — qualquer cliente
|
|
33638
34189
|
// que honre `instructions` recebe gates/serial-only/pipeline sem instalar nada.
|
|
33639
34190
|
{ instructions: BRIEF }
|
|
33640
34191
|
);
|
|
33641
|
-
server
|
|
33642
|
-
"tia_ping",
|
|
33643
|
-
{
|
|
33644
|
-
title: "TIA \u2014 connection diagnostics",
|
|
33645
|
-
description: "Diagnoses connectivity to the TIA Openness `serve` API and whether the server is ACTIVATED. Tests GET /health (reachability) and GET /readiness (license activation). Ideal for the MCP-on-Mac-pointing-at-a-`serve`-on-a-Windows-VM scenario. Read-only. Returns { base, reachable, activated, latencyMs, hint }.",
|
|
33646
|
-
inputSchema: {}
|
|
33647
|
-
},
|
|
33648
|
-
async () => {
|
|
33649
|
-
const report = {
|
|
33650
|
-
base: BASE,
|
|
33651
|
-
timeoutMs: TIMEOUT_MS,
|
|
33652
|
-
reachable: false,
|
|
33653
|
-
activated: null,
|
|
33654
|
-
latencyMs: null,
|
|
33655
|
-
detail: null,
|
|
33656
|
-
hint: null
|
|
33657
|
-
};
|
|
33658
|
-
const start = Date.now();
|
|
33659
|
-
try {
|
|
33660
|
-
await tiaFetch("/health");
|
|
33661
|
-
report.reachable = true;
|
|
33662
|
-
report.latencyMs = Date.now() - start;
|
|
33663
|
-
} catch (e) {
|
|
33664
|
-
const err = asTiaError(e);
|
|
33665
|
-
report.detail = err.message;
|
|
33666
|
-
report.hint = hintFor(err);
|
|
33667
|
-
return textResult(report);
|
|
33668
|
-
}
|
|
33669
|
-
try {
|
|
33670
|
-
await tiaFetch("/readiness");
|
|
33671
|
-
report.activated = true;
|
|
33672
|
-
} catch (e) {
|
|
33673
|
-
const err = asTiaError(e);
|
|
33674
|
-
report.activated = err.kind === "license_required" || err.status === 403 ? false : null;
|
|
33675
|
-
report.detail = err.message;
|
|
33676
|
-
report.hint = hintFor(err);
|
|
33677
|
-
}
|
|
33678
|
-
return textResult(report);
|
|
33679
|
-
}
|
|
33680
|
-
);
|
|
33681
|
-
server.registerTool(
|
|
33682
|
-
"tia_readiness",
|
|
33683
|
-
{
|
|
33684
|
-
title: "TIA \u2014 environment readiness",
|
|
33685
|
-
description: "Readiness diagnostic for the TIA Openness V21 environment ON THE SERVE HOST (x64 process, Windows 'Siemens TIA Openness' group, PublicAPI, 21.0 registry key, and TIA instances). Call BEFORE connecting. Maps to GET /readiness. Read-only (class R). Returns { ready, checks:[{ name, status, detail, remediation }] }.",
|
|
33686
|
-
inputSchema: {}
|
|
33687
|
-
},
|
|
33688
|
-
async () => {
|
|
33689
|
-
try {
|
|
33690
|
-
const data = await tiaFetch("/readiness");
|
|
33691
|
-
return textResult(data);
|
|
33692
|
-
} catch (e) {
|
|
33693
|
-
const err = asTiaError(e);
|
|
33694
|
-
return textResult({ error: err.message, kind: err.kind, status: err.status, details: err.details ?? null, hint: hintFor(err) }, true);
|
|
33695
|
-
}
|
|
33696
|
-
}
|
|
33697
|
-
);
|
|
34192
|
+
registerDiagnosticTools(server);
|
|
33698
34193
|
registerGuideTool(server);
|
|
33699
34194
|
registerJobTools(server);
|
|
33700
34195
|
registerReadOnlyTools(server);
|
|
33701
34196
|
registerLifecycleTools(server);
|
|
33702
34197
|
registerAuthoringTools(server);
|
|
33703
34198
|
registerAsCodeTools(server);
|
|
33704
|
-
|
|
34199
|
+
registerCompileTools(server);
|
|
34200
|
+
registerDownloadTools(server);
|
|
34201
|
+
registerUploadTools(server);
|
|
34202
|
+
registerOnlineTools(server);
|
|
33705
34203
|
registerSpecTools(server);
|
|
33706
34204
|
async function main() {
|
|
33707
34205
|
const transport = new StdioServerTransport();
|