@kenhkl/agent-moss 0.17.43 → 0.17.45
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/cli.js +2759 -705
- package/dist/engine/coordinator.d.ts +2 -0
- package/dist/engine/coordinator.js +2661 -616
- package/dist/server.js +2735 -681
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -409,22 +409,22 @@ function loadToolRegistry() {
|
|
|
409
409
|
data.tools = tools;
|
|
410
410
|
return data;
|
|
411
411
|
}
|
|
412
|
-
function scanStructEntry(cat, value,
|
|
412
|
+
function scanStructEntry(cat, value, path10) {
|
|
413
413
|
if (cat === "skills") {
|
|
414
414
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
415
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
415
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u7684 skills \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u7C7B\u522B: {\u6280\u80FD\u540D: [\u5173\u952E\u8BCD]}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
416
416
|
return null;
|
|
417
417
|
}
|
|
418
418
|
const out = {};
|
|
419
419
|
for (const [skCat, skills] of Object.entries(value)) {
|
|
420
420
|
if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
|
|
421
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
421
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u7684 skills.${skCat} \u5E94\u4E3A\u5BF9\u8C61\uFF08\u6280\u80FD\u540D \u2192 \u5173\u952E\u8BCD\u6570\u7EC4\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
|
|
422
422
|
continue;
|
|
423
423
|
}
|
|
424
424
|
const keep = {};
|
|
425
425
|
for (const [name, kws] of Object.entries(skills)) {
|
|
426
426
|
if (Array.isArray(kws)) keep[name] = kws;
|
|
427
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
427
|
+
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u7684 skills.${skCat}.${name} \u5173\u952E\u8BCD\u4E0D\u662F\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
428
428
|
}
|
|
429
429
|
if (Object.keys(keep).length > 0) out[skCat] = keep;
|
|
430
430
|
}
|
|
@@ -432,37 +432,37 @@ function scanStructEntry(cat, value, path9) {
|
|
|
432
432
|
}
|
|
433
433
|
if (cat === "ltl_rules") {
|
|
434
434
|
if (!Array.isArray(value)) {
|
|
435
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
435
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
436
436
|
return null;
|
|
437
437
|
}
|
|
438
438
|
const keep = value.filter((r) => r && typeof r === "object" && r.id);
|
|
439
439
|
if (keep.length !== value.length) {
|
|
440
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
440
|
+
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u7684 ltl_rules \u6709\u6761\u76EE\u7F3A id \u6216\u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
441
441
|
}
|
|
442
442
|
return keep.length > 0 ? keep : null;
|
|
443
443
|
}
|
|
444
444
|
if (cat === "tools") {
|
|
445
445
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
446
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
446
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u7684 tools \u5E94\u4E3A\u5BF9\u8C61\uFF08{\u5DE5\u5177\u540D: {actionClass, ...}}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
447
447
|
return null;
|
|
448
448
|
}
|
|
449
449
|
const keep = {};
|
|
450
450
|
for (const [k, v] of Object.entries(value)) {
|
|
451
451
|
if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
|
|
452
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
452
|
+
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
453
453
|
}
|
|
454
454
|
return Object.keys(keep).length > 0 ? keep : null;
|
|
455
455
|
}
|
|
456
456
|
return null;
|
|
457
457
|
}
|
|
458
|
-
function scanRulesFile(
|
|
458
|
+
function scanRulesFile(path10, kind) {
|
|
459
459
|
const out = {};
|
|
460
460
|
const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
|
|
461
461
|
let parsed;
|
|
462
462
|
try {
|
|
463
|
-
parsed = JSON.parse(readFileSync2(
|
|
463
|
+
parsed = JSON.parse(readFileSync2(path10, "utf-8"));
|
|
464
464
|
} catch (e) {
|
|
465
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
465
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u635F\u574F/\u4E0D\u53EF\u8BFB\uFF0C\u5DF2\u8DF3\u8FC7\uFF08${kind} \u89C4\u5219\u4E0D\u751F\u6548\uFF09: ${e.message}`);
|
|
466
466
|
return out;
|
|
467
467
|
}
|
|
468
468
|
const classifyFlat = (r) => {
|
|
@@ -486,44 +486,44 @@ function scanRulesFile(path9, kind) {
|
|
|
486
486
|
}
|
|
487
487
|
if (flatBad > 0) {
|
|
488
488
|
console.warn(
|
|
489
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
489
|
+
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u6709 ${flatBad} \u6761\u5E73\u94FA\u6761\u76EE\u65E0\u6CD5\u5F52\u7C7B\uFF08\u88F8 pattern \u4E0D\u5E26 risk_level/risk_type \u65F6\u533A\u5206\u4E0D\u4E86 L1 \u5371\u9669\u547D\u4EE4\u4E0E L2 \u6388\u6743\u7C7B\uFF09\u2014\u2014 \u8BF7\u6539\u7528\u5BF9\u8C61\u5F62\u5F0F\uFF1A{"\u7C7B\u522B\u952E": [\u6761\u76EE...]}\u3002`
|
|
490
490
|
);
|
|
491
491
|
}
|
|
492
492
|
} else {
|
|
493
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
493
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u9876\u5C42\u5E94\u662F\u5BF9\u8C61\uFF08\u7C7B\u522B\u952E\u2192\u6761\u76EE\u6570\u7EC4\uFF09\u6216\u6570\u7EC4\uFF0C\u5DF2\u8DF3\u8FC7\u3002`);
|
|
494
494
|
return out;
|
|
495
495
|
}
|
|
496
496
|
for (const [cat, rules] of pairs) {
|
|
497
497
|
if (String(cat).startsWith("_")) continue;
|
|
498
498
|
if (STRUCT_KEYS.includes(cat)) {
|
|
499
|
-
const got = scanStructEntry(cat, rules,
|
|
499
|
+
const got = scanStructEntry(cat, rules, path10);
|
|
500
500
|
if (got !== null) out[cat] = got;
|
|
501
501
|
continue;
|
|
502
502
|
}
|
|
503
503
|
const required = EXTRA_CATEGORIES[cat];
|
|
504
504
|
if (!required) {
|
|
505
505
|
console.warn(
|
|
506
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
506
|
+
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u542B\u672A\u77E5\u7C7B\u522B\u952E "${cat}"\uFF08\u53EF\u7528\uFF1A${Object.keys(EXTRA_CATEGORIES).join(", ")}\uFF09\u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`
|
|
507
507
|
);
|
|
508
508
|
continue;
|
|
509
509
|
}
|
|
510
510
|
if (rules && typeof rules === "object" && !Array.isArray(rules)) {
|
|
511
511
|
console.error(
|
|
512
|
-
`[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${
|
|
512
|
+
`[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${path10} \u7684\u7C7B\u522B "${cat}" \u662F**\u5BF9\u8C61**\uFF0C\u5E94\u4E3A**\u5BF9\u8C61\u6570\u7EC4** \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002
|
|
513
513
|
\u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
|
|
514
514
|
\u4F60\u5199\u7684\u50CF\u662F runtime config \u7684\u683C\u5F0F\uFF08{"category_enabled": ..., "rules": [...]}\uFF09\u2014\u2014\u90A3\u662F ~/.config/agentmoss/agent_moss_runtime.json \u7684\u683C\u5F0F\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5F53\u89C4\u5219\u6587\u4EF6\u7528\u3002`
|
|
515
515
|
);
|
|
516
516
|
continue;
|
|
517
517
|
}
|
|
518
518
|
if (!Array.isArray(rules)) {
|
|
519
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
519
|
+
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u7684\u7C7B\u522B "${cat}" \u5E94\u4E3A\u6570\u7EC4\uFF0C\u5B9E\u9645\u662F ${typeof rules} \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u7C7B\u522B\u3002`);
|
|
520
520
|
continue;
|
|
521
521
|
}
|
|
522
522
|
const items = [];
|
|
523
523
|
for (const r of rules) {
|
|
524
524
|
if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
|
|
525
525
|
console.warn(
|
|
526
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
526
|
+
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u7C7B\u522B ${cat} \u6709\u6761\u76EE\u7F3A\u5FC5\u9700\u5B57\u6BB5 [${required.join(", ")}] \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`
|
|
527
527
|
);
|
|
528
528
|
continue;
|
|
529
529
|
}
|
|
@@ -533,7 +533,7 @@ function scanRulesFile(path9, kind) {
|
|
|
533
533
|
}
|
|
534
534
|
if (Object.keys(out).length > 0) {
|
|
535
535
|
console.info(
|
|
536
|
-
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${
|
|
536
|
+
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path10}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
|
|
537
537
|
);
|
|
538
538
|
}
|
|
539
539
|
return out;
|
|
@@ -962,46 +962,46 @@ function readExplicitTokenResult() {
|
|
|
962
962
|
if (tok) return [tok, ""];
|
|
963
963
|
const fdTok = readFdToken();
|
|
964
964
|
if (fdTok) return [fdTok, ""];
|
|
965
|
-
const
|
|
966
|
-
if (
|
|
965
|
+
const path10 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
|
|
966
|
+
if (path10) {
|
|
967
967
|
try {
|
|
968
|
-
const fileTok = readFileSync4(
|
|
968
|
+
const fileTok = readFileSync4(path10, "utf-8").trim();
|
|
969
969
|
if (!fileTok) {
|
|
970
|
-
return ["", `AGENT_MOSS_AUTH_TOKEN_FILE \u6307\u5411\u7684\u6587\u4EF6\u4E3A\u7A7A: ${
|
|
970
|
+
return ["", `AGENT_MOSS_AUTH_TOKEN_FILE \u6307\u5411\u7684\u6587\u4EF6\u4E3A\u7A7A: ${path10}\u3002\u8BF7\u5199\u5165 token\uFF0C\u6216\u663E\u5F0F\u8BBE AGENT_MOSS_AUTH_MODE=off`];
|
|
971
971
|
}
|
|
972
972
|
return [fileTok, ""];
|
|
973
973
|
} catch (e) {
|
|
974
|
-
return ["", `AGENT_MOSS_AUTH_TOKEN_FILE \u5DF2\u8BBE\u7F6E\u4F46\u65E0\u6CD5\u8BFB\u53D6 ${
|
|
974
|
+
return ["", `AGENT_MOSS_AUTH_TOKEN_FILE \u5DF2\u8BBE\u7F6E\u4F46\u65E0\u6CD5\u8BFB\u53D6 ${path10}: ${e?.message ?? e}\u3002\u8BF7\u786E\u8BA4\u6587\u4EF6\u5B58\u5728\u3001\u8FD0\u884C\u7528\u6237\u53EF\u8BFB\uFF1B\u6216\u6539\u7528 AGENT_MOSS_AUTH_TOKEN / AGENT_MOSS_AUTH_TOKEN_FD\uFF1B\u4E0D\u9700\u8981\u9274\u6743\u5219\u663E\u5F0F\u8BBE AGENT_MOSS_AUTH_MODE=off`];
|
|
975
975
|
}
|
|
976
976
|
}
|
|
977
977
|
return ["", ""];
|
|
978
978
|
}
|
|
979
979
|
function ensureAutoToken() {
|
|
980
|
-
const
|
|
980
|
+
const path10 = autoTokenPath();
|
|
981
981
|
try {
|
|
982
|
-
if (existsSync3(
|
|
983
|
-
const tok2 = readFileSync4(
|
|
982
|
+
if (existsSync3(path10) && !lstatSync(path10).isSymbolicLink()) {
|
|
983
|
+
const tok2 = readFileSync4(path10, "utf-8").trim();
|
|
984
984
|
if (tok2) {
|
|
985
985
|
try {
|
|
986
|
-
chmodSync(
|
|
986
|
+
chmodSync(path10, 384);
|
|
987
987
|
} catch {
|
|
988
988
|
}
|
|
989
989
|
return tok2;
|
|
990
990
|
}
|
|
991
991
|
}
|
|
992
992
|
const tok = randomBytes(32).toString("base64url");
|
|
993
|
-
if (!ensurePrivateDir(dirname2(
|
|
994
|
-
throw new Error(`\u65E0\u6CD5\u521B\u5EFA/\u6536\u7D27 token \u76EE\u5F55\uFF08\u6743\u9650\u6216\u5C5E\u4E3B\u5F02\u5E38\uFF09: ${dirname2(
|
|
993
|
+
if (!ensurePrivateDir(dirname2(path10))) {
|
|
994
|
+
throw new Error(`\u65E0\u6CD5\u521B\u5EFA/\u6536\u7D27 token \u76EE\u5F55\uFF08\u6743\u9650\u6216\u5C5E\u4E3B\u5F02\u5E38\uFF09: ${dirname2(path10)}`);
|
|
995
995
|
}
|
|
996
|
-
if (!writePrivateText(
|
|
997
|
-
throw new Error(`\u5199\u5165\u81EA\u52A8 token \u5931\u8D25: ${
|
|
996
|
+
if (!writePrivateText(path10, tok + "\n")) {
|
|
997
|
+
throw new Error(`\u5199\u5165\u81EA\u52A8 token \u5931\u8D25: ${path10}`);
|
|
998
998
|
}
|
|
999
999
|
console.warn(
|
|
1000
|
-
`[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${
|
|
1000
|
+
`[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${path10}\uFF080600\uFF09\u3002\u5BA2\u6237\u7AEF\u9700\u5E26 \`Authorization: Bearer <token>\`\uFF1B\u67E5\u770B\uFF1Acat ${path10}\uFF1B\u5982\u9700\u5173\u95ED\u9274\u6743\uFF1AAGENT_MOSS_AUTH_MODE=off`
|
|
1001
1001
|
);
|
|
1002
1002
|
return tok;
|
|
1003
1003
|
} catch (e) {
|
|
1004
|
-
throw new Error(`\u81EA\u52A8\u8BBF\u95EE token \u751F\u6210/\u8BFB\u53D6\u5931\u8D25\uFF08${
|
|
1004
|
+
throw new Error(`\u81EA\u52A8\u8BBF\u95EE token \u751F\u6210/\u8BFB\u53D6\u5931\u8D25\uFF08${path10}\uFF09\uFF1A${e?.message ?? e}`);
|
|
1005
1005
|
}
|
|
1006
1006
|
}
|
|
1007
1007
|
function parseAgentTokens(raw) {
|
|
@@ -1090,9 +1090,9 @@ function constEq(a, b) {
|
|
|
1090
1090
|
if (ba.length !== bb.length) return false;
|
|
1091
1091
|
return timingSafeEqual(ba, bb);
|
|
1092
1092
|
}
|
|
1093
|
-
function checkRequestAuth(headers,
|
|
1093
|
+
function checkRequestAuth(headers, path10) {
|
|
1094
1094
|
if (authMode() === AUTH_MODE_OFF) return [true, ""];
|
|
1095
|
-
const normalizedPath =
|
|
1095
|
+
const normalizedPath = path10.replace(/\/+$/, "");
|
|
1096
1096
|
const isHealth = HEALTH_PATHS.includes(normalizedPath);
|
|
1097
1097
|
const [gt0, agents, err] = resolveAuth();
|
|
1098
1098
|
const gateToken = env("AGENT_MOSS_GATE_AUTH_TOKEN");
|
|
@@ -1123,8 +1123,8 @@ function bindAgent(principal, agentId) {
|
|
|
1123
1123
|
if (!agentId) return [true, bound];
|
|
1124
1124
|
return [bound === agentId, bound];
|
|
1125
1125
|
}
|
|
1126
|
-
function principalOf(headers,
|
|
1127
|
-
const [ok, principal] = checkRequestAuth(headers,
|
|
1126
|
+
function principalOf(headers, path10 = "") {
|
|
1127
|
+
const [ok, principal] = checkRequestAuth(headers, path10);
|
|
1128
1128
|
return ok ? principal : "";
|
|
1129
1129
|
}
|
|
1130
1130
|
function principalHash(principal) {
|
|
@@ -1411,11 +1411,11 @@ function errorDetailMode() {
|
|
|
1411
1411
|
function maxBodyBytes() {
|
|
1412
1412
|
return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
|
|
1413
1413
|
}
|
|
1414
|
-
function poolOf(
|
|
1415
|
-
if (
|
|
1416
|
-
if (
|
|
1417
|
-
if (
|
|
1418
|
-
if (
|
|
1414
|
+
function poolOf(path10) {
|
|
1415
|
+
if (path10 === "/api/v1/analyze" || path10.startsWith("/api/v1/analyze/")) return "biz";
|
|
1416
|
+
if (path10 === "/api/v1/review" || path10.startsWith("/api/v1/review/")) return "review";
|
|
1417
|
+
if (path10 === "/console" || path10.startsWith("/console/") || path10.startsWith("/api/v1/brain")) return "ops";
|
|
1418
|
+
if (path10 === "/api/v1/health") return "health";
|
|
1419
1419
|
return "other";
|
|
1420
1420
|
}
|
|
1421
1421
|
function poolLimit(name) {
|
|
@@ -1856,7 +1856,7 @@ function splitPythonStatements(code) {
|
|
|
1856
1856
|
parts.push(current);
|
|
1857
1857
|
return parts.map((s) => s.trim()).filter((s) => s.length > 0);
|
|
1858
1858
|
}
|
|
1859
|
-
function isSimpleOpenCall(expr,
|
|
1859
|
+
function isSimpleOpenCall(expr, path10, binding) {
|
|
1860
1860
|
const m = expr.match(/^open\s*\(([\s\S]*)\)$/);
|
|
1861
1861
|
if (!m || hasTopLevelChar(m[1], "=")) return false;
|
|
1862
1862
|
const args = splitPythonArgs(m[1]);
|
|
@@ -1866,12 +1866,12 @@ function isSimpleOpenCall(expr, path9, binding) {
|
|
|
1866
1866
|
}
|
|
1867
1867
|
const target = args[0].trim();
|
|
1868
1868
|
const literal = pythonStringLiteral(target);
|
|
1869
|
-
if (literal !== null) return literal ===
|
|
1869
|
+
if (literal !== null) return literal === path10;
|
|
1870
1870
|
return !!binding && target === binding;
|
|
1871
1871
|
}
|
|
1872
|
-
function confirmsInlineRead(command,
|
|
1873
|
-
if (command.length > 8192 || !
|
|
1874
|
-
if (
|
|
1872
|
+
function confirmsInlineRead(command, path10) {
|
|
1873
|
+
if (command.length > 8192 || !path10 || path10.startsWith("~")) return false;
|
|
1874
|
+
if (path10.includes("/") && !path10.startsWith("/")) return false;
|
|
1875
1875
|
const wrapper = command.trim().match(/^python3?[ \t]+-c[ \t]+([\s\S]+)$/);
|
|
1876
1876
|
if (!wrapper) return false;
|
|
1877
1877
|
const code = literalShellWord(wrapper[1]);
|
|
@@ -1890,13 +1890,13 @@ function confirmsInlineRead(command, path9) {
|
|
|
1890
1890
|
const child = pythonStringLiteral(args[0]);
|
|
1891
1891
|
if (child === null) return false;
|
|
1892
1892
|
const cat = child.trim().match(/^cat[ \t]+([\s\S]+)$/);
|
|
1893
|
-
return !!cat && !
|
|
1893
|
+
return !!cat && !path10.startsWith("-") && literalShellWord(cat[1].trim()) === path10;
|
|
1894
1894
|
}
|
|
1895
1895
|
const assign = first.match(/^([A-Za-z_]\w*)\s*=\s*([\s\S]+)$/);
|
|
1896
1896
|
if (!assign) return false;
|
|
1897
1897
|
const name = assign[1];
|
|
1898
1898
|
const value = pythonStringLiteral(assign[2]);
|
|
1899
|
-
if (value !==
|
|
1899
|
+
if (value !== path10 || ["open", "print", "__debug__"].includes(name)) return false;
|
|
1900
1900
|
binding = name;
|
|
1901
1901
|
expr = statements[1];
|
|
1902
1902
|
} else {
|
|
@@ -1911,7 +1911,7 @@ function confirmsInlineRead(command, path9) {
|
|
|
1911
1911
|
}
|
|
1912
1912
|
const readCall = expr.match(/^([\s\S]+)\.read\s*\(\s*\)$/);
|
|
1913
1913
|
if (readCall) expr = readCall[1];
|
|
1914
|
-
return isSimpleOpenCall(expr,
|
|
1914
|
+
return isSimpleOpenCall(expr, path10, binding);
|
|
1915
1915
|
}
|
|
1916
1916
|
function analyzeInlineScript(command) {
|
|
1917
1917
|
const code = extractInlineCode(command);
|
|
@@ -2066,7 +2066,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
|
|
|
2066
2066
|
os: String(sp.os || "linux").toLowerCase()
|
|
2067
2067
|
}));
|
|
2068
2068
|
}
|
|
2069
|
-
function _scopeOf(os6,
|
|
2069
|
+
function _scopeOf(os6, path10) {
|
|
2070
2070
|
if (!_scopeIndex) {
|
|
2071
2071
|
_scopeIndex = /* @__PURE__ */ new Map();
|
|
2072
2072
|
for (const sp of loadL1().sensitive_path_access || []) {
|
|
@@ -2074,7 +2074,7 @@ function _scopeOf(os6, path9) {
|
|
|
2074
2074
|
if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
|
|
2075
2075
|
}
|
|
2076
2076
|
}
|
|
2077
|
-
return _scopeIndex.get(`${String(os6 || "linux").toLowerCase()}|${
|
|
2077
|
+
return _scopeIndex.get(`${String(os6 || "linux").toLowerCase()}|${path10}`) || "root";
|
|
2078
2078
|
}
|
|
2079
2079
|
function getSensitivePathsForOs(osType) {
|
|
2080
2080
|
const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
|
|
@@ -2892,36 +2892,36 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2892
2892
|
}
|
|
2893
2893
|
const preciseEdit = isPreciseEditTool(actionType);
|
|
2894
2894
|
const unreadPaths = [];
|
|
2895
|
-
for (const
|
|
2896
|
-
if (isDirectoryTarget(
|
|
2895
|
+
for (const path10 of checkTargets) {
|
|
2896
|
+
if (isDirectoryTarget(path10)) continue;
|
|
2897
2897
|
let isFullRead = [...normalizedFullReads].some(
|
|
2898
|
-
(rp) => pathIsSameOrUnder(
|
|
2898
|
+
(rp) => pathIsSameOrUnder(path10, rp) || pathIsSameOrUnder(rp, path10)
|
|
2899
2899
|
);
|
|
2900
2900
|
if (!isFullRead && preciseEdit && [...normalizedWrittenPaths].some(
|
|
2901
|
-
(wp) => pathIsSameOrUnder(
|
|
2901
|
+
(wp) => pathIsSameOrUnder(path10, wp) || pathIsSameOrUnder(wp, path10)
|
|
2902
2902
|
)) {
|
|
2903
2903
|
isFullRead = true;
|
|
2904
2904
|
}
|
|
2905
|
-
if (!isFullRead && !isProtectedWritePath(
|
|
2905
|
+
if (!isFullRead && !isProtectedWritePath(path10) && isScriptGeneratedTarget(path10, historyWrittenScripts, shellRunActions)) {
|
|
2906
2906
|
isFullRead = true;
|
|
2907
2907
|
}
|
|
2908
2908
|
let isPartialCovered = false;
|
|
2909
2909
|
if (!isFullRead) {
|
|
2910
2910
|
for (const [pp, upto] of normalizedPartialReads) {
|
|
2911
|
-
if (!(pathIsSameOrUnder(
|
|
2912
|
-
if (preciseEdit || upto != null && fileHasAtMostLines(
|
|
2911
|
+
if (!(pathIsSameOrUnder(path10, pp) || pathIsSameOrUnder(pp, path10))) continue;
|
|
2912
|
+
if (preciseEdit || upto != null && fileHasAtMostLines(path10, upto)) {
|
|
2913
2913
|
isPartialCovered = true;
|
|
2914
2914
|
break;
|
|
2915
2915
|
}
|
|
2916
2916
|
}
|
|
2917
2917
|
}
|
|
2918
2918
|
if (!isFullRead && !isPartialCovered) {
|
|
2919
|
-
let isCreate = !fs.existsSync(
|
|
2919
|
+
let isCreate = !fs.existsSync(path10);
|
|
2920
2920
|
if (!isCreate) {
|
|
2921
2921
|
isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
|
|
2922
2922
|
}
|
|
2923
2923
|
if (!isCreate) {
|
|
2924
|
-
unreadPaths.push(
|
|
2924
|
+
unreadPaths.push(path10);
|
|
2925
2925
|
}
|
|
2926
2926
|
}
|
|
2927
2927
|
}
|
|
@@ -3115,16 +3115,16 @@ var init_logic_rules = __esm({
|
|
|
3115
3115
|
ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
|
|
3116
3116
|
ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
|
|
3117
3117
|
HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
|
|
3118
|
-
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path:
|
|
3118
|
+
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path10, riskLevel, desc, dirDelOnly }) => ({ path: path10, riskLevel, desc, credential: true, dirDelOnly }));
|
|
3119
3119
|
ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
|
|
3120
3120
|
HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
|
|
3121
|
-
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path:
|
|
3121
|
+
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path10, riskLevel, desc, dirDelOnly }) => ({ path: path10, riskLevel, desc, credential: true, dirDelOnly }));
|
|
3122
3122
|
ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
|
|
3123
3123
|
HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
|
|
3124
|
-
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path:
|
|
3124
|
+
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path10, riskLevel, desc, dirDelOnly }) => ({ path: path10, riskLevel, desc, credential: true, dirDelOnly }));
|
|
3125
3125
|
ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
|
|
3126
3126
|
HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
|
|
3127
|
-
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path:
|
|
3127
|
+
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path10, riskLevel, desc, dirDelOnly }) => ({ path: path10, riskLevel, desc, credential: true, dirDelOnly }));
|
|
3128
3128
|
_scopeIndex = null;
|
|
3129
3129
|
NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
|
|
3130
3130
|
"ask_user_question",
|
|
@@ -5492,24 +5492,24 @@ function extractWritePayload(actionType, actionDetailRaw) {
|
|
|
5492
5492
|
const detail = actionDetailRaw || "";
|
|
5493
5493
|
const m = detail.match(WRITE_PREFIX_RE);
|
|
5494
5494
|
if (m) {
|
|
5495
|
-
const
|
|
5495
|
+
const path10 = m[1];
|
|
5496
5496
|
let content = m[2] || "";
|
|
5497
|
-
if (!
|
|
5497
|
+
if (!path10 || path10 === "?" || path10 === "-" || !content.trim()) return null;
|
|
5498
5498
|
if ((actionType || "").toLowerCase().includes("editfile")) {
|
|
5499
5499
|
const nm = content.match(EDIT_NEW_RE);
|
|
5500
5500
|
if (nm) content = nm[1];
|
|
5501
5501
|
}
|
|
5502
|
-
return { path:
|
|
5502
|
+
return { path: path10, content };
|
|
5503
5503
|
}
|
|
5504
5504
|
const stripped = detail.trim();
|
|
5505
5505
|
if (stripped.startsWith("{")) {
|
|
5506
5506
|
try {
|
|
5507
5507
|
const obj = JSON.parse(stripped);
|
|
5508
5508
|
if (obj && typeof obj === "object") {
|
|
5509
|
-
const
|
|
5509
|
+
const path10 = obj.path || obj.file_path || obj.filePath;
|
|
5510
5510
|
const content = obj.content || obj.newString || obj.new_string;
|
|
5511
|
-
if (typeof
|
|
5512
|
-
return { path:
|
|
5511
|
+
if (typeof path10 === "string" && path10 !== "" && path10 !== "?" && path10 !== "-" && typeof content === "string" && content.trim()) {
|
|
5512
|
+
return { path: path10, content };
|
|
5513
5513
|
}
|
|
5514
5514
|
}
|
|
5515
5515
|
} catch {
|
|
@@ -5522,8 +5522,8 @@ function handlesWrittenContent(actionType, actionDetailRaw) {
|
|
|
5522
5522
|
if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
|
|
5523
5523
|
return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
|
|
5524
5524
|
}
|
|
5525
|
-
function detectLanguage(
|
|
5526
|
-
const ext =
|
|
5525
|
+
function detectLanguage(path10, content) {
|
|
5526
|
+
const ext = path10.slice(path10.lastIndexOf(".") >= 0 ? path10.lastIndexOf(".") : path10.length).toLowerCase();
|
|
5527
5527
|
if (SHELL_EXTS.has(ext)) return "shell";
|
|
5528
5528
|
if (PY_EXTS.has(ext)) return "python";
|
|
5529
5529
|
if (DATA_EXTS.has(ext)) return "data";
|
|
@@ -5537,8 +5537,8 @@ function detectLanguage(path9, content) {
|
|
|
5537
5537
|
}
|
|
5538
5538
|
return "other";
|
|
5539
5539
|
}
|
|
5540
|
-
function isInstructionTarget(
|
|
5541
|
-
const p = (
|
|
5540
|
+
function isInstructionTarget(path10) {
|
|
5541
|
+
const p = (path10 || "").replace(/\\/g, "/").toLowerCase();
|
|
5542
5542
|
if (!p) return false;
|
|
5543
5543
|
const base = p.split("/").pop() || "";
|
|
5544
5544
|
if (["agents.md", "claude.md", "system.md", "prompt.md", "instructions.md", ".cursorrules"].includes(base)) {
|
|
@@ -5696,8 +5696,8 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
|
|
|
5696
5696
|
if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
|
|
5697
5697
|
const payload = extractWritePayload(actionType, actionDetailRaw);
|
|
5698
5698
|
if (!payload) return [];
|
|
5699
|
-
const { path:
|
|
5700
|
-
const language = detectLanguage(
|
|
5699
|
+
const { path: path10, content: rawContent } = payload;
|
|
5700
|
+
const language = detectLanguage(path10, rawContent);
|
|
5701
5701
|
if (language === "data") return [];
|
|
5702
5702
|
let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
|
|
5703
5703
|
const started = Date.now();
|
|
@@ -6398,16 +6398,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6398
6398
|
if (String(osType || "").toLowerCase() === "windows") {
|
|
6399
6399
|
pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
|
|
6400
6400
|
}
|
|
6401
|
-
const pathMatches = (text,
|
|
6402
|
-
const parts =
|
|
6401
|
+
const pathMatches = (text, path10) => {
|
|
6402
|
+
const parts = path10.split(/(\(\?!.*?\))/);
|
|
6403
6403
|
const escaped = parts.map((part) => {
|
|
6404
6404
|
if (part.startsWith("(?!")) return part;
|
|
6405
6405
|
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6406
6406
|
}).join("");
|
|
6407
|
-
const re =
|
|
6407
|
+
const re = path10.startsWith(".") || path10.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
|
|
6408
6408
|
return re.test(text);
|
|
6409
6409
|
};
|
|
6410
|
-
const pathMatchesAny = (
|
|
6410
|
+
const pathMatchesAny = (path10) => pathScanTexts.some((t) => pathMatches(t, path10));
|
|
6411
6411
|
for (const sp of rootPaths) {
|
|
6412
6412
|
if (pathMatchesAny(sp.path.toLowerCase())) {
|
|
6413
6413
|
if (keygenGenerate) continue;
|
|
@@ -6555,8 +6555,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6555
6555
|
}
|
|
6556
6556
|
return null;
|
|
6557
6557
|
}
|
|
6558
|
-
function isHomeValue(
|
|
6559
|
-
let p =
|
|
6558
|
+
function isHomeValue(path10) {
|
|
6559
|
+
let p = path10.trim().toLowerCase();
|
|
6560
6560
|
if (p.startsWith("$(") && p.endsWith(")")) {
|
|
6561
6561
|
const inner = p.slice(2, -1).trim();
|
|
6562
6562
|
return HOME_TARGET_RE.test(" " + inner);
|
|
@@ -6624,15 +6624,15 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
6624
6624
|
nameRe.lastIndex = nm.index + nm[0].length;
|
|
6625
6625
|
}
|
|
6626
6626
|
}
|
|
6627
|
-
for (const [varName,
|
|
6628
|
-
if (!isHomeValue(
|
|
6627
|
+
for (const [varName, path10] of Object.entries(assigned)) {
|
|
6628
|
+
if (!isHomeValue(path10)) continue;
|
|
6629
6629
|
const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
|
|
6630
6630
|
for (const seg of segs) {
|
|
6631
6631
|
if (!isDeleteCommand(seg)) continue;
|
|
6632
6632
|
if (varRefRe.test(seg)) {
|
|
6633
6633
|
return {
|
|
6634
6634
|
allowed: false,
|
|
6635
|
-
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${
|
|
6635
|
+
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path10}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
|
|
6636
6636
|
riskLevel: "high",
|
|
6637
6637
|
riskType: "script_execution",
|
|
6638
6638
|
confidence: 90,
|
|
@@ -7087,8 +7087,64 @@ var init_script_analyzer = __esm({
|
|
|
7087
7087
|
}
|
|
7088
7088
|
});
|
|
7089
7089
|
|
|
7090
|
+
// src/engine/script-engine/ir.ts
|
|
7091
|
+
import { createHash as createHash3 } from "crypto";
|
|
7092
|
+
function encodeUtf8SurrogatePass(content) {
|
|
7093
|
+
const bytes = [];
|
|
7094
|
+
for (let i = 0; i < content.length; i++) {
|
|
7095
|
+
let codePoint = content.charCodeAt(i);
|
|
7096
|
+
if (codePoint >= 55296 && codePoint <= 56319 && i + 1 < content.length) {
|
|
7097
|
+
const low = content.charCodeAt(i + 1);
|
|
7098
|
+
if (low >= 56320 && low <= 57343) {
|
|
7099
|
+
codePoint = 65536 + (codePoint - 55296 << 10) + (low - 56320);
|
|
7100
|
+
i += 1;
|
|
7101
|
+
}
|
|
7102
|
+
}
|
|
7103
|
+
if (codePoint < 128) {
|
|
7104
|
+
bytes.push(codePoint);
|
|
7105
|
+
} else if (codePoint < 2048) {
|
|
7106
|
+
bytes.push(192 | codePoint >> 6, 128 | codePoint & 63);
|
|
7107
|
+
} else if (codePoint < 65536) {
|
|
7108
|
+
bytes.push(
|
|
7109
|
+
224 | codePoint >> 12,
|
|
7110
|
+
128 | codePoint >> 6 & 63,
|
|
7111
|
+
128 | codePoint & 63
|
|
7112
|
+
);
|
|
7113
|
+
} else {
|
|
7114
|
+
bytes.push(
|
|
7115
|
+
240 | codePoint >> 18,
|
|
7116
|
+
128 | codePoint >> 12 & 63,
|
|
7117
|
+
128 | codePoint >> 6 & 63,
|
|
7118
|
+
128 | codePoint & 63
|
|
7119
|
+
);
|
|
7120
|
+
}
|
|
7121
|
+
}
|
|
7122
|
+
return Buffer.from(bytes);
|
|
7123
|
+
}
|
|
7124
|
+
function scanFingerprint(content) {
|
|
7125
|
+
const digest = createHash3("sha256");
|
|
7126
|
+
let length = 0;
|
|
7127
|
+
for (let start = 0; start < content.length; start += 4096) {
|
|
7128
|
+
const chunk = encodeUtf8SurrogatePass(content.slice(start, start + 4096));
|
|
7129
|
+
length += chunk.length;
|
|
7130
|
+
digest.update(chunk);
|
|
7131
|
+
}
|
|
7132
|
+
return { bytes: length, sha256: digest.digest("hex") };
|
|
7133
|
+
}
|
|
7134
|
+
var WORKING_DIRECTORY_UNKNOWN;
|
|
7135
|
+
var init_ir = __esm({
|
|
7136
|
+
"src/engine/script-engine/ir.ts"() {
|
|
7137
|
+
"use strict";
|
|
7138
|
+
init_esm_shims();
|
|
7139
|
+
WORKING_DIRECTORY_UNKNOWN = /* @__PURE__ */ Symbol.for(
|
|
7140
|
+
"agent-moss.script-engine.working-directory-unknown"
|
|
7141
|
+
);
|
|
7142
|
+
}
|
|
7143
|
+
});
|
|
7144
|
+
|
|
7090
7145
|
// src/engine/script-engine/backends/python-backend.ts
|
|
7091
7146
|
import { parser } from "@lezer/python";
|
|
7147
|
+
import * as path4 from "path";
|
|
7092
7148
|
function buildLineStarts(content) {
|
|
7093
7149
|
const starts = [0];
|
|
7094
7150
|
for (let i = 0; i < content.length; i++) {
|
|
@@ -7124,14 +7180,117 @@ function makeEnv(argv) {
|
|
|
7124
7180
|
function srcSlice(node) {
|
|
7125
7181
|
return SOURCE.slice(node.from, node.to);
|
|
7126
7182
|
}
|
|
7127
|
-
function
|
|
7128
|
-
|
|
7129
|
-
if (
|
|
7130
|
-
|
|
7131
|
-
|
|
7183
|
+
function decodePythonStringLiteral(raw) {
|
|
7184
|
+
const m = /^([rubfRUBF]*)(\"\"\"|'''|"|')/.exec(raw);
|
|
7185
|
+
if (m === null) return null;
|
|
7186
|
+
const prefix = m[1].toLowerCase();
|
|
7187
|
+
const quote = m[2];
|
|
7188
|
+
if (prefix.includes("b") && (prefix.includes("f") || prefix.includes("u"))) return null;
|
|
7189
|
+
if (prefix.includes("f")) return null;
|
|
7190
|
+
if (!raw.endsWith(quote) || raw.length < m[0].length + quote.length) return null;
|
|
7191
|
+
const inner = raw.slice(m[0].length, raw.length - quote.length);
|
|
7192
|
+
const isBytes = prefix.includes("b");
|
|
7193
|
+
if (prefix.includes("r")) {
|
|
7194
|
+
return { value: inner.replace(/\r\n/g, "\n"), bytes: isBytes };
|
|
7195
|
+
}
|
|
7196
|
+
const decoded = unescapePythonString(inner, isBytes);
|
|
7197
|
+
if (decoded === null) return null;
|
|
7198
|
+
return { value: decoded, bytes: isBytes };
|
|
7199
|
+
}
|
|
7200
|
+
function unescapePythonString(text, isBytes) {
|
|
7201
|
+
let out = "";
|
|
7202
|
+
for (let i = 0; i < text.length; i++) {
|
|
7203
|
+
const ch = text[i];
|
|
7204
|
+
if (ch !== "\\") {
|
|
7205
|
+
out += ch;
|
|
7206
|
+
continue;
|
|
7207
|
+
}
|
|
7208
|
+
const next = text[i + 1];
|
|
7209
|
+
if (next === void 0) return null;
|
|
7210
|
+
i += 1;
|
|
7211
|
+
switch (next) {
|
|
7212
|
+
case "\n":
|
|
7213
|
+
break;
|
|
7214
|
+
// line continuation
|
|
7215
|
+
case "\\":
|
|
7216
|
+
out += "\\";
|
|
7217
|
+
break;
|
|
7218
|
+
case "'":
|
|
7219
|
+
out += "'";
|
|
7220
|
+
break;
|
|
7221
|
+
case '"':
|
|
7222
|
+
out += '"';
|
|
7223
|
+
break;
|
|
7224
|
+
case "a":
|
|
7225
|
+
out += "\x07";
|
|
7226
|
+
break;
|
|
7227
|
+
case "b":
|
|
7228
|
+
out += "\b";
|
|
7229
|
+
break;
|
|
7230
|
+
case "f":
|
|
7231
|
+
out += "\f";
|
|
7232
|
+
break;
|
|
7233
|
+
case "n":
|
|
7234
|
+
out += "\n";
|
|
7235
|
+
break;
|
|
7236
|
+
case "r":
|
|
7237
|
+
out += "\r";
|
|
7238
|
+
break;
|
|
7239
|
+
case "t":
|
|
7240
|
+
out += " ";
|
|
7241
|
+
break;
|
|
7242
|
+
case "v":
|
|
7243
|
+
out += "\v";
|
|
7244
|
+
break;
|
|
7245
|
+
case "x": {
|
|
7246
|
+
const hex = text.slice(i + 1, i + 3);
|
|
7247
|
+
if (!/^[0-9a-fA-F]{2}$/.test(hex)) return null;
|
|
7248
|
+
out += String.fromCharCode(parseInt(hex, 16));
|
|
7249
|
+
i += 2;
|
|
7250
|
+
break;
|
|
7251
|
+
}
|
|
7252
|
+
case "u": {
|
|
7253
|
+
if (isBytes) return null;
|
|
7254
|
+
const hex = text.slice(i + 1, i + 5);
|
|
7255
|
+
if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null;
|
|
7256
|
+
out += String.fromCharCode(parseInt(hex, 16));
|
|
7257
|
+
i += 4;
|
|
7258
|
+
break;
|
|
7259
|
+
}
|
|
7260
|
+
case "U": {
|
|
7261
|
+
if (isBytes) return null;
|
|
7262
|
+
const hex = text.slice(i + 1, i + 9);
|
|
7263
|
+
if (!/^[0-9a-fA-F]{8}$/.test(hex)) return null;
|
|
7264
|
+
const cp = parseInt(hex, 16);
|
|
7265
|
+
if (cp > 1114111) return null;
|
|
7266
|
+
out += String.fromCodePoint(cp);
|
|
7267
|
+
i += 8;
|
|
7268
|
+
break;
|
|
7269
|
+
}
|
|
7270
|
+
case "0":
|
|
7271
|
+
case "1":
|
|
7272
|
+
case "2":
|
|
7273
|
+
case "3":
|
|
7274
|
+
case "4":
|
|
7275
|
+
case "5":
|
|
7276
|
+
case "6":
|
|
7277
|
+
case "7": {
|
|
7278
|
+
let oct = next;
|
|
7279
|
+
for (let k = 0; k < 2 && /[0-7]/.test(text[i + 1] ?? ""); k++) {
|
|
7280
|
+
oct += text[i + 1];
|
|
7281
|
+
i += 1;
|
|
7282
|
+
}
|
|
7283
|
+
out += String.fromCharCode(parseInt(oct, 8));
|
|
7284
|
+
break;
|
|
7285
|
+
}
|
|
7286
|
+
case "N":
|
|
7287
|
+
return null;
|
|
7288
|
+
default:
|
|
7289
|
+
out += "\\" + next;
|
|
7290
|
+
break;
|
|
7291
|
+
}
|
|
7132
7292
|
}
|
|
7133
|
-
|
|
7134
|
-
return s;
|
|
7293
|
+
return out;
|
|
7135
7294
|
}
|
|
7136
7295
|
function isSysArgv(node) {
|
|
7137
7296
|
if (!node || node.name !== "MemberExpression") return false;
|
|
@@ -7143,7 +7302,14 @@ function isSysArgv(node) {
|
|
|
7143
7302
|
function evalExpr(node, env2) {
|
|
7144
7303
|
if (!node) return null;
|
|
7145
7304
|
const name = node.name;
|
|
7146
|
-
if (name === "String")
|
|
7305
|
+
if (name === "String") {
|
|
7306
|
+
const decoded = decodePythonStringLiteral(srcSlice(node));
|
|
7307
|
+
return decoded !== null && !decoded.bytes ? decoded.value : null;
|
|
7308
|
+
}
|
|
7309
|
+
if (name === "ContinuedString") {
|
|
7310
|
+
const decoded = literalStringText(node);
|
|
7311
|
+
return decoded;
|
|
7312
|
+
}
|
|
7147
7313
|
if (name === "Number") return srcSlice(node);
|
|
7148
7314
|
if (name === "VariableName") {
|
|
7149
7315
|
const id = srcSlice(node);
|
|
@@ -7175,6 +7341,9 @@ function evalExpr(node, env2) {
|
|
|
7175
7341
|
}
|
|
7176
7342
|
return null;
|
|
7177
7343
|
}
|
|
7344
|
+
if (name === "ParenthesizedExpression") {
|
|
7345
|
+
return evalExpr(firstNamedChild(node), env2);
|
|
7346
|
+
}
|
|
7178
7347
|
if (name === "ConditionalExpression") {
|
|
7179
7348
|
const ifKw = node.getChild("if");
|
|
7180
7349
|
const elseKw = node.getChild("else");
|
|
@@ -7218,7 +7387,7 @@ function lastNamedChild(node) {
|
|
|
7218
7387
|
function findOp(node) {
|
|
7219
7388
|
let c = node.firstChild;
|
|
7220
7389
|
while (c) {
|
|
7221
|
-
if (c.name === "CompareOp" || c.name === "and" || c.name === "or" || c.name === "UpdateOp") {
|
|
7390
|
+
if (c.name === "CompareOp" || c.name === "and" || c.name === "or" || c.name === "UpdateOp" || c.name === "ArithOp") {
|
|
7222
7391
|
return srcSlice(c).trim();
|
|
7223
7392
|
}
|
|
7224
7393
|
c = c.nextSibling;
|
|
@@ -7228,6 +7397,9 @@ function findOp(node) {
|
|
|
7228
7397
|
function evalCondition(node, env2) {
|
|
7229
7398
|
if (!node) return null;
|
|
7230
7399
|
const name = node.name;
|
|
7400
|
+
if (name === "ParenthesizedExpression") {
|
|
7401
|
+
return evalCondition(firstNamedChild(node), env2);
|
|
7402
|
+
}
|
|
7231
7403
|
if (name === "Boolean") {
|
|
7232
7404
|
const t = srcSlice(node).trim();
|
|
7233
7405
|
return t === "True" ? true : t === "False" ? false : null;
|
|
@@ -7235,7 +7407,7 @@ function evalCondition(node, env2) {
|
|
|
7235
7407
|
if (name === "BinaryExpression") {
|
|
7236
7408
|
const op = findOp(node);
|
|
7237
7409
|
if (op === "and" || op === "or") {
|
|
7238
|
-
const parts2 = namedChildren(node);
|
|
7410
|
+
const parts2 = namedChildren(node).filter((p) => p.name !== "and" && p.name !== "or");
|
|
7239
7411
|
const vals = parts2.map((p) => evalCondition(p, env2));
|
|
7240
7412
|
if (op === "and") {
|
|
7241
7413
|
if (vals.some((v) => v === false)) return false;
|
|
@@ -7321,8 +7493,8 @@ function evalCompare(left, opText, right, env2) {
|
|
|
7321
7493
|
}
|
|
7322
7494
|
return null;
|
|
7323
7495
|
}
|
|
7324
|
-
function processStmts(stmts, env2, lineStarts, lines, branches) {
|
|
7325
|
-
for (const s of stmts) processStmt(s, env2, lineStarts, lines, branches);
|
|
7496
|
+
function processStmts(stmts, env2, lineStarts, lines, branches, ifDecisions) {
|
|
7497
|
+
for (const s of stmts) processStmt(s, env2, lineStarts, lines, branches, ifDecisions);
|
|
7326
7498
|
}
|
|
7327
7499
|
function invalidateEnvOnCalls(node, env2) {
|
|
7328
7500
|
const cursor = node.cursor();
|
|
@@ -7337,15 +7509,31 @@ function invalidateEnvOnCalls(node, env2) {
|
|
|
7337
7509
|
return true;
|
|
7338
7510
|
});
|
|
7339
7511
|
}
|
|
7340
|
-
function
|
|
7512
|
+
function assignmentParts(stmt) {
|
|
7513
|
+
const targets = [];
|
|
7514
|
+
let lastAssign = null;
|
|
7515
|
+
let c = stmt.firstChild;
|
|
7516
|
+
while (c) {
|
|
7517
|
+
if (c.name === "AssignOp") lastAssign = c;
|
|
7518
|
+
c = c.nextSibling;
|
|
7519
|
+
}
|
|
7520
|
+
if (lastAssign === null) return { targets, value: null };
|
|
7521
|
+
const value = lastAssign.nextSibling;
|
|
7522
|
+
c = stmt.firstChild;
|
|
7523
|
+
while (c && !sameNode(c, lastAssign)) {
|
|
7524
|
+
if (c.name === "VariableName") targets.push(c);
|
|
7525
|
+
c = c.nextSibling;
|
|
7526
|
+
}
|
|
7527
|
+
return { targets, value };
|
|
7528
|
+
}
|
|
7529
|
+
function processStmt(stmt, env2, lineStarts, lines, branches, ifDecisions) {
|
|
7341
7530
|
const name = stmt.name;
|
|
7531
|
+
if (name === "Comment") return;
|
|
7342
7532
|
if (name === "AssignStatement") {
|
|
7343
|
-
const
|
|
7344
|
-
if (
|
|
7345
|
-
const valNode = target.nextSibling ? target.nextSibling.nextSibling : null;
|
|
7533
|
+
const { targets, value } = assignmentParts(stmt);
|
|
7534
|
+
if (targets.length === 1) {
|
|
7346
7535
|
invalidateEnvOnCalls(stmt, env2);
|
|
7347
|
-
|
|
7348
|
-
env2.vars[srcSlice(target)] = val;
|
|
7536
|
+
env2.vars[srcSlice(targets[0])] = evalExpr(value, env2);
|
|
7349
7537
|
}
|
|
7350
7538
|
markNodeLines(stmt, lines, lineStarts);
|
|
7351
7539
|
return;
|
|
@@ -7358,34 +7546,34 @@ function processStmt(stmt, env2, lineStarts, lines, branches) {
|
|
|
7358
7546
|
return;
|
|
7359
7547
|
}
|
|
7360
7548
|
if (name === "IfStatement") {
|
|
7361
|
-
processIf(stmt, env2, lineStarts, lines, branches);
|
|
7549
|
+
processIf(stmt, env2, lineStarts, lines, branches, ifDecisions);
|
|
7362
7550
|
return;
|
|
7363
7551
|
}
|
|
7364
7552
|
if (name === "ForStatement" || name === "WhileStatement") {
|
|
7365
7553
|
markNodeLines(stmt, lines, lineStarts);
|
|
7366
7554
|
for (const body of stmt.getChildren("Body")) {
|
|
7367
|
-
processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
|
|
7555
|
+
processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
|
|
7368
7556
|
}
|
|
7369
7557
|
return;
|
|
7370
7558
|
}
|
|
7371
7559
|
if (name === "TryStatement") {
|
|
7372
7560
|
markNodeLines(stmt, lines, lineStarts);
|
|
7373
7561
|
for (const body of stmt.getChildren("Body")) {
|
|
7374
|
-
processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
|
|
7562
|
+
processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
|
|
7375
7563
|
}
|
|
7376
7564
|
return;
|
|
7377
7565
|
}
|
|
7378
7566
|
if (name === "WithStatement") {
|
|
7379
7567
|
markNodeLines(stmt, lines, lineStarts);
|
|
7380
7568
|
const body = stmt.getChild("Body");
|
|
7381
|
-
if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
|
|
7569
|
+
if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
|
|
7382
7570
|
return;
|
|
7383
7571
|
}
|
|
7384
7572
|
if (name === "MatchStatement") {
|
|
7385
7573
|
markNodeLines(stmt, lines, lineStarts);
|
|
7386
7574
|
for (const clause of stmt.getChildren("MatchClause")) {
|
|
7387
7575
|
const body = clause.getChild("Body");
|
|
7388
|
-
if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
|
|
7576
|
+
if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
|
|
7389
7577
|
}
|
|
7390
7578
|
return;
|
|
7391
7579
|
}
|
|
@@ -7407,14 +7595,26 @@ function markDefTree(stmt, lines, lineStarts) {
|
|
|
7407
7595
|
}
|
|
7408
7596
|
function bodyStmts(body) {
|
|
7409
7597
|
const out = [];
|
|
7598
|
+
const append = (node) => {
|
|
7599
|
+
if (node.name === "StatementGroup") {
|
|
7600
|
+
let c2 = node.firstChild;
|
|
7601
|
+
while (c2) {
|
|
7602
|
+
append(c2);
|
|
7603
|
+
c2 = c2.nextSibling;
|
|
7604
|
+
}
|
|
7605
|
+
return;
|
|
7606
|
+
}
|
|
7607
|
+
if (node.name === ":" || node.name === ";" || node.name === "\n") return;
|
|
7608
|
+
out.push(node);
|
|
7609
|
+
};
|
|
7410
7610
|
let c = body.firstChild;
|
|
7411
7611
|
while (c) {
|
|
7412
|
-
|
|
7612
|
+
append(c);
|
|
7413
7613
|
c = c.nextSibling;
|
|
7414
7614
|
}
|
|
7415
7615
|
return out;
|
|
7416
7616
|
}
|
|
7417
|
-
function
|
|
7617
|
+
function collectIfSections(stmt) {
|
|
7418
7618
|
const sections = [];
|
|
7419
7619
|
let c = stmt.firstChild;
|
|
7420
7620
|
while (c) {
|
|
@@ -7429,17 +7629,24 @@ function processIf(stmt, env2, lineStarts, lines, branches) {
|
|
|
7429
7629
|
}
|
|
7430
7630
|
c = c.nextSibling;
|
|
7431
7631
|
}
|
|
7432
|
-
|
|
7632
|
+
return sections;
|
|
7433
7633
|
}
|
|
7434
|
-
function
|
|
7634
|
+
function processIf(stmt, env2, lineStarts, lines, branches, ifDecisions) {
|
|
7635
|
+
const sections = collectIfSections(stmt);
|
|
7636
|
+
const decisions = [];
|
|
7637
|
+
ifDecisions.set(stmt.from, decisions);
|
|
7638
|
+
processIfSections(sections, decisions, 0, env2, lineStarts, lines, branches, ifDecisions);
|
|
7639
|
+
}
|
|
7640
|
+
function processIfSections(sections, decisions, idx, env2, lineStarts, lines, branches, ifDecisions) {
|
|
7435
7641
|
if (idx >= sections.length) return;
|
|
7436
7642
|
const s = sections[idx];
|
|
7437
7643
|
if (s.cond) markNodeLines(s.cond, lines, lineStarts);
|
|
7438
7644
|
if (s.isElse) {
|
|
7439
|
-
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches);
|
|
7645
|
+
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches, ifDecisions);
|
|
7440
7646
|
return;
|
|
7441
7647
|
}
|
|
7442
7648
|
const cond = s.cond ? evalCondition(s.cond, env2) : null;
|
|
7649
|
+
decisions[idx] = cond;
|
|
7443
7650
|
branches.push({
|
|
7444
7651
|
kind: "if",
|
|
7445
7652
|
label: s.cond ? srcSlice(s.cond) : "",
|
|
@@ -7447,138 +7654,1107 @@ function processIfSections(_stmt, sections, idx, env2, lineStarts, lines, branch
|
|
|
7447
7654
|
reachable: cond !== false
|
|
7448
7655
|
});
|
|
7449
7656
|
if (cond === true) {
|
|
7450
|
-
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches);
|
|
7657
|
+
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches, ifDecisions);
|
|
7451
7658
|
return;
|
|
7452
7659
|
}
|
|
7453
7660
|
if (cond === false) {
|
|
7454
|
-
processIfSections(
|
|
7661
|
+
processIfSections(sections, decisions, idx + 1, env2, lineStarts, lines, branches, ifDecisions);
|
|
7455
7662
|
return;
|
|
7456
7663
|
}
|
|
7457
|
-
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches);
|
|
7664
|
+
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches, ifDecisions);
|
|
7458
7665
|
for (let j = idx + 1; j < sections.length; j++) {
|
|
7459
7666
|
const sj = sections[j];
|
|
7460
7667
|
if (sj.cond) markNodeLines(sj.cond, lines, lineStarts);
|
|
7461
|
-
if (sj.body) processStmts(bodyStmts(sj.body), env2, lineStarts, lines, branches);
|
|
7668
|
+
if (sj.body) processStmts(bodyStmts(sj.body), env2, lineStarts, lines, branches, ifDecisions);
|
|
7462
7669
|
}
|
|
7463
7670
|
}
|
|
7464
|
-
function
|
|
7465
|
-
|
|
7466
|
-
|
|
7467
|
-
|
|
7468
|
-
|
|
7469
|
-
|
|
7470
|
-
|
|
7471
|
-
|
|
7472
|
-
|
|
7473
|
-
|
|
7474
|
-
|
|
7475
|
-
|
|
7671
|
+
function basenameOf(p) {
|
|
7672
|
+
const index = p.lastIndexOf("/");
|
|
7673
|
+
return index < 0 ? p : p.slice(index + 1);
|
|
7674
|
+
}
|
|
7675
|
+
function callKey(call) {
|
|
7676
|
+
const cwd = call.launchCwd === WORKING_DIRECTORY_UNKNOWN ? "\0UNKNOWN" : call.launchCwd === void 0 || call.launchCwd === null ? "\0NONE" : call.launchCwd;
|
|
7677
|
+
return `${call.path}\0${call.args.join("\0")}\0${call.interpreter}\0${cwd}`;
|
|
7678
|
+
}
|
|
7679
|
+
function sameNode(a, b) {
|
|
7680
|
+
return a !== null && b !== null && a.from === b.from && a.to === b.to && a.name === b.name;
|
|
7681
|
+
}
|
|
7682
|
+
function firstInnerNode(node) {
|
|
7683
|
+
let c = node.firstChild;
|
|
7684
|
+
while (c) {
|
|
7685
|
+
if (!["(", ")", ",", ":", "[", "]", "{", "}"].includes(c.name)) return c;
|
|
7686
|
+
c = c.nextSibling;
|
|
7687
|
+
}
|
|
7688
|
+
return null;
|
|
7689
|
+
}
|
|
7690
|
+
function unwrapParens(node) {
|
|
7691
|
+
let current = node;
|
|
7692
|
+
while (current && current.name === "ParenthesizedExpression") {
|
|
7693
|
+
current = firstInnerNode(current);
|
|
7694
|
+
}
|
|
7695
|
+
return current;
|
|
7696
|
+
}
|
|
7697
|
+
function literalStringText(node) {
|
|
7698
|
+
if (!node) return null;
|
|
7699
|
+
if (node.name === "String") {
|
|
7700
|
+
const decoded = decodePythonStringLiteral(srcSlice(node));
|
|
7701
|
+
return decoded !== null && !decoded.bytes ? decoded.value : null;
|
|
7702
|
+
}
|
|
7703
|
+
if (node.name === "ContinuedString") {
|
|
7704
|
+
let out = "";
|
|
7705
|
+
let c = node.firstChild;
|
|
7706
|
+
while (c) {
|
|
7707
|
+
if (c.name === "String") {
|
|
7708
|
+
const decoded = decodePythonStringLiteral(srcSlice(c));
|
|
7709
|
+
if (decoded === null || decoded.bytes) return null;
|
|
7710
|
+
out += decoded.value;
|
|
7711
|
+
}
|
|
7712
|
+
c = c.nextSibling;
|
|
7476
7713
|
}
|
|
7477
|
-
return
|
|
7714
|
+
return out;
|
|
7715
|
+
}
|
|
7716
|
+
if (node.name === "ParenthesizedExpression") {
|
|
7717
|
+
return literalStringText(firstInnerNode(node));
|
|
7718
|
+
}
|
|
7719
|
+
if (node.name === "FormatString") {
|
|
7720
|
+
let hasReplacement = false;
|
|
7721
|
+
const cursor = node.cursor();
|
|
7722
|
+
cursor.iterate((n) => {
|
|
7723
|
+
if (n.node.name === "FormatReplacement") {
|
|
7724
|
+
hasReplacement = true;
|
|
7725
|
+
return false;
|
|
7726
|
+
}
|
|
7727
|
+
return true;
|
|
7728
|
+
});
|
|
7729
|
+
if (hasReplacement) return null;
|
|
7730
|
+
const raw = srcSlice(node);
|
|
7731
|
+
const m = /^([rRfF]*)(\"\"\"|'''|"|')/.exec(raw);
|
|
7732
|
+
if (m === null || !raw.endsWith(m[2]) || raw.length < m[0].length + m[2].length) return null;
|
|
7733
|
+
let inner = raw.slice(m[0].length, raw.length - m[2].length);
|
|
7734
|
+
inner = inner.replace(/\{\{/g, "{").replace(/\}\}/g, "}");
|
|
7735
|
+
return m[1].toLowerCase().includes("r") ? inner : unescapePythonString(inner, false);
|
|
7478
7736
|
}
|
|
7479
7737
|
return null;
|
|
7480
7738
|
}
|
|
7481
|
-
function
|
|
7739
|
+
function literalText(node, bindings) {
|
|
7740
|
+
if (!node) return null;
|
|
7741
|
+
if (node.name === "VariableName") return bindings.strings.get(srcSlice(node)) ?? null;
|
|
7742
|
+
if (node.name === "ParenthesizedExpression") return literalText(firstInnerNode(node), bindings);
|
|
7743
|
+
return literalStringText(node);
|
|
7744
|
+
}
|
|
7745
|
+
function* literalShellCommands(command) {
|
|
7746
|
+
let words = [];
|
|
7747
|
+
let assigned = false;
|
|
7748
|
+
let redirected = false;
|
|
7749
|
+
let redirectTarget = false;
|
|
7750
|
+
let index = 0;
|
|
7751
|
+
let statementStart = 0;
|
|
7752
|
+
while (index <= command.length) {
|
|
7753
|
+
const char = index < command.length ? command[index] : "\n";
|
|
7754
|
+
if (char === " " || char === " ") {
|
|
7755
|
+
index += 1;
|
|
7756
|
+
continue;
|
|
7757
|
+
}
|
|
7758
|
+
if (char === "#") {
|
|
7759
|
+
const newline = command.indexOf("\n", index);
|
|
7760
|
+
index = newline < 0 ? command.length : newline;
|
|
7761
|
+
continue;
|
|
7762
|
+
}
|
|
7763
|
+
if (char === "\n" || char === ";" || command.startsWith("&&", index) || command.startsWith("||", index)) {
|
|
7764
|
+
if (redirectTarget) return;
|
|
7765
|
+
const separator = char === "&" || char === "|" ? command.slice(index, index + 2) : char;
|
|
7766
|
+
if (words.length || redirected || assigned) {
|
|
7767
|
+
yield { words, separator, start: statementStart, redirected };
|
|
7768
|
+
}
|
|
7769
|
+
words = [];
|
|
7770
|
+
assigned = false;
|
|
7771
|
+
redirected = false;
|
|
7772
|
+
index += separator.length;
|
|
7773
|
+
statementStart = index;
|
|
7774
|
+
continue;
|
|
7775
|
+
}
|
|
7776
|
+
if ((char === "<" || char === ">") && !command.startsWith("<<", index)) {
|
|
7777
|
+
if (redirectTarget) return;
|
|
7778
|
+
FILE_REDIRECT_RE.lastIndex = index;
|
|
7779
|
+
const redirect = FILE_REDIRECT_RE.exec(command);
|
|
7780
|
+
if (!redirect || redirect.index !== index) return;
|
|
7781
|
+
index += redirect[0].length;
|
|
7782
|
+
redirected = true;
|
|
7783
|
+
redirectTarget = true;
|
|
7784
|
+
continue;
|
|
7785
|
+
}
|
|
7786
|
+
const start = index;
|
|
7787
|
+
const parts = [];
|
|
7788
|
+
if (char !== "~") {
|
|
7789
|
+
while (true) {
|
|
7790
|
+
LITERAL_PART_RE.lastIndex = index;
|
|
7791
|
+
const match = LITERAL_PART_RE.exec(command);
|
|
7792
|
+
if (!match || match.index !== index) break;
|
|
7793
|
+
const raw = match[0];
|
|
7794
|
+
if (raw.startsWith('"')) parts.push(raw.slice(1, -1).replace(SHELL_DOUBLE_ESCAPE_RE, "$1"));
|
|
7795
|
+
else if (raw.startsWith("'")) parts.push(raw.slice(1, -1));
|
|
7796
|
+
else if (raw.startsWith("\\")) parts.push(raw.slice(1));
|
|
7797
|
+
else parts.push(raw);
|
|
7798
|
+
index += raw.length;
|
|
7799
|
+
}
|
|
7800
|
+
}
|
|
7801
|
+
if (parts.length === 0 || index < command.length && !" \n;<>|&".includes(command[index])) {
|
|
7802
|
+
yield { words: null, separator: "", start: statementStart, redirected };
|
|
7803
|
+
return;
|
|
7804
|
+
}
|
|
7805
|
+
if (redirectTarget) {
|
|
7806
|
+
redirectTarget = false;
|
|
7807
|
+
} else if (words.length === 0 && SHELL_ASSIGNMENT.test(command.slice(start, index))) {
|
|
7808
|
+
assigned = true;
|
|
7809
|
+
} else if (!(index < command.length && "<>".includes(command[index]) && IO_NUMBER.test(command.slice(start, index)))) {
|
|
7810
|
+
words.push(parts.join(""));
|
|
7811
|
+
}
|
|
7812
|
+
}
|
|
7813
|
+
}
|
|
7814
|
+
function legacyLiteralCalls(command, source) {
|
|
7815
|
+
let calls = extractCallsRegex(command);
|
|
7816
|
+
if (calls.length && source !== null && command !== source) {
|
|
7817
|
+
const old = new Set(extractCallsRegex(source).map(callKey));
|
|
7818
|
+
calls = calls.filter((call) => old.has(callKey(call)));
|
|
7819
|
+
}
|
|
7820
|
+
return calls.filter((call) => !call.path.includes("\0"));
|
|
7821
|
+
}
|
|
7822
|
+
function shellProgramOperand(words) {
|
|
7823
|
+
if (!words.length) return null;
|
|
7824
|
+
const name = basenameOf(words[0]);
|
|
7825
|
+
if (!SHELL_INTERPRETERS.has(name)) return null;
|
|
7826
|
+
let kind = "script";
|
|
7827
|
+
for (let index = 1; index < words.length; index++) {
|
|
7828
|
+
const word = words[index];
|
|
7829
|
+
if (word === "--") {
|
|
7830
|
+
return index + 1 < words.length ? { kind, index: index + 1 } : null;
|
|
7831
|
+
}
|
|
7832
|
+
if (!word.startsWith("-") && !word.startsWith("+")) return { kind, index };
|
|
7833
|
+
if (word.length < 2 || [...word.slice(1)].some((flag) => !"acefuvx".includes(flag))) {
|
|
7834
|
+
return null;
|
|
7835
|
+
}
|
|
7836
|
+
if (word.slice(1).includes("c")) kind = "command";
|
|
7837
|
+
}
|
|
7838
|
+
return null;
|
|
7839
|
+
}
|
|
7840
|
+
function envCommand(words) {
|
|
7841
|
+
if (!words.length || !ENV_PROGRAMS.has(words[0])) return words;
|
|
7842
|
+
let index = words.length > 1 && words[1] === "--" ? 2 : 1;
|
|
7843
|
+
while (index < words.length && SHELL_ASSIGNMENT.test(words[index])) {
|
|
7844
|
+
if (words[index].includes("\0")) return [];
|
|
7845
|
+
index += 1;
|
|
7846
|
+
}
|
|
7847
|
+
return words.slice(index);
|
|
7848
|
+
}
|
|
7849
|
+
function literalScriptCall(words) {
|
|
7850
|
+
if (words.length < 2) return null;
|
|
7851
|
+
const interpreter = words[0];
|
|
7852
|
+
const name = basenameOf(interpreter);
|
|
7853
|
+
if (!SCRIPT_INTERPRETERS.has(name) && !VERSIONED_PYTHON.test(name)) return null;
|
|
7854
|
+
if (words.some((word) => word.includes("\0"))) return null;
|
|
7855
|
+
let index = 1;
|
|
7856
|
+
if (SHELL_INTERPRETERS.has(name)) {
|
|
7857
|
+
const operand = shellProgramOperand(words);
|
|
7858
|
+
if (operand === null || operand.kind !== "script") return null;
|
|
7859
|
+
index = operand.index;
|
|
7860
|
+
} else if (words[index].startsWith("-")) {
|
|
7861
|
+
return null;
|
|
7862
|
+
}
|
|
7863
|
+
const scriptPath = words[index];
|
|
7864
|
+
if (!scriptPath || scriptPath.startsWith("$") || scriptPath.startsWith("~") || scriptPath.includes("/dev/")) {
|
|
7865
|
+
return null;
|
|
7866
|
+
}
|
|
7867
|
+
return { path: scriptPath, args: words.slice(index + 1), interpreter };
|
|
7868
|
+
}
|
|
7869
|
+
function literalShellCalls(command, source) {
|
|
7482
7870
|
const calls = [];
|
|
7483
|
-
|
|
7484
|
-
const
|
|
7485
|
-
|
|
7486
|
-
|
|
7487
|
-
|
|
7488
|
-
calls.push(
|
|
7871
|
+
let eligible = null;
|
|
7872
|
+
const statuses = /* @__PURE__ */ new Set([true, false]);
|
|
7873
|
+
let required = null;
|
|
7874
|
+
for (const entry of literalShellCommands(command)) {
|
|
7875
|
+
if (entry.words === null) {
|
|
7876
|
+
calls.push(...legacyLiteralCalls(command.slice(entry.start), source));
|
|
7877
|
+
break;
|
|
7489
7878
|
}
|
|
7490
|
-
|
|
7491
|
-
|
|
7492
|
-
|
|
7493
|
-
|
|
7494
|
-
|
|
7495
|
-
|
|
7879
|
+
if (required === null || statuses.has(required)) {
|
|
7880
|
+
if (required === null) statuses.clear();
|
|
7881
|
+
else statuses.delete(required);
|
|
7882
|
+
const words = entry.words;
|
|
7883
|
+
const head = words.length ? words[0] : "";
|
|
7884
|
+
const replacesShell = head === "exec" && words.length > 1;
|
|
7885
|
+
const program = replacesShell ? words.slice(1) : words;
|
|
7886
|
+
const call = literalScriptCall(envCommand(program));
|
|
7887
|
+
if (call !== null) {
|
|
7888
|
+
if (eligible === null || eligible.has(callKey(call))) calls.push(call);
|
|
7889
|
+
} else if (head !== "" && !["echo", "printf", ":", "true", "false", "exit"].includes(head) && !ENV_PROGRAMS.has(head) && eligible === null) {
|
|
7890
|
+
eligible = new Set(legacyLiteralCalls(command, source).map(callKey));
|
|
7891
|
+
}
|
|
7892
|
+
const exits = head === "exit" && (words.length === 1 || words.length === 2 && /^[+-]?[0-9]+$/.test(words[1]));
|
|
7893
|
+
if (exits || call !== null && replacesShell) {
|
|
7894
|
+
if (entry.redirected) statuses.add(false);
|
|
7895
|
+
} else if (!entry.redirected && [":", "true", "false"].includes(head)) {
|
|
7896
|
+
statuses.add(head !== "false");
|
|
7897
|
+
} else {
|
|
7898
|
+
statuses.add(true);
|
|
7899
|
+
statuses.add(false);
|
|
7900
|
+
}
|
|
7901
|
+
if (statuses.size === 0) break;
|
|
7902
|
+
}
|
|
7903
|
+
required = entry.separator === "&&" ? true : entry.separator === "||" ? false : null;
|
|
7904
|
+
}
|
|
7905
|
+
return calls;
|
|
7906
|
+
}
|
|
7907
|
+
function mergeBindings(maps, same) {
|
|
7908
|
+
const out = /* @__PURE__ */ new Map();
|
|
7909
|
+
if (!maps.length) return out;
|
|
7910
|
+
for (const [key, value] of maps[0]) {
|
|
7911
|
+
if (maps.every((map) => map.has(key) && same(map.get(key), value))) {
|
|
7912
|
+
out.set(key, value);
|
|
7913
|
+
}
|
|
7914
|
+
}
|
|
7915
|
+
return out;
|
|
7916
|
+
}
|
|
7917
|
+
function sameTuple(a, b) {
|
|
7918
|
+
return a[0] === b[0] && a[1] === b[1];
|
|
7919
|
+
}
|
|
7920
|
+
function purePathNormalize(p) {
|
|
7921
|
+
const absolute = p.startsWith("/");
|
|
7922
|
+
const parts = p.split("/").filter((part) => part !== "" && part !== ".");
|
|
7923
|
+
if (absolute) return "/" + parts.join("/");
|
|
7924
|
+
return parts.length ? parts.join("/") : ".";
|
|
7925
|
+
}
|
|
7926
|
+
function directoryFor(bindings, directory) {
|
|
7927
|
+
if (directory && !directory.includes("\0")) {
|
|
7928
|
+
if (path4.isAbsolute(directory)) return purePathNormalize(directory);
|
|
7929
|
+
if (bindings.cwd !== WORKING_DIRECTORY_UNKNOWN) {
|
|
7930
|
+
return purePathNormalize(`${bindings.cwd === null ? "." : bindings.cwd}/${directory}`);
|
|
7931
|
+
}
|
|
7932
|
+
}
|
|
7933
|
+
return WORKING_DIRECTORY_UNKNOWN;
|
|
7934
|
+
}
|
|
7935
|
+
function recordImportText(node, bindings) {
|
|
7936
|
+
const text = srcSlice(node).trim();
|
|
7937
|
+
const fromMatch = /^from\s+([\s\S]*?)\s+import\s+([\s\S]+)$/.exec(text);
|
|
7938
|
+
if (fromMatch !== null) {
|
|
7939
|
+
const head = fromMatch[1].trim();
|
|
7940
|
+
const levelMatch = /^(\.+)([\s\S]*)$/.exec(head);
|
|
7941
|
+
const level = levelMatch === null ? 0 : levelMatch[1].length;
|
|
7942
|
+
const module = (levelMatch === null ? head : levelMatch[2]).trim();
|
|
7943
|
+
for (const part of fromMatch[2].replace(/[()]/g, " ").split(",")) {
|
|
7944
|
+
const trimmed = part.trim();
|
|
7945
|
+
if (trimmed === "*") {
|
|
7946
|
+
bindings.invalidate();
|
|
7947
|
+
continue;
|
|
7948
|
+
}
|
|
7949
|
+
const nameMatch = /^([A-Za-z_][\w.]*)(?:\s+as\s+([A-Za-z_][\w.]*))?$/.exec(trimmed);
|
|
7950
|
+
if (nameMatch === null) continue;
|
|
7951
|
+
const name = nameMatch[1];
|
|
7952
|
+
const bound = nameMatch[2] || name.split(".")[0];
|
|
7953
|
+
bindings.forget(bound);
|
|
7954
|
+
if (level === 0 && module && CALL_FUNCTIONS[module]?.has(name)) {
|
|
7955
|
+
bindings.functions.set(bound, [module, name]);
|
|
7956
|
+
}
|
|
7957
|
+
}
|
|
7958
|
+
return;
|
|
7959
|
+
}
|
|
7960
|
+
const importMatch = /^import\s+([\s\S]+)$/.exec(text);
|
|
7961
|
+
if (importMatch === null) return;
|
|
7962
|
+
for (const part of importMatch[1].split(",")) {
|
|
7963
|
+
const nameMatch = /^([A-Za-z_][\w.]*)(?:\s+as\s+([A-Za-z_][\w.]*))?$/.exec(part.trim());
|
|
7964
|
+
if (nameMatch === null) continue;
|
|
7965
|
+
const full = nameMatch[1];
|
|
7966
|
+
const alias = nameMatch[2];
|
|
7967
|
+
const name = alias || full;
|
|
7968
|
+
const bound = alias || full.split(".")[0];
|
|
7969
|
+
bindings.forget(bound);
|
|
7970
|
+
const module = alias ? full : full.split(".")[0];
|
|
7971
|
+
if (CALL_FUNCTIONS[module]) bindings.modules.set(bound, module);
|
|
7972
|
+
}
|
|
7973
|
+
}
|
|
7974
|
+
function sequenceElements(node) {
|
|
7975
|
+
if (node.name !== "ArrayExpression" && node.name !== "TupleExpression") return null;
|
|
7976
|
+
const out = [];
|
|
7977
|
+
let c = node.firstChild;
|
|
7978
|
+
while (c) {
|
|
7979
|
+
if (!["[", "]", "(", ")", ","].includes(c.name)) out.push(c);
|
|
7980
|
+
c = c.nextSibling;
|
|
7981
|
+
}
|
|
7982
|
+
return out;
|
|
7983
|
+
}
|
|
7984
|
+
function literalKeywordDict(node) {
|
|
7985
|
+
if (!node || node.name !== "DictionaryExpression") return null;
|
|
7986
|
+
const out = /* @__PURE__ */ new Map();
|
|
7987
|
+
let c = node.firstChild;
|
|
7988
|
+
while (c) {
|
|
7989
|
+
if (["{", "}", ","].includes(c.name)) {
|
|
7990
|
+
c = c.nextSibling;
|
|
7991
|
+
continue;
|
|
7992
|
+
}
|
|
7993
|
+
if (c.name === "**") {
|
|
7994
|
+
const nestedNode = c.nextSibling;
|
|
7995
|
+
const nested = nestedNode === null ? null : literalKeywordDict(nestedNode);
|
|
7996
|
+
if (nested === null) return null;
|
|
7997
|
+
for (const [key, value2] of nested) out.set(key, value2);
|
|
7998
|
+
c = nestedNode === null ? null : nestedNode.nextSibling;
|
|
7999
|
+
continue;
|
|
8000
|
+
}
|
|
8001
|
+
const keyNode = c;
|
|
8002
|
+
const colon = keyNode.nextSibling;
|
|
8003
|
+
const value = colon === null ? null : colon.nextSibling;
|
|
8004
|
+
if (colon === null || colon.name !== ":" || value === null) return null;
|
|
8005
|
+
const decoded = keyNode.name === "String" ? decodePythonStringLiteral(srcSlice(keyNode)) : null;
|
|
8006
|
+
if (decoded === null || decoded.bytes) return null;
|
|
8007
|
+
out.set(decoded.value, value);
|
|
8008
|
+
c = value.nextSibling;
|
|
8009
|
+
}
|
|
8010
|
+
return out;
|
|
8011
|
+
}
|
|
8012
|
+
function parseCallArgs(node) {
|
|
8013
|
+
const argList = node.getChild("ArgList");
|
|
8014
|
+
if (!argList) return { positional: [], keywords: /* @__PURE__ */ new Map(), hasStar: false };
|
|
8015
|
+
const positional = [];
|
|
8016
|
+
const keywords = /* @__PURE__ */ new Map();
|
|
8017
|
+
let hasStar = false;
|
|
8018
|
+
let keywordInvalid = false;
|
|
8019
|
+
let c = argList.firstChild;
|
|
8020
|
+
while (c) {
|
|
8021
|
+
const name = c.name;
|
|
8022
|
+
if (name === "(" || name === ")" || name === ",") {
|
|
8023
|
+
c = c.nextSibling;
|
|
8024
|
+
continue;
|
|
8025
|
+
}
|
|
8026
|
+
if (name === "**") {
|
|
8027
|
+
const value = c.nextSibling;
|
|
8028
|
+
const expansion = value === null ? null : literalKeywordDict(value);
|
|
8029
|
+
if (expansion === null) {
|
|
8030
|
+
keywordInvalid = true;
|
|
8031
|
+
} else {
|
|
8032
|
+
for (const [key, val] of expansion) {
|
|
8033
|
+
if (keywords.has(key)) keywordInvalid = true;
|
|
8034
|
+
else keywords.set(key, val);
|
|
8035
|
+
}
|
|
8036
|
+
}
|
|
8037
|
+
c = value === null ? null : value.nextSibling;
|
|
8038
|
+
continue;
|
|
8039
|
+
}
|
|
8040
|
+
if (name === "*") {
|
|
8041
|
+
hasStar = true;
|
|
8042
|
+
const value = c.nextSibling;
|
|
8043
|
+
c = value === null ? null : value.nextSibling;
|
|
8044
|
+
continue;
|
|
8045
|
+
}
|
|
8046
|
+
if (name === "VariableName" && c.nextSibling !== null && c.nextSibling.name === "AssignOp") {
|
|
8047
|
+
const key = srcSlice(c);
|
|
8048
|
+
const value = c.nextSibling.nextSibling;
|
|
8049
|
+
if (value === null || keywords.has(key)) keywordInvalid = true;
|
|
8050
|
+
else keywords.set(key, value);
|
|
8051
|
+
c = value === null ? null : value.nextSibling;
|
|
8052
|
+
continue;
|
|
8053
|
+
}
|
|
8054
|
+
positional.push(c);
|
|
8055
|
+
c = c.nextSibling;
|
|
8056
|
+
}
|
|
8057
|
+
return { positional, keywords: keywordInvalid ? null : keywords, hasStar };
|
|
8058
|
+
}
|
|
8059
|
+
function callIdentity(node, bindings) {
|
|
8060
|
+
const func = unwrapParens(node.firstChild);
|
|
8061
|
+
if (!func) return null;
|
|
8062
|
+
if (func.name === "MemberExpression") {
|
|
8063
|
+
const moduleNode = unwrapParens(func.firstChild);
|
|
8064
|
+
if (!moduleNode || moduleNode.name !== "VariableName") return null;
|
|
8065
|
+
const property = func.getChild("PropertyName");
|
|
8066
|
+
if (!property) return null;
|
|
8067
|
+
const module = bindings.modules.get(srcSlice(moduleNode));
|
|
8068
|
+
const method = srcSlice(property);
|
|
8069
|
+
if (module !== void 0 && CALL_FUNCTIONS[module]?.has(method)) return [module, method];
|
|
8070
|
+
return null;
|
|
8071
|
+
}
|
|
8072
|
+
if (func.name === "VariableName") {
|
|
8073
|
+
return bindings.functions.get(srcSlice(func)) ?? null;
|
|
8074
|
+
}
|
|
8075
|
+
return null;
|
|
8076
|
+
}
|
|
8077
|
+
function isConstantNode(node) {
|
|
8078
|
+
return ["String", "Number", "Boolean", "None"].includes(node.name);
|
|
8079
|
+
}
|
|
8080
|
+
function isLiteralPrint(node, bindings) {
|
|
8081
|
+
if (!bindings.builtinPrint) return false;
|
|
8082
|
+
const func = unwrapParens(node.firstChild);
|
|
8083
|
+
if (!func || func.name !== "VariableName" || srcSlice(func) !== "print") return false;
|
|
8084
|
+
const args = parseCallArgs(node);
|
|
8085
|
+
if (args === null || args.hasStar || args.keywords === null) return false;
|
|
8086
|
+
if (!args.positional.every(isConstantNode)) return false;
|
|
8087
|
+
for (const [key, value] of args.keywords) {
|
|
8088
|
+
if (!["sep", "end", "flush"].includes(key) || !isConstantNode(value)) return false;
|
|
8089
|
+
}
|
|
8090
|
+
return true;
|
|
8091
|
+
}
|
|
8092
|
+
function observeChdir(node, bindings, method, standalone) {
|
|
8093
|
+
let directory = null;
|
|
8094
|
+
if (standalone && method === "chdir") {
|
|
8095
|
+
const args = parseCallArgs(node);
|
|
8096
|
+
if (args !== null && !args.hasStar && args.keywords !== null) {
|
|
8097
|
+
if (args.positional.length === 1 && args.keywords.size === 0) {
|
|
8098
|
+
directory = literalText(args.positional[0], bindings);
|
|
8099
|
+
} else if (args.positional.length === 0 && args.keywords.size === 1 && args.keywords.has("path")) {
|
|
8100
|
+
directory = literalText(args.keywords.get("path"), bindings);
|
|
8101
|
+
}
|
|
8102
|
+
}
|
|
8103
|
+
}
|
|
8104
|
+
bindings.changeDirectory(directory);
|
|
8105
|
+
}
|
|
8106
|
+
function subprocessCalls(command, options, source, bindings) {
|
|
8107
|
+
const executableNode = options.get("executable");
|
|
8108
|
+
const shellNode = options.get("shell");
|
|
8109
|
+
let executable = null;
|
|
8110
|
+
if (executableNode !== void 0) {
|
|
8111
|
+
if (executableNode.name === "None") {
|
|
8112
|
+
executable = null;
|
|
8113
|
+
} else if (executableNode.name === "String") {
|
|
8114
|
+
const decoded = decodePythonStringLiteral(srcSlice(executableNode));
|
|
8115
|
+
if (decoded === null || decoded.bytes || decoded.value === "" || decoded.value.includes("\0")) {
|
|
8116
|
+
return [];
|
|
8117
|
+
}
|
|
8118
|
+
executable = decoded.value;
|
|
8119
|
+
} else {
|
|
8120
|
+
return [];
|
|
8121
|
+
}
|
|
8122
|
+
}
|
|
8123
|
+
let shell = false;
|
|
8124
|
+
if (shellNode !== void 0) {
|
|
8125
|
+
if (shellNode.name !== "Boolean") return [];
|
|
8126
|
+
shell = srcSlice(shellNode) === "True";
|
|
8127
|
+
}
|
|
8128
|
+
if (shell) {
|
|
8129
|
+
if (executable !== null && !SHELL_INTERPRETERS.has(basenameOf(executable))) return [];
|
|
8130
|
+
let commandNode = command;
|
|
8131
|
+
if (commandNode.name === "ArrayExpression" || commandNode.name === "TupleExpression") {
|
|
8132
|
+
const elements2 = sequenceElements(commandNode);
|
|
8133
|
+
if (elements2 !== null && elements2.length) commandNode = elements2[0];
|
|
8134
|
+
}
|
|
8135
|
+
const text = literalText(commandNode, bindings);
|
|
8136
|
+
return text !== null ? literalShellCalls(text, source) : [];
|
|
8137
|
+
}
|
|
8138
|
+
if (shell !== false) return [];
|
|
8139
|
+
const elements = sequenceElements(command);
|
|
8140
|
+
if (elements === null) return [];
|
|
8141
|
+
const words = [];
|
|
8142
|
+
for (const operand of elements) {
|
|
8143
|
+
const word = literalText(operand, bindings);
|
|
8144
|
+
if (word === null || word.includes("\0")) return [];
|
|
8145
|
+
words.push(word);
|
|
8146
|
+
}
|
|
8147
|
+
if (executable !== null && words.length) words[0] = executable;
|
|
8148
|
+
const resolved = envCommand(words);
|
|
8149
|
+
const program = shellProgramOperand(resolved);
|
|
8150
|
+
if (program !== null && program.kind === "command") {
|
|
8151
|
+
return literalShellCalls(resolved[program.index], source);
|
|
8152
|
+
}
|
|
8153
|
+
const call = literalScriptCall(resolved);
|
|
8154
|
+
return call === null ? [] : [call];
|
|
8155
|
+
}
|
|
8156
|
+
function decodeProcessCall(node, module, method, source, bindings) {
|
|
8157
|
+
if (module === "os" && !OS_FUNCS.has(method)) return [];
|
|
8158
|
+
const argumentName = module === "subprocess" ? "args" : method === "system" ? "command" : method === "popen" ? "cmd" : null;
|
|
8159
|
+
const args = parseCallArgs(node);
|
|
8160
|
+
if (args === null || args.hasStar || args.keywords === null) return [];
|
|
8161
|
+
const options = args.keywords;
|
|
8162
|
+
const named = argumentName === null ? void 0 : options.get(argumentName);
|
|
8163
|
+
if (named !== void 0 && args.positional.length) return [];
|
|
8164
|
+
const operand = args.positional.length ? args.positional[0] : named ?? null;
|
|
8165
|
+
if (!operand) return [];
|
|
8166
|
+
if (module === "subprocess") {
|
|
8167
|
+
for (const [name, index] of [["executable", 2], ["shell", 8], ["cwd", 9]]) {
|
|
8168
|
+
if (args.positional.length > index) {
|
|
8169
|
+
if (options.has(name)) return [];
|
|
8170
|
+
options.set(name, args.positional[index]);
|
|
8171
|
+
}
|
|
8172
|
+
}
|
|
8173
|
+
const calls = subprocessCalls(operand, options, source, bindings);
|
|
8174
|
+
const directoryNode = options.get("cwd");
|
|
8175
|
+
if (!calls.length || directoryNode === void 0) return calls;
|
|
8176
|
+
let directory;
|
|
8177
|
+
if (directoryNode.name === "None") {
|
|
8178
|
+
return calls;
|
|
8179
|
+
} else if (directoryNode.name === "String") {
|
|
8180
|
+
const decoded = decodePythonStringLiteral(srcSlice(directoryNode));
|
|
8181
|
+
if (decoded === null || decoded.value === "") return [];
|
|
8182
|
+
directory = decoded.value;
|
|
8183
|
+
} else if (isConstantNode(directoryNode)) {
|
|
8184
|
+
return [];
|
|
8185
|
+
} else {
|
|
8186
|
+
directory = literalText(directoryNode, bindings);
|
|
8187
|
+
}
|
|
8188
|
+
if (directory === "" || directory !== null && directory.includes("\0")) return [];
|
|
8189
|
+
const launchCwd = directoryFor(bindings, directory);
|
|
8190
|
+
for (const call of calls) call.launchCwd = launchCwd;
|
|
8191
|
+
return calls;
|
|
8192
|
+
}
|
|
8193
|
+
const text = literalText(operand, bindings);
|
|
8194
|
+
return text === null ? [] : literalShellCalls(text, source);
|
|
8195
|
+
}
|
|
8196
|
+
function isNodeReachable(node, ctx) {
|
|
8197
|
+
if (ctx.reachableLines === null) return true;
|
|
8198
|
+
return ctx.reachableLines.has(lineAt(ctx.lineStarts, node.from));
|
|
8199
|
+
}
|
|
8200
|
+
function forgetTarget(node, bindings) {
|
|
8201
|
+
const cursor = node.cursor();
|
|
7496
8202
|
cursor.iterate((n) => {
|
|
7497
|
-
|
|
7498
|
-
|
|
7499
|
-
|
|
7500
|
-
|
|
7501
|
-
|
|
7502
|
-
|
|
7503
|
-
|
|
7504
|
-
|
|
7505
|
-
|
|
7506
|
-
const
|
|
7507
|
-
const
|
|
7508
|
-
|
|
7509
|
-
|
|
7510
|
-
if (
|
|
7511
|
-
|
|
7512
|
-
|
|
7513
|
-
|
|
7514
|
-
|
|
7515
|
-
|
|
7516
|
-
|
|
7517
|
-
|
|
7518
|
-
|
|
7519
|
-
|
|
8203
|
+
if (n.node.name === "VariableName") bindings.forget(srcSlice(n.node));
|
|
8204
|
+
return true;
|
|
8205
|
+
});
|
|
8206
|
+
}
|
|
8207
|
+
function visitExpression(node, bindings, ctx, standaloneRoot = false) {
|
|
8208
|
+
const stack = [
|
|
8209
|
+
{ node, standalone: standaloneRoot }
|
|
8210
|
+
];
|
|
8211
|
+
while (stack.length) {
|
|
8212
|
+
const entry = stack.pop();
|
|
8213
|
+
const current = entry.node;
|
|
8214
|
+
if (current.name === "CallExpression") {
|
|
8215
|
+
handleCall(current, bindings, ctx, entry.standalone);
|
|
8216
|
+
} else if (current.name === "NamedExpression") {
|
|
8217
|
+
const target = current.firstChild;
|
|
8218
|
+
const value = current.lastChild;
|
|
8219
|
+
const literal = value === null || sameNode(value, target) ? null : literalText(value, bindings);
|
|
8220
|
+
if (target !== null && target.name === "VariableName") {
|
|
8221
|
+
bindings.forget(srcSlice(target));
|
|
8222
|
+
if (literal !== null) bindings.strings.set(srcSlice(target), literal);
|
|
8223
|
+
}
|
|
8224
|
+
} else if (current.name === "LambdaExpression") {
|
|
8225
|
+
const params = current.getChild("ParamList");
|
|
8226
|
+
const colon = current.getChild(":");
|
|
8227
|
+
if (params) {
|
|
8228
|
+
let c2 = params.firstChild;
|
|
8229
|
+
while (c2) {
|
|
8230
|
+
if (c2.name !== "ParamList") visitExpression(c2, bindings, ctx);
|
|
8231
|
+
c2 = c2.nextSibling;
|
|
7520
8232
|
}
|
|
7521
|
-
|
|
7522
|
-
|
|
7523
|
-
|
|
7524
|
-
|
|
7525
|
-
|
|
7526
|
-
|
|
7527
|
-
|
|
8233
|
+
}
|
|
8234
|
+
const local = bindings.fork();
|
|
8235
|
+
if (params) {
|
|
8236
|
+
let c2 = params.firstChild;
|
|
8237
|
+
while (c2) {
|
|
8238
|
+
if (c2.name === "VariableName") local.forget(srcSlice(c2));
|
|
8239
|
+
c2 = c2.nextSibling;
|
|
7528
8240
|
}
|
|
7529
8241
|
}
|
|
7530
|
-
if (
|
|
7531
|
-
|
|
7532
|
-
if (sc) add(sc);
|
|
8242
|
+
if (colon !== null && colon.nextSibling !== null) {
|
|
8243
|
+
visitExpression(colon.nextSibling, local, ctx);
|
|
7533
8244
|
}
|
|
7534
|
-
|
|
7535
|
-
|
|
7536
|
-
|
|
7537
|
-
|
|
8245
|
+
continue;
|
|
8246
|
+
}
|
|
8247
|
+
const children = [];
|
|
8248
|
+
let c = current.lastChild;
|
|
8249
|
+
while (c) {
|
|
8250
|
+
children.push(c);
|
|
8251
|
+
c = c.prevSibling;
|
|
8252
|
+
}
|
|
8253
|
+
for (const child of children) stack.push({ node: child, standalone: false });
|
|
8254
|
+
}
|
|
8255
|
+
}
|
|
8256
|
+
function functionNameNode(stmt) {
|
|
8257
|
+
let c = stmt.firstChild;
|
|
8258
|
+
while (c) {
|
|
8259
|
+
if (c.name === "VariableName") return c;
|
|
8260
|
+
if (c.name === "Body") return null;
|
|
8261
|
+
c = c.nextSibling;
|
|
8262
|
+
}
|
|
8263
|
+
return null;
|
|
8264
|
+
}
|
|
8265
|
+
function parameterNames(stmt) {
|
|
8266
|
+
const params = stmt.getChild("ParamList");
|
|
8267
|
+
if (!params) return [];
|
|
8268
|
+
const names = [];
|
|
8269
|
+
let c = params.firstChild;
|
|
8270
|
+
while (c) {
|
|
8271
|
+
if (c.name === "VariableName") names.push(srcSlice(c));
|
|
8272
|
+
c = c.nextSibling;
|
|
8273
|
+
}
|
|
8274
|
+
return names;
|
|
8275
|
+
}
|
|
8276
|
+
function isDocstringStatement(stmt) {
|
|
8277
|
+
if (stmt.name !== "ExpressionStatement") return false;
|
|
8278
|
+
const value = firstInnerNode(stmt);
|
|
8279
|
+
return value !== null && ["String", "ContinuedString", "FormatString"].includes(value.name);
|
|
8280
|
+
}
|
|
8281
|
+
function bodyStatements(body) {
|
|
8282
|
+
return body === null ? [] : bodyStmts(body);
|
|
8283
|
+
}
|
|
8284
|
+
function containsCallOrWalrus(node) {
|
|
8285
|
+
let found = false;
|
|
8286
|
+
const cursor = node.cursor();
|
|
8287
|
+
cursor.iterate((n) => {
|
|
8288
|
+
if (n.node.name === "CallExpression" || n.node.name === "NamedExpression") {
|
|
8289
|
+
found = true;
|
|
8290
|
+
return false;
|
|
8291
|
+
}
|
|
8292
|
+
return true;
|
|
8293
|
+
});
|
|
8294
|
+
return found;
|
|
8295
|
+
}
|
|
8296
|
+
function recordWrapper(stmt, bindings) {
|
|
8297
|
+
const params = stmt.getChild("ParamList");
|
|
8298
|
+
if (params !== null) {
|
|
8299
|
+
let c = params.firstChild;
|
|
8300
|
+
while (c) {
|
|
8301
|
+
if (c.name !== "(" && c.name !== ")") return false;
|
|
8302
|
+
c = c.nextSibling;
|
|
8303
|
+
}
|
|
8304
|
+
}
|
|
8305
|
+
const body = stmt.getChild("Body");
|
|
8306
|
+
if (body === null) return false;
|
|
8307
|
+
let statements = bodyStatements(body);
|
|
8308
|
+
if (statements.length && isDocstringStatement(statements[0])) statements = statements.slice(1);
|
|
8309
|
+
if (statements.length !== 1) return false;
|
|
8310
|
+
const only = statements[0];
|
|
8311
|
+
if (only.name !== "ExpressionStatement") return false;
|
|
8312
|
+
const value = firstInnerNode(only);
|
|
8313
|
+
if (value === null || value.name !== "CallExpression") return false;
|
|
8314
|
+
const func = unwrapParens(value.firstChild);
|
|
8315
|
+
if (func === null || func.name !== "VariableName" || !bindings.functions.has(srcSlice(func))) {
|
|
8316
|
+
return false;
|
|
8317
|
+
}
|
|
8318
|
+
const argList = value.getChild("ArgList");
|
|
8319
|
+
if (argList !== null && containsCallOrWalrus(argList)) return false;
|
|
8320
|
+
const nameNode = functionNameNode(stmt);
|
|
8321
|
+
if (nameNode === null) return false;
|
|
8322
|
+
bindings.forget(srcSlice(nameNode));
|
|
8323
|
+
bindings.wrappers.set(srcSlice(nameNode), value);
|
|
8324
|
+
return true;
|
|
8325
|
+
}
|
|
8326
|
+
function wrapperCalls(node, bindings, ctx) {
|
|
8327
|
+
const func = unwrapParens(node.firstChild);
|
|
8328
|
+
if (!func || func.name !== "VariableName") return null;
|
|
8329
|
+
const args = parseCallArgs(node);
|
|
8330
|
+
if (args === null || args.hasStar || args.positional.length || args.keywords !== null && args.keywords.size > 0) {
|
|
8331
|
+
return null;
|
|
8332
|
+
}
|
|
8333
|
+
const stored = bindings.wrappers.get(srcSlice(func));
|
|
8334
|
+
if (stored === void 0) return null;
|
|
8335
|
+
const identity = callIdentity(stored, bindings);
|
|
8336
|
+
if (identity === null) return [];
|
|
8337
|
+
const calls = decodeProcessCall(stored, identity[0], identity[1], ctx.source, bindings);
|
|
8338
|
+
for (const call of calls) {
|
|
8339
|
+
if (call.launchCwd === void 0 || call.launchCwd === null) {
|
|
8340
|
+
call.launchCwd = bindings.cwd === null ? "." : bindings.cwd;
|
|
8341
|
+
}
|
|
8342
|
+
}
|
|
8343
|
+
return calls;
|
|
8344
|
+
}
|
|
8345
|
+
function handleCall(node, bindings, ctx, standalone) {
|
|
8346
|
+
if (!isNodeReachable(node, ctx)) return;
|
|
8347
|
+
const identity = callIdentity(node, bindings);
|
|
8348
|
+
if (identity === null) {
|
|
8349
|
+
const forwarded = wrapperCalls(node, bindings, ctx);
|
|
8350
|
+
if (forwarded !== null) {
|
|
8351
|
+
ctx.found.set(node.from, forwarded);
|
|
8352
|
+
return;
|
|
8353
|
+
}
|
|
8354
|
+
if (!isLiteralPrint(node, bindings)) bindings.invalidate();
|
|
8355
|
+
return;
|
|
8356
|
+
}
|
|
8357
|
+
const [module, method] = identity;
|
|
8358
|
+
if (module === "os" && CWD_METHODS.has(method)) {
|
|
8359
|
+
observeChdir(node, bindings, method, standalone);
|
|
8360
|
+
return;
|
|
8361
|
+
}
|
|
8362
|
+
const calls = decodeProcessCall(node, module, method, ctx.source, bindings);
|
|
8363
|
+
if (!calls.length) return;
|
|
8364
|
+
let directory = bindings.cwd;
|
|
8365
|
+
if (directory === null) {
|
|
8366
|
+
const func = unwrapParens(node.firstChild);
|
|
8367
|
+
const isModuleAttribute = func !== null && func.name === "MemberExpression" && unwrapParens(func.firstChild)?.name === "VariableName" && srcSlice(unwrapParens(func.firstChild)) === module;
|
|
8368
|
+
let capturedArgument = false;
|
|
8369
|
+
const cursor = node.cursor();
|
|
8370
|
+
cursor.iterate((n) => {
|
|
8371
|
+
if (n.node.name === "VariableName" && bindings.strings.has(srcSlice(n.node))) {
|
|
8372
|
+
capturedArgument = true;
|
|
8373
|
+
return false;
|
|
7538
8374
|
}
|
|
8375
|
+
return true;
|
|
8376
|
+
});
|
|
8377
|
+
if (!isModuleAttribute || capturedArgument) directory = ".";
|
|
8378
|
+
}
|
|
8379
|
+
for (const call of calls) {
|
|
8380
|
+
if (call.launchCwd === void 0 || call.launchCwd === null) call.launchCwd = directory;
|
|
8381
|
+
}
|
|
8382
|
+
ctx.found.set(node.from, calls);
|
|
8383
|
+
}
|
|
8384
|
+
function assignedNamesInBody(body) {
|
|
8385
|
+
const assigned = /* @__PURE__ */ new Set();
|
|
8386
|
+
const external = /* @__PURE__ */ new Set();
|
|
8387
|
+
const walk = (node) => {
|
|
8388
|
+
if (node.name === "AssignStatement") {
|
|
8389
|
+
const { targets } = assignmentParts(node);
|
|
8390
|
+
for (const target of targets) assigned.add(srcSlice(target));
|
|
8391
|
+
} else if (node.name === "UpdateStatement") {
|
|
8392
|
+
const target = node.firstChild;
|
|
8393
|
+
if (target && target.name === "VariableName") assigned.add(srcSlice(target));
|
|
8394
|
+
} else if (node.name === "ForStatement") {
|
|
8395
|
+
const forToken = node.getChild("for");
|
|
8396
|
+
const target = forToken === null ? null : forToken.nextSibling;
|
|
8397
|
+
if (target) forgetTargetInto(target, assigned);
|
|
8398
|
+
} else if (node.name === "FunctionDefinition" || node.name === "ClassDefinition") {
|
|
8399
|
+
const name = functionNameNode(node);
|
|
8400
|
+
if (name) assigned.add(srcSlice(name));
|
|
8401
|
+
} else if (node.name === "ImportStatement") {
|
|
8402
|
+
const text = srcSlice(node);
|
|
8403
|
+
for (const part of text.split(",")) {
|
|
8404
|
+
const m = /([A-Za-z_][\w.]*)(?:\s+as\s+([A-Za-z_][\w.]*))?$/.exec(part.trim());
|
|
8405
|
+
if (m) assigned.add(m[2] || m[1].split(".")[0]);
|
|
8406
|
+
}
|
|
8407
|
+
} else if (node.name === "WithStatement" || node.name === "NamedExpression") {
|
|
8408
|
+
const cursor = node.cursor();
|
|
8409
|
+
let afterAs = false;
|
|
8410
|
+
cursor.iterate((n) => {
|
|
8411
|
+
if (n.node.name === "as") afterAs = true;
|
|
8412
|
+
else if (afterAs && n.node.name === "VariableName") assigned.add(srcSlice(n.node));
|
|
8413
|
+
return true;
|
|
8414
|
+
});
|
|
8415
|
+
} else if (node.name === "GlobalStatement" || node.name === "NonlocalStatement") {
|
|
8416
|
+
const cursor = node.cursor();
|
|
8417
|
+
cursor.iterate((n) => {
|
|
8418
|
+
if (n.node.name === "VariableName") external.add(srcSlice(n.node));
|
|
8419
|
+
return true;
|
|
8420
|
+
});
|
|
7539
8421
|
}
|
|
8422
|
+
let c = node.firstChild;
|
|
8423
|
+
while (c) {
|
|
8424
|
+
if (!(node.name === "FunctionDefinition" || node.name === "ClassDefinition")) walk(c);
|
|
8425
|
+
c = c.nextSibling;
|
|
8426
|
+
}
|
|
8427
|
+
};
|
|
8428
|
+
walk(body);
|
|
8429
|
+
return { assigned, external };
|
|
8430
|
+
}
|
|
8431
|
+
function forgetTargetInto(node, names) {
|
|
8432
|
+
const cursor = node.cursor();
|
|
8433
|
+
cursor.iterate((n) => {
|
|
8434
|
+
if (n.node.name === "VariableName") names.add(srcSlice(n.node));
|
|
7540
8435
|
return true;
|
|
7541
8436
|
});
|
|
7542
|
-
|
|
7543
|
-
|
|
8437
|
+
}
|
|
8438
|
+
function extractFunction(stmt, bindings, ctx) {
|
|
8439
|
+
const body = stmt.getChild("Body");
|
|
8440
|
+
let c = stmt.firstChild;
|
|
8441
|
+
while (c) {
|
|
8442
|
+
if (!sameNode(c, body) && c.name !== "def" && c.name !== "async") {
|
|
8443
|
+
visitExpression(c, bindings, ctx);
|
|
8444
|
+
}
|
|
8445
|
+
c = c.nextSibling;
|
|
8446
|
+
}
|
|
8447
|
+
if (recordWrapper(stmt, bindings)) return;
|
|
8448
|
+
const local = bindings.fork();
|
|
8449
|
+
for (const name of parameterNames(stmt)) local.forget(name);
|
|
8450
|
+
if (body !== null) {
|
|
8451
|
+
const { assigned, external } = assignedNamesInBody(body);
|
|
8452
|
+
for (const name of assigned) {
|
|
8453
|
+
if (!external.has(name)) local.forget(name);
|
|
8454
|
+
}
|
|
8455
|
+
extractBlock(bodyStatements(body), local, ctx);
|
|
8456
|
+
}
|
|
8457
|
+
if (stmt.name === "ClassDefinition") bindings.cwd = local.cwd;
|
|
8458
|
+
const nameNode = functionNameNode(stmt);
|
|
8459
|
+
if (nameNode) bindings.forget(srcSlice(nameNode));
|
|
8460
|
+
}
|
|
8461
|
+
function extractIfSections(sections, decisions, idx, bindings, ctx) {
|
|
8462
|
+
if (idx >= sections.length) return;
|
|
8463
|
+
const section = sections[idx];
|
|
8464
|
+
if (section.cond) visitExpression(section.cond, bindings, ctx);
|
|
8465
|
+
if (section.isElse) {
|
|
8466
|
+
if (section.body) extractBlock(bodyStatements(section.body), bindings, ctx);
|
|
8467
|
+
return;
|
|
8468
|
+
}
|
|
8469
|
+
const decision = decisions[idx] ?? null;
|
|
8470
|
+
if (decision === true) {
|
|
8471
|
+
if (section.body) extractBlock(bodyStatements(section.body), bindings, ctx);
|
|
8472
|
+
return;
|
|
8473
|
+
}
|
|
8474
|
+
if (decision === false) {
|
|
8475
|
+
extractIfSections(sections, decisions, idx + 1, bindings, ctx);
|
|
8476
|
+
return;
|
|
8477
|
+
}
|
|
8478
|
+
const left = bindings.fork();
|
|
8479
|
+
if (section.body) extractBlock(bodyStatements(section.body), left, ctx);
|
|
8480
|
+
const right = bindings.fork();
|
|
8481
|
+
extractIfSections(sections, decisions, idx + 1, right, ctx);
|
|
8482
|
+
bindings.merge([left, right]);
|
|
8483
|
+
}
|
|
8484
|
+
function extractBlock(stmts, bindings, ctx) {
|
|
8485
|
+
for (const stmt of stmts) {
|
|
8486
|
+
if (!isNodeReachable(stmt, ctx) && !(stmt.name === "IfStatement" && ctx.ifDecisions.has(stmt.from))) {
|
|
8487
|
+
continue;
|
|
8488
|
+
}
|
|
8489
|
+
extractStmt(stmt, bindings, ctx);
|
|
8490
|
+
}
|
|
8491
|
+
}
|
|
8492
|
+
function extractStatementExpression(stmt, bindings, ctx) {
|
|
8493
|
+
const value = firstInnerNode(stmt);
|
|
8494
|
+
if (value === null) return;
|
|
8495
|
+
visitExpression(value, bindings, ctx, true);
|
|
8496
|
+
}
|
|
8497
|
+
function extractStmt(stmt, bindings, ctx) {
|
|
8498
|
+
switch (stmt.name) {
|
|
8499
|
+
case "ImportStatement":
|
|
8500
|
+
recordImportText(stmt, bindings);
|
|
8501
|
+
return;
|
|
8502
|
+
case "DecoratedStatement": {
|
|
8503
|
+
let c = stmt.firstChild;
|
|
8504
|
+
while (c) {
|
|
8505
|
+
if (c.name === "Decorator") visitExpression(c, bindings, ctx);
|
|
8506
|
+
else if (c.name === "FunctionDefinition" || c.name === "ClassDefinition") {
|
|
8507
|
+
extractFunction(c, bindings, ctx);
|
|
8508
|
+
}
|
|
8509
|
+
c = c.nextSibling;
|
|
8510
|
+
}
|
|
8511
|
+
return;
|
|
8512
|
+
}
|
|
8513
|
+
case "FunctionDefinition":
|
|
8514
|
+
case "ClassDefinition":
|
|
8515
|
+
extractFunction(stmt, bindings, ctx);
|
|
8516
|
+
return;
|
|
8517
|
+
case "IfStatement": {
|
|
8518
|
+
const sections = collectIfSections(stmt);
|
|
8519
|
+
const decisions = ctx.ifDecisions.get(stmt.from) ?? [];
|
|
8520
|
+
extractIfSections(sections, decisions, 0, bindings, ctx);
|
|
8521
|
+
return;
|
|
8522
|
+
}
|
|
8523
|
+
case "ForStatement": {
|
|
8524
|
+
const forToken = stmt.getChild("for");
|
|
8525
|
+
const target = forToken === null ? null : forToken.nextSibling;
|
|
8526
|
+
const inToken = target === null ? null : target.nextSibling;
|
|
8527
|
+
const iter = inToken === null ? null : inToken.nextSibling;
|
|
8528
|
+
if (iter) visitExpression(iter, bindings, ctx);
|
|
8529
|
+
const bodies = stmt.getChildren("Body");
|
|
8530
|
+
if (bodies.length) {
|
|
8531
|
+
const bodyBindings = bindings.fork();
|
|
8532
|
+
if (target) forgetTarget(target, bodyBindings);
|
|
8533
|
+
extractBlock(bodyStatements(bodies[0]), bodyBindings, ctx);
|
|
8534
|
+
bindings.merge([bindings, bodyBindings]);
|
|
8535
|
+
}
|
|
8536
|
+
if (bodies.length > 1) {
|
|
8537
|
+
const elseBindings = bindings.fork();
|
|
8538
|
+
extractBlock(bodyStatements(bodies[1]), elseBindings, ctx);
|
|
8539
|
+
bindings.merge([bindings, elseBindings]);
|
|
8540
|
+
}
|
|
8541
|
+
return;
|
|
8542
|
+
}
|
|
8543
|
+
case "WhileStatement": {
|
|
8544
|
+
const whileToken = stmt.getChild("while");
|
|
8545
|
+
const body = stmt.getChild("Body");
|
|
8546
|
+
if (whileToken !== null) {
|
|
8547
|
+
const test = whileToken.nextSibling;
|
|
8548
|
+
if (test && !sameNode(test, body)) visitExpression(test, bindings, ctx);
|
|
8549
|
+
}
|
|
8550
|
+
const bodies = stmt.getChildren("Body");
|
|
8551
|
+
if (bodies.length) {
|
|
8552
|
+
const bodyBindings = bindings.fork();
|
|
8553
|
+
extractBlock(bodyStatements(bodies[0]), bodyBindings, ctx);
|
|
8554
|
+
bindings.merge([bindings, bodyBindings]);
|
|
8555
|
+
}
|
|
8556
|
+
if (bodies.length > 1) {
|
|
8557
|
+
const elseBindings = bindings.fork();
|
|
8558
|
+
extractBlock(bodyStatements(bodies[1]), elseBindings, ctx);
|
|
8559
|
+
bindings.merge([bindings, elseBindings]);
|
|
8560
|
+
}
|
|
8561
|
+
return;
|
|
8562
|
+
}
|
|
8563
|
+
case "WithStatement": {
|
|
8564
|
+
const body = stmt.getChild("Body");
|
|
8565
|
+
const bodyBindings = bindings.fork();
|
|
8566
|
+
let afterAs = false;
|
|
8567
|
+
let c = stmt.firstChild;
|
|
8568
|
+
while (c && !sameNode(c, body)) {
|
|
8569
|
+
if (c.name === "as") afterAs = true;
|
|
8570
|
+
else if (afterAs && c.name === "VariableName") {
|
|
8571
|
+
forgetTarget(c, bodyBindings);
|
|
8572
|
+
afterAs = false;
|
|
8573
|
+
} else if (!["with", ",", ":"].includes(c.name)) {
|
|
8574
|
+
visitExpression(c, bodyBindings, ctx);
|
|
8575
|
+
afterAs = false;
|
|
8576
|
+
}
|
|
8577
|
+
c = c.nextSibling;
|
|
8578
|
+
}
|
|
8579
|
+
if (body) extractBlock(bodyStatements(body), bodyBindings, ctx);
|
|
8580
|
+
bindings.merge([bindings, bodyBindings]);
|
|
8581
|
+
return;
|
|
8582
|
+
}
|
|
8583
|
+
case "TryStatement": {
|
|
8584
|
+
const bodies = stmt.getChildren("Body");
|
|
8585
|
+
let finallyToken = null;
|
|
8586
|
+
let c = stmt.firstChild;
|
|
8587
|
+
while (c) {
|
|
8588
|
+
if (c.name === "finally") finallyToken = c;
|
|
8589
|
+
c = c.nextSibling;
|
|
8590
|
+
}
|
|
8591
|
+
const finalBody = finallyToken === null ? null : finallyToken.nextSibling;
|
|
8592
|
+
const alternatives = [];
|
|
8593
|
+
let inExcept = false;
|
|
8594
|
+
const handlerNames = [];
|
|
8595
|
+
c = stmt.firstChild;
|
|
8596
|
+
while (c) {
|
|
8597
|
+
if (c.name === "except") {
|
|
8598
|
+
inExcept = true;
|
|
8599
|
+
handlerNames.length = 0;
|
|
8600
|
+
} else if (c.name === "as" && inExcept) {
|
|
8601
|
+
const nameNode = c.nextSibling;
|
|
8602
|
+
if (nameNode && nameNode.name === "VariableName") handlerNames.push(srcSlice(nameNode));
|
|
8603
|
+
} else if (c.name === "Body" && !sameNode(c, finalBody)) {
|
|
8604
|
+
const fork = bindings.fork();
|
|
8605
|
+
for (const name of handlerNames) fork.forget(name);
|
|
8606
|
+
handlerNames.length = 0;
|
|
8607
|
+
inExcept = false;
|
|
8608
|
+
extractBlock(bodyStatements(c), fork, ctx);
|
|
8609
|
+
alternatives.push(fork);
|
|
8610
|
+
} else if (c.name === "else" || c.name === "finally") {
|
|
8611
|
+
inExcept = false;
|
|
8612
|
+
}
|
|
8613
|
+
c = c.nextSibling;
|
|
8614
|
+
}
|
|
8615
|
+
bindings.merge([bindings, ...alternatives]);
|
|
8616
|
+
if (finalBody) extractBlock(bodyStatements(finalBody), bindings, ctx);
|
|
8617
|
+
return;
|
|
8618
|
+
}
|
|
8619
|
+
case "MatchStatement": {
|
|
8620
|
+
const matchToken = stmt.getChild("match");
|
|
8621
|
+
const matchBody = stmt.getChild("MatchBody");
|
|
8622
|
+
if (matchToken !== null && matchBody !== null) {
|
|
8623
|
+
const subject = matchToken.nextSibling;
|
|
8624
|
+
if (subject && !sameNode(subject, matchBody)) visitExpression(subject, bindings, ctx);
|
|
8625
|
+
}
|
|
8626
|
+
const alternatives = [];
|
|
8627
|
+
if (matchBody !== null) {
|
|
8628
|
+
for (const clause of matchBody.getChildren("MatchClause")) {
|
|
8629
|
+
const fork = bindings.fork();
|
|
8630
|
+
let c = clause.firstChild;
|
|
8631
|
+
const body = clause.getChild("Body");
|
|
8632
|
+
while (c && !sameNode(c, body)) {
|
|
8633
|
+
if (c.name !== "case") visitExpression(c, fork, ctx);
|
|
8634
|
+
c = c.nextSibling;
|
|
8635
|
+
}
|
|
8636
|
+
if (body) extractBlock(bodyStatements(body), fork, ctx);
|
|
8637
|
+
alternatives.push(fork);
|
|
8638
|
+
}
|
|
8639
|
+
}
|
|
8640
|
+
bindings.merge([bindings, ...alternatives]);
|
|
8641
|
+
return;
|
|
8642
|
+
}
|
|
8643
|
+
case "AssignStatement": {
|
|
8644
|
+
const { targets, value } = assignmentParts(stmt);
|
|
8645
|
+
if (value) visitExpression(value, bindings, ctx);
|
|
8646
|
+
if (targets.length === 1) {
|
|
8647
|
+
bindings.bindString(srcSlice(targets[0]), literalText(value, bindings));
|
|
8648
|
+
} else {
|
|
8649
|
+
for (const target of targets) forgetTarget(target, bindings);
|
|
8650
|
+
}
|
|
8651
|
+
return;
|
|
8652
|
+
}
|
|
8653
|
+
case "UpdateStatement": {
|
|
8654
|
+
const target = stmt.firstChild;
|
|
8655
|
+
const value = stmt.lastChild;
|
|
8656
|
+
if (value && value !== target) visitExpression(value, bindings, ctx);
|
|
8657
|
+
if (target && target.name === "VariableName") bindings.forget(srcSlice(target));
|
|
8658
|
+
return;
|
|
8659
|
+
}
|
|
8660
|
+
case "ExpressionStatement":
|
|
8661
|
+
extractStatementExpression(stmt, bindings, ctx);
|
|
8662
|
+
return;
|
|
8663
|
+
default: {
|
|
8664
|
+
let c = stmt.firstChild;
|
|
8665
|
+
while (c) {
|
|
8666
|
+
if (c.name !== "del") visitExpression(c, bindings, ctx);
|
|
8667
|
+
c = c.nextSibling;
|
|
8668
|
+
}
|
|
8669
|
+
}
|
|
8670
|
+
}
|
|
8671
|
+
}
|
|
8672
|
+
function relativeImportCalls(tree) {
|
|
8673
|
+
const calls = [];
|
|
8674
|
+
const cursor = tree.cursor();
|
|
8675
|
+
cursor.iterate((n) => {
|
|
7544
8676
|
const node = n.node;
|
|
7545
8677
|
if (node.name !== "ImportStatement") return true;
|
|
7546
|
-
const
|
|
7547
|
-
|
|
7548
|
-
|
|
7549
|
-
if (m) {
|
|
7550
|
-
|
|
7551
|
-
|
|
7552
|
-
|
|
8678
|
+
const text = srcSlice(node);
|
|
8679
|
+
const m = text.match(/^\s*from\s+(\.+)([A-Za-z_][\w.]*)?\s+import\s+([\s\S]+)$/);
|
|
8680
|
+
if (!m) return true;
|
|
8681
|
+
if (m[2]) {
|
|
8682
|
+
calls.push({
|
|
8683
|
+
path: m[2].replace(/\./g, "/") + ".py",
|
|
8684
|
+
args: [],
|
|
8685
|
+
interpreter: "python3",
|
|
8686
|
+
isImport: true
|
|
8687
|
+
});
|
|
8688
|
+
}
|
|
8689
|
+
for (const part of m[3].replace(/[()]/g, "").split(",")) {
|
|
8690
|
+
const name = part.trim().replace(/\s+as\s+\w+$/, "").trim();
|
|
8691
|
+
if (name && name !== "*" && /^[A-Za-z_][\w.]*$/.test(name)) {
|
|
8692
|
+
calls.push({ path: name.replace(/\./g, "/") + ".py", args: [], interpreter: "python3", isImport: true });
|
|
7553
8693
|
}
|
|
7554
8694
|
}
|
|
7555
8695
|
return true;
|
|
7556
8696
|
});
|
|
7557
8697
|
return calls;
|
|
7558
8698
|
}
|
|
8699
|
+
function extractCallsFromTree(tree, reachableLines, ifDecisions, lineStarts) {
|
|
8700
|
+
const ctx = {
|
|
8701
|
+
source: null,
|
|
8702
|
+
reachableLines,
|
|
8703
|
+
lineStarts,
|
|
8704
|
+
ifDecisions,
|
|
8705
|
+
found: /* @__PURE__ */ new Map()
|
|
8706
|
+
};
|
|
8707
|
+
const bindings = new CallBindings(null);
|
|
8708
|
+
extractBlock(bodyStmts(tree), bindings, ctx);
|
|
8709
|
+
const calls = [];
|
|
8710
|
+
const queue = [tree];
|
|
8711
|
+
for (let index = 0; index < queue.length; index++) {
|
|
8712
|
+
const node = queue[index];
|
|
8713
|
+
if (node.name === "CallExpression") {
|
|
8714
|
+
const found = ctx.found.get(node.from);
|
|
8715
|
+
if (found !== void 0) calls.push(...found);
|
|
8716
|
+
}
|
|
8717
|
+
let c = node.firstChild;
|
|
8718
|
+
while (c) {
|
|
8719
|
+
queue.push(c);
|
|
8720
|
+
c = c.nextSibling;
|
|
8721
|
+
}
|
|
8722
|
+
}
|
|
8723
|
+
calls.push(...relativeImportCalls(tree));
|
|
8724
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8725
|
+
const unique = [];
|
|
8726
|
+
for (const call of calls) {
|
|
8727
|
+
const key = callKey(call);
|
|
8728
|
+
if (seen.has(key)) continue;
|
|
8729
|
+
seen.add(key);
|
|
8730
|
+
unique.push(call);
|
|
8731
|
+
}
|
|
8732
|
+
return unique;
|
|
8733
|
+
}
|
|
7559
8734
|
function extractCallsRegex(content) {
|
|
7560
8735
|
const calls = [];
|
|
7561
8736
|
CHILD_CALL_RE.lastIndex = 0;
|
|
7562
8737
|
let m;
|
|
7563
8738
|
while ((m = CHILD_CALL_RE.exec(content)) !== null) {
|
|
7564
8739
|
const interp = m[1];
|
|
7565
|
-
const
|
|
8740
|
+
const path10 = m[2].trim();
|
|
7566
8741
|
let rest = m[3].trim();
|
|
7567
|
-
if (
|
|
8742
|
+
if (path10.startsWith("-") || path10.startsWith("$") || path10.includes("/dev/")) continue;
|
|
7568
8743
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
7569
8744
|
const args = [];
|
|
7570
8745
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
7571
8746
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
7572
8747
|
}
|
|
7573
|
-
calls.push({ path:
|
|
8748
|
+
calls.push({ path: path10, args, interpreter: interp });
|
|
7574
8749
|
}
|
|
7575
8750
|
return calls;
|
|
7576
8751
|
}
|
|
7577
|
-
var MAX_LINES, PURE_BUILTINS, CHILD_CALL_RE, SUBPROCESS_FUNCS, OS_FUNCS, SOURCE, PythonBackend;
|
|
8752
|
+
var MAX_LINES, PURE_BUILTINS, CHILD_CALL_RE, SUBPROCESS_FUNCS, OS_FUNCS, SOURCE, CWD_METHODS, CALL_FUNCTIONS, SHELL_INTERPRETERS, SCRIPT_INTERPRETERS, VERSIONED_PYTHON, ENV_PROGRAMS, SHELL_ASSIGNMENT, IO_NUMBER, LITERAL_PART_RE, SHELL_DOUBLE_ESCAPE_RE, FILE_REDIRECT_RE, CallBindings, PythonBackend;
|
|
7578
8753
|
var init_python_backend = __esm({
|
|
7579
8754
|
"src/engine/script-engine/backends/python-backend.ts"() {
|
|
7580
8755
|
"use strict";
|
|
7581
8756
|
init_esm_shims();
|
|
8757
|
+
init_ir();
|
|
7582
8758
|
MAX_LINES = 500;
|
|
7583
8759
|
PURE_BUILTINS = /* @__PURE__ */ new Set([
|
|
7584
8760
|
"len",
|
|
@@ -7627,9 +8803,86 @@ var init_python_backend = __esm({
|
|
|
7627
8803
|
SUBPROCESS_FUNCS = /* @__PURE__ */ new Set(["run", "call", "Popen", "check_call", "check_output"]);
|
|
7628
8804
|
OS_FUNCS = /* @__PURE__ */ new Set(["system", "popen", "popen2", "popen3", "popen4"]);
|
|
7629
8805
|
SOURCE = "";
|
|
8806
|
+
CWD_METHODS = /* @__PURE__ */ new Set(["chdir", "fchdir"]);
|
|
8807
|
+
CALL_FUNCTIONS = {
|
|
8808
|
+
os: /* @__PURE__ */ new Set([...OS_FUNCS, ...CWD_METHODS]),
|
|
8809
|
+
subprocess: SUBPROCESS_FUNCS
|
|
8810
|
+
};
|
|
8811
|
+
SHELL_INTERPRETERS = /* @__PURE__ */ new Set(["bash", "dash", "sh", "zsh"]);
|
|
8812
|
+
SCRIPT_INTERPRETERS = /* @__PURE__ */ new Set([
|
|
8813
|
+
...SHELL_INTERPRETERS,
|
|
8814
|
+
"python",
|
|
8815
|
+
"python3",
|
|
8816
|
+
"node",
|
|
8817
|
+
"ruby",
|
|
8818
|
+
"perl",
|
|
8819
|
+
"php",
|
|
8820
|
+
"lua"
|
|
8821
|
+
]);
|
|
8822
|
+
VERSIONED_PYTHON = /^python3\.[0-9]+t?$/;
|
|
8823
|
+
ENV_PROGRAMS = /* @__PURE__ */ new Set(["env", "/bin/env", "/usr/bin/env"]);
|
|
8824
|
+
SHELL_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
8825
|
+
IO_NUMBER = /^[0-9]+$/;
|
|
8826
|
+
LITERAL_PART_RE = /[^\s'"\\$`*?\[\]{}();|&<>]+|'[^']*'|"(?:[^"\\$`]|\\.)*"|\\[^\n]/y;
|
|
8827
|
+
SHELL_DOUBLE_ESCAPE_RE = /\\(["\\$`])/g;
|
|
8828
|
+
FILE_REDIRECT_RE = />>|>\||>&|<>|<&|[<>]/y;
|
|
8829
|
+
CallBindings = class _CallBindings {
|
|
8830
|
+
cwd;
|
|
8831
|
+
modules = /* @__PURE__ */ new Map([["os", "os"], ["subprocess", "subprocess"]]);
|
|
8832
|
+
builtinPrint = true;
|
|
8833
|
+
functions = /* @__PURE__ */ new Map();
|
|
8834
|
+
wrappers = /* @__PURE__ */ new Map();
|
|
8835
|
+
strings = /* @__PURE__ */ new Map([["__name__", "__main__"]]);
|
|
8836
|
+
constructor(cwd = ".") {
|
|
8837
|
+
this.cwd = cwd;
|
|
8838
|
+
}
|
|
8839
|
+
fork() {
|
|
8840
|
+
const other = new _CallBindings(this.cwd);
|
|
8841
|
+
other.modules = new Map(this.modules);
|
|
8842
|
+
other.functions = new Map(this.functions);
|
|
8843
|
+
other.wrappers = new Map(this.wrappers);
|
|
8844
|
+
other.strings = new Map(this.strings);
|
|
8845
|
+
other.builtinPrint = this.builtinPrint;
|
|
8846
|
+
return other;
|
|
8847
|
+
}
|
|
8848
|
+
merge(paths) {
|
|
8849
|
+
this.modules = mergeBindings(paths.map((p) => p.modules), (a, b) => a === b);
|
|
8850
|
+
this.functions = mergeBindings(paths.map((p) => p.functions), sameTuple);
|
|
8851
|
+
this.strings = mergeBindings(paths.map((p) => p.strings), (a, b) => a === b);
|
|
8852
|
+
this.wrappers = mergeBindings(paths.map((p) => p.wrappers), (a, b) => a === b);
|
|
8853
|
+
const first = paths[0].cwd;
|
|
8854
|
+
this.cwd = paths.every((p) => p.cwd === first) ? first : WORKING_DIRECTORY_UNKNOWN;
|
|
8855
|
+
this.builtinPrint = paths.every((p) => p.builtinPrint);
|
|
8856
|
+
}
|
|
8857
|
+
invalidate() {
|
|
8858
|
+
this.builtinPrint = false;
|
|
8859
|
+
this.functions.clear();
|
|
8860
|
+
this.wrappers.clear();
|
|
8861
|
+
this.strings.clear();
|
|
8862
|
+
for (const [name, module] of [...this.modules]) {
|
|
8863
|
+
if (name !== module) this.modules.delete(name);
|
|
8864
|
+
}
|
|
8865
|
+
}
|
|
8866
|
+
forget(name) {
|
|
8867
|
+
if (name === "print") this.builtinPrint = false;
|
|
8868
|
+
this.functions.delete(name);
|
|
8869
|
+
this.strings.delete(name);
|
|
8870
|
+
this.modules.delete(name);
|
|
8871
|
+
this.wrappers.delete(name);
|
|
8872
|
+
}
|
|
8873
|
+
bindString(name, value) {
|
|
8874
|
+
this.forget(name);
|
|
8875
|
+
if (value !== null) this.strings.set(name, value);
|
|
8876
|
+
}
|
|
8877
|
+
changeDirectory(directory) {
|
|
8878
|
+
this.cwd = directoryFor(this, directory);
|
|
8879
|
+
}
|
|
8880
|
+
};
|
|
7630
8881
|
PythonBackend = class {
|
|
7631
8882
|
language = "python";
|
|
7632
|
-
parse(content, entryArgs) {
|
|
8883
|
+
parse(content, entryArgs, options = {}) {
|
|
8884
|
+
const diagnostics = options.diagnostics;
|
|
8885
|
+
const argsKnown = options.argsKnown !== false;
|
|
7633
8886
|
const c = content || "";
|
|
7634
8887
|
SOURCE = c;
|
|
7635
8888
|
const sourceLines = c.split("\n");
|
|
@@ -7637,7 +8890,16 @@ var init_python_backend = __esm({
|
|
|
7637
8890
|
const env2 = makeEnv(entryArgs || []);
|
|
7638
8891
|
const lines = /* @__PURE__ */ new Set();
|
|
7639
8892
|
const branches = [];
|
|
8893
|
+
const ifDecisions = /* @__PURE__ */ new Map();
|
|
8894
|
+
if (diagnostics) {
|
|
8895
|
+
diagnostics.physical_lines = sourceLines.length;
|
|
8896
|
+
diagnostics.line_limit = MAX_LINES;
|
|
8897
|
+
}
|
|
7640
8898
|
if (sourceLines.length > MAX_LINES) {
|
|
8899
|
+
if (diagnostics) {
|
|
8900
|
+
diagnostics.parser = "python_full";
|
|
8901
|
+
diagnostics.fallback_reason = "line_budget";
|
|
8902
|
+
}
|
|
7641
8903
|
return {
|
|
7642
8904
|
reachableContent: c,
|
|
7643
8905
|
controlFlowResolved: false,
|
|
@@ -7651,6 +8913,10 @@ var init_python_backend = __esm({
|
|
|
7651
8913
|
try {
|
|
7652
8914
|
tree = parser.parse(c).topNode;
|
|
7653
8915
|
} catch {
|
|
8916
|
+
if (diagnostics) {
|
|
8917
|
+
diagnostics.parser = "python_full";
|
|
8918
|
+
diagnostics.fallback_reason = "syntax_error";
|
|
8919
|
+
}
|
|
7654
8920
|
return {
|
|
7655
8921
|
reachableContent: c,
|
|
7656
8922
|
controlFlowResolved: false,
|
|
@@ -7660,11 +8926,32 @@ var init_python_backend = __esm({
|
|
|
7660
8926
|
language: this.language
|
|
7661
8927
|
};
|
|
7662
8928
|
}
|
|
8929
|
+
if (!argsKnown) {
|
|
8930
|
+
if (diagnostics) {
|
|
8931
|
+
diagnostics.parser = "python_full";
|
|
8932
|
+
diagnostics.fallback_reason = "unknown_args";
|
|
8933
|
+
diagnostics.child_extractor = "ast";
|
|
8934
|
+
}
|
|
8935
|
+
return {
|
|
8936
|
+
reachableContent: c,
|
|
8937
|
+
controlFlowResolved: false,
|
|
8938
|
+
calls: extractCallsFromTree(tree, null, /* @__PURE__ */ new Map(), lineStarts),
|
|
8939
|
+
branches: [],
|
|
8940
|
+
unresolvedSnippets: [],
|
|
8941
|
+
language: this.language
|
|
8942
|
+
};
|
|
8943
|
+
}
|
|
7663
8944
|
const stmts = bodyStmts(tree);
|
|
7664
|
-
processStmts(stmts, env2, lineStarts, lines, branches);
|
|
8945
|
+
processStmts(stmts, env2, lineStarts, lines, branches, ifDecisions);
|
|
7665
8946
|
const reachable = reconstruct(sourceLines, lines);
|
|
7666
|
-
|
|
7667
|
-
if (
|
|
8947
|
+
const calls = extractCallsFromTree(tree, lines, ifDecisions, lineStarts);
|
|
8948
|
+
if (diagnostics) {
|
|
8949
|
+
diagnostics.parser = "python_ast";
|
|
8950
|
+
diagnostics.child_extractor = "ast";
|
|
8951
|
+
diagnostics.retained_lines = lines.size;
|
|
8952
|
+
diagnostics.branch_count = branches.length;
|
|
8953
|
+
diagnostics.branch_reachable = branches.slice(0, 4).map((b) => b.reachable);
|
|
8954
|
+
}
|
|
7668
8955
|
const srcNonblank = sourceLines.filter((l) => l.trim().length > 0);
|
|
7669
8956
|
const rcNonblank = reachable.split("\n").filter((l) => l.trim().length > 0);
|
|
7670
8957
|
const resolved = rcNonblank.length !== srcNonblank.length || rcNonblank.some((l, i) => l !== srcNonblank[i]);
|
|
@@ -7707,6 +8994,23 @@ function fold(val) {
|
|
|
7707
8994
|
}
|
|
7708
8995
|
return svalConc(parts.join(""));
|
|
7709
8996
|
}
|
|
8997
|
+
function maskCaseLiteral(literal) {
|
|
8998
|
+
const unsupported = literal === "\\\n" || literal.startsWith('"') && (literal.includes("$(") || literal.includes("`"));
|
|
8999
|
+
const mask = unsupported ? "\0" : "x";
|
|
9000
|
+
return literal.replace(/[^\n]/g, mask);
|
|
9001
|
+
}
|
|
9002
|
+
function maskCaseWord(text) {
|
|
9003
|
+
if (text.startsWith("#")) return " ".repeat(text.length);
|
|
9004
|
+
if (text === "<<" || text === "'" || text === '"' || text === "\\" || text === "`") {
|
|
9005
|
+
return "\0".repeat(text.length);
|
|
9006
|
+
}
|
|
9007
|
+
CASE_QUOTED_RE.lastIndex = 0;
|
|
9008
|
+
return text.replace(CASE_QUOTED_RE, maskCaseLiteral);
|
|
9009
|
+
}
|
|
9010
|
+
function caseSyntaxLines(content) {
|
|
9011
|
+
const re = new RegExp(CASE_SYNTAX_TOKEN_SOURCE, "g");
|
|
9012
|
+
return content.replace(re, maskCaseWord).split("\n");
|
|
9013
|
+
}
|
|
7710
9014
|
function countMatches(re, s) {
|
|
7711
9015
|
const m = s.match(re);
|
|
7712
9016
|
return m ? m.length : 0;
|
|
@@ -7719,176 +9023,225 @@ function findBlockEnd(lines, startLine, openRe, closeRe) {
|
|
|
7719
9023
|
}
|
|
7720
9024
|
return -1;
|
|
7721
9025
|
}
|
|
7722
|
-
function
|
|
7723
|
-
return findBlockEnd(lines,
|
|
7724
|
-
}
|
|
7725
|
-
function findIfEnd(lines, start) {
|
|
7726
|
-
return findBlockEnd(lines, start, IF_OPEN_RE, IF_CLOSE_RE);
|
|
9026
|
+
function findIfEnd(lines, startLine) {
|
|
9027
|
+
return findBlockEnd(lines, startLine, IF_OPEN_RE, IF_CLOSE_RE);
|
|
7727
9028
|
}
|
|
7728
|
-
function findLoopEnd(lines,
|
|
9029
|
+
function findLoopEnd(lines, startLine) {
|
|
7729
9030
|
let depth = 0;
|
|
7730
|
-
for (let idx =
|
|
9031
|
+
for (let idx = startLine; idx < lines.length; idx++) {
|
|
7731
9032
|
depth += countMatches(LOOP_DO_RE, lines[idx]) - countMatches(LOOP_DONE_RE, lines[idx]);
|
|
7732
|
-
if (depth <= 0 && idx >
|
|
9033
|
+
if (depth <= 0 && idx > startLine) return idx;
|
|
7733
9034
|
}
|
|
7734
9035
|
return -1;
|
|
7735
9036
|
}
|
|
7736
|
-
function findFnEnd(lines,
|
|
9037
|
+
function findFnEnd(lines, startLine) {
|
|
7737
9038
|
let depth = 0;
|
|
7738
|
-
for (let idx =
|
|
9039
|
+
for (let idx = startLine; idx < lines.length; idx++) {
|
|
7739
9040
|
depth += (lines[idx].match(/\{/g) || []).length - (lines[idx].match(/\}/g) || []).length;
|
|
7740
|
-
if (depth <= 0 && idx >
|
|
9041
|
+
if (depth <= 0 && idx > startLine) return idx;
|
|
7741
9042
|
}
|
|
7742
9043
|
return -1;
|
|
7743
9044
|
}
|
|
7744
|
-
function
|
|
7745
|
-
|
|
7746
|
-
|
|
7747
|
-
|
|
7748
|
-
|
|
7749
|
-
|
|
7750
|
-
|
|
7751
|
-
|
|
7752
|
-
let headerLine = 0;
|
|
7753
|
-
for (let i = 0; i < lines.length; i++) {
|
|
7754
|
-
if (/\bin\b/.test(lines[i]) && /\bcase\b/.test(lines[i])) {
|
|
7755
|
-
headerLine = i;
|
|
7756
|
-
break;
|
|
7757
|
-
}
|
|
7758
|
-
}
|
|
7759
|
-
const bodyStartLine = headerLine + 1;
|
|
7760
|
-
const endLine = findCaseEnd(lines, 0);
|
|
7761
|
-
if (endLine === -1) return null;
|
|
7762
|
-
const branches = splitCaseBranchesDepthAware(lines.slice(bodyStartLine, endLine));
|
|
7763
|
-
if (!branches.length) return null;
|
|
7764
|
-
return { kind: "case", line: block, modelable: true, selector: sel, branches };
|
|
7765
|
-
}
|
|
7766
|
-
function splitCaseBranchesDepthAware(bodyLines) {
|
|
7767
|
-
let depth = 0;
|
|
7768
|
-
let curPat = null;
|
|
7769
|
-
let curBody = [];
|
|
7770
|
-
const branches = [];
|
|
7771
|
-
const flush = () => {
|
|
7772
|
-
if (curPat !== null) {
|
|
7773
|
-
branches.push({ pat: curPat, body: curBody.join("\n") });
|
|
9045
|
+
function caseDepthDelta(line, rawLine) {
|
|
9046
|
+
if (COPROC_GROUP_RE.test(line)) return null;
|
|
9047
|
+
CASE_FUNCTION_G.lastIndex = 0;
|
|
9048
|
+
let fn;
|
|
9049
|
+
while ((fn = CASE_FUNCTION_G.exec(line)) !== null) {
|
|
9050
|
+
if (fn[0] === "") {
|
|
9051
|
+
CASE_FUNCTION_G.lastIndex++;
|
|
9052
|
+
continue;
|
|
7774
9053
|
}
|
|
7775
|
-
|
|
7776
|
-
|
|
7777
|
-
|
|
7778
|
-
|
|
7779
|
-
const
|
|
7780
|
-
if (
|
|
7781
|
-
|
|
7782
|
-
if (bm) {
|
|
7783
|
-
if (curPat !== null) flush();
|
|
7784
|
-
curPat = bm[1].trim().replace(/^["']|["']$/g, "");
|
|
7785
|
-
curBody = bm[2].trim() ? [bm[2].trim()] : [];
|
|
7786
|
-
continue;
|
|
7787
|
-
}
|
|
9054
|
+
const name = fn.groups?.name;
|
|
9055
|
+
if (name === void 0) return null;
|
|
9056
|
+
const range = fn.indices?.groups?.name;
|
|
9057
|
+
if (!range) return null;
|
|
9058
|
+
const [startIdx, endIdx] = range;
|
|
9059
|
+
if (rawLine[endIdx] !== "(" || !CASE_ARRAY_ASSIGNMENT_RE.test(rawLine.slice(startIdx, endIdx))) {
|
|
9060
|
+
return null;
|
|
7788
9061
|
}
|
|
7789
|
-
|
|
7790
|
-
|
|
7791
|
-
|
|
7792
|
-
|
|
7793
|
-
|
|
9062
|
+
}
|
|
9063
|
+
const opens = countMatches(CASE_OPEN_G, line);
|
|
9064
|
+
const closes = [];
|
|
9065
|
+
CASE_CLOSE_G.lastIndex = 0;
|
|
9066
|
+
let cm;
|
|
9067
|
+
while ((cm = CASE_CLOSE_G.exec(line)) !== null) {
|
|
9068
|
+
if (cm[0] === "") {
|
|
9069
|
+
CASE_CLOSE_G.lastIndex++;
|
|
9070
|
+
continue;
|
|
7794
9071
|
}
|
|
9072
|
+
closes.push(cm.index);
|
|
7795
9073
|
}
|
|
7796
|
-
if (
|
|
7797
|
-
return
|
|
9074
|
+
if (opens + closes.length > 1 || closes.length > 0 && closes[0] !== 0) return null;
|
|
9075
|
+
return opens - closes.length;
|
|
7798
9076
|
}
|
|
7799
|
-
function
|
|
7800
|
-
|
|
7801
|
-
|
|
7802
|
-
|
|
7803
|
-
|
|
7804
|
-
|
|
7805
|
-
|
|
7806
|
-
const body = lines.slice(1, fiLine).join("\n");
|
|
7807
|
-
const elseM = /\belse\b/.exec(body);
|
|
7808
|
-
let thenBody;
|
|
7809
|
-
let elseBody;
|
|
7810
|
-
if (elseM) {
|
|
7811
|
-
thenBody = body.slice(0, elseM.index);
|
|
7812
|
-
elseBody = body.slice(elseM.index + 4);
|
|
7813
|
-
} else {
|
|
7814
|
-
thenBody = body;
|
|
7815
|
-
elseBody = null;
|
|
9077
|
+
function findCaseEnd(lines, syntaxLines, startLine) {
|
|
9078
|
+
let depth = 0;
|
|
9079
|
+
for (let index = startLine; index < lines.length; index++) {
|
|
9080
|
+
const delta = caseDepthDelta(syntaxLines[index], lines[index]);
|
|
9081
|
+
if (delta === null || index === startLine && delta !== 1) return -1;
|
|
9082
|
+
depth += delta;
|
|
9083
|
+
if (depth === 0) return index;
|
|
7816
9084
|
}
|
|
7817
|
-
return
|
|
9085
|
+
return -1;
|
|
7818
9086
|
}
|
|
7819
|
-
function
|
|
7820
|
-
|
|
9087
|
+
function containsCommandSubstitution(line) {
|
|
9088
|
+
return NOT_MODELED_RE.test(line);
|
|
9089
|
+
}
|
|
9090
|
+
function splitStatements(content) {
|
|
9091
|
+
const lines = content.split("\n");
|
|
9092
|
+
const syntaxLines = CASE_HEADER_RE.test(content) ? caseSyntaxLines(content) : lines;
|
|
7821
9093
|
const stmts = [];
|
|
7822
9094
|
let i = 0;
|
|
7823
|
-
|
|
9095
|
+
const n = lines.length;
|
|
9096
|
+
while (i < n) {
|
|
7824
9097
|
const ln = lines[i];
|
|
7825
9098
|
const stripped = ln.trim();
|
|
7826
|
-
if (!stripped) {
|
|
7827
|
-
i
|
|
9099
|
+
if (!syntaxLines[i].trim() || stripped.startsWith("#")) {
|
|
9100
|
+
i += 1;
|
|
7828
9101
|
continue;
|
|
7829
9102
|
}
|
|
7830
|
-
if (
|
|
9103
|
+
if (LOOP_OPEN_RE.test(stripped) && !/^\s*case\s+/.test(stripped) && !/^\s*if\s+/.test(stripped)) {
|
|
7831
9104
|
const endLine = findLoopEnd(lines, i);
|
|
7832
9105
|
if (endLine !== -1) {
|
|
7833
|
-
for (let k = i; k <= endLine; k++)
|
|
9106
|
+
for (let k = i; k <= endLine; k++) {
|
|
9107
|
+
stmts.push({ kind: "not_modeled", line: lines[k], modelable: false, reason: "loop" });
|
|
9108
|
+
}
|
|
7834
9109
|
i = endLine + 1;
|
|
7835
9110
|
continue;
|
|
7836
9111
|
}
|
|
7837
|
-
stmts.push({ kind: "
|
|
7838
|
-
i
|
|
9112
|
+
stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "loop" });
|
|
9113
|
+
i += 1;
|
|
7839
9114
|
continue;
|
|
7840
9115
|
}
|
|
7841
9116
|
if (FN_DEF_RE.test(stripped) || FN_DEF_KW_RE.test(stripped)) {
|
|
7842
9117
|
const endLine = findFnEnd(lines, i);
|
|
7843
9118
|
if (endLine !== -1) {
|
|
7844
|
-
for (let k = i; k <= endLine; k++)
|
|
9119
|
+
for (let k = i; k <= endLine; k++) {
|
|
9120
|
+
stmts.push({ kind: "not_modeled", line: lines[k], modelable: false, reason: "function" });
|
|
9121
|
+
}
|
|
7845
9122
|
i = endLine + 1;
|
|
7846
9123
|
continue;
|
|
7847
9124
|
}
|
|
7848
|
-
stmts.push({ kind: "
|
|
7849
|
-
i
|
|
9125
|
+
stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "function" });
|
|
9126
|
+
i += 1;
|
|
7850
9127
|
continue;
|
|
7851
9128
|
}
|
|
7852
|
-
if (
|
|
7853
|
-
const
|
|
7854
|
-
|
|
7855
|
-
|
|
7856
|
-
i++;
|
|
7857
|
-
continue;
|
|
7858
|
-
}
|
|
7859
|
-
const parsed = parseCaseStmt(lines.slice(i, endLine + 1).join("\n"));
|
|
7860
|
-
stmts.push(parsed || { kind: "plain", line: ln, modelable: false });
|
|
7861
|
-
i = endLine + 1;
|
|
9129
|
+
if (CASE_HEADER_RE.test(syntaxLines[i])) {
|
|
9130
|
+
const parsed = parseCaseStatement(lines, syntaxLines, i);
|
|
9131
|
+
stmts.push(parsed ?? { kind: "not_modeled", line: ln, modelable: false, reason: "case_syntax" });
|
|
9132
|
+
i += parsed === null ? 1 : parsed.line.split("\n").length;
|
|
7862
9133
|
continue;
|
|
7863
9134
|
}
|
|
7864
|
-
if (
|
|
9135
|
+
if (/^\s*if\s+/.test(stripped)) {
|
|
7865
9136
|
const endLine = findIfEnd(lines, i);
|
|
7866
9137
|
if (endLine === -1) {
|
|
7867
|
-
stmts.push({ kind: "
|
|
7868
|
-
i
|
|
9138
|
+
stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "if_syntax" });
|
|
9139
|
+
i += 1;
|
|
7869
9140
|
continue;
|
|
7870
9141
|
}
|
|
7871
|
-
const
|
|
7872
|
-
|
|
9142
|
+
const blockText = lines.slice(i, endLine + 1).join("\n");
|
|
9143
|
+
const parsed = parseIfStmt(blockText);
|
|
9144
|
+
stmts.push(parsed ?? { kind: "not_modeled", line: ln, modelable: false, reason: "if_syntax" });
|
|
7873
9145
|
i = endLine + 1;
|
|
7874
9146
|
continue;
|
|
7875
9147
|
}
|
|
7876
9148
|
if (/\bshift\b|\bset\s+--(?:\s|$)|[\s;|&]read\b|^\s*read\b/.test(stripped)) {
|
|
7877
|
-
stmts.push({ kind: "
|
|
7878
|
-
i
|
|
9149
|
+
stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "positional_mutation" });
|
|
9150
|
+
i += 1;
|
|
7879
9151
|
continue;
|
|
7880
9152
|
}
|
|
7881
|
-
const am =
|
|
7882
|
-
if (am && !
|
|
9153
|
+
const am = ASGN_RE.exec(stripped);
|
|
9154
|
+
if (am && !containsCommandSubstitution(stripped)) {
|
|
7883
9155
|
stmts.push({ kind: "assign", line: stripped, modelable: true, name: am[1], rhs: am[2].trim() });
|
|
7884
|
-
i
|
|
9156
|
+
i += 1;
|
|
7885
9157
|
continue;
|
|
7886
9158
|
}
|
|
7887
|
-
stmts.push(
|
|
7888
|
-
i
|
|
9159
|
+
stmts.push(containsCommandSubstitution(stripped) ? { kind: "not_modeled", line: ln, modelable: false, reason: "command_substitution" } : { kind: "plain", line: ln, modelable: true });
|
|
9160
|
+
i += 1;
|
|
7889
9161
|
}
|
|
7890
9162
|
return stmts;
|
|
7891
9163
|
}
|
|
9164
|
+
function parseCaseStatement(lines, syntaxLines, start) {
|
|
9165
|
+
const header = CASE_HEADER_LINE_RE.exec(syntaxLines[start]);
|
|
9166
|
+
if (header === null) return null;
|
|
9167
|
+
let bodyStart = start + 1;
|
|
9168
|
+
if (header[2] === void 0) {
|
|
9169
|
+
while (bodyStart < syntaxLines.length && !syntaxLines[bodyStart].trim()) bodyStart += 1;
|
|
9170
|
+
if (bodyStart === syntaxLines.length || syntaxLines[bodyStart].trim() !== "in") return null;
|
|
9171
|
+
bodyStart += 1;
|
|
9172
|
+
}
|
|
9173
|
+
const end = findCaseEnd(lines, syntaxLines, start);
|
|
9174
|
+
if (end < bodyStart || !/^\s*esac\s*;?\s*$/.test(syntaxLines[end])) return null;
|
|
9175
|
+
for (let i = start; i <= end; i++) {
|
|
9176
|
+
if (syntaxLines[i].includes("\0") || syntaxLines[i].includes("$(")) return null;
|
|
9177
|
+
}
|
|
9178
|
+
const selectorRange = header.indices?.[1];
|
|
9179
|
+
if (!selectorRange) return null;
|
|
9180
|
+
const selector = lines[start].slice(selectorRange[0], selectorRange[1]);
|
|
9181
|
+
const branches = [];
|
|
9182
|
+
let label = null;
|
|
9183
|
+
let body = [];
|
|
9184
|
+
let depth = 0;
|
|
9185
|
+
for (let index = bodyStart; index < end; index++) {
|
|
9186
|
+
let line = lines[index];
|
|
9187
|
+
let syntax = syntaxLines[index];
|
|
9188
|
+
if (label === null) {
|
|
9189
|
+
if (!syntax.trim()) continue;
|
|
9190
|
+
const branch = CASE_LABEL_END_RE.exec(syntax);
|
|
9191
|
+
if (branch === null) return null;
|
|
9192
|
+
const labelRange = branch.indices?.[1];
|
|
9193
|
+
if (!labelRange) return null;
|
|
9194
|
+
label = line.slice(labelRange[0], labelRange[1]).trim();
|
|
9195
|
+
const consumed = branch[0].length;
|
|
9196
|
+
line = line.slice(consumed);
|
|
9197
|
+
syntax = syntax.slice(consumed);
|
|
9198
|
+
}
|
|
9199
|
+
const delta = caseDepthDelta(syntax, line);
|
|
9200
|
+
if (delta === null || depth + delta < 0) return null;
|
|
9201
|
+
depth += delta;
|
|
9202
|
+
body.push(line);
|
|
9203
|
+
if (depth === 0) {
|
|
9204
|
+
const terminator = CASE_TERMINATOR_RE.exec(syntax);
|
|
9205
|
+
if (terminator !== null) {
|
|
9206
|
+
if (terminator[0] !== ";;" || syntax.slice(terminator.index + terminator[0].length).trim()) {
|
|
9207
|
+
return null;
|
|
9208
|
+
}
|
|
9209
|
+
branches.push({ label, body: body.join("\n") });
|
|
9210
|
+
label = null;
|
|
9211
|
+
body = [];
|
|
9212
|
+
}
|
|
9213
|
+
}
|
|
9214
|
+
}
|
|
9215
|
+
if (depth) return null;
|
|
9216
|
+
if (label !== null) branches.push({ label, body: body.join("\n") });
|
|
9217
|
+
return {
|
|
9218
|
+
kind: "case",
|
|
9219
|
+
line: lines.slice(start, end + 1).join("\n"),
|
|
9220
|
+
modelable: true,
|
|
9221
|
+
selector,
|
|
9222
|
+
branches
|
|
9223
|
+
};
|
|
9224
|
+
}
|
|
9225
|
+
function parseIfStmt(block) {
|
|
9226
|
+
const m = /^\s*if\s+([^\n;]+?)\s*;\s*then/.exec(block);
|
|
9227
|
+
if (!m) return null;
|
|
9228
|
+
const cond = m[1].trim();
|
|
9229
|
+
const blockLines = block.split("\n");
|
|
9230
|
+
const fiLine = findIfEnd(blockLines, 0);
|
|
9231
|
+
if (fiLine === -1) return null;
|
|
9232
|
+
const body = blockLines.slice(1, fiLine).join("\n");
|
|
9233
|
+
const elseM = /\belse\b/.exec(body);
|
|
9234
|
+
let thenBody;
|
|
9235
|
+
let elseBody;
|
|
9236
|
+
if (elseM) {
|
|
9237
|
+
thenBody = body.slice(0, elseM.index);
|
|
9238
|
+
elseBody = body.slice(elseM.index + 4);
|
|
9239
|
+
} else {
|
|
9240
|
+
thenBody = body;
|
|
9241
|
+
elseBody = null;
|
|
9242
|
+
}
|
|
9243
|
+
return { kind: "if", line: block, modelable: true, cond, thenBody, elseBody };
|
|
9244
|
+
}
|
|
7892
9245
|
function evalExpr2(text, env2) {
|
|
7893
9246
|
const isSingleQuoted = text.length >= 2 && text[0] === "'" && text[text.length - 1] === "'";
|
|
7894
9247
|
if (text.length >= 2 && (text[0] === '"' || text[0] === "'") && text[text.length - 1] === text[0]) {
|
|
@@ -7975,16 +9328,71 @@ function globToRegex(pattern) {
|
|
|
7975
9328
|
i++;
|
|
7976
9329
|
}
|
|
7977
9330
|
out += "$";
|
|
7978
|
-
return new RegExp(out,
|
|
9331
|
+
return new RegExp(out, "s");
|
|
7979
9332
|
}
|
|
7980
|
-
function
|
|
9333
|
+
function fnmatchCase(value, pattern) {
|
|
7981
9334
|
if (!HAS_GLOB.test(pattern)) return pattern === value;
|
|
7982
9335
|
return globToRegex(pattern).test(value);
|
|
7983
9336
|
}
|
|
9337
|
+
function matchGlobStrict(pattern, value) {
|
|
9338
|
+
if (!CASE_PATTERN_FULL_RE.test(pattern)) return null;
|
|
9339
|
+
if (pattern.startsWith("'") || pattern.startsWith('"')) {
|
|
9340
|
+
return pattern.slice(1, -1) === value;
|
|
9341
|
+
}
|
|
9342
|
+
if (!/^[\x00-\x7F]*$/.test(value) && (pattern.includes("?") || pattern.includes("["))) {
|
|
9343
|
+
return null;
|
|
9344
|
+
}
|
|
9345
|
+
return fnmatchCase(value, pattern);
|
|
9346
|
+
}
|
|
9347
|
+
function selectCaseBranch(caseStmt, value) {
|
|
9348
|
+
for (let index = 0; index < caseStmt.branches.length; index++) {
|
|
9349
|
+
const label = caseStmt.branches[index].label;
|
|
9350
|
+
if (!CASE_LABEL_FULL_RE.test(label)) return null;
|
|
9351
|
+
CASE_PATTERN_ITER_RE.lastIndex = 0;
|
|
9352
|
+
let m;
|
|
9353
|
+
while ((m = CASE_PATTERN_ITER_RE.exec(label)) !== null) {
|
|
9354
|
+
if (m[0] === "") {
|
|
9355
|
+
CASE_PATTERN_ITER_RE.lastIndex++;
|
|
9356
|
+
continue;
|
|
9357
|
+
}
|
|
9358
|
+
const pattern = m[0];
|
|
9359
|
+
const matched = matchGlobStrict(pattern, value);
|
|
9360
|
+
if (matched === null) return null;
|
|
9361
|
+
if (matched) return [index, pattern === "*" ? "default" : "match"];
|
|
9362
|
+
}
|
|
9363
|
+
}
|
|
9364
|
+
return null;
|
|
9365
|
+
}
|
|
9366
|
+
function unicodeDigitValue(codePoint) {
|
|
9367
|
+
for (const [start, end] of DECIMAL_DIGIT_RANGES) {
|
|
9368
|
+
if (codePoint >= start && codePoint <= end) {
|
|
9369
|
+
return start === 120782 ? (codePoint - start) % 10 : codePoint - start;
|
|
9370
|
+
}
|
|
9371
|
+
}
|
|
9372
|
+
return null;
|
|
9373
|
+
}
|
|
9374
|
+
function normalizeDecimalDigits(text) {
|
|
9375
|
+
let out = "";
|
|
9376
|
+
for (const ch of text) {
|
|
9377
|
+
const codePoint = ch.codePointAt(0);
|
|
9378
|
+
const digit = unicodeDigitValue(codePoint);
|
|
9379
|
+
out += digit === null ? ch : String(digit);
|
|
9380
|
+
}
|
|
9381
|
+
return out;
|
|
9382
|
+
}
|
|
9383
|
+
function parsePythonInt(text) {
|
|
9384
|
+
const t = normalizeDecimalDigits(text.trim());
|
|
9385
|
+
if (!/^[+-]?\d(?:_?\d)*$/.test(t)) return null;
|
|
9386
|
+
try {
|
|
9387
|
+
return BigInt(t.replace(/_/g, ""));
|
|
9388
|
+
} catch {
|
|
9389
|
+
return null;
|
|
9390
|
+
}
|
|
9391
|
+
}
|
|
7984
9392
|
function evalNumericCompare(op, left, right) {
|
|
7985
|
-
const li =
|
|
7986
|
-
const ri =
|
|
7987
|
-
if (
|
|
9393
|
+
const li = parsePythonInt(left);
|
|
9394
|
+
const ri = parsePythonInt(right);
|
|
9395
|
+
if (li === null || ri === null) return null;
|
|
7988
9396
|
switch (op) {
|
|
7989
9397
|
case "-gt":
|
|
7990
9398
|
return li > ri;
|
|
@@ -8005,99 +9413,203 @@ function resolveVarSide(tok, env2) {
|
|
|
8005
9413
|
const ev = evalExpr2(tok, env2);
|
|
8006
9414
|
return ev.kind === "concrete" ? ev.value : null;
|
|
8007
9415
|
}
|
|
8008
|
-
function
|
|
8009
|
-
|
|
8010
|
-
|
|
9416
|
+
function unquoteConditionToken(tok) {
|
|
9417
|
+
tok = tok.trim();
|
|
9418
|
+
let quoted = false;
|
|
9419
|
+
if (tok.length >= 2 && (tok[0] === '"' || tok[0] === "'") && tok[tok.length - 1] === tok[0]) {
|
|
9420
|
+
tok = tok.slice(1, -1);
|
|
9421
|
+
quoted = true;
|
|
9422
|
+
}
|
|
9423
|
+
if (tok.includes('"') || tok.includes("'") || tok.includes("\\")) return null;
|
|
9424
|
+
return [tok, quoted];
|
|
9425
|
+
}
|
|
9426
|
+
function evalCondition2(cond, env2, diagnostics) {
|
|
9427
|
+
if (diagnostics) {
|
|
9428
|
+
delete diagnostics.condition_operator;
|
|
9429
|
+
delete diagnostics.condition_failure;
|
|
9430
|
+
}
|
|
9431
|
+
const doubleBracket = cond.trim().startsWith("[[");
|
|
9432
|
+
const inner = cond.replace(/^\[\[?|\]\]?$/g, "").trim();
|
|
9433
|
+
if (/^-[A-Za-z]\s/.test(inner) || inner.startsWith("-d") || inner.startsWith("-f")) {
|
|
9434
|
+
if (diagnostics) diagnostics.condition_failure = "unsupported_predicate";
|
|
9435
|
+
return null;
|
|
9436
|
+
}
|
|
8011
9437
|
const innerQ = inner.replace(/"/g, "").replace(/'/g, "");
|
|
8012
9438
|
for (const op2 of ["-gt", "-lt", "-eq", "-ge", "-le"]) {
|
|
8013
|
-
const
|
|
8014
|
-
const opm = re.exec(innerQ);
|
|
9439
|
+
const opm = new RegExp("\\s" + op2 + "\\s").exec(innerQ);
|
|
8015
9440
|
if (!opm) continue;
|
|
8016
9441
|
const left2 = innerQ.slice(0, opm.index).trim();
|
|
8017
9442
|
const right2 = innerQ.slice(opm.index + opm[0].length).trim();
|
|
9443
|
+
if (diagnostics) diagnostics.condition_operator = op2;
|
|
8018
9444
|
const lv2 = resolveVarSide(left2, env2);
|
|
8019
9445
|
const rv2 = resolveVarSide(right2, env2);
|
|
8020
|
-
if (lv2 === null || rv2 === null)
|
|
8021
|
-
|
|
9446
|
+
if (lv2 === null || rv2 === null) {
|
|
9447
|
+
if (diagnostics) diagnostics.condition_failure = "unbound_operand";
|
|
9448
|
+
return null;
|
|
9449
|
+
}
|
|
9450
|
+
const result = evalNumericCompare(op2, lv2, rv2);
|
|
9451
|
+
if (result === null && diagnostics) diagnostics.condition_failure = "not_integer";
|
|
9452
|
+
return result;
|
|
9453
|
+
}
|
|
9454
|
+
const sm = /(.*?)\s*(=~|==|!=|=)\s*(.*)/.exec(inner);
|
|
9455
|
+
if (!sm) {
|
|
9456
|
+
if (diagnostics) diagnostics.condition_failure = "unsupported_comparison";
|
|
9457
|
+
return null;
|
|
9458
|
+
}
|
|
9459
|
+
const op = sm[2];
|
|
9460
|
+
if (diagnostics) diagnostics.condition_operator = op;
|
|
9461
|
+
const leftPair = unquoteConditionToken(sm[1]);
|
|
9462
|
+
const rightPair = unquoteConditionToken(sm[3]);
|
|
9463
|
+
if (leftPair === null || rightPair === null) {
|
|
9464
|
+
if (diagnostics) diagnostics.condition_failure = "unsupported_quoting";
|
|
9465
|
+
return null;
|
|
9466
|
+
}
|
|
9467
|
+
const [left] = leftPair;
|
|
9468
|
+
const [right, rightQuoted] = rightPair;
|
|
9469
|
+
const lv = resolveVarSide(left, env2);
|
|
9470
|
+
if (lv === null) {
|
|
9471
|
+
if (diagnostics) diagnostics.condition_failure = "unbound_operand";
|
|
9472
|
+
return null;
|
|
8022
9473
|
}
|
|
8023
|
-
const sm = innerQ.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
|
|
8024
|
-
if (!sm) return null;
|
|
8025
|
-
const op = sm[2];
|
|
8026
|
-
let left = sm[1].trim();
|
|
8027
|
-
let right = sm[3].trim();
|
|
8028
9474
|
if (op === "=~") {
|
|
8029
|
-
if (
|
|
8030
|
-
|
|
8031
|
-
|
|
9475
|
+
if (!doubleBracket) {
|
|
9476
|
+
if (diagnostics) diagnostics.condition_failure = "unsupported_operator";
|
|
9477
|
+
return null;
|
|
9478
|
+
}
|
|
9479
|
+
let rv2 = resolveVarSide(right, env2);
|
|
9480
|
+
if (rv2 === null) {
|
|
9481
|
+
if (diagnostics) diagnostics.condition_failure = "unbound_operand";
|
|
9482
|
+
return null;
|
|
9483
|
+
}
|
|
9484
|
+
if (rv2.startsWith("/") && rv2.endsWith("/") && rv2.length > 1) rv2 = rv2.slice(1, -1);
|
|
9485
|
+
const pattern = rightQuoted || right.startsWith("$") ? reescape(rv2) : rv2;
|
|
8032
9486
|
try {
|
|
8033
|
-
return new RegExp(
|
|
9487
|
+
return new RegExp(pattern).test(lv);
|
|
8034
9488
|
} catch {
|
|
9489
|
+
if (diagnostics) diagnostics.condition_failure = "invalid_regex";
|
|
8035
9490
|
return null;
|
|
8036
9491
|
}
|
|
8037
9492
|
}
|
|
8038
|
-
const lv = resolveVarSide(left, env2);
|
|
8039
9493
|
const rv = resolveVarSide(right, env2);
|
|
8040
|
-
if (
|
|
8041
|
-
|
|
9494
|
+
if (rv === null) {
|
|
9495
|
+
if (diagnostics) diagnostics.condition_failure = "unbound_operand";
|
|
9496
|
+
return null;
|
|
9497
|
+
}
|
|
9498
|
+
const glob = rv.includes("*") || rv.includes("?") || rv.includes("[");
|
|
9499
|
+
let matched;
|
|
9500
|
+
if (!rightQuoted && (glob || right.startsWith("$"))) {
|
|
9501
|
+
if (!doubleBracket) {
|
|
9502
|
+
if (diagnostics) diagnostics.condition_failure = "pathname_expansion";
|
|
9503
|
+
return null;
|
|
9504
|
+
}
|
|
9505
|
+
matched = glob ? fnmatchCase(lv, rv) : lv === rv;
|
|
9506
|
+
} else {
|
|
9507
|
+
matched = lv === rv;
|
|
9508
|
+
}
|
|
8042
9509
|
return op === "!=" ? !matched : matched;
|
|
8043
9510
|
}
|
|
8044
|
-
function symbolicProcess(content, entryArgs) {
|
|
8045
|
-
|
|
8046
|
-
|
|
8047
|
-
|
|
8048
|
-
|
|
9511
|
+
function symbolicProcess(content, entryArgs, diagnostics) {
|
|
9512
|
+
const recordResult = (reason, budget2 = null, variables = 0) => {
|
|
9513
|
+
if (!diagnostics) return;
|
|
9514
|
+
diagnostics.result = reason ? "none" : "text";
|
|
9515
|
+
diagnostics.fallback_reason = reason;
|
|
9516
|
+
diagnostics.lines = budget2 ? budget2.lines : 0;
|
|
9517
|
+
diagnostics.branches = budget2 ? budget2.branches : 0;
|
|
9518
|
+
diagnostics.variables = variables;
|
|
9519
|
+
};
|
|
9520
|
+
if (diagnostics) {
|
|
9521
|
+
diagnostics.line_limit = MAX_LINES2;
|
|
9522
|
+
diagnostics.branch_limit = MAX_BRANCHES;
|
|
9523
|
+
diagnostics.variable_limit = MAX_VARS;
|
|
9524
|
+
}
|
|
9525
|
+
if (content === null || content === void 0) {
|
|
9526
|
+
recordResult("empty");
|
|
9527
|
+
return null;
|
|
9528
|
+
}
|
|
9529
|
+
const stmts = splitStatements(content);
|
|
9530
|
+
if (diagnostics) {
|
|
9531
|
+
diagnostics.statement_count = stmts.length;
|
|
9532
|
+
const unsupported = stmts.find((s) => s.kind === "not_modeled");
|
|
9533
|
+
if (unsupported !== void 0) diagnostics.unsupported = unsupported.reason;
|
|
9534
|
+
}
|
|
9535
|
+
if (!stmts.some((s) => s.kind === "case" || s.kind === "if" || s.kind === "assign")) {
|
|
9536
|
+
recordResult(stmts.length ? "no_modeled_statements" : "empty");
|
|
9537
|
+
return null;
|
|
9538
|
+
}
|
|
9539
|
+
if (stmts.some((s) => !s.modelable)) {
|
|
9540
|
+
recordResult("unsupported_statement");
|
|
9541
|
+
return null;
|
|
9542
|
+
}
|
|
9543
|
+
const budget = { lines: 0, branches: 0 };
|
|
8049
9544
|
const env2 = initEnv(entryArgs);
|
|
8050
|
-
if (env2.size > MAX_VARS)
|
|
8051
|
-
|
|
8052
|
-
|
|
8053
|
-
|
|
9545
|
+
if (env2.size > MAX_VARS) {
|
|
9546
|
+
recordResult("variable_budget", budget, env2.size);
|
|
9547
|
+
return null;
|
|
9548
|
+
}
|
|
8054
9549
|
const out = [];
|
|
9550
|
+
let modelableEncountered = false;
|
|
9551
|
+
const choices = diagnostics ? [] : null;
|
|
9552
|
+
if (diagnostics) diagnostics.choices = choices;
|
|
8055
9553
|
for (const s of stmts) {
|
|
8056
|
-
|
|
8057
|
-
if (
|
|
9554
|
+
budget.lines += 1;
|
|
9555
|
+
if (budget.lines > MAX_LINES2 || budget.branches > MAX_BRANCHES) {
|
|
9556
|
+
recordResult("line_budget", budget, env2.size);
|
|
9557
|
+
return null;
|
|
9558
|
+
}
|
|
8058
9559
|
if (s.kind === "assign") {
|
|
8059
|
-
|
|
8060
|
-
|
|
8061
|
-
|
|
8062
|
-
|
|
9560
|
+
if (!env2.has(s.name) && env2.size >= MAX_VARS) {
|
|
9561
|
+
recordResult("variable_budget", budget, env2.size);
|
|
9562
|
+
return null;
|
|
9563
|
+
}
|
|
9564
|
+
modelableEncountered = true;
|
|
9565
|
+
env2.set(s.name, fold(evalExpr2(s.rhs, env2)));
|
|
8063
9566
|
out.push(s.line);
|
|
8064
9567
|
continue;
|
|
8065
9568
|
}
|
|
8066
9569
|
if (s.kind === "case") {
|
|
8067
|
-
|
|
8068
|
-
|
|
8069
|
-
if (
|
|
9570
|
+
modelableEncountered = true;
|
|
9571
|
+
budget.branches += s.branches.length;
|
|
9572
|
+
if (budget.branches > MAX_BRANCHES) {
|
|
9573
|
+
recordResult("branch_budget", budget, env2.size);
|
|
9574
|
+
return null;
|
|
9575
|
+
}
|
|
8070
9576
|
const selVal = fold(evalExpr2(s.selector, env2));
|
|
8071
|
-
if (selVal.kind !== "concrete")
|
|
8072
|
-
|
|
8073
|
-
|
|
8074
|
-
|
|
8075
|
-
|
|
8076
|
-
|
|
8077
|
-
|
|
8078
|
-
|
|
8079
|
-
|
|
8080
|
-
|
|
8081
|
-
|
|
8082
|
-
|
|
8083
|
-
break;
|
|
8084
|
-
}
|
|
9577
|
+
if (selVal.kind !== "concrete") {
|
|
9578
|
+
recordResult("unbound_selector", budget, env2.size);
|
|
9579
|
+
return null;
|
|
9580
|
+
}
|
|
9581
|
+
const selection = selectCaseBranch(s, selVal.value || "");
|
|
9582
|
+
if (selection === null) {
|
|
9583
|
+
recordResult("case_unresolved", budget, env2.size);
|
|
9584
|
+
return null;
|
|
9585
|
+
}
|
|
9586
|
+
const [index, kind] = selection;
|
|
9587
|
+
if (choices !== null && choices.length < 4) {
|
|
9588
|
+
choices.push(`${kind === "default" ? "case_default" : "case"}:${index + 1}`);
|
|
8085
9589
|
}
|
|
8086
|
-
const final = selected !== null ? selected : fallback || null;
|
|
8087
|
-
if (final === null) return null;
|
|
8088
9590
|
out.push(`case ${s.selector} in
|
|
8089
|
-
${
|
|
9591
|
+
${s.branches[index].body}
|
|
8090
9592
|
esac`);
|
|
8091
9593
|
continue;
|
|
8092
9594
|
}
|
|
8093
9595
|
if (s.kind === "if") {
|
|
8094
|
-
|
|
8095
|
-
|
|
8096
|
-
if (
|
|
8097
|
-
|
|
8098
|
-
|
|
9596
|
+
modelableEncountered = true;
|
|
9597
|
+
budget.branches += 1;
|
|
9598
|
+
if (budget.branches > MAX_BRANCHES) {
|
|
9599
|
+
recordResult("branch_budget", budget, env2.size);
|
|
9600
|
+
return null;
|
|
9601
|
+
}
|
|
9602
|
+
const truth = evalCondition2(s.cond, env2, diagnostics);
|
|
9603
|
+
if (truth === null) {
|
|
9604
|
+
recordResult("condition_unresolved", budget, env2.size);
|
|
9605
|
+
return null;
|
|
9606
|
+
}
|
|
8099
9607
|
const chosen = truth ? s.thenBody : s.elseBody;
|
|
8100
|
-
if (chosen === null)
|
|
9608
|
+
if (chosen === null) {
|
|
9609
|
+
recordResult("missing_else", budget, env2.size);
|
|
9610
|
+
return null;
|
|
9611
|
+
}
|
|
9612
|
+
if (choices !== null && choices.length < 4) choices.push(truth ? "then" : "else");
|
|
8101
9613
|
out.push(`if ${s.cond}; then
|
|
8102
9614
|
${chosen}
|
|
8103
9615
|
fi`);
|
|
@@ -8105,231 +9617,547 @@ fi`);
|
|
|
8105
9617
|
}
|
|
8106
9618
|
out.push(s.line);
|
|
8107
9619
|
}
|
|
8108
|
-
if (!
|
|
9620
|
+
if (!modelableEncountered) {
|
|
9621
|
+
recordResult("no_modeled_statements", budget, env2.size);
|
|
9622
|
+
return null;
|
|
9623
|
+
}
|
|
9624
|
+
recordResult("", budget, env2.size);
|
|
8109
9625
|
return out.join("\n");
|
|
8110
9626
|
}
|
|
8111
|
-
var
|
|
9627
|
+
var MAX_LINES2, MAX_BRANCHES, MAX_VARS, CASE_QUOTED_PART, CASE_SYNTAX_TOKEN_SOURCE, CASE_QUOTED_RE, CASE_COMMAND_START, COPROC_PREFIX, CASE_OPEN_SOURCE, COPROC_GROUP_SOURCE, CASE_FUNCTION_SOURCE, CASE_ARRAY_ASSIGNMENT_SOURCE, CASE_CLOSE_SOURCE, CASE_HEADER_LINE_SOURCE, CASE_HEADER_RE, CASE_OPEN_G, COPROC_GROUP_RE, CASE_FUNCTION_G, CASE_ARRAY_ASSIGNMENT_RE, CASE_CLOSE_G, CASE_HEADER_LINE_RE, CASE_TERMINATOR_RE, CASE_LABEL_END_RE, IF_OPEN_RE, IF_CLOSE_RE, LOOP_OPEN_RE, LOOP_DO_RE, LOOP_DONE_RE, FN_DEF_RE, FN_DEF_KW_RE, ASGN_RE, NOT_MODELED_RE, EXPR_SPLIT_RE, HAS_GLOB, CASE_BARE_PATTERN, CASE_PATTERN, CASE_PATTERN_FULL_RE, CASE_PATTERN_ITER_RE, CASE_LABEL_FULL_RE, DECIMAL_DIGIT_RANGES;
|
|
8112
9628
|
var init_symbolic = __esm({
|
|
8113
9629
|
"src/engine/script-engine/symbolic.ts"() {
|
|
8114
9630
|
"use strict";
|
|
8115
9631
|
init_esm_shims();
|
|
8116
|
-
RE_DOTALL = "s";
|
|
8117
9632
|
MAX_LINES2 = 500;
|
|
8118
9633
|
MAX_BRANCHES = 50;
|
|
8119
9634
|
MAX_VARS = 200;
|
|
8120
|
-
|
|
8121
|
-
|
|
8122
|
-
|
|
8123
|
-
|
|
8124
|
-
|
|
8125
|
-
|
|
8126
|
-
|
|
8127
|
-
|
|
9635
|
+
CASE_QUOTED_PART = String.raw`'[^']*'|"(?:\\[\s\S]|[^"\\])*"|\\[\s\S]`;
|
|
9636
|
+
CASE_SYNTAX_TOKEN_SOURCE = String.raw`\#[^\n]*` + String.raw`|(?:` + CASE_QUOTED_PART + String.raw`|[^\s;&|()<>'"\\\x60])+` + String.raw`|<<|['"\\\x60]`;
|
|
9637
|
+
CASE_QUOTED_RE = new RegExp(CASE_QUOTED_PART, "g");
|
|
9638
|
+
CASE_COMMAND_START = String.raw`(?:^|(?<=[;|&()]))[ \t]*` + String.raw`(?:(?:if|then|elif|else|while|until|do|\{|!|time(?:[ \t]+-p)?(?:[ \t]+--)?)[ \t]+)*`;
|
|
9639
|
+
COPROC_PREFIX = String.raw`coproc[ \t]+(?:[^\s;&|()<>]+[ \t]+)?`;
|
|
9640
|
+
CASE_OPEN_SOURCE = CASE_COMMAND_START + String.raw`(?:` + COPROC_PREFIX + String.raw`)?case[ \t]+(?=[^\s;&|()<>])`;
|
|
9641
|
+
COPROC_GROUP_SOURCE = CASE_COMMAND_START + COPROC_PREFIX + String.raw`(?:(?:\{|if|for|while|until|select)(?=$|[\s;&|()<>])|\()`;
|
|
9642
|
+
CASE_FUNCTION_SOURCE = CASE_COMMAND_START + String.raw`(?:function[ \t]+[^\s;&|()<>]+|(?<name>[^\s;&|()<>]+)[ \t]*\([ \t]*)`;
|
|
9643
|
+
CASE_ARRAY_ASSIGNMENT_SOURCE = String.raw`[A-Za-z_][A-Za-z0-9_]*(?:\[.+\])?\+?=`;
|
|
9644
|
+
CASE_CLOSE_SOURCE = String.raw`(?:^|(?<=[;&]))[ \t]*esac(?=$|[ \t;&|])`;
|
|
9645
|
+
CASE_HEADER_LINE_SOURCE = String.raw`[ \t]*case[ \t]+([^\s;&|()<>]+)(?:[ \t]+(in))?[ \t]*`;
|
|
9646
|
+
CASE_HEADER_RE = /^[ \t]*case[ \t]+/m;
|
|
9647
|
+
CASE_OPEN_G = new RegExp(CASE_OPEN_SOURCE, "g");
|
|
9648
|
+
COPROC_GROUP_RE = new RegExp(COPROC_GROUP_SOURCE);
|
|
9649
|
+
CASE_FUNCTION_G = new RegExp(CASE_FUNCTION_SOURCE, "gd");
|
|
9650
|
+
CASE_ARRAY_ASSIGNMENT_RE = new RegExp("^(?:" + CASE_ARRAY_ASSIGNMENT_SOURCE + ")$");
|
|
9651
|
+
CASE_CLOSE_G = new RegExp(CASE_CLOSE_SOURCE, "g");
|
|
9652
|
+
CASE_HEADER_LINE_RE = new RegExp("^(?:" + CASE_HEADER_LINE_SOURCE + ")$", "d");
|
|
9653
|
+
CASE_TERMINATOR_RE = /;;&|;&|;;/;
|
|
9654
|
+
CASE_LABEL_END_RE = new RegExp(String.raw`^\s*\(?([^()]+)\)\s*`, "d");
|
|
9655
|
+
IF_OPEN_RE = /\bif\b/g;
|
|
9656
|
+
IF_CLOSE_RE = /\bfi\b/g;
|
|
9657
|
+
LOOP_OPEN_RE = /\b(?:while|for|until)\b/;
|
|
8128
9658
|
LOOP_DO_RE = /\bdo\b/g;
|
|
8129
9659
|
LOOP_DONE_RE = /\bdone\b/g;
|
|
8130
9660
|
FN_DEF_RE = /^\s*(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{/;
|
|
8131
9661
|
FN_DEF_KW_RE = /^\s*function\s+[A-Za-z_][A-Za-z0-9_]*\s*\{?/;
|
|
9662
|
+
ASGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/;
|
|
9663
|
+
NOT_MODELED_RE = /\$\(|`[^`]*`/;
|
|
8132
9664
|
EXPR_SPLIT_RE = /(\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*|\$\d+)/;
|
|
8133
9665
|
HAS_GLOB = /[*?[]/;
|
|
9666
|
+
CASE_BARE_PATTERN = String.raw`(?:[A-Za-z0-9_./:+,@%=-]|\*|\?|\[!?(?:[0-9]-[0-9]|[A-Za-z0-9_.])+\])+`;
|
|
9667
|
+
CASE_PATTERN = String.raw`(?:` + CASE_BARE_PATTERN + String.raw`|'[^']*'|"[^"\\$\x60]*")`;
|
|
9668
|
+
CASE_PATTERN_FULL_RE = new RegExp("^(?:" + CASE_PATTERN + ")$");
|
|
9669
|
+
CASE_PATTERN_ITER_RE = new RegExp(CASE_PATTERN, "g");
|
|
9670
|
+
CASE_LABEL_FULL_RE = new RegExp(
|
|
9671
|
+
"^(?:" + CASE_PATTERN + String.raw`)(?:[ \t]*\|[ \t]*(?:` + CASE_PATTERN + "))*$"
|
|
9672
|
+
);
|
|
9673
|
+
DECIMAL_DIGIT_RANGES = [
|
|
9674
|
+
[48, 57],
|
|
9675
|
+
[1632, 1641],
|
|
9676
|
+
[1776, 1785],
|
|
9677
|
+
[1984, 1993],
|
|
9678
|
+
[2406, 2415],
|
|
9679
|
+
[2534, 2543],
|
|
9680
|
+
[2662, 2671],
|
|
9681
|
+
[2790, 2799],
|
|
9682
|
+
[2918, 2927],
|
|
9683
|
+
[3046, 3055],
|
|
9684
|
+
[3174, 3183],
|
|
9685
|
+
[3302, 3311],
|
|
9686
|
+
[3430, 3439],
|
|
9687
|
+
[3558, 3567],
|
|
9688
|
+
[3664, 3673],
|
|
9689
|
+
[3792, 3801],
|
|
9690
|
+
[3872, 3881],
|
|
9691
|
+
[4160, 4169],
|
|
9692
|
+
[4240, 4249],
|
|
9693
|
+
[6112, 6121],
|
|
9694
|
+
[6160, 6169],
|
|
9695
|
+
[6470, 6479],
|
|
9696
|
+
[6608, 6617],
|
|
9697
|
+
[6784, 6793],
|
|
9698
|
+
[6800, 6809],
|
|
9699
|
+
[6992, 7001],
|
|
9700
|
+
[7088, 7097],
|
|
9701
|
+
[7232, 7241],
|
|
9702
|
+
[7248, 7257],
|
|
9703
|
+
[42528, 42537],
|
|
9704
|
+
[43216, 43225],
|
|
9705
|
+
[43264, 43273],
|
|
9706
|
+
[43472, 43481],
|
|
9707
|
+
[43504, 43513],
|
|
9708
|
+
[43600, 43609],
|
|
9709
|
+
[44016, 44025],
|
|
9710
|
+
[65296, 65305],
|
|
9711
|
+
[66720, 66729],
|
|
9712
|
+
[68912, 68921],
|
|
9713
|
+
[69734, 69743],
|
|
9714
|
+
[69872, 69881],
|
|
9715
|
+
[69942, 69951],
|
|
9716
|
+
[70096, 70105],
|
|
9717
|
+
[70384, 70393],
|
|
9718
|
+
[70736, 70745],
|
|
9719
|
+
[70864, 70873],
|
|
9720
|
+
[71248, 71257],
|
|
9721
|
+
[71360, 71369],
|
|
9722
|
+
[71472, 71481],
|
|
9723
|
+
[71904, 71913],
|
|
9724
|
+
[72016, 72025],
|
|
9725
|
+
[72784, 72793],
|
|
9726
|
+
[73040, 73049],
|
|
9727
|
+
[73120, 73129],
|
|
9728
|
+
[92768, 92777],
|
|
9729
|
+
[93008, 93017],
|
|
9730
|
+
[120782, 120831],
|
|
9731
|
+
[123200, 123209],
|
|
9732
|
+
[123632, 123641],
|
|
9733
|
+
[125264, 125273],
|
|
9734
|
+
[130032, 130041]
|
|
9735
|
+
];
|
|
8134
9736
|
}
|
|
8135
9737
|
});
|
|
8136
9738
|
|
|
8137
9739
|
// src/engine/script-engine/backends/shell-backend.ts
|
|
8138
|
-
function
|
|
8139
|
-
|
|
8140
|
-
|
|
8141
|
-
|
|
8142
|
-
|
|
8143
|
-
|
|
8144
|
-
|
|
8145
|
-
|
|
8146
|
-
return
|
|
8147
|
-
}
|
|
8148
|
-
|
|
8149
|
-
|
|
8150
|
-
|
|
8151
|
-
|
|
8152
|
-
|
|
8153
|
-
|
|
8154
|
-
|
|
8155
|
-
|
|
8156
|
-
|
|
8157
|
-
|
|
8158
|
-
|
|
8159
|
-
|
|
9740
|
+
function positionalMatch(token) {
|
|
9741
|
+
const m = POSITIONAL_RE.exec(token);
|
|
9742
|
+
return m !== null && m.index === 0 ? m : null;
|
|
9743
|
+
}
|
|
9744
|
+
function substitutionEnd(text, startPos, opening, level) {
|
|
9745
|
+
if (level >= MAX_DEFAULT_DEPTH) return null;
|
|
9746
|
+
if (opening === "`") {
|
|
9747
|
+
const m = BACKTICK_ANCHORED_RE.exec(text.slice(startPos - 1));
|
|
9748
|
+
return m ? startPos - 1 + m[0].length : null;
|
|
9749
|
+
}
|
|
9750
|
+
let depth = 1;
|
|
9751
|
+
let start = startPos;
|
|
9752
|
+
const boundary = new RegExp(SUBSTITUTION_BOUNDARY_PART, "g");
|
|
9753
|
+
while (start !== null) {
|
|
9754
|
+
boundary.lastIndex = start;
|
|
9755
|
+
const token = boundary.exec(text);
|
|
9756
|
+
if (!token) return null;
|
|
9757
|
+
const part = token[0];
|
|
9758
|
+
start = token.index + part.length;
|
|
9759
|
+
if (part === "(" || part === "$(") {
|
|
9760
|
+
depth += 1;
|
|
9761
|
+
} else if (part === ")") {
|
|
9762
|
+
depth -= 1;
|
|
9763
|
+
if (!depth) return start;
|
|
9764
|
+
} else if (part === '"') {
|
|
9765
|
+
start = doubleQuoteEnd(text, start, level + 1);
|
|
9766
|
+
} else if (part === "${") {
|
|
9767
|
+
start = bracedWordEnd(text, start, level + 1);
|
|
9768
|
+
} else if (part === "`") {
|
|
9769
|
+
start = substitutionEnd(text, start, part, level + 1);
|
|
9770
|
+
} else if (part === "'" || part === "<<" || part === "case") {
|
|
9771
|
+
return null;
|
|
9772
|
+
}
|
|
9773
|
+
}
|
|
9774
|
+
return null;
|
|
8160
9775
|
}
|
|
8161
|
-
function
|
|
8162
|
-
if (
|
|
8163
|
-
|
|
8164
|
-
|
|
8165
|
-
|
|
8166
|
-
|
|
8167
|
-
|
|
9776
|
+
function bracedWordEnd(text, startPos, level = 0) {
|
|
9777
|
+
if (level >= MAX_DEFAULT_DEPTH) return null;
|
|
9778
|
+
let depth = 1;
|
|
9779
|
+
let start = startPos;
|
|
9780
|
+
const boundary = new RegExp(DEFAULT_BOUNDARY_PART, "g");
|
|
9781
|
+
while (start !== null) {
|
|
9782
|
+
boundary.lastIndex = start;
|
|
9783
|
+
const token = boundary.exec(text);
|
|
9784
|
+
if (!token) return null;
|
|
9785
|
+
const part = token[0];
|
|
9786
|
+
start = token.index + part.length;
|
|
9787
|
+
if (part === "${") {
|
|
9788
|
+
depth += 1;
|
|
9789
|
+
} else if (part === "}") {
|
|
9790
|
+
depth -= 1;
|
|
9791
|
+
if (!depth) return start;
|
|
9792
|
+
} else if (part === "$(" || part === "`") {
|
|
9793
|
+
start = substitutionEnd(text, start, part, level + 1);
|
|
9794
|
+
} else if (part === '"') {
|
|
9795
|
+
start = doubleQuoteEnd(text, start, level + 1);
|
|
9796
|
+
} else if (part === "'") {
|
|
9797
|
+
return null;
|
|
9798
|
+
}
|
|
8168
9799
|
}
|
|
8169
9800
|
return null;
|
|
8170
9801
|
}
|
|
8171
|
-
function
|
|
8172
|
-
|
|
8173
|
-
|
|
8174
|
-
|
|
8175
|
-
|
|
8176
|
-
|
|
8177
|
-
|
|
8178
|
-
|
|
8179
|
-
|
|
8180
|
-
|
|
8181
|
-
|
|
8182
|
-
|
|
8183
|
-
|
|
8184
|
-
|
|
8185
|
-
|
|
9802
|
+
function doubleQuoteEnd(text, startPos, level = 0) {
|
|
9803
|
+
if (level >= MAX_DEFAULT_DEPTH) return null;
|
|
9804
|
+
let start = startPos;
|
|
9805
|
+
const boundary = new RegExp(DOUBLE_QUOTE_END_PART, "g");
|
|
9806
|
+
while (start !== null) {
|
|
9807
|
+
boundary.lastIndex = start;
|
|
9808
|
+
const token = boundary.exec(text);
|
|
9809
|
+
if (!token) return null;
|
|
9810
|
+
const part = token[0];
|
|
9811
|
+
if (part === '"') return token.index + part.length;
|
|
9812
|
+
start = token.index + part.length;
|
|
9813
|
+
if (part === "${") {
|
|
9814
|
+
start = bracedWordEnd(text, start, level + 1);
|
|
9815
|
+
} else if (part === "$(" || part === "`") {
|
|
9816
|
+
start = substitutionEnd(text, start, part, level + 1);
|
|
9817
|
+
}
|
|
9818
|
+
}
|
|
9819
|
+
return null;
|
|
9820
|
+
}
|
|
9821
|
+
function* shellWordParts(text, quoted = false, opts = {}) {
|
|
9822
|
+
const syntax = opts.syntax === void 0 ? null : opts.syntax;
|
|
9823
|
+
const defaultText = opts.defaultText === true;
|
|
9824
|
+
let patternSource;
|
|
9825
|
+
if (defaultText) {
|
|
9826
|
+
patternSource = quoted ? QUOTED_DEFAULT_PART : DEFAULT_WORD_PART;
|
|
9827
|
+
} else if (quoted) {
|
|
9828
|
+
patternSource = QUOTED_WORD_PART;
|
|
9829
|
+
} else {
|
|
9830
|
+
patternSource = syntax !== null ? SHELL_SOURCE_PART : SHELL_WORD_PART;
|
|
9831
|
+
}
|
|
9832
|
+
const pattern = new RegExp(patternSource, "g");
|
|
9833
|
+
let offset = 0;
|
|
9834
|
+
while (true) {
|
|
9835
|
+
pattern.lastIndex = offset;
|
|
9836
|
+
const token = pattern.exec(text);
|
|
9837
|
+
if (!token) return;
|
|
9838
|
+
const part = token[0];
|
|
9839
|
+
let end = token.index + part.length;
|
|
9840
|
+
if (part === "#" && syntax !== null && syntax[token.index] === " ") {
|
|
9841
|
+
const newline = text.indexOf("\n", end);
|
|
9842
|
+
if (newline < 0) return;
|
|
9843
|
+
offset = newline + 1;
|
|
9844
|
+
continue;
|
|
9845
|
+
}
|
|
9846
|
+
if (part === "${") {
|
|
9847
|
+
end = bracedWordEnd(text, end);
|
|
9848
|
+
} else if (part === '"') {
|
|
9849
|
+
end = doubleQuoteEnd(text, end);
|
|
9850
|
+
} else if (part === "$(" || part === "`") {
|
|
9851
|
+
end = substitutionEnd(text, end, part, 0);
|
|
9852
|
+
}
|
|
9853
|
+
if (end === null) {
|
|
9854
|
+
if (syntax === null) return;
|
|
9855
|
+
const newline = text.indexOf("\n", token.index + part.length);
|
|
9856
|
+
if (newline < 0) return;
|
|
9857
|
+
offset = newline + 1;
|
|
8186
9858
|
continue;
|
|
8187
9859
|
}
|
|
8188
|
-
|
|
8189
|
-
|
|
8190
|
-
|
|
8191
|
-
|
|
8192
|
-
|
|
9860
|
+
yield [token.index, end];
|
|
9861
|
+
offset = end;
|
|
9862
|
+
}
|
|
9863
|
+
}
|
|
9864
|
+
function* splitFields(text) {
|
|
9865
|
+
const parts = text.split(SHELL_IFS_RE);
|
|
9866
|
+
for (let index = 0; index < parts.length; index++) {
|
|
9867
|
+
if (index % 2) yield null;
|
|
9868
|
+
else if (parts[index]) yield parts[index];
|
|
9869
|
+
}
|
|
9870
|
+
}
|
|
9871
|
+
function positionalValue(token, args) {
|
|
9872
|
+
const part = positionalMatch(token);
|
|
9873
|
+
if (part === null) return [token, false];
|
|
9874
|
+
const name = part[1] || part[2];
|
|
9875
|
+
const operator = part[3];
|
|
9876
|
+
if (name === "@") return [args, false];
|
|
9877
|
+
if (name === "*") return [args.join(" "), false];
|
|
9878
|
+
const index = name.length <= String(args.length).length ? parseInt(name, 10) - 1 : args.length;
|
|
9879
|
+
if (index < args.length && (operator !== ":-" || args[index])) {
|
|
9880
|
+
return [args[index], false];
|
|
9881
|
+
}
|
|
9882
|
+
return operator ? [token.slice(part[0].length, -1), true] : ["", false];
|
|
9883
|
+
}
|
|
9884
|
+
function defaultHasSubstitution(text, quoted) {
|
|
9885
|
+
for (const [start, end] of shellWordParts(text, quoted, { defaultText: true })) {
|
|
9886
|
+
const part = text.slice(start, end);
|
|
9887
|
+
if (part.startsWith("$(") || part.startsWith("`")) return true;
|
|
9888
|
+
if (part.startsWith('"') && defaultHasSubstitution(part.slice(1, -1), true)) return true;
|
|
9889
|
+
}
|
|
9890
|
+
return false;
|
|
9891
|
+
}
|
|
9892
|
+
function* argumentParts(word, args, opts = {}) {
|
|
9893
|
+
const quoted = opts.quoted === true;
|
|
9894
|
+
const defaultText = opts.defaultText === true;
|
|
9895
|
+
const defaultDepth = opts.defaultDepth ?? 0;
|
|
9896
|
+
const fieldSplit = !quoted;
|
|
9897
|
+
let offset = 0;
|
|
9898
|
+
for (const [start, end] of shellWordParts(word, quoted, { defaultText })) {
|
|
9899
|
+
if (start > offset) {
|
|
9900
|
+
const literal = word.slice(offset, start);
|
|
9901
|
+
if (fieldSplit) yield* splitFields(literal);
|
|
9902
|
+
else yield literal;
|
|
9903
|
+
}
|
|
9904
|
+
offset = end;
|
|
9905
|
+
const text = word.slice(start, end);
|
|
9906
|
+
if (!quoted && text.startsWith("'")) {
|
|
9907
|
+
yield text.slice(1, -1);
|
|
9908
|
+
} else if (text.startsWith('"')) {
|
|
9909
|
+
if (text === '""') {
|
|
9910
|
+
yield "";
|
|
9911
|
+
} else {
|
|
9912
|
+
yield* argumentParts(text.slice(1, -1), args, { quoted: true, defaultDepth });
|
|
9913
|
+
}
|
|
9914
|
+
} else if (text.startsWith("\\")) {
|
|
9915
|
+
const escaped = text.slice(1);
|
|
9916
|
+
if (escaped !== "\n") {
|
|
9917
|
+
const specials = defaultText ? '$"\\`}' : '$"\\`';
|
|
9918
|
+
yield !quoted || specials.includes(escaped) ? escaped : text;
|
|
9919
|
+
}
|
|
9920
|
+
} else if (positionalMatch(text) === null) {
|
|
9921
|
+
yield text;
|
|
9922
|
+
} else if (args === null) {
|
|
9923
|
+
yield UNRESOLVED;
|
|
9924
|
+
} else {
|
|
9925
|
+
const [value, useDefault] = positionalValue(text, args);
|
|
9926
|
+
if (useDefault) {
|
|
9927
|
+
if (defaultDepth >= MAX_DEFAULT_DEPTH || defaultHasSubstitution(value, quoted)) {
|
|
9928
|
+
yield UNRESOLVED;
|
|
9929
|
+
continue;
|
|
9930
|
+
}
|
|
9931
|
+
yield* argumentParts(value, args, {
|
|
9932
|
+
quoted,
|
|
9933
|
+
defaultText: true,
|
|
9934
|
+
defaultDepth: defaultDepth + 1
|
|
9935
|
+
});
|
|
9936
|
+
if (!value && !fieldSplit) yield "";
|
|
9937
|
+
} else if (!fieldSplit && Array.isArray(value)) {
|
|
9938
|
+
for (let index = 0; index < value.length; index++) {
|
|
9939
|
+
if (index) yield null;
|
|
9940
|
+
yield value[index];
|
|
9941
|
+
}
|
|
9942
|
+
} else if (!fieldSplit) {
|
|
9943
|
+
yield value;
|
|
9944
|
+
} else {
|
|
9945
|
+
yield* splitFields(Array.isArray(value) ? value.join(" ") : value);
|
|
8193
9946
|
}
|
|
8194
9947
|
}
|
|
8195
9948
|
}
|
|
8196
|
-
if (
|
|
8197
|
-
|
|
9949
|
+
if (offset < word.length) {
|
|
9950
|
+
const literal = word.slice(offset);
|
|
9951
|
+
if (fieldSplit) yield* splitFields(literal);
|
|
9952
|
+
else yield literal;
|
|
8198
9953
|
}
|
|
8199
|
-
return branches;
|
|
8200
9954
|
}
|
|
8201
|
-
function
|
|
8202
|
-
const
|
|
8203
|
-
|
|
8204
|
-
|
|
8205
|
-
const
|
|
8206
|
-
|
|
8207
|
-
|
|
8208
|
-
|
|
8209
|
-
|
|
8210
|
-
|
|
8211
|
-
|
|
8212
|
-
|
|
8213
|
-
|
|
8214
|
-
|
|
8215
|
-
|
|
8216
|
-
if (final === null) return null;
|
|
8217
|
-
} else {
|
|
8218
|
-
const branches = splitCaseBody(body);
|
|
8219
|
-
let selected = null;
|
|
8220
|
-
let fallback = "";
|
|
8221
|
-
for (const b of branches) {
|
|
8222
|
-
const values = b.label.split("|").map((v) => v.trim()).filter(Boolean);
|
|
8223
|
-
if (values.includes("*")) fallback = b.body;
|
|
8224
|
-
else if (values.includes(val)) selected = b.body;
|
|
8225
|
-
}
|
|
8226
|
-
final = selected !== null ? selected : fallback || null;
|
|
8227
|
-
if (final === null) return null;
|
|
8228
|
-
}
|
|
8229
|
-
const prefix = content.slice(0, m.index ?? 0);
|
|
8230
|
-
const suffix = lines.slice(endMatch + 1).join("\n");
|
|
8231
|
-
return `${prefix}
|
|
8232
|
-
${final}
|
|
8233
|
-
${suffix}`;
|
|
8234
|
-
}
|
|
8235
|
-
function findCaseEndInLines(lines, headerLine) {
|
|
8236
|
-
let depth = 0;
|
|
8237
|
-
for (let idx = headerLine; idx < lines.length; idx++) {
|
|
8238
|
-
const ln = lines[idx];
|
|
8239
|
-
const opens = (ln.match(/\bcase\b/g) || []).length;
|
|
8240
|
-
const closes = (ln.match(/\besac\b/g) || []).length;
|
|
8241
|
-
depth += opens - closes;
|
|
8242
|
-
if (depth <= 0 && idx > headerLine) return idx;
|
|
9955
|
+
function expandShellWord(word, args, opts = {}) {
|
|
9956
|
+
const quotedDefault = opts.quotedDefault === true;
|
|
9957
|
+
const fields = [];
|
|
9958
|
+
let pieces = [];
|
|
9959
|
+
for (const part of argumentParts(word, args, {
|
|
9960
|
+
quoted: quotedDefault,
|
|
9961
|
+
defaultText: quotedDefault
|
|
9962
|
+
})) {
|
|
9963
|
+
if (part === UNRESOLVED) return null;
|
|
9964
|
+
if (part !== null) {
|
|
9965
|
+
pieces.push(part);
|
|
9966
|
+
} else if (pieces.length) {
|
|
9967
|
+
fields.push(pieces.join(""));
|
|
9968
|
+
pieces = [];
|
|
9969
|
+
}
|
|
8243
9970
|
}
|
|
8244
|
-
|
|
9971
|
+
if (pieces.length) fields.push(pieces.join(""));
|
|
9972
|
+
return fields;
|
|
8245
9973
|
}
|
|
8246
|
-
function
|
|
8247
|
-
|
|
8248
|
-
|
|
8249
|
-
|
|
8250
|
-
|
|
8251
|
-
|
|
8252
|
-
|
|
8253
|
-
|
|
8254
|
-
|
|
8255
|
-
|
|
8256
|
-
|
|
8257
|
-
if (
|
|
8258
|
-
|
|
8259
|
-
|
|
8260
|
-
|
|
8261
|
-
|
|
8262
|
-
|
|
8263
|
-
|
|
8264
|
-
|
|
8265
|
-
|
|
8266
|
-
|
|
8267
|
-
|
|
8268
|
-
|
|
8269
|
-
|
|
8270
|
-
|
|
8271
|
-
|
|
8272
|
-
|
|
9974
|
+
function bindPositionalArgs(content, args) {
|
|
9975
|
+
if (!args.length || !content.includes("$")) return content;
|
|
9976
|
+
const bindText = (text, quoted = false) => {
|
|
9977
|
+
const out = [];
|
|
9978
|
+
let offset = 0;
|
|
9979
|
+
let syntax = null;
|
|
9980
|
+
if (!quoted) syntax = text.includes("#") ? caseSyntaxLines(text).join("\n") : text;
|
|
9981
|
+
for (const [start, end] of shellWordParts(text, quoted, { syntax })) {
|
|
9982
|
+
const token = text.slice(start, end);
|
|
9983
|
+
out.push(text.slice(offset, start));
|
|
9984
|
+
offset = end;
|
|
9985
|
+
if (token.startsWith('"')) {
|
|
9986
|
+
out.push('"' + bindText(token.slice(1, -1), true) + '"');
|
|
9987
|
+
} else if (positionalMatch(token)) {
|
|
9988
|
+
const [value, useDefault] = positionalValue(token, args);
|
|
9989
|
+
let values = Array.isArray(value) ? value : [value];
|
|
9990
|
+
if (useDefault) {
|
|
9991
|
+
if (defaultHasSubstitution(values[0], quoted)) {
|
|
9992
|
+
out.push(token);
|
|
9993
|
+
continue;
|
|
9994
|
+
}
|
|
9995
|
+
const expanded = expandShellWord(values[0], args, { quotedDefault: quoted });
|
|
9996
|
+
if (expanded === null) {
|
|
9997
|
+
out.push(token);
|
|
9998
|
+
continue;
|
|
9999
|
+
}
|
|
10000
|
+
values = expanded;
|
|
10001
|
+
}
|
|
10002
|
+
if (quoted) values = values.map((item) => item.replace(/([\\$"`])/g, "\\$1"));
|
|
10003
|
+
out.push(values.join(quoted ? '" "' : " "));
|
|
10004
|
+
} else {
|
|
10005
|
+
out.push(token);
|
|
8273
10006
|
}
|
|
8274
10007
|
}
|
|
8275
|
-
|
|
8276
|
-
|
|
8277
|
-
|
|
8278
|
-
|
|
8279
|
-
|
|
10008
|
+
out.push(text.slice(offset));
|
|
10009
|
+
return out.join("");
|
|
10010
|
+
};
|
|
10011
|
+
return bindText(content);
|
|
10012
|
+
}
|
|
10013
|
+
function findSelectorValue(selector, args) {
|
|
10014
|
+
if (!args || !args.length) return null;
|
|
10015
|
+
const m = selector.match(/^\$\{?(\d+)\}?$/);
|
|
10016
|
+
if (m) {
|
|
10017
|
+
const idx = parseInt(m[1], 10);
|
|
10018
|
+
if (1 <= idx && idx <= args.length) return args[idx - 1];
|
|
10019
|
+
return null;
|
|
10020
|
+
}
|
|
10021
|
+
return null;
|
|
10022
|
+
}
|
|
10023
|
+
function parseCase(content, args, diagnostics) {
|
|
10024
|
+
if (!args || !args.length || !CASE_HEADER_RE.test(content)) return null;
|
|
10025
|
+
const lines = content.split("\n");
|
|
10026
|
+
const syntaxLines = caseSyntaxLines(content);
|
|
10027
|
+
let index = -1;
|
|
10028
|
+
for (let i = 0; i < syntaxLines.length; i++) {
|
|
10029
|
+
if (CASE_HEADER_RE.test(syntaxLines[i])) {
|
|
10030
|
+
index = i;
|
|
10031
|
+
break;
|
|
8280
10032
|
}
|
|
8281
10033
|
}
|
|
8282
|
-
if (
|
|
8283
|
-
|
|
10034
|
+
if (index < 0) return null;
|
|
10035
|
+
const caseStmt = parseCaseStatement(lines, syntaxLines, index);
|
|
10036
|
+
if (caseStmt === null) return null;
|
|
10037
|
+
const value = findSelectorValue(caseStmt.selector, args);
|
|
10038
|
+
if (value === null) return null;
|
|
10039
|
+
const selection = selectCaseBranch(caseStmt, value);
|
|
10040
|
+
if (selection === null) return null;
|
|
10041
|
+
const [branch, kind] = selection;
|
|
10042
|
+
if (diagnostics) diagnostics.p1_case = kind;
|
|
10043
|
+
const end = index + caseStmt.line.split("\n").length;
|
|
10044
|
+
return [...lines.slice(0, index), caseStmt.branches[branch].body, ...lines.slice(end)].join("\n");
|
|
10045
|
+
}
|
|
10046
|
+
function unquoteIfToken(tok) {
|
|
10047
|
+
tok = tok.trim();
|
|
10048
|
+
let quoted = false;
|
|
10049
|
+
if (tok.length >= 2 && (tok[0] === '"' || tok[0] === "'") && tok[tok.length - 1] === tok[0]) {
|
|
10050
|
+
tok = tok.slice(1, -1);
|
|
10051
|
+
quoted = true;
|
|
10052
|
+
}
|
|
10053
|
+
if (tok.includes('"') || tok.includes("'") || tok.includes("\\")) return null;
|
|
10054
|
+
return [tok, quoted];
|
|
8284
10055
|
}
|
|
8285
10056
|
function evalIfCondition(cond, args) {
|
|
8286
10057
|
if (!args || !args.length) return null;
|
|
8287
|
-
const
|
|
8288
|
-
const
|
|
10058
|
+
const doubleBracket = cond.trimStart().startsWith("[[");
|
|
10059
|
+
const inner = cond.replace(/^\[\[?|\]\]?$/g, "").trim();
|
|
10060
|
+
const m = /(.*?)\s*(=~|==|!=|=)\s*(.*)/.exec(inner);
|
|
8289
10061
|
if (!m) return null;
|
|
8290
10062
|
const op = m[2];
|
|
8291
|
-
|
|
8292
|
-
|
|
10063
|
+
const leftPair = unquoteIfToken(m[1]);
|
|
10064
|
+
const rightPair = unquoteIfToken(m[3]);
|
|
10065
|
+
if (leftPair === null || rightPair === null) return null;
|
|
10066
|
+
const [left] = leftPair;
|
|
10067
|
+
const [right, rightQuoted] = rightPair;
|
|
8293
10068
|
const resolve13 = (tok) => {
|
|
8294
10069
|
const rm = tok.match(/^\$(\d+)$/);
|
|
8295
10070
|
if (rm) {
|
|
8296
10071
|
const idx = parseInt(rm[1], 10);
|
|
8297
10072
|
return 1 <= idx && idx <= args.length ? args[idx - 1] : null;
|
|
8298
10073
|
}
|
|
8299
|
-
|
|
10074
|
+
if (tok.startsWith("$")) return null;
|
|
10075
|
+
return tok;
|
|
8300
10076
|
};
|
|
8301
10077
|
const lv = resolve13(left);
|
|
8302
10078
|
const rv = resolve13(right);
|
|
8303
10079
|
if (lv === null || rv === null) return null;
|
|
8304
10080
|
if (op === "=~") {
|
|
8305
|
-
|
|
8306
|
-
|
|
10081
|
+
if (!doubleBracket) return null;
|
|
10082
|
+
let pattern = rv;
|
|
10083
|
+
if (pattern.startsWith("/") && pattern.endsWith("/") && pattern.length > 1) {
|
|
10084
|
+
pattern = pattern.slice(1, -1);
|
|
10085
|
+
}
|
|
10086
|
+
const source = rightQuoted ? escapeRegex(pattern) : pattern;
|
|
8307
10087
|
try {
|
|
8308
|
-
return new RegExp(
|
|
10088
|
+
return new RegExp(source).test(lv);
|
|
8309
10089
|
} catch {
|
|
8310
10090
|
return null;
|
|
8311
10091
|
}
|
|
8312
10092
|
}
|
|
8313
|
-
|
|
10093
|
+
let matched;
|
|
10094
|
+
if (!rightQuoted && (rv.includes("*") || rv.includes("?") || rv.includes("["))) {
|
|
10095
|
+
if (!doubleBracket) {
|
|
10096
|
+
return null;
|
|
10097
|
+
}
|
|
10098
|
+
matched = fnmatchCase2(lv, rv);
|
|
10099
|
+
} else {
|
|
10100
|
+
matched = lv === rv;
|
|
10101
|
+
}
|
|
8314
10102
|
return op === "!=" ? !matched : matched;
|
|
8315
10103
|
}
|
|
8316
|
-
function
|
|
8317
|
-
|
|
10104
|
+
function escapeRegex(s) {
|
|
10105
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
10106
|
+
}
|
|
10107
|
+
function fnmatchCase2(value, pattern) {
|
|
10108
|
+
if (!/[*?[]/.test(pattern)) return pattern === value;
|
|
10109
|
+
let out = "^";
|
|
10110
|
+
let i = 0;
|
|
10111
|
+
while (i < pattern.length) {
|
|
10112
|
+
const c = pattern[i];
|
|
10113
|
+
if (c === "*") out += ".*";
|
|
10114
|
+
else if (c === "?") out += ".";
|
|
10115
|
+
else if (c === "[") {
|
|
10116
|
+
let j = i + 1;
|
|
10117
|
+
let neg = false;
|
|
10118
|
+
if (j < pattern.length && (pattern[j] === "!" || pattern[j] === "^")) {
|
|
10119
|
+
neg = true;
|
|
10120
|
+
j++;
|
|
10121
|
+
}
|
|
10122
|
+
let cls = "";
|
|
10123
|
+
while (j < pattern.length && pattern[j] !== "]") {
|
|
10124
|
+
cls += pattern[j];
|
|
10125
|
+
j++;
|
|
10126
|
+
}
|
|
10127
|
+
if (j >= pattern.length) {
|
|
10128
|
+
out += escapeRegex(pattern.slice(i));
|
|
10129
|
+
break;
|
|
10130
|
+
}
|
|
10131
|
+
out += "[" + (neg ? "^" : "") + escapeRegex(cls) + "]";
|
|
10132
|
+
i = j;
|
|
10133
|
+
} else {
|
|
10134
|
+
out += escapeRegex(c);
|
|
10135
|
+
}
|
|
10136
|
+
i++;
|
|
10137
|
+
}
|
|
10138
|
+
out += "$";
|
|
10139
|
+
return new RegExp(out, "s").test(value);
|
|
10140
|
+
}
|
|
10141
|
+
function parseIf(content, args, diagnostics) {
|
|
10142
|
+
const m = /\bif\s+([^\n;]+?)\s*;\s*then/.exec(content);
|
|
8318
10143
|
if (!m) return null;
|
|
8319
|
-
const
|
|
10144
|
+
const cond = m[1].trim();
|
|
10145
|
+
const truth = evalIfCondition(cond, args);
|
|
8320
10146
|
if (truth === null) return null;
|
|
8321
|
-
const start = m.index
|
|
10147
|
+
const start = m.index;
|
|
8322
10148
|
const thenBodyStart = start + m[0].length;
|
|
8323
10149
|
const fiPos = content.indexOf("fi", thenBodyStart);
|
|
8324
10150
|
if (fiPos === -1) return null;
|
|
8325
10151
|
const segment = content.slice(thenBodyStart, fiPos);
|
|
8326
|
-
const elseM =
|
|
10152
|
+
const elseM = /\belse\b/.exec(segment);
|
|
8327
10153
|
let chosen;
|
|
8328
|
-
if (truth)
|
|
8329
|
-
|
|
10154
|
+
if (truth) {
|
|
10155
|
+
chosen = elseM ? segment.slice(0, elseM.index) : segment;
|
|
10156
|
+
} else {
|
|
8330
10157
|
if (!elseM) return null;
|
|
8331
|
-
chosen = segment.slice(
|
|
10158
|
+
chosen = segment.slice(elseM.index + 4);
|
|
8332
10159
|
}
|
|
10160
|
+
if (diagnostics) diagnostics.p1_if = truth ? "then" : "else";
|
|
8333
10161
|
return `${content.slice(0, start)}
|
|
8334
10162
|
${chosen}
|
|
8335
10163
|
${content.slice(fiPos + 2)}`;
|
|
@@ -8358,63 +10186,153 @@ function stripNonExecutableLines(content) {
|
|
|
8358
10186
|
function markLoopsReachable(content) {
|
|
8359
10187
|
return content;
|
|
8360
10188
|
}
|
|
8361
|
-
function extractCallsFromContent(content) {
|
|
10189
|
+
function extractCallsFromContent(content, entryArgs = null) {
|
|
10190
|
+
if (!CHILD_INTERPRETER_RE.test(content)) return [];
|
|
10191
|
+
let syntax = caseSyntaxLines(content).join("\n");
|
|
10192
|
+
if (content.includes("${")) {
|
|
10193
|
+
const parts = [];
|
|
10194
|
+
let offset = 0;
|
|
10195
|
+
for (const [start, end] of shellWordParts(content, false, { syntax })) {
|
|
10196
|
+
const token = content.slice(start, end);
|
|
10197
|
+
if (!token.includes("${") || syntax[start] === " ") continue;
|
|
10198
|
+
if (token.startsWith('"') && defaultHasSubstitution(token.slice(1, -1), true)) continue;
|
|
10199
|
+
parts.push(syntax.slice(offset, start));
|
|
10200
|
+
parts.push(token.replace(/[^\n]/g, "x"));
|
|
10201
|
+
offset = end;
|
|
10202
|
+
}
|
|
10203
|
+
parts.push(syntax.slice(offset));
|
|
10204
|
+
syntax = parts.join("");
|
|
10205
|
+
}
|
|
8362
10206
|
const calls = [];
|
|
8363
|
-
|
|
8364
|
-
|
|
8365
|
-
while ((
|
|
8366
|
-
|
|
8367
|
-
|
|
8368
|
-
|
|
8369
|
-
|
|
8370
|
-
|
|
8371
|
-
|
|
8372
|
-
|
|
8373
|
-
|
|
10207
|
+
const re = new RegExp(CHILD_CALL_SOURCE, "gmd");
|
|
10208
|
+
let match;
|
|
10209
|
+
while ((match = re.exec(syntax)) !== null) {
|
|
10210
|
+
if (match[0] === "") {
|
|
10211
|
+
re.lastIndex += 1;
|
|
10212
|
+
continue;
|
|
10213
|
+
}
|
|
10214
|
+
const range = match.indices?.[2];
|
|
10215
|
+
if (!range) continue;
|
|
10216
|
+
const [start, end] = range;
|
|
10217
|
+
const words = [...syntax.slice(start, end).matchAll(/[^ \t]+/g)];
|
|
10218
|
+
const truncated = syntax.slice(end, end + 1) === "\0" && !content.startsWith("<<", end) || syntax.startsWith("$(", end - 1);
|
|
10219
|
+
if (truncated && words.length && words[words.length - 1].index + words[words.length - 1][0].length === end - start) {
|
|
10220
|
+
words.pop();
|
|
10221
|
+
}
|
|
10222
|
+
const argv = [];
|
|
10223
|
+
let argsKnown = !truncated;
|
|
10224
|
+
for (const word of words) {
|
|
10225
|
+
const fields = expandShellWord(
|
|
10226
|
+
content.slice(start + word.index, start + word.index + word[0].length),
|
|
10227
|
+
entryArgs
|
|
10228
|
+
);
|
|
10229
|
+
if (fields === null) {
|
|
10230
|
+
argsKnown = false;
|
|
10231
|
+
break;
|
|
10232
|
+
}
|
|
10233
|
+
argv.push(...fields);
|
|
10234
|
+
}
|
|
10235
|
+
if (argv.length && argv[0] && !argv[0].startsWith("-") && !argv[0].startsWith("$") && !argv[0].includes("/dev/")) {
|
|
10236
|
+
calls.push({
|
|
10237
|
+
path: argv[0],
|
|
10238
|
+
args: argsKnown ? argv.slice(1) : [],
|
|
10239
|
+
interpreter: match[1],
|
|
10240
|
+
argsKnown
|
|
10241
|
+
});
|
|
8374
10242
|
}
|
|
8375
|
-
calls.push({ path: path9, args, interpreter: interp });
|
|
8376
10243
|
}
|
|
8377
10244
|
return calls;
|
|
8378
10245
|
}
|
|
8379
|
-
var HEREDOC_RE,
|
|
10246
|
+
var POSITIONAL_RE, QUOTED_WORD_PART, SHELL_WORD_PART, SHELL_SOURCE_PART, SUBSTITUTION_START, DEFAULT_WORD_PART, QUOTED_DEFAULT_PART, DOUBLE_QUOTE_END_PART, DEFAULT_BOUNDARY_PART, SUBSTITUTION_BOUNDARY_PART, BACKTICK_PART, BACKTICK_ANCHORED_RE, SHELL_IFS_RE, UNRESOLVED, MAX_DEFAULT_DEPTH, HEREDOC_RE, CHILD_INTERPRETER_RE, CHILD_CALL_SOURCE, ShellBackend;
|
|
8380
10247
|
var init_shell_backend = __esm({
|
|
8381
10248
|
"src/engine/script-engine/backends/shell-backend.ts"() {
|
|
8382
10249
|
"use strict";
|
|
8383
10250
|
init_esm_shims();
|
|
10251
|
+
init_ir();
|
|
8384
10252
|
init_symbolic();
|
|
10253
|
+
POSITIONAL_RE = /\$(?:([1-9@*])|\{([1-9][0-9]*|[@*])(?:(:-|-)|\}))/;
|
|
10254
|
+
QUOTED_WORD_PART = String.raw`\$\{|\\[\s\S]|\$[1-9@*]`;
|
|
10255
|
+
SHELL_WORD_PART = String.raw`'[^']*'|"|` + QUOTED_WORD_PART;
|
|
10256
|
+
SHELL_SOURCE_PART = String.raw`\#|` + SHELL_WORD_PART;
|
|
10257
|
+
SUBSTITUTION_START = String.raw`\$\(|\x60`;
|
|
10258
|
+
DEFAULT_WORD_PART = SUBSTITUTION_START + "|" + SHELL_WORD_PART;
|
|
10259
|
+
QUOTED_DEFAULT_PART = SUBSTITUTION_START + String.raw`|"|` + QUOTED_WORD_PART;
|
|
10260
|
+
DOUBLE_QUOTE_END_PART = String.raw`\\[\s\S]|\$\{|` + SUBSTITUTION_START + String.raw`|"`;
|
|
10261
|
+
DEFAULT_BOUNDARY_PART = String.raw`\\[\s\S]|'[^']*'|"|\$\{|` + SUBSTITUTION_START + String.raw`|[}']`;
|
|
10262
|
+
SUBSTITUTION_BOUNDARY_PART = String.raw`\\[\s\S]|'[^']*'|"|\$\{|` + SUBSTITUTION_START + String.raw`|[()']|<<` + String.raw`|(?<![^\s;&|()<>])(?:\#[^\n]*|case(?=[ \t]))`;
|
|
10263
|
+
BACKTICK_PART = String.raw`\x60(?:\\[\s\S]|[^\x60\\])*\x60`;
|
|
10264
|
+
BACKTICK_ANCHORED_RE = new RegExp("^(?:" + BACKTICK_PART + ")");
|
|
10265
|
+
SHELL_IFS_RE = /([ \t\n]+)/;
|
|
10266
|
+
UNRESOLVED = /* @__PURE__ */ Symbol("unresolved");
|
|
10267
|
+
MAX_DEFAULT_DEPTH = 32;
|
|
8385
10268
|
HEREDOC_RE = /<<-?\s*['"]?(\w+)['"]?/;
|
|
8386
|
-
|
|
10269
|
+
CHILD_INTERPRETER_RE = /\b(?:bash|sh|zsh|python(?:3(?:\.[0-9]+)?)?|node|ruby|perl|php|lua)\b/;
|
|
10270
|
+
CHILD_CALL_SOURCE = String.raw`(?:^[ \t]*(?:\(?[^()\n;&<>]+\)[ \t]*)?|(?<=[;&|])(?<![<>][&|]))[ \t]*` + String.raw`(?:(?:if|then|elif|else|while|until|do|!|\{)[ \t]+|\([ \t]*` + String.raw`|command(?:[ \t]+-p)?(?:[ \t]+--)?[ \t]+` + String.raw`|exec(?:[ \t]+(?:-[cl]+|-a[ \t]+[^ \t\n;&|<>()\x00]+))*(?:[ \t]+--)?[ \t]+` + String.raw`|(?:(?:/usr)?/bin/)?time(?:[ \t]+-p)?(?:[ \t]+--)?[ \t]+` + String.raw`|(?:(?:/usr)?/bin/)?env(?:[ \t]+(?:-i|--ignore-environment` + String.raw`|(?:-u[ \t]*|--unset(?:[ \t]+|=))[^ \t\n;&|<>()\x00]+` + String.raw`))*(?:[ \t]+--)?[ \t]+` + String.raw`|[A-Za-z_][A-Za-z0-9_]*=[^ \t\n;&|<>()\x00]*[ \t]+)*` + String.raw`((?:(?:/usr)?(?:/local)?/bin/)?(?:bash|sh|zsh|python(?:3(?:\.[0-9]+)?)?|node|ruby|perl|php|lua))[ \t]+` + String.raw`([^\n;|&<>()\x00]+)`;
|
|
8387
10271
|
ShellBackend = class {
|
|
8388
10272
|
language = "shell";
|
|
8389
|
-
|
|
8390
|
-
|
|
8391
|
-
|
|
8392
|
-
|
|
10273
|
+
ENTRY_PATTERNS = [
|
|
10274
|
+
String.raw`(?:^|\s|&&|\|\|)\s*bash\s+(\S+)`,
|
|
10275
|
+
String.raw`(?:^|\s|&&|\|\|)\s*(?:/bin/)?sh\s+(\S+)`,
|
|
10276
|
+
String.raw`(?:^|\s|&&|\|\|)\s*zsh\s+(\S+)`,
|
|
10277
|
+
String.raw`\./(\S+)`,
|
|
10278
|
+
String.raw`(?:^|\s|&&|\|\|)\s*source\s+(\S+)`
|
|
10279
|
+
];
|
|
10280
|
+
parse(content, entryArgs, options = {}) {
|
|
10281
|
+
const diagnostics = options.diagnostics;
|
|
10282
|
+
const argsKnown = options.argsKnown !== false;
|
|
10283
|
+
let candidate = content || "";
|
|
8393
10284
|
let resolved = false;
|
|
8394
|
-
const
|
|
10285
|
+
const P1_UNSAFE_RE = /\bshift\b|\bset\s+--(?:\s|$)|[\s;|&]read\b|^\s*read\b|\(\)\s*\{|function\s+\w+/;
|
|
10286
|
+
const p1Safe = argsKnown && !P1_UNSAFE_RE.test(candidate);
|
|
8395
10287
|
if (p1Safe) {
|
|
8396
|
-
const caseOut = parseCase(candidate, entryArgs);
|
|
10288
|
+
const caseOut = parseCase(candidate, entryArgs, diagnostics);
|
|
8397
10289
|
if (caseOut !== null && caseOut !== candidate) {
|
|
8398
10290
|
resolved = true;
|
|
8399
10291
|
candidate = caseOut;
|
|
8400
10292
|
}
|
|
8401
|
-
|
|
8402
|
-
|
|
8403
|
-
|
|
8404
|
-
|
|
10293
|
+
if (!CASE_HEADER_RE.test(candidate)) {
|
|
10294
|
+
const ifOut = parseIf(candidate, entryArgs, diagnostics);
|
|
10295
|
+
if (ifOut !== null && ifOut !== candidate) {
|
|
10296
|
+
resolved = true;
|
|
10297
|
+
candidate = ifOut;
|
|
10298
|
+
}
|
|
8405
10299
|
}
|
|
8406
10300
|
}
|
|
8407
|
-
|
|
8408
|
-
|
|
8409
|
-
|
|
8410
|
-
|
|
10301
|
+
if (diagnostics) {
|
|
10302
|
+
diagnostics.parser = "shell_p1";
|
|
10303
|
+
diagnostics.p1_safe = p1Safe;
|
|
10304
|
+
diagnostics.child_extractor = "regex";
|
|
10305
|
+
}
|
|
10306
|
+
if (!argsKnown) {
|
|
10307
|
+
if (diagnostics) {
|
|
10308
|
+
diagnostics.parser = "shell_full";
|
|
10309
|
+
diagnostics.fallback_reason = "unknown_args";
|
|
10310
|
+
}
|
|
10311
|
+
} else if (!resolved) {
|
|
10312
|
+
const symbolicDiagnostics = diagnostics ? {} : void 0;
|
|
10313
|
+
const symOut = symbolicProcess(content ?? "", entryArgs, symbolicDiagnostics);
|
|
10314
|
+
if (symOut !== null && symOut !== content) {
|
|
8411
10315
|
resolved = true;
|
|
8412
|
-
|
|
10316
|
+
candidate = symOut;
|
|
10317
|
+
}
|
|
10318
|
+
if (diagnostics && symbolicDiagnostics) {
|
|
10319
|
+
diagnostics.parser = resolved ? "shell_litese" : "shell_full";
|
|
10320
|
+
diagnostics.symbolic = symbolicDiagnostics;
|
|
10321
|
+
if (!resolved) {
|
|
10322
|
+
diagnostics.fallback_reason = symbolicDiagnostics.fallback_reason || "no_pruning";
|
|
10323
|
+
}
|
|
10324
|
+
if (symOut !== null && symOut !== void 0) {
|
|
10325
|
+
const fingerprint2 = scanFingerprint(symOut);
|
|
10326
|
+
symbolicDiagnostics.output_bytes = fingerprint2.bytes;
|
|
10327
|
+
symbolicDiagnostics.output_sha256 = fingerprint2.sha256;
|
|
10328
|
+
}
|
|
8413
10329
|
}
|
|
8414
10330
|
}
|
|
8415
|
-
|
|
10331
|
+
candidate = stripNonExecutableLines(candidate);
|
|
10332
|
+
const bindArgs = p1Safe ? entryArgs : null;
|
|
10333
|
+
const calls = extractCallsFromContent(candidate, bindArgs);
|
|
10334
|
+
const bound = bindPositionalArgs(candidate, bindArgs || []);
|
|
8416
10335
|
const loopMarked = markLoopsReachable(bound);
|
|
8417
|
-
const calls = extractCallsFromContent(loopMarked);
|
|
8418
10336
|
return {
|
|
8419
10337
|
reachableContent: loopMarked,
|
|
8420
10338
|
controlFlowResolved: resolved,
|
|
@@ -8441,7 +10359,7 @@ var init_backends = __esm({
|
|
|
8441
10359
|
|
|
8442
10360
|
// src/engine/script-engine/tracker.ts
|
|
8443
10361
|
import * as fs3 from "fs";
|
|
8444
|
-
import * as
|
|
10362
|
+
import * as path5 from "path";
|
|
8445
10363
|
import * as os2 from "os";
|
|
8446
10364
|
function maxFileSizeFromEnv() {
|
|
8447
10365
|
const raw = (process.env.AGENT_MOSS_SCRIPT_MAX_FILE_SIZE || "").trim();
|
|
@@ -8458,14 +10376,44 @@ function pickBackend(pathStr) {
|
|
|
8458
10376
|
}
|
|
8459
10377
|
return DEFAULT_BACKEND;
|
|
8460
10378
|
}
|
|
10379
|
+
function realpathBestEffort(absolutePath) {
|
|
10380
|
+
try {
|
|
10381
|
+
return fs3.realpathSync.native(absolutePath);
|
|
10382
|
+
} catch {
|
|
10383
|
+
}
|
|
10384
|
+
try {
|
|
10385
|
+
return fs3.realpathSync(absolutePath);
|
|
10386
|
+
} catch {
|
|
10387
|
+
}
|
|
10388
|
+
const tail = [];
|
|
10389
|
+
let current = absolutePath;
|
|
10390
|
+
while (true) {
|
|
10391
|
+
const parent = path5.dirname(current);
|
|
10392
|
+
if (parent === current) break;
|
|
10393
|
+
tail.unshift(path5.basename(current));
|
|
10394
|
+
current = parent;
|
|
10395
|
+
if (fs3.existsSync(current)) {
|
|
10396
|
+
try {
|
|
10397
|
+
return path5.join(realpathBestEffort(current), ...tail);
|
|
10398
|
+
} catch {
|
|
10399
|
+
break;
|
|
10400
|
+
}
|
|
10401
|
+
}
|
|
10402
|
+
}
|
|
10403
|
+
return absolutePath;
|
|
10404
|
+
}
|
|
10405
|
+
function isAbsoluteExpanded(p) {
|
|
10406
|
+
if (p === "~" || p.startsWith("~/")) return true;
|
|
10407
|
+
return path5.isAbsolute(p);
|
|
10408
|
+
}
|
|
8461
10409
|
function resolvePath(p, baseDir) {
|
|
8462
10410
|
let expanded = p;
|
|
8463
10411
|
if (expanded.startsWith("~/") || expanded === "~") {
|
|
8464
|
-
expanded =
|
|
8465
|
-
} else if (!
|
|
8466
|
-
expanded =
|
|
10412
|
+
expanded = path5.join(os2.homedir(), expanded.slice(1));
|
|
10413
|
+
} else if (!path5.isAbsolute(expanded) && baseDir) {
|
|
10414
|
+
expanded = path5.join(baseDir, expanded);
|
|
8467
10415
|
}
|
|
8468
|
-
return
|
|
10416
|
+
return realpathBestEffort(path5.resolve(expanded));
|
|
8469
10417
|
}
|
|
8470
10418
|
function readScript(pathStr, maxFileSize) {
|
|
8471
10419
|
try {
|
|
@@ -8510,28 +10458,41 @@ function emptyNode(pathStr, depth) {
|
|
|
8510
10458
|
keywordRiskReason: ""
|
|
8511
10459
|
};
|
|
8512
10460
|
}
|
|
8513
|
-
|
|
10461
|
+
function captureReachableContent(details, source, reachable) {
|
|
10462
|
+
details.reachable_content_matches_source = reachable === source;
|
|
10463
|
+
if ([...reachable].length <= MAX_DIAGNOSTIC_CONTENT_BYTES) {
|
|
10464
|
+
details.reachable_content = reachable;
|
|
10465
|
+
} else {
|
|
10466
|
+
details.reachable_content_omitted = true;
|
|
10467
|
+
}
|
|
10468
|
+
}
|
|
10469
|
+
var DEFAULT_MAX_DEPTH, DEFAULT_MAX_NODES, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_TOTAL_SIZE, DIAGNOSTIC_NODE_LIMIT, DIAGNOSTIC_CHILD_LIMIT, MAX_DIAGNOSTIC_CONTENT_BYTES, BACKENDS, DEFAULT_BACKEND, RecursiveTracker;
|
|
8514
10470
|
var init_tracker = __esm({
|
|
8515
10471
|
"src/engine/script-engine/tracker.ts"() {
|
|
8516
10472
|
"use strict";
|
|
8517
10473
|
init_esm_shims();
|
|
10474
|
+
init_ir();
|
|
8518
10475
|
init_python_backend();
|
|
8519
10476
|
init_backends();
|
|
8520
10477
|
DEFAULT_MAX_DEPTH = 14;
|
|
8521
10478
|
DEFAULT_MAX_NODES = 64;
|
|
8522
10479
|
DEFAULT_MAX_FILE_SIZE = maxFileSizeFromEnv();
|
|
8523
10480
|
DEFAULT_MAX_TOTAL_SIZE = 8 * 1024 * 1024;
|
|
10481
|
+
DIAGNOSTIC_NODE_LIMIT = 8;
|
|
10482
|
+
DIAGNOSTIC_CHILD_LIMIT = 4;
|
|
10483
|
+
MAX_DIAGNOSTIC_CONTENT_BYTES = 8 * 1024;
|
|
8524
10484
|
BACKENDS = {
|
|
8525
10485
|
".py": new PythonBackend()
|
|
8526
10486
|
};
|
|
8527
10487
|
DEFAULT_BACKEND = new ShellBackend();
|
|
8528
10488
|
RecursiveTracker = class {
|
|
8529
|
-
constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
|
|
10489
|
+
constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true, diagnostics = null) {
|
|
8530
10490
|
this.maxDepth = maxDepth;
|
|
8531
10491
|
this.maxNodes = maxNodes;
|
|
8532
10492
|
this.maxFileSize = maxFileSize;
|
|
8533
10493
|
this.maxTotalSize = maxTotalSize;
|
|
8534
10494
|
this.stopOnCritical = stopOnCritical;
|
|
10495
|
+
this.diagnostics = diagnostics;
|
|
8535
10496
|
this._scanner = commandScanner;
|
|
8536
10497
|
this.result = {
|
|
8537
10498
|
nodes: [],
|
|
@@ -8553,39 +10514,78 @@ var init_tracker = __esm({
|
|
|
8553
10514
|
maxFileSize;
|
|
8554
10515
|
maxTotalSize;
|
|
8555
10516
|
stopOnCritical;
|
|
10517
|
+
diagnostics;
|
|
8556
10518
|
result;
|
|
8557
10519
|
visiting = /* @__PURE__ */ new Set();
|
|
8558
|
-
|
|
10520
|
+
/**
|
|
10521
|
+
* 已处理集合:按 (路径 → 调用上下文) 去重。
|
|
10522
|
+
* 同一脚本可能先以带参直接调用扫描过,再被 import / 另一组参数调用;
|
|
10523
|
+
* sys.argv 分支完全不同,不能因为"路径访问过"就跳过(会漏掉危险分支)。
|
|
10524
|
+
*/
|
|
10525
|
+
visited = /* @__PURE__ */ new Map();
|
|
8559
10526
|
_scanner;
|
|
10527
|
+
_diagnosticNodes = [];
|
|
10528
|
+
_budgetSkips = { depth: 0, nodes: 0, total_bytes: 0 };
|
|
8560
10529
|
track(entryPath, entryArgs, cwd = "") {
|
|
8561
|
-
const
|
|
8562
|
-
const resolved = resolvePath(entryPath);
|
|
10530
|
+
const processCwd = resolvePath(cwd || ".");
|
|
10531
|
+
const resolved = resolvePath(entryPath, processCwd);
|
|
8563
10532
|
this.result.entryPath = resolved;
|
|
8564
|
-
this.visitScript(resolved, 0,
|
|
10533
|
+
this.visitScript(resolved, 0, processCwd, entryArgs);
|
|
8565
10534
|
const nodes = this.result.nodes;
|
|
8566
10535
|
this.result.hasCritical = nodes.some((n) => n.l1RiskLevel === "critical" || n.l2RiskLevel === "critical" || n.keywordRiskLevel === "critical") || this.result.hasCritical;
|
|
8567
10536
|
this.result.hasHigh = nodes.some((n) => ["high", "critical"].includes(n.l1RiskLevel) || ["high", "critical"].includes(n.l2RiskLevel) || ["high", "critical"].includes(n.keywordRiskLevel));
|
|
8568
10537
|
this.result.firstHitNode = nodes.find((n) => n.l1Hit || n.l2Hit || n.isSuspicious) || null;
|
|
10538
|
+
if (this.diagnostics !== null) {
|
|
10539
|
+
const maxVisitedDepth = nodes.reduce((max, node) => Math.max(max, node.depth), 0);
|
|
10540
|
+
this.diagnostics.nodes = this._diagnosticNodes;
|
|
10541
|
+
this.diagnostics.node_count = nodes.length;
|
|
10542
|
+
this.diagnostics.omitted_nodes = nodes.length - this._diagnosticNodes.length;
|
|
10543
|
+
this.diagnostics.max_visited_depth = maxVisitedDepth;
|
|
10544
|
+
this.diagnostics.total_bytes = this.result.totalSize;
|
|
10545
|
+
this.diagnostics.budget_skips = this._budgetSkips;
|
|
10546
|
+
this.diagnostics.limits = {
|
|
10547
|
+
depth: this.maxDepth,
|
|
10548
|
+
nodes: this.maxNodes,
|
|
10549
|
+
file_bytes: this.maxFileSize,
|
|
10550
|
+
total_bytes: this.maxTotalSize
|
|
10551
|
+
};
|
|
10552
|
+
}
|
|
8569
10553
|
return this.result;
|
|
8570
10554
|
}
|
|
8571
|
-
visitScript(pathStr, depth,
|
|
10555
|
+
visitScript(pathStr, depth, processCwd, args, isImport = false, argsKnown = true) {
|
|
8572
10556
|
pathStr = resolvePath(pathStr);
|
|
8573
10557
|
if (this.visiting.has(pathStr)) return;
|
|
8574
|
-
|
|
10558
|
+
const effectiveArgs = argsKnown ? args : null;
|
|
10559
|
+
const invocation = `${argsKnown ? "1" : "0"}\0${effectiveArgs === null ? "" : JSON.stringify(effectiveArgs)}\0${processCwd === null ? "\0UNKNOWN" : processCwd}`;
|
|
10560
|
+
const seen = this.visited.get(pathStr);
|
|
10561
|
+
if (seen !== void 0 && seen.has(invocation)) return;
|
|
8575
10562
|
if (depth > this.maxDepth) {
|
|
10563
|
+
if (this.diagnostics !== null) this._budgetSkips.depth += 1;
|
|
8576
10564
|
this.result.maxDepthReached = true;
|
|
8577
10565
|
return;
|
|
8578
10566
|
}
|
|
8579
10567
|
if (this.result.nodes.length >= this.maxNodes) {
|
|
10568
|
+
if (this.diagnostics !== null) this._budgetSkips.nodes += 1;
|
|
8580
10569
|
this.result.maxNodesReached = true;
|
|
8581
10570
|
return;
|
|
8582
10571
|
}
|
|
8583
10572
|
if (this.result.totalSize >= this.maxTotalSize) {
|
|
10573
|
+
if (this.diagnostics !== null) this._budgetSkips.total_bytes += 1;
|
|
8584
10574
|
this.result.maxSizeReached = true;
|
|
8585
10575
|
return;
|
|
8586
10576
|
}
|
|
8587
10577
|
this.visiting.add(pathStr);
|
|
8588
|
-
this.
|
|
10578
|
+
let seenSet = this.visited.get(pathStr);
|
|
10579
|
+
if (seenSet === void 0) {
|
|
10580
|
+
seenSet = /* @__PURE__ */ new Set();
|
|
10581
|
+
this.visited.set(pathStr, seenSet);
|
|
10582
|
+
}
|
|
10583
|
+
seenSet.add(invocation);
|
|
10584
|
+
let details = null;
|
|
10585
|
+
if (this.diagnostics !== null && this._diagnosticNodes.length < DIAGNOSTIC_NODE_LIMIT) {
|
|
10586
|
+
details = { depth };
|
|
10587
|
+
this._diagnosticNodes.push(details);
|
|
10588
|
+
}
|
|
8589
10589
|
const { content, lineCount, fileSize, error } = readScript(pathStr, this.maxFileSize);
|
|
8590
10590
|
if (error) {
|
|
8591
10591
|
const node2 = emptyNode(pathStr, depth);
|
|
@@ -8594,12 +10594,20 @@ var init_tracker = __esm({
|
|
|
8594
10594
|
node2.lineCount = lineCount;
|
|
8595
10595
|
node2.unanalyzable = error.startsWith("\u811A\u672C\u6587\u4EF6\u8FC7\u5927");
|
|
8596
10596
|
this.result.nodes.push(node2);
|
|
10597
|
+
if (details !== null) {
|
|
10598
|
+
details.read_status = node2.unanalyzable ? "file_size_limit" : "read_error";
|
|
10599
|
+
details.file_bytes = fileSize;
|
|
10600
|
+
}
|
|
8597
10601
|
this.visiting.delete(pathStr);
|
|
8598
10602
|
return;
|
|
8599
10603
|
}
|
|
8600
10604
|
this.result.totalSize += fileSize;
|
|
8601
10605
|
this.result.totalLines += lineCount;
|
|
8602
|
-
const ir = pickBackend(pathStr).parse(
|
|
10606
|
+
const ir = pickBackend(pathStr).parse(
|
|
10607
|
+
content,
|
|
10608
|
+
effectiveArgs,
|
|
10609
|
+
details === null ? { argsKnown } : { argsKnown, diagnostics: details }
|
|
10610
|
+
);
|
|
8603
10611
|
const node = emptyNode(pathStr, depth);
|
|
8604
10612
|
node.rawContent = content;
|
|
8605
10613
|
node.preprocessedContent = ir.reachableContent;
|
|
@@ -8607,8 +10615,24 @@ var init_tracker = __esm({
|
|
|
8607
10615
|
node.fileSize = fileSize;
|
|
8608
10616
|
this.result.nodes.push(node);
|
|
8609
10617
|
this.result.totalNodes = this.result.nodes.length;
|
|
10618
|
+
if (details !== null) {
|
|
10619
|
+
const fingerprint2 = scanFingerprint(ir.reachableContent);
|
|
10620
|
+
details.language = ir.language;
|
|
10621
|
+
details.control_flow_resolved = ir.controlFlowResolved;
|
|
10622
|
+
details.file_bytes = fileSize;
|
|
10623
|
+
details.scan_bytes = fingerprint2.bytes;
|
|
10624
|
+
details.scan_sha256 = fingerprint2.sha256;
|
|
10625
|
+
details.child_count = ir.calls.length;
|
|
10626
|
+
details.child_arg_counts = ir.calls.slice(0, DIAGNOSTIC_CHILD_LIMIT).map((call) => call.args.length);
|
|
10627
|
+
details.inline_l1_scan = false;
|
|
10628
|
+
captureReachableContent(details, content, ir.reachableContent);
|
|
10629
|
+
}
|
|
8610
10630
|
if (this._scanner && ir.reachableContent) {
|
|
8611
10631
|
const l1 = this._scanner(ir.reachableContent);
|
|
10632
|
+
if (details !== null) {
|
|
10633
|
+
details.inline_l1_scan = true;
|
|
10634
|
+
details.inline_l1_hit = l1.hit;
|
|
10635
|
+
}
|
|
8612
10636
|
if (l1.hit) {
|
|
8613
10637
|
node.l1Hit = true;
|
|
8614
10638
|
node.l1RiskLevel = l1.riskLevel;
|
|
@@ -8625,12 +10649,38 @@ var init_tracker = __esm({
|
|
|
8625
10649
|
}
|
|
8626
10650
|
}
|
|
8627
10651
|
}
|
|
8628
|
-
const parentDir =
|
|
10652
|
+
const parentDir = path5.dirname(pathStr);
|
|
8629
10653
|
const childPaths = [];
|
|
8630
10654
|
for (const call of ir.calls) {
|
|
8631
|
-
|
|
10655
|
+
let childCwd = processCwd;
|
|
10656
|
+
let pathBase = parentDir;
|
|
10657
|
+
const launchCwd = call.launchCwd;
|
|
10658
|
+
if (launchCwd === WORKING_DIRECTORY_UNKNOWN) {
|
|
10659
|
+
childCwd = null;
|
|
10660
|
+
} else if (launchCwd !== void 0 && launchCwd !== null) {
|
|
10661
|
+
if (path5.isAbsolute(launchCwd)) {
|
|
10662
|
+
childCwd = path5.resolve(launchCwd);
|
|
10663
|
+
} else if (processCwd !== null) {
|
|
10664
|
+
childCwd = path5.resolve(processCwd, launchCwd);
|
|
10665
|
+
}
|
|
10666
|
+
}
|
|
10667
|
+
if (launchCwd !== void 0 && launchCwd !== null) {
|
|
10668
|
+
if (childCwd !== null) {
|
|
10669
|
+
pathBase = childCwd;
|
|
10670
|
+
} else if (!isAbsoluteExpanded(call.path)) {
|
|
10671
|
+
continue;
|
|
10672
|
+
}
|
|
10673
|
+
}
|
|
10674
|
+
const child = resolvePath(call.path, pathBase);
|
|
8632
10675
|
childPaths.push(child);
|
|
8633
|
-
this.visitScript(
|
|
10676
|
+
this.visitScript(
|
|
10677
|
+
child,
|
|
10678
|
+
depth + 1,
|
|
10679
|
+
childCwd,
|
|
10680
|
+
call.args,
|
|
10681
|
+
call.isImport === true,
|
|
10682
|
+
call.argsKnown !== false
|
|
10683
|
+
);
|
|
8634
10684
|
if (this.stopOnCritical && this.result.hasCritical) break;
|
|
8635
10685
|
}
|
|
8636
10686
|
node.childPaths = childPaths;
|
|
@@ -8642,7 +10692,7 @@ var init_tracker = __esm({
|
|
|
8642
10692
|
|
|
8643
10693
|
// src/engine/script-content-analyzer.ts
|
|
8644
10694
|
import { statSync as statSync6, existsSync as existsSync13 } from "fs";
|
|
8645
|
-
import { resolve as resolve11, join as join13, isAbsolute as
|
|
10695
|
+
import { resolve as resolve11, join as join13, isAbsolute as isAbsolute5 } from "path";
|
|
8646
10696
|
import { homedir as homedir5 } from "os";
|
|
8647
10697
|
function emptyChain() {
|
|
8648
10698
|
return {
|
|
@@ -8913,7 +10963,7 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
|
8913
10963
|
resolvedPath = inline;
|
|
8914
10964
|
isInline = true;
|
|
8915
10965
|
}
|
|
8916
|
-
if (resolvedPath && !
|
|
10966
|
+
if (resolvedPath && !isAbsolute5(resolvedPath) && !resolvedPath.startsWith("~/")) {
|
|
8917
10967
|
resolvedPath = join13(input.cwd || process.cwd(), resolvedPath);
|
|
8918
10968
|
}
|
|
8919
10969
|
const l1Adapter = (content) => {
|
|
@@ -9048,7 +11098,7 @@ var init_script_content_analyzer = __esm({
|
|
|
9048
11098
|
|
|
9049
11099
|
// src/infra/trace-log.ts
|
|
9050
11100
|
import fs4 from "fs";
|
|
9051
|
-
import
|
|
11101
|
+
import path6 from "path";
|
|
9052
11102
|
function traceLevel() {
|
|
9053
11103
|
if (_levelCache !== null) return _levelCache;
|
|
9054
11104
|
const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
|
|
@@ -9075,7 +11125,7 @@ function tracePath() {
|
|
|
9075
11125
|
const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
|
|
9076
11126
|
if (explicit) return explicit;
|
|
9077
11127
|
try {
|
|
9078
|
-
return
|
|
11128
|
+
return path6.join(getDataRoot(), "agent_moss_trace.log");
|
|
9079
11129
|
} catch {
|
|
9080
11130
|
return "agent_moss_trace.log";
|
|
9081
11131
|
}
|
|
@@ -9114,7 +11164,7 @@ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
|
|
|
9114
11164
|
`;
|
|
9115
11165
|
const file = tracePath();
|
|
9116
11166
|
try {
|
|
9117
|
-
const dir =
|
|
11167
|
+
const dir = path6.dirname(file);
|
|
9118
11168
|
if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
|
|
9119
11169
|
try {
|
|
9120
11170
|
const st = fs4.statSync(file);
|
|
@@ -9718,7 +11768,7 @@ var init_token_stats = __esm({
|
|
|
9718
11768
|
});
|
|
9719
11769
|
|
|
9720
11770
|
// src/engine/llm-analyzer.ts
|
|
9721
|
-
import { createHash as
|
|
11771
|
+
import { createHash as createHash4 } from "crypto";
|
|
9722
11772
|
import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
|
|
9723
11773
|
import OpenAI from "openai";
|
|
9724
11774
|
function reasoningTextFallback(raw) {
|
|
@@ -9797,7 +11847,7 @@ async function runLLMAnalysis(input, previous) {
|
|
|
9797
11847
|
}
|
|
9798
11848
|
const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
|
|
9799
11849
|
const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
|
|
9800
|
-
const cacheKey2 = `${input.aNext.actionType}:${
|
|
11850
|
+
const cacheKey2 = `${input.aNext.actionType}:${createHash4("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
|
|
9801
11851
|
const cached2 = llmCache.get(cacheKey2);
|
|
9802
11852
|
if (cached2) {
|
|
9803
11853
|
console.log("[AgentMoss] LLM cache hit");
|
|
@@ -9812,7 +11862,7 @@ async function runLLMAnalysis(input, previous) {
|
|
|
9812
11862
|
} else {
|
|
9813
11863
|
scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
|
|
9814
11864
|
}
|
|
9815
|
-
const maxPromptTokens =
|
|
11865
|
+
const maxPromptTokens = getMaxPromptTokens();
|
|
9816
11866
|
const budgetMode = getAgentMossSetting("AGENT_MOSS_LLM_BUDGET_MODE", "hard").trim().toLowerCase() === "soft" ? "soft" : "hard";
|
|
9817
11867
|
const budgetActive = maxPromptTokens > 0;
|
|
9818
11868
|
const tokenLimit = budgetActive && budgetMode === "hard" ? Math.floor(maxPromptTokens * 100 / 115) : maxPromptTokens;
|
|
@@ -9919,6 +11969,10 @@ function getNumSetting(key, def) {
|
|
|
9919
11969
|
const v = parseInt(getAgentMossSetting(key, String(def)), 10);
|
|
9920
11970
|
return Number.isFinite(v) ? v : def;
|
|
9921
11971
|
}
|
|
11972
|
+
function getMaxPromptTokens() {
|
|
11973
|
+
const configured = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
|
|
11974
|
+
return configured > 0 ? Math.max(1200, configured) : 0;
|
|
11975
|
+
}
|
|
9922
11976
|
function truncateDetail(detail, maxChars) {
|
|
9923
11977
|
if (maxChars <= 0 || detail.length <= maxChars) return detail;
|
|
9924
11978
|
const head = Math.max(1, Math.floor(maxChars * 0.6));
|
|
@@ -10313,8 +12367,8 @@ var init_rule_store = __esm({
|
|
|
10313
12367
|
BrainRuleStore = class {
|
|
10314
12368
|
path;
|
|
10315
12369
|
data;
|
|
10316
|
-
constructor(
|
|
10317
|
-
this.path =
|
|
12370
|
+
constructor(path10) {
|
|
12371
|
+
this.path = path10 || getRulesPath();
|
|
10318
12372
|
this.data = this.load();
|
|
10319
12373
|
}
|
|
10320
12374
|
load() {
|
|
@@ -10767,10 +12821,10 @@ ${reason.slice(0, 500)}
|
|
|
10767
12821
|
const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
|
|
10768
12822
|
let mm;
|
|
10769
12823
|
while ((mm = pathRe.exec(src)) !== null) {
|
|
10770
|
-
const
|
|
10771
|
-
if (
|
|
10772
|
-
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(
|
|
10773
|
-
const gen = this.generalizePath(
|
|
12824
|
+
const path10 = mm[1];
|
|
12825
|
+
if (path10.split("/").length < 3) continue;
|
|
12826
|
+
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path10)) continue;
|
|
12827
|
+
const gen = this.generalizePath(path10);
|
|
10774
12828
|
if (seen.has(gen)) continue;
|
|
10775
12829
|
seen.add(gen);
|
|
10776
12830
|
patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
|
|
@@ -10789,8 +12843,8 @@ ${reason.slice(0, 500)}
|
|
|
10789
12843
|
}
|
|
10790
12844
|
return false;
|
|
10791
12845
|
}
|
|
10792
|
-
generalizePath(
|
|
10793
|
-
const p =
|
|
12846
|
+
generalizePath(path10) {
|
|
12847
|
+
const p = path10.toLowerCase();
|
|
10794
12848
|
if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
|
|
10795
12849
|
return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
|
|
10796
12850
|
}
|
|
@@ -11178,26 +13232,26 @@ function writeExportFiles(outDir, rules, skills) {
|
|
|
11178
13232
|
byLayer.get(r.layer).push(r);
|
|
11179
13233
|
}
|
|
11180
13234
|
for (const layer of [...byLayer.keys()].sort((a, b) => a - b)) {
|
|
11181
|
-
const
|
|
11182
|
-
writeFileSync5(
|
|
11183
|
-
written.push(
|
|
13235
|
+
const path10 = join16(rulesDir2, `l${layer}_brain_rules.json`);
|
|
13236
|
+
writeFileSync5(path10, JSON.stringify(byLayer.get(layer), null, 2), "utf-8");
|
|
13237
|
+
written.push(path10);
|
|
11184
13238
|
}
|
|
11185
13239
|
if (rules.length === 0) {
|
|
11186
|
-
const
|
|
11187
|
-
writeFileSync5(
|
|
11188
|
-
written.push(
|
|
13240
|
+
const path10 = join16(rulesDir2, "empty.txt");
|
|
13241
|
+
writeFileSync5(path10, "(no brain rules to contribute)", "utf-8");
|
|
13242
|
+
written.push(path10);
|
|
11189
13243
|
}
|
|
11190
13244
|
const skillsDir = join16(outDir, "skills");
|
|
11191
13245
|
mkdirSync6(skillsDir, { recursive: true });
|
|
11192
13246
|
for (const sk of skills) {
|
|
11193
|
-
const
|
|
11194
|
-
writeFileSync5(
|
|
11195
|
-
written.push(
|
|
13247
|
+
const path10 = join16(skillsDir, `${sk.name}.md`);
|
|
13248
|
+
writeFileSync5(path10, sk.content || "", "utf-8");
|
|
13249
|
+
written.push(path10);
|
|
11196
13250
|
}
|
|
11197
13251
|
if (skills.length === 0) {
|
|
11198
|
-
const
|
|
11199
|
-
writeFileSync5(
|
|
11200
|
-
written.push(
|
|
13252
|
+
const path10 = join16(skillsDir, "empty.txt");
|
|
13253
|
+
writeFileSync5(path10, "(no brain skills to contribute)", "utf-8");
|
|
13254
|
+
written.push(path10);
|
|
11201
13255
|
}
|
|
11202
13256
|
return written;
|
|
11203
13257
|
}
|
|
@@ -11616,7 +13670,7 @@ function allEdges(mg) {
|
|
|
11616
13670
|
function emptyVerificationResult() {
|
|
11617
13671
|
return { verified: true, violations: [] };
|
|
11618
13672
|
}
|
|
11619
|
-
var
|
|
13673
|
+
var init_ir2 = __esm({
|
|
11620
13674
|
"src/engine/formal-engine/ir.ts"() {
|
|
11621
13675
|
"use strict";
|
|
11622
13676
|
init_esm_shims();
|
|
@@ -11712,7 +13766,7 @@ function checkMCRules(graph) {
|
|
|
11712
13766
|
if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
|
|
11713
13767
|
if (ruleViolates(rule, trace2, witnessMode)) {
|
|
11714
13768
|
const pathNodes = nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3);
|
|
11715
|
-
const
|
|
13769
|
+
const path10 = pathNodes.map((n) => ({
|
|
11716
13770
|
sessionId: n.sessionId,
|
|
11717
13771
|
seq: n.seq,
|
|
11718
13772
|
detail: n.actionDetail.slice(0, 60)
|
|
@@ -11721,7 +13775,7 @@ function checkMCRules(graph) {
|
|
|
11721
13775
|
propertyId: String(rule.id || "mc-ltl"),
|
|
11722
13776
|
reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
|
|
11723
13777
|
riskLevel: String(rule.risk_level || "high"),
|
|
11724
|
-
path:
|
|
13778
|
+
path: path10,
|
|
11725
13779
|
graph: {
|
|
11726
13780
|
property_id: String(rule.id || "mc-ltl"),
|
|
11727
13781
|
property_short: "P6",
|
|
@@ -11752,7 +13806,7 @@ var init_ltl = __esm({
|
|
|
11752
13806
|
"use strict";
|
|
11753
13807
|
init_esm_shims();
|
|
11754
13808
|
init_rules_loader();
|
|
11755
|
-
|
|
13809
|
+
init_ir2();
|
|
11756
13810
|
init_decode();
|
|
11757
13811
|
AP_RE = null;
|
|
11758
13812
|
}
|
|
@@ -11939,12 +13993,12 @@ var init_builder = __esm({
|
|
|
11939
13993
|
});
|
|
11940
13994
|
|
|
11941
13995
|
// src/engine/formal-engine/properties.ts
|
|
11942
|
-
function graphFromPath(nodes,
|
|
13996
|
+
function graphFromPath(nodes, path10, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
|
|
11943
13997
|
const byKey = /* @__PURE__ */ new Map();
|
|
11944
13998
|
for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
|
|
11945
13999
|
const gNodes = [];
|
|
11946
14000
|
const gEdges = [];
|
|
11947
|
-
for (const item of
|
|
14001
|
+
for (const item of path10) {
|
|
11948
14002
|
const n = byKey.get(`${item.sessionId}#${item.seq}`);
|
|
11949
14003
|
gNodes.push({
|
|
11950
14004
|
session_id: item.sessionId,
|
|
@@ -12010,22 +14064,22 @@ function checkCrossSessionChain(graph) {
|
|
|
12010
14064
|
if (witness !== void 0) {
|
|
12011
14065
|
if (nodes[witness].stage !== stages[stages.length - 1]) continue;
|
|
12012
14066
|
let matched = 0;
|
|
12013
|
-
const
|
|
14067
|
+
const path10 = [];
|
|
12014
14068
|
for (let k = 0; k < witness; k++) {
|
|
12015
14069
|
const n = nodes[k];
|
|
12016
14070
|
if (matched < stages.length - 1 && n.stage === stages[matched]) {
|
|
12017
14071
|
matched += 1;
|
|
12018
|
-
|
|
14072
|
+
path10.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
12019
14073
|
}
|
|
12020
14074
|
}
|
|
12021
14075
|
if (matched < stages.length - 1) continue;
|
|
12022
|
-
|
|
14076
|
+
path10.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
|
|
12023
14077
|
violations.push({
|
|
12024
14078
|
propertyId: "cross-" + chain.id,
|
|
12025
14079
|
reason: chain.reason,
|
|
12026
14080
|
riskLevel: chain.riskLevel,
|
|
12027
|
-
path:
|
|
12028
|
-
graph: graphFromPath(nodes,
|
|
14081
|
+
path: path10,
|
|
14082
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
12029
14083
|
property_id: "cross-" + chain.id,
|
|
12030
14084
|
property_short: "P1",
|
|
12031
14085
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -12035,11 +14089,11 @@ function checkCrossSessionChain(graph) {
|
|
|
12035
14089
|
} else {
|
|
12036
14090
|
let matched = 0;
|
|
12037
14091
|
let stageIdx = 0;
|
|
12038
|
-
const
|
|
14092
|
+
const path10 = [];
|
|
12039
14093
|
for (const n of nodes) {
|
|
12040
14094
|
if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
|
|
12041
14095
|
matched += 1;
|
|
12042
|
-
|
|
14096
|
+
path10.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
12043
14097
|
stageIdx += 1;
|
|
12044
14098
|
if (matched >= stages.length) break;
|
|
12045
14099
|
}
|
|
@@ -12049,8 +14103,8 @@ function checkCrossSessionChain(graph) {
|
|
|
12049
14103
|
propertyId: "cross-" + chain.id,
|
|
12050
14104
|
reason: chain.reason,
|
|
12051
14105
|
riskLevel: chain.riskLevel,
|
|
12052
|
-
path:
|
|
12053
|
-
graph: graphFromPath(nodes,
|
|
14106
|
+
path: path10,
|
|
14107
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
12054
14108
|
property_id: "cross-" + chain.id,
|
|
12055
14109
|
property_short: "P1",
|
|
12056
14110
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -12271,7 +14325,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
12271
14325
|
if (candidates.length > 0) {
|
|
12272
14326
|
const pre = nodes[candidates[candidates.length - 1]];
|
|
12273
14327
|
const post = nodes[firstEv];
|
|
12274
|
-
const
|
|
14328
|
+
const path10 = [
|
|
12275
14329
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
12276
14330
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
12277
14331
|
];
|
|
@@ -12279,8 +14333,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
12279
14333
|
propertyId: "no-exfil-after-privesc",
|
|
12280
14334
|
reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
|
|
12281
14335
|
riskLevel: "critical",
|
|
12282
|
-
path:
|
|
12283
|
-
graph: graphFromPath(nodes,
|
|
14336
|
+
path: path10,
|
|
14337
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
12284
14338
|
property_id: "no-exfil-after-privesc",
|
|
12285
14339
|
property_short: "P4",
|
|
12286
14340
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -12297,7 +14351,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
12297
14351
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
12298
14352
|
if (!isExfilNode(nodes[j])) continue;
|
|
12299
14353
|
if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
|
|
12300
|
-
const
|
|
14354
|
+
const path10 = [
|
|
12301
14355
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
12302
14356
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
12303
14357
|
];
|
|
@@ -12305,8 +14359,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
12305
14359
|
propertyId: "no-exfil-after-privesc",
|
|
12306
14360
|
reason: "\u63D0\u6743\u540E\u51FA\u73B0\u5916\u4F20\uFF1A\u63D0\u6743(\u524D) \u2192 \u5916\u4F20(\u540E)\uFF0C\u8FDD\u53CD \u25A1(PRIVESC\u2192\u25C7EXFIL) \u7A97\u53E3\u7EA6\u675F",
|
|
12307
14361
|
riskLevel: "critical",
|
|
12308
|
-
path:
|
|
12309
|
-
graph: graphFromPath(nodes,
|
|
14362
|
+
path: path10,
|
|
14363
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
12310
14364
|
property_id: "no-exfil-after-privesc",
|
|
12311
14365
|
property_short: "P4",
|
|
12312
14366
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -12338,7 +14392,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
12338
14392
|
}
|
|
12339
14393
|
if (pre) {
|
|
12340
14394
|
const post = nodes[firstEv];
|
|
12341
|
-
const
|
|
14395
|
+
const path10 = [
|
|
12342
14396
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
12343
14397
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
12344
14398
|
];
|
|
@@ -12346,8 +14400,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
12346
14400
|
propertyId: "no-exfil-after-credential",
|
|
12347
14401
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
12348
14402
|
riskLevel: "critical",
|
|
12349
|
-
path:
|
|
12350
|
-
graph: graphFromPath(nodes,
|
|
14403
|
+
path: path10,
|
|
14404
|
+
graph: graphFromPath(nodes, path10, "data", {
|
|
12351
14405
|
property_id: "no-exfil-after-credential",
|
|
12352
14406
|
property_short: "P5",
|
|
12353
14407
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -12363,7 +14417,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
12363
14417
|
if (!isCredNode(nodes[i])) continue;
|
|
12364
14418
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
12365
14419
|
if (isExfilNode(nodes[j])) {
|
|
12366
|
-
const
|
|
14420
|
+
const path10 = [
|
|
12367
14421
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
12368
14422
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
12369
14423
|
];
|
|
@@ -12371,8 +14425,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
12371
14425
|
propertyId: "no-exfil-after-credential",
|
|
12372
14426
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
12373
14427
|
riskLevel: "critical",
|
|
12374
|
-
path:
|
|
12375
|
-
graph: graphFromPath(nodes,
|
|
14428
|
+
path: path10,
|
|
14429
|
+
graph: graphFromPath(nodes, path10, "data", {
|
|
12376
14430
|
property_id: "no-exfil-after-credential",
|
|
12377
14431
|
property_short: "P5",
|
|
12378
14432
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -12439,13 +14493,13 @@ function checkLowIntegrityCommandExec(graph) {
|
|
|
12439
14493
|
for (const i of candidates) {
|
|
12440
14494
|
const n = nodes[i];
|
|
12441
14495
|
if (lowAt.has(i) && isComputeNode(n)) {
|
|
12442
|
-
const
|
|
14496
|
+
const path10 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
12443
14497
|
violations.push({
|
|
12444
14498
|
propertyId: "low-integrity-command-exec",
|
|
12445
14499
|
reason: `\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u63A7\u5236\u547D\u4EE4\u6267\u884C\uFF1A${lowAt.get(i)} \u2192 ${n.sessionId}#${n.seq} \u6267\u884C\u4E0D\u53EF\u4FE1\u5185\u5BB9`,
|
|
12446
14500
|
riskLevel: "critical",
|
|
12447
|
-
path:
|
|
12448
|
-
graph: graphFromPath(nodes,
|
|
14501
|
+
path: path10,
|
|
14502
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
12449
14503
|
property_id: "low-integrity-command-exec",
|
|
12450
14504
|
property_short: "P7",
|
|
12451
14505
|
property_name: "\u4F4E\u5B8C\u6574\u6027\u547D\u4EE4\u6267\u884C"
|
|
@@ -12491,7 +14545,7 @@ function checkCrossSessionReachability(graph) {
|
|
|
12491
14545
|
if (reached.has(i)) {
|
|
12492
14546
|
const srcIdx = Math.min(...sources);
|
|
12493
14547
|
const srcDesc = nodes[srcIdx].actionDetail.slice(0, 40);
|
|
12494
|
-
const
|
|
14548
|
+
const path10 = nodes.slice(-3).map((m) => ({
|
|
12495
14549
|
sessionId: m.sessionId,
|
|
12496
14550
|
seq: m.seq,
|
|
12497
14551
|
detail: m.actionDetail.slice(0, 60)
|
|
@@ -12500,8 +14554,8 @@ function checkCrossSessionReachability(graph) {
|
|
|
12500
14554
|
propertyId: "low-integrity-reachability",
|
|
12501
14555
|
reason: `\u4F4E\u5B8C\u6574\u6027\u6E90\u7ECF\u8DE8 session \u6570\u636E\u94FE\u591A\u8DF3\u5230\u8FBE\u5F53\u524D\u6267\u884C\uFF08\u6E90: ${srcDesc} \u2192 ${n.sessionId}#${n.seq}\uFF09`,
|
|
12502
14556
|
riskLevel: "high",
|
|
12503
|
-
path:
|
|
12504
|
-
graph: graphFromPath(nodes,
|
|
14557
|
+
path: path10,
|
|
14558
|
+
graph: graphFromPath(nodes, path10, "data", {
|
|
12505
14559
|
property_id: "low-integrity-reachability",
|
|
12506
14560
|
property_short: "P3",
|
|
12507
14561
|
property_name: "\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u6D41\u53EF\u8FBE"
|
|
@@ -12547,13 +14601,13 @@ function checkSensitiveDataAggregation(graph) {
|
|
|
12547
14601
|
if (!isExfilNode(n)) continue;
|
|
12548
14602
|
const srcs = sourcesFor(i);
|
|
12549
14603
|
if (srcs.size >= 2) {
|
|
12550
|
-
const
|
|
14604
|
+
const path10 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
12551
14605
|
violations.push({
|
|
12552
14606
|
propertyId: "sensitive-data-aggregation",
|
|
12553
14607
|
reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
|
|
12554
14608
|
riskLevel: "critical",
|
|
12555
|
-
path:
|
|
12556
|
-
graph: graphFromPath(nodes,
|
|
14609
|
+
path: path10,
|
|
14610
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
12557
14611
|
property_id: "sensitive-data-aggregation",
|
|
12558
14612
|
property_short: "P8",
|
|
12559
14613
|
property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
|
|
@@ -12572,7 +14626,7 @@ var init_properties = __esm({
|
|
|
12572
14626
|
"use strict";
|
|
12573
14627
|
init_esm_shims();
|
|
12574
14628
|
init_rules_loader();
|
|
12575
|
-
|
|
14629
|
+
init_ir2();
|
|
12576
14630
|
init_ltl();
|
|
12577
14631
|
init_decode();
|
|
12578
14632
|
CROSS_SESSION_CHAINS = null;
|
|
@@ -12625,7 +14679,7 @@ var init_engine = __esm({
|
|
|
12625
14679
|
"use strict";
|
|
12626
14680
|
init_esm_shims();
|
|
12627
14681
|
init_builder();
|
|
12628
|
-
|
|
14682
|
+
init_ir2();
|
|
12629
14683
|
init_properties();
|
|
12630
14684
|
FormalEngine = class {
|
|
12631
14685
|
properties;
|
|
@@ -12675,10 +14729,10 @@ var init_engine = __esm({
|
|
|
12675
14729
|
});
|
|
12676
14730
|
|
|
12677
14731
|
// src/engine/formal-engine/stateful.ts
|
|
12678
|
-
import { createHash as
|
|
14732
|
+
import { createHash as createHash5 } from "crypto";
|
|
12679
14733
|
import * as fs5 from "fs";
|
|
12680
14734
|
import * as os3 from "os";
|
|
12681
|
-
import * as
|
|
14735
|
+
import * as path7 from "path";
|
|
12682
14736
|
import { gzipSync } from "zlib";
|
|
12683
14737
|
function extractInstances(actionDetail, stage) {
|
|
12684
14738
|
const out = [];
|
|
@@ -12764,7 +14818,7 @@ function envInt3(name, def) {
|
|
|
12764
14818
|
function cleanupChainArchives(dir, maxBytes = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_MAX_MB", 512) * 1024 * 1024, maxAgeDays = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_MAX_AGE_DAYS", 0)) {
|
|
12765
14819
|
let files = [];
|
|
12766
14820
|
try {
|
|
12767
|
-
files = fs5.readdirSync(dir).filter((f) => f.startsWith("chain-nodes-") && f.endsWith(".jsonl.gz")).map((f) =>
|
|
14821
|
+
files = fs5.readdirSync(dir).filter((f) => f.startsWith("chain-nodes-") && f.endsWith(".jsonl.gz")).map((f) => path7.join(dir, f)).sort((a, b) => fs5.statSync(a).mtimeMs - fs5.statSync(b).mtimeMs);
|
|
12768
14822
|
} catch {
|
|
12769
14823
|
return { deleted: 0, files: 0, bytes: 0 };
|
|
12770
14824
|
}
|
|
@@ -12810,7 +14864,7 @@ function cleanupChainArchives(dir, maxBytes = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_
|
|
|
12810
14864
|
for (const f of fs5.readdirSync(dir)) {
|
|
12811
14865
|
if (!f.startsWith("chain-nodes-") || !f.endsWith(".jsonl.gz")) continue;
|
|
12812
14866
|
remainFiles += 1;
|
|
12813
|
-
remainBytes += fs5.statSync(
|
|
14867
|
+
remainBytes += fs5.statSync(path7.join(dir, f)).size;
|
|
12814
14868
|
}
|
|
12815
14869
|
} catch {
|
|
12816
14870
|
}
|
|
@@ -12823,7 +14877,7 @@ function canonicalActionType(actionType) {
|
|
|
12823
14877
|
function canonicalDetail(actionDetail) {
|
|
12824
14878
|
const detail = String(actionDetail || "");
|
|
12825
14879
|
const m = TRUNCATED_DETAIL_RE.exec(detail);
|
|
12826
|
-
const digest = m ? m[1] :
|
|
14880
|
+
const digest = m ? m[1] : createHash5("sha256").update(detail).digest("hex").slice(0, 16);
|
|
12827
14881
|
return `sha256:${digest}`;
|
|
12828
14882
|
}
|
|
12829
14883
|
function canonicalCalledAt(calledAt) {
|
|
@@ -12843,7 +14897,7 @@ function fingerprint(sessionId, actionType, actionDetail, calledAt) {
|
|
|
12843
14897
|
canonicalDetail(actionDetail),
|
|
12844
14898
|
canonicalCalledAt(calledAt)
|
|
12845
14899
|
].join("\0");
|
|
12846
|
-
return
|
|
14900
|
+
return createHash5("blake2b512").update(raw).digest("hex").slice(0, 16);
|
|
12847
14901
|
}
|
|
12848
14902
|
function gateOrder(action) {
|
|
12849
14903
|
const callId = String(action?.gateCallId ?? "");
|
|
@@ -12860,7 +14914,7 @@ function gateFingerprint(action, isError, agentId, instanceId, order) {
|
|
|
12860
14914
|
Boolean(isError),
|
|
12861
14915
|
order.callTimeUs
|
|
12862
14916
|
];
|
|
12863
|
-
return
|
|
14917
|
+
return createHash5("sha256").update(JSON.stringify(values)).digest("hex");
|
|
12864
14918
|
}
|
|
12865
14919
|
var DESTROY_RE, NEVER_ACTIVATED_RE, CRED_FILE_RE2, EXFIL_RE2, PORT_RE, BARE_PORT_RE, SOCK_RE, UNIT_RE, PORT_STAGE_RE, StatefulAnalysisUnavailable, UnconfirmedGateRetry, GateCallConflict, STAGES_PATTERNS, CHAINS, COMMON_DIR_RESOURCES2, MAX_NODES, TRUNCATED_DETAIL_RE, SHELL_ACTION_ALIASES, StatefulChainTracker;
|
|
12866
14920
|
var init_stateful = __esm({
|
|
@@ -13065,10 +15119,10 @@ var init_stateful = __esm({
|
|
|
13065
15119
|
if (this.nodes_.length <= keep) return { archived: 0, file: "" };
|
|
13066
15120
|
const old = this.nodes_.slice(0, this.nodes_.length - keep);
|
|
13067
15121
|
const kept = this.nodes_.slice(-keep);
|
|
13068
|
-
const dir = archiveDir || process.env.AGENT_MOSS_CHAIN_ARCHIVE_DIR ||
|
|
15122
|
+
const dir = archiveDir || process.env.AGENT_MOSS_CHAIN_ARCHIVE_DIR || path7.join(process.env.AGENT_MOSS_STATE_DIR || path7.join(os3.homedir(), ".agentmoss"), "chain-archive");
|
|
13069
15123
|
fs5.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
13070
15124
|
const safeAgent = (this.agentId || "default").replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
13071
|
-
const file =
|
|
15125
|
+
const file = path7.join(dir, `chain-nodes-${safeAgent}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.jsonl.gz`);
|
|
13072
15126
|
const payload = old.map((n) => JSON.stringify(n)).join("\n") + "\n";
|
|
13073
15127
|
fs5.writeFileSync(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
13074
15128
|
try {
|
|
@@ -13292,11 +15346,11 @@ var init_stateful = __esm({
|
|
|
13292
15346
|
}
|
|
13293
15347
|
}
|
|
13294
15348
|
chainPath(stages) {
|
|
13295
|
-
const
|
|
15349
|
+
const path10 = [];
|
|
13296
15350
|
let want = stages[0];
|
|
13297
15351
|
for (const n of this.nodes_) {
|
|
13298
15352
|
if (n.stage === want) {
|
|
13299
|
-
|
|
15353
|
+
path10.push({
|
|
13300
15354
|
sessionId: n.sessionId,
|
|
13301
15355
|
seq: n.seq,
|
|
13302
15356
|
stage: n.stage,
|
|
@@ -13312,12 +15366,12 @@ var init_stateful = __esm({
|
|
|
13312
15366
|
}
|
|
13313
15367
|
}
|
|
13314
15368
|
}
|
|
13315
|
-
return
|
|
15369
|
+
return path10;
|
|
13316
15370
|
}
|
|
13317
15371
|
/** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
|
|
13318
15372
|
buildChainGraph(stages, chainId) {
|
|
13319
|
-
const
|
|
13320
|
-
const gNodes =
|
|
15373
|
+
const path10 = this.chainPath(stages);
|
|
15374
|
+
const gNodes = path10.map((p, i) => {
|
|
13321
15375
|
const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
|
|
13322
15376
|
return {
|
|
13323
15377
|
session_id: p.sessionId,
|
|
@@ -13585,16 +15639,16 @@ var init_stateful = __esm({
|
|
|
13585
15639
|
// src/engine/formal-engine/chain_state.ts
|
|
13586
15640
|
import * as fs6 from "fs";
|
|
13587
15641
|
import * as os4 from "os";
|
|
13588
|
-
import * as
|
|
13589
|
-
import { createHash as
|
|
15642
|
+
import * as path8 from "path";
|
|
15643
|
+
import { createHash as createHash6 } from "crypto";
|
|
13590
15644
|
function defaultStateDbPath() {
|
|
13591
|
-
const base = process.env.AGENT_MOSS_STATE_DIR ||
|
|
15645
|
+
const base = process.env.AGENT_MOSS_STATE_DIR || path8.join(os4.homedir(), ".agentmoss");
|
|
13592
15646
|
const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
|
|
13593
|
-
const dir = instance ?
|
|
13594
|
-
const tag =
|
|
13595
|
-
const target =
|
|
15647
|
+
const dir = instance ? path8.join(base, instance) : base;
|
|
15648
|
+
const tag = createHash6("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
|
|
15649
|
+
const target = path8.join(dir, `stateful_chains_${tag}.json`);
|
|
13596
15650
|
if (instance) {
|
|
13597
|
-
const legacy =
|
|
15651
|
+
const legacy = path8.join(base, `stateful_chains_${tag}.json`);
|
|
13598
15652
|
if (!fs6.existsSync(target) && fs6.existsSync(legacy)) {
|
|
13599
15653
|
try {
|
|
13600
15654
|
fs6.mkdirSync(dir, { recursive: true });
|
|
@@ -13691,7 +15745,7 @@ var init_chain_state = __esm({
|
|
|
13691
15745
|
this._timer = null;
|
|
13692
15746
|
try {
|
|
13693
15747
|
this._syncDirtyToData();
|
|
13694
|
-
ensurePrivateDir(
|
|
15748
|
+
ensurePrivateDir(path8.dirname(this.filePath));
|
|
13695
15749
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
13696
15750
|
} catch {
|
|
13697
15751
|
}
|
|
@@ -13714,7 +15768,7 @@ var init_chain_state = __esm({
|
|
|
13714
15768
|
}
|
|
13715
15769
|
try {
|
|
13716
15770
|
this._syncDirtyToData();
|
|
13717
|
-
ensurePrivateDir(
|
|
15771
|
+
ensurePrivateDir(path8.dirname(this.filePath));
|
|
13718
15772
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
13719
15773
|
} catch {
|
|
13720
15774
|
}
|
|
@@ -13782,7 +15836,7 @@ var init_chain_state = __esm({
|
|
|
13782
15836
|
_flushNow() {
|
|
13783
15837
|
this._syncDirtyToData();
|
|
13784
15838
|
try {
|
|
13785
|
-
const _dirOk = ensurePrivateDir(
|
|
15839
|
+
const _dirOk = ensurePrivateDir(path8.dirname(this.filePath));
|
|
13786
15840
|
const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
13787
15841
|
if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
|
|
13788
15842
|
} catch (e) {
|
|
@@ -13831,7 +15885,7 @@ var init_formal_engine = __esm({
|
|
|
13831
15885
|
"use strict";
|
|
13832
15886
|
init_esm_shims();
|
|
13833
15887
|
init_engine();
|
|
13834
|
-
|
|
15888
|
+
init_ir2();
|
|
13835
15889
|
init_builder();
|
|
13836
15890
|
init_properties();
|
|
13837
15891
|
init_stateful();
|
|
@@ -14424,7 +16478,7 @@ var init_types = __esm({
|
|
|
14424
16478
|
});
|
|
14425
16479
|
|
|
14426
16480
|
// src/infra/policy-cache.ts
|
|
14427
|
-
import { createHash as
|
|
16481
|
+
import { createHash as createHash7 } from "crypto";
|
|
14428
16482
|
import { existsSync as existsSync18, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync18, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
|
|
14429
16483
|
import { tmpdir as tmpdir3 } from "os";
|
|
14430
16484
|
import { join as join19 } from "path";
|
|
@@ -14469,7 +16523,7 @@ var init_policy_cache = __esm({
|
|
|
14469
16523
|
return `${sessionId}::${promptSession}`;
|
|
14470
16524
|
}
|
|
14471
16525
|
cacheFilePath(sessionId, promptSession) {
|
|
14472
|
-
const promptHash =
|
|
16526
|
+
const promptHash = createHash7("md5").update(promptSession).digest("hex").slice(0, 12);
|
|
14473
16527
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
14474
16528
|
return join19(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
|
|
14475
16529
|
}
|
|
@@ -15126,7 +17180,7 @@ var init_pattern_miner = __esm({
|
|
|
15126
17180
|
// src/agent-gate-reader.ts
|
|
15127
17181
|
import * as fs8 from "fs";
|
|
15128
17182
|
import * as os5 from "os";
|
|
15129
|
-
import * as
|
|
17183
|
+
import * as path9 from "path";
|
|
15130
17184
|
function normalizeAction(row) {
|
|
15131
17185
|
const act = {
|
|
15132
17186
|
actionType: String(row.action_type || row.tool_name || row.name || ""),
|
|
@@ -15151,7 +17205,7 @@ function readJsonDir(dirPath, limit = 1e5, strict = false) {
|
|
|
15151
17205
|
const files = fs8.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
|
|
15152
17206
|
for (const f of files.slice(-200)) {
|
|
15153
17207
|
const sid = f.replace(/\.json$/, "");
|
|
15154
|
-
const raw = fs8.readFileSync(
|
|
17208
|
+
const raw = fs8.readFileSync(path9.join(dirPath, f), "utf-8");
|
|
15155
17209
|
const arr = JSON.parse(raw);
|
|
15156
17210
|
if (!Array.isArray(arr)) continue;
|
|
15157
17211
|
for (const item of arr) {
|
|
@@ -15225,7 +17279,7 @@ function loadAgentGateSessions(dbPath = "") {
|
|
|
15225
17279
|
}
|
|
15226
17280
|
const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
|
|
15227
17281
|
if (sql.length > 0) return sql;
|
|
15228
|
-
const jsonDefault =
|
|
17282
|
+
const jsonDefault = path9.join(os5.homedir(), ".local", "share", "agent_gate", "tool_calls");
|
|
15229
17283
|
return readJsonDir(jsonDefault);
|
|
15230
17284
|
}
|
|
15231
17285
|
var DEFAULT_AGENTGATE_SQLITE;
|
|
@@ -15234,7 +17288,7 @@ var init_agent_gate_reader = __esm({
|
|
|
15234
17288
|
"use strict";
|
|
15235
17289
|
init_esm_shims();
|
|
15236
17290
|
init_esm_require();
|
|
15237
|
-
DEFAULT_AGENTGATE_SQLITE =
|
|
17291
|
+
DEFAULT_AGENTGATE_SQLITE = path9.join(
|
|
15238
17292
|
os5.homedir(),
|
|
15239
17293
|
".local",
|
|
15240
17294
|
"share",
|
|
@@ -16580,7 +18634,7 @@ function createApp() {
|
|
|
16580
18634
|
startLoopMonitor();
|
|
16581
18635
|
const limiter = new RateLimiter(rateLimitQps());
|
|
16582
18636
|
app.use("*", async (c, next) => {
|
|
16583
|
-
const
|
|
18637
|
+
const path10 = new URL(c.req.url).pathname;
|
|
16584
18638
|
const method = c.req.method.toUpperCase();
|
|
16585
18639
|
if (method === "OPTIONS") return next();
|
|
16586
18640
|
const maxBody = maxBodyBytes();
|
|
@@ -16594,18 +18648,18 @@ function createApp() {
|
|
|
16594
18648
|
if (originCheckEnabled()) {
|
|
16595
18649
|
const origin = c.req.header("origin") || "";
|
|
16596
18650
|
if (origin && !originAllowed(origin, c.req.header("host") || "")) {
|
|
16597
|
-
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${
|
|
18651
|
+
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path10}`);
|
|
16598
18652
|
return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
|
|
16599
18653
|
}
|
|
16600
18654
|
}
|
|
16601
|
-
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers,
|
|
16602
|
-
const isPublicPage = !
|
|
18655
|
+
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path10);
|
|
18656
|
+
const isPublicPage = !path10.startsWith("/console/api") && (path10 === "/console" || path10.startsWith("/console/"));
|
|
16603
18657
|
if (!okAuth && !isPublicPage) {
|
|
16604
18658
|
return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
|
|
16605
18659
|
}
|
|
16606
18660
|
let gateCallId = null;
|
|
16607
18661
|
const gateRequired = c.req.header(GATE_IDENTITY_HEADER);
|
|
16608
|
-
const gatePath =
|
|
18662
|
+
const gatePath = path10.replace(/\/+$/, "");
|
|
16609
18663
|
if (method === "POST" && gateRequired !== void 0 && (gatePath === "/api/v1/analyze" || gatePath === "/api/v1/review")) {
|
|
16610
18664
|
if (principal !== GATE_PRINCIPAL) {
|
|
16611
18665
|
return c.json({ detail: "AgentGate \u4E13\u7528\u8EAB\u4EFD\u6821\u9A8C\u5931\u8D25" }, 403);
|
|
@@ -16622,7 +18676,7 @@ function createApp() {
|
|
|
16622
18676
|
gateCallId = id;
|
|
16623
18677
|
c.set("gateCallId", id);
|
|
16624
18678
|
}
|
|
16625
|
-
if (limiter.enabled &&
|
|
18679
|
+
if (limiter.enabled && path10.startsWith("/api/")) {
|
|
16626
18680
|
const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
|
|
16627
18681
|
if (!limiter.allow(key)) {
|
|
16628
18682
|
if (gateCallId) c.header(GATE_RATE_LIMIT_HEADER, gateCallId);
|
|
@@ -16658,7 +18712,7 @@ function createApp() {
|
|
|
16658
18712
|
return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
|
|
16659
18713
|
}
|
|
16660
18714
|
}
|
|
16661
|
-
const pool = poolOf(
|
|
18715
|
+
const pool = poolOf(path10);
|
|
16662
18716
|
if (!take(`pool:${pool}`, poolLimit(pool))) {
|
|
16663
18717
|
const qkey = principal ? "p:" + principalHash(principal) : "c:local";
|
|
16664
18718
|
const [qn, abusive] = noteQueueReject(qkey);
|
|
@@ -16752,8 +18806,8 @@ async function warmUpEngine() {
|
|
|
16752
18806
|
}
|
|
16753
18807
|
function writePortFile(port) {
|
|
16754
18808
|
try {
|
|
16755
|
-
const
|
|
16756
|
-
mkdirSync11(dirname16(
|
|
18809
|
+
const path10 = getPortFilePath();
|
|
18810
|
+
mkdirSync11(dirname16(path10), { recursive: true });
|
|
16757
18811
|
const payload = JSON.stringify({
|
|
16758
18812
|
port,
|
|
16759
18813
|
pid: process.pid,
|
|
@@ -16762,10 +18816,10 @@ function writePortFile(port) {
|
|
|
16762
18816
|
version,
|
|
16763
18817
|
started_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
16764
18818
|
});
|
|
16765
|
-
const tmp = `${
|
|
18819
|
+
const tmp = `${path10}.tmp`;
|
|
16766
18820
|
writeFileSync8(tmp, payload, "utf-8");
|
|
16767
|
-
renameSync3(tmp,
|
|
16768
|
-
console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${
|
|
18821
|
+
renameSync3(tmp, path10);
|
|
18822
|
+
console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path10} (port=${port})`);
|
|
16769
18823
|
} catch (err) {
|
|
16770
18824
|
console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
|
|
16771
18825
|
}
|
|
@@ -17093,7 +19147,7 @@ init_esm_shims();
|
|
|
17093
19147
|
init_server();
|
|
17094
19148
|
init_package_json();
|
|
17095
19149
|
import { fileURLToPath as fileURLToPath14 } from "url";
|
|
17096
|
-
import { realpathSync as
|
|
19150
|
+
import { realpathSync as realpathSync3 } from "fs";
|
|
17097
19151
|
function printHelp() {
|
|
17098
19152
|
console.log(`AgentMoss security analysis engine (TypeScript v${version})
|
|
17099
19153
|
|
|
@@ -17198,7 +19252,7 @@ async function main() {
|
|
|
17198
19252
|
process.exit(1);
|
|
17199
19253
|
}
|
|
17200
19254
|
const fs9 = await import("fs");
|
|
17201
|
-
const
|
|
19255
|
+
const path10 = await import("path");
|
|
17202
19256
|
const useJson = args.includes("--json");
|
|
17203
19257
|
const osType = process.platform === "win32" ? "windows" : "linux";
|
|
17204
19258
|
const isFile = fs9.existsSync(target) && fs9.statSync(target).isFile();
|
|
@@ -17217,7 +19271,7 @@ async function main() {
|
|
|
17217
19271
|
}
|
|
17218
19272
|
process.exit(await analyzeRawCommand(target, useJson));
|
|
17219
19273
|
}
|
|
17220
|
-
const filePath =
|
|
19274
|
+
const filePath = path10.resolve(target);
|
|
17221
19275
|
const data = JSON.parse(fs9.readFileSync(filePath, "utf-8"));
|
|
17222
19276
|
const { analyze: analyze2 } = await Promise.resolve().then(() => (init_analyzer(), analyzer_exports));
|
|
17223
19277
|
const sessionId = String(data.session_id || "unknown");
|
|
@@ -17229,11 +19283,11 @@ async function main() {
|
|
|
17229
19283
|
fs9.mkdirSync(outDir, { recursive: true });
|
|
17230
19284
|
const safeSession = sessionId.replace(/\//g, "_");
|
|
17231
19285
|
if (result.decision === "Allow") {
|
|
17232
|
-
const policyPath =
|
|
19286
|
+
const policyPath = path10.join(outDir, `${safeSession}_policy.toml`);
|
|
17233
19287
|
fs9.writeFileSync(policyPath, result.policy || "", "utf-8");
|
|
17234
19288
|
console.log(`Policy written to ${policyPath}`);
|
|
17235
19289
|
} else {
|
|
17236
|
-
const denyPath =
|
|
19290
|
+
const denyPath = path10.join(outDir, `${safeSession}_deny_reason.txt`);
|
|
17237
19291
|
fs9.writeFileSync(denyPath, result.violated_policy || result.reason || "", "utf-8");
|
|
17238
19292
|
console.log(`Deny reason written to ${denyPath}`);
|
|
17239
19293
|
}
|
|
@@ -17324,7 +19378,7 @@ async function main() {
|
|
|
17324
19378
|
const enable = args.includes("--enable");
|
|
17325
19379
|
const { execSync } = await import("child_process");
|
|
17326
19380
|
const fs9 = await import("fs");
|
|
17327
|
-
const
|
|
19381
|
+
const path10 = await import("path");
|
|
17328
19382
|
const { fileURLToPath: fileURLToPath15 } = await import("url");
|
|
17329
19383
|
if (process.getuid?.() !== 0) {
|
|
17330
19384
|
try {
|
|
@@ -17341,17 +19395,17 @@ async function main() {
|
|
|
17341
19395
|
process.exit(0);
|
|
17342
19396
|
}
|
|
17343
19397
|
const __filename7 = fileURLToPath15(import.meta.url);
|
|
17344
|
-
const __dirname12 =
|
|
17345
|
-
let srcPath =
|
|
19398
|
+
const __dirname12 = path10.dirname(__filename7);
|
|
19399
|
+
let srcPath = path10.join(__dirname12, "data", "agent_moss.service");
|
|
17346
19400
|
if (!fs9.existsSync(srcPath)) {
|
|
17347
|
-
srcPath =
|
|
19401
|
+
srcPath = path10.join(__dirname12, "..", "src", "data", "agent_moss.service");
|
|
17348
19402
|
}
|
|
17349
19403
|
if (!fs9.existsSync(srcPath)) {
|
|
17350
19404
|
console.error("\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230 agent_moss.service \u6A21\u677F\u6587\u4EF6");
|
|
17351
19405
|
process.exit(1);
|
|
17352
19406
|
}
|
|
17353
19407
|
const which = execSync("which agent-moss 2>/dev/null || true", { encoding: "utf-8" }).trim();
|
|
17354
|
-
const binPath = which || `${process.execPath} ${
|
|
19408
|
+
const binPath = which || `${process.execPath} ${path10.join(__dirname12, "cli.js")}`;
|
|
17355
19409
|
let content = fs9.readFileSync(srcPath, "utf-8");
|
|
17356
19410
|
content = content.replace("__AGENT_MOSS_BIN__", binPath);
|
|
17357
19411
|
const dst = "/etc/systemd/system/agent-moss.service";
|
|
@@ -17514,8 +19568,8 @@ async function main() {
|
|
|
17514
19568
|
var isMain = (() => {
|
|
17515
19569
|
try {
|
|
17516
19570
|
if (!process.argv[1]) return false;
|
|
17517
|
-
const thisFile =
|
|
17518
|
-
const argv1 =
|
|
19571
|
+
const thisFile = realpathSync3(fileURLToPath14(import.meta.url));
|
|
19572
|
+
const argv1 = realpathSync3(
|
|
17519
19573
|
process.argv[1].startsWith("file://") ? fileURLToPath14(process.argv[1]) : process.argv[1]
|
|
17520
19574
|
);
|
|
17521
19575
|
return thisFile === argv1;
|