@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/server.js
CHANGED
|
@@ -408,22 +408,22 @@ function loadToolRegistry() {
|
|
|
408
408
|
data.tools = tools;
|
|
409
409
|
return data;
|
|
410
410
|
}
|
|
411
|
-
function scanStructEntry(cat, value,
|
|
411
|
+
function scanStructEntry(cat, value, path10) {
|
|
412
412
|
if (cat === "skills") {
|
|
413
413
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
414
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
414
|
+
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`);
|
|
415
415
|
return null;
|
|
416
416
|
}
|
|
417
417
|
const out = {};
|
|
418
418
|
for (const [skCat, skills] of Object.entries(value)) {
|
|
419
419
|
if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
|
|
420
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
420
|
+
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`);
|
|
421
421
|
continue;
|
|
422
422
|
}
|
|
423
423
|
const keep = {};
|
|
424
424
|
for (const [name, kws] of Object.entries(skills)) {
|
|
425
425
|
if (Array.isArray(kws)) keep[name] = kws;
|
|
426
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
426
|
+
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`);
|
|
427
427
|
}
|
|
428
428
|
if (Object.keys(keep).length > 0) out[skCat] = keep;
|
|
429
429
|
}
|
|
@@ -431,37 +431,37 @@ function scanStructEntry(cat, value, path9) {
|
|
|
431
431
|
}
|
|
432
432
|
if (cat === "ltl_rules") {
|
|
433
433
|
if (!Array.isArray(value)) {
|
|
434
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
434
|
+
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u7684 ltl_rules \u5E94\u4E3A\u5BF9\u8C61\u6570\u7EC4 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u3002`);
|
|
435
435
|
return null;
|
|
436
436
|
}
|
|
437
437
|
const keep = value.filter((r) => r && typeof r === "object" && r.id);
|
|
438
438
|
if (keep.length !== value.length) {
|
|
439
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
439
|
+
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`);
|
|
440
440
|
}
|
|
441
441
|
return keep.length > 0 ? keep : null;
|
|
442
442
|
}
|
|
443
443
|
if (cat === "tools") {
|
|
444
444
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
445
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
445
|
+
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`);
|
|
446
446
|
return null;
|
|
447
447
|
}
|
|
448
448
|
const keep = {};
|
|
449
449
|
for (const [k, v] of Object.entries(value)) {
|
|
450
450
|
if (v && typeof v === "object" && !Array.isArray(v)) keep[k] = v;
|
|
451
|
-
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
451
|
+
else console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${path10} \u7684 tools.${k} \u4E0D\u662F\u5BF9\u8C61 \u2014\u2014 \u5DF2\u8DF3\u8FC7\u8BE5\u6761\u3002`);
|
|
452
452
|
}
|
|
453
453
|
return Object.keys(keep).length > 0 ? keep : null;
|
|
454
454
|
}
|
|
455
455
|
return null;
|
|
456
456
|
}
|
|
457
|
-
function scanRulesFile(
|
|
457
|
+
function scanRulesFile(path10, kind) {
|
|
458
458
|
const out = {};
|
|
459
459
|
const label = kind === "override" ? "\u8986\u76D6" : "\u8FFD\u52A0";
|
|
460
460
|
let parsed;
|
|
461
461
|
try {
|
|
462
|
-
parsed = JSON.parse(readFileSync2(
|
|
462
|
+
parsed = JSON.parse(readFileSync2(path10, "utf-8"));
|
|
463
463
|
} catch (e) {
|
|
464
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
464
|
+
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}`);
|
|
465
465
|
return out;
|
|
466
466
|
}
|
|
467
467
|
const classifyFlat = (r) => {
|
|
@@ -485,44 +485,44 @@ function scanRulesFile(path9, kind) {
|
|
|
485
485
|
}
|
|
486
486
|
if (flatBad > 0) {
|
|
487
487
|
console.warn(
|
|
488
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
488
|
+
`[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`
|
|
489
489
|
);
|
|
490
490
|
}
|
|
491
491
|
} else {
|
|
492
|
-
console.error(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
492
|
+
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`);
|
|
493
493
|
return out;
|
|
494
494
|
}
|
|
495
495
|
for (const [cat, rules] of pairs) {
|
|
496
496
|
if (String(cat).startsWith("_")) continue;
|
|
497
497
|
if (STRUCT_KEYS.includes(cat)) {
|
|
498
|
-
const got = scanStructEntry(cat, rules,
|
|
498
|
+
const got = scanStructEntry(cat, rules, path10);
|
|
499
499
|
if (got !== null) out[cat] = got;
|
|
500
500
|
continue;
|
|
501
501
|
}
|
|
502
502
|
const required = EXTRA_CATEGORIES[cat];
|
|
503
503
|
if (!required) {
|
|
504
504
|
console.warn(
|
|
505
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
505
|
+
`[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`
|
|
506
506
|
);
|
|
507
507
|
continue;
|
|
508
508
|
}
|
|
509
509
|
if (rules && typeof rules === "object" && !Array.isArray(rules)) {
|
|
510
510
|
console.error(
|
|
511
|
-
`[AgentMoss] \u274C \u89C4\u5219\u6587\u4EF6 ${
|
|
511
|
+
`[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
|
|
512
512
|
\u6B63\u786E\u5199\u6CD5: {"${cat}": [{"pattern": "...", "risk_level": "high", ...}]}
|
|
513
513
|
\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`
|
|
514
514
|
);
|
|
515
515
|
continue;
|
|
516
516
|
}
|
|
517
517
|
if (!Array.isArray(rules)) {
|
|
518
|
-
console.warn(`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
518
|
+
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`);
|
|
519
519
|
continue;
|
|
520
520
|
}
|
|
521
521
|
const items = [];
|
|
522
522
|
for (const r of rules) {
|
|
523
523
|
if (!r || typeof r !== "object" || !required.every((k) => r[k])) {
|
|
524
524
|
console.warn(
|
|
525
|
-
`[AgentMoss] \u89C4\u5219\u6587\u4EF6 ${
|
|
525
|
+
`[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`
|
|
526
526
|
);
|
|
527
527
|
continue;
|
|
528
528
|
}
|
|
@@ -532,7 +532,7 @@ function scanRulesFile(path9, kind) {
|
|
|
532
532
|
}
|
|
533
533
|
if (Object.keys(out).length > 0) {
|
|
534
534
|
console.info(
|
|
535
|
-
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${
|
|
535
|
+
`[AgentMoss] \u5DF2\u52A0\u8F7D${label}\u89C4\u5219\u6587\u4EF6 ${path10}\uFF1A` + Object.entries(out).map(([k, v]) => `${k}\xD7${v.length}`).join(", ")
|
|
536
536
|
);
|
|
537
537
|
}
|
|
538
538
|
return out;
|
|
@@ -808,46 +808,46 @@ function readExplicitTokenResult() {
|
|
|
808
808
|
if (tok) return [tok, ""];
|
|
809
809
|
const fdTok = readFdToken();
|
|
810
810
|
if (fdTok) return [fdTok, ""];
|
|
811
|
-
const
|
|
812
|
-
if (
|
|
811
|
+
const path10 = env("AGENT_MOSS_AUTH_TOKEN_FILE");
|
|
812
|
+
if (path10) {
|
|
813
813
|
try {
|
|
814
|
-
const fileTok = readFileSync4(
|
|
814
|
+
const fileTok = readFileSync4(path10, "utf-8").trim();
|
|
815
815
|
if (!fileTok) {
|
|
816
|
-
return ["", `AGENT_MOSS_AUTH_TOKEN_FILE \u6307\u5411\u7684\u6587\u4EF6\u4E3A\u7A7A: ${
|
|
816
|
+
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`];
|
|
817
817
|
}
|
|
818
818
|
return [fileTok, ""];
|
|
819
819
|
} catch (e) {
|
|
820
|
-
return ["", `AGENT_MOSS_AUTH_TOKEN_FILE \u5DF2\u8BBE\u7F6E\u4F46\u65E0\u6CD5\u8BFB\u53D6 ${
|
|
820
|
+
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`];
|
|
821
821
|
}
|
|
822
822
|
}
|
|
823
823
|
return ["", ""];
|
|
824
824
|
}
|
|
825
825
|
function ensureAutoToken() {
|
|
826
|
-
const
|
|
826
|
+
const path10 = autoTokenPath();
|
|
827
827
|
try {
|
|
828
|
-
if (existsSync3(
|
|
829
|
-
const tok2 = readFileSync4(
|
|
828
|
+
if (existsSync3(path10) && !lstatSync(path10).isSymbolicLink()) {
|
|
829
|
+
const tok2 = readFileSync4(path10, "utf-8").trim();
|
|
830
830
|
if (tok2) {
|
|
831
831
|
try {
|
|
832
|
-
chmodSync(
|
|
832
|
+
chmodSync(path10, 384);
|
|
833
833
|
} catch {
|
|
834
834
|
}
|
|
835
835
|
return tok2;
|
|
836
836
|
}
|
|
837
837
|
}
|
|
838
838
|
const tok = randomBytes(32).toString("base64url");
|
|
839
|
-
if (!ensurePrivateDir(dirname2(
|
|
840
|
-
throw new Error(`\u65E0\u6CD5\u521B\u5EFA/\u6536\u7D27 token \u76EE\u5F55\uFF08\u6743\u9650\u6216\u5C5E\u4E3B\u5F02\u5E38\uFF09: ${dirname2(
|
|
839
|
+
if (!ensurePrivateDir(dirname2(path10))) {
|
|
840
|
+
throw new Error(`\u65E0\u6CD5\u521B\u5EFA/\u6536\u7D27 token \u76EE\u5F55\uFF08\u6743\u9650\u6216\u5C5E\u4E3B\u5F02\u5E38\uFF09: ${dirname2(path10)}`);
|
|
841
841
|
}
|
|
842
|
-
if (!writePrivateText(
|
|
843
|
-
throw new Error(`\u5199\u5165\u81EA\u52A8 token \u5931\u8D25: ${
|
|
842
|
+
if (!writePrivateText(path10, tok + "\n")) {
|
|
843
|
+
throw new Error(`\u5199\u5165\u81EA\u52A8 token \u5931\u8D25: ${path10}`);
|
|
844
844
|
}
|
|
845
845
|
console.warn(
|
|
846
|
-
`[AgentMoss] \u5DF2\u751F\u6210\u8BBF\u95EE token \u5E76\u5199\u5165 ${
|
|
846
|
+
`[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`
|
|
847
847
|
);
|
|
848
848
|
return tok;
|
|
849
849
|
} catch (e) {
|
|
850
|
-
throw new Error(`\u81EA\u52A8\u8BBF\u95EE token \u751F\u6210/\u8BFB\u53D6\u5931\u8D25\uFF08${
|
|
850
|
+
throw new Error(`\u81EA\u52A8\u8BBF\u95EE token \u751F\u6210/\u8BFB\u53D6\u5931\u8D25\uFF08${path10}\uFF09\uFF1A${e?.message ?? e}`);
|
|
851
851
|
}
|
|
852
852
|
}
|
|
853
853
|
function parseAgentTokens(raw) {
|
|
@@ -936,9 +936,9 @@ function constEq(a, b) {
|
|
|
936
936
|
if (ba.length !== bb.length) return false;
|
|
937
937
|
return timingSafeEqual(ba, bb);
|
|
938
938
|
}
|
|
939
|
-
function checkRequestAuth(headers,
|
|
939
|
+
function checkRequestAuth(headers, path10) {
|
|
940
940
|
if (authMode() === AUTH_MODE_OFF) return [true, ""];
|
|
941
|
-
const normalizedPath =
|
|
941
|
+
const normalizedPath = path10.replace(/\/+$/, "");
|
|
942
942
|
const isHealth = HEALTH_PATHS.includes(normalizedPath);
|
|
943
943
|
const [gt0, agents, err] = resolveAuth();
|
|
944
944
|
const gateToken = env("AGENT_MOSS_GATE_AUTH_TOKEN");
|
|
@@ -969,8 +969,8 @@ function bindAgent(principal, agentId) {
|
|
|
969
969
|
if (!agentId) return [true, bound];
|
|
970
970
|
return [bound === agentId, bound];
|
|
971
971
|
}
|
|
972
|
-
function principalOf(headers,
|
|
973
|
-
const [ok, principal] = checkRequestAuth(headers,
|
|
972
|
+
function principalOf(headers, path10 = "") {
|
|
973
|
+
const [ok, principal] = checkRequestAuth(headers, path10);
|
|
974
974
|
return ok ? principal : "";
|
|
975
975
|
}
|
|
976
976
|
function principalHash(principal) {
|
|
@@ -1257,11 +1257,11 @@ function errorDetailMode() {
|
|
|
1257
1257
|
function maxBodyBytes() {
|
|
1258
1258
|
return envInt("AGENT_MOSS_MAX_BODY_BYTES", 16 * 1024 * 1024);
|
|
1259
1259
|
}
|
|
1260
|
-
function poolOf(
|
|
1261
|
-
if (
|
|
1262
|
-
if (
|
|
1263
|
-
if (
|
|
1264
|
-
if (
|
|
1260
|
+
function poolOf(path10) {
|
|
1261
|
+
if (path10 === "/api/v1/analyze" || path10.startsWith("/api/v1/analyze/")) return "biz";
|
|
1262
|
+
if (path10 === "/api/v1/review" || path10.startsWith("/api/v1/review/")) return "review";
|
|
1263
|
+
if (path10 === "/console" || path10.startsWith("/console/") || path10.startsWith("/api/v1/brain")) return "ops";
|
|
1264
|
+
if (path10 === "/api/v1/health") return "health";
|
|
1265
1265
|
return "other";
|
|
1266
1266
|
}
|
|
1267
1267
|
function poolLimit(name) {
|
|
@@ -1523,7 +1523,7 @@ function splitPythonStatements(code) {
|
|
|
1523
1523
|
parts.push(current);
|
|
1524
1524
|
return parts.map((s) => s.trim()).filter((s) => s.length > 0);
|
|
1525
1525
|
}
|
|
1526
|
-
function isSimpleOpenCall(expr,
|
|
1526
|
+
function isSimpleOpenCall(expr, path10, binding) {
|
|
1527
1527
|
const m = expr.match(/^open\s*\(([\s\S]*)\)$/);
|
|
1528
1528
|
if (!m || hasTopLevelChar(m[1], "=")) return false;
|
|
1529
1529
|
const args = splitPythonArgs(m[1]);
|
|
@@ -1533,12 +1533,12 @@ function isSimpleOpenCall(expr, path9, binding) {
|
|
|
1533
1533
|
}
|
|
1534
1534
|
const target = args[0].trim();
|
|
1535
1535
|
const literal = pythonStringLiteral(target);
|
|
1536
|
-
if (literal !== null) return literal ===
|
|
1536
|
+
if (literal !== null) return literal === path10;
|
|
1537
1537
|
return !!binding && target === binding;
|
|
1538
1538
|
}
|
|
1539
|
-
function confirmsInlineRead(command,
|
|
1540
|
-
if (command.length > 8192 || !
|
|
1541
|
-
if (
|
|
1539
|
+
function confirmsInlineRead(command, path10) {
|
|
1540
|
+
if (command.length > 8192 || !path10 || path10.startsWith("~")) return false;
|
|
1541
|
+
if (path10.includes("/") && !path10.startsWith("/")) return false;
|
|
1542
1542
|
const wrapper = command.trim().match(/^python3?[ \t]+-c[ \t]+([\s\S]+)$/);
|
|
1543
1543
|
if (!wrapper) return false;
|
|
1544
1544
|
const code = literalShellWord(wrapper[1]);
|
|
@@ -1557,13 +1557,13 @@ function confirmsInlineRead(command, path9) {
|
|
|
1557
1557
|
const child = pythonStringLiteral(args[0]);
|
|
1558
1558
|
if (child === null) return false;
|
|
1559
1559
|
const cat = child.trim().match(/^cat[ \t]+([\s\S]+)$/);
|
|
1560
|
-
return !!cat && !
|
|
1560
|
+
return !!cat && !path10.startsWith("-") && literalShellWord(cat[1].trim()) === path10;
|
|
1561
1561
|
}
|
|
1562
1562
|
const assign = first.match(/^([A-Za-z_]\w*)\s*=\s*([\s\S]+)$/);
|
|
1563
1563
|
if (!assign) return false;
|
|
1564
1564
|
const name = assign[1];
|
|
1565
1565
|
const value = pythonStringLiteral(assign[2]);
|
|
1566
|
-
if (value !==
|
|
1566
|
+
if (value !== path10 || ["open", "print", "__debug__"].includes(name)) return false;
|
|
1567
1567
|
binding = name;
|
|
1568
1568
|
expr = statements[1];
|
|
1569
1569
|
} else {
|
|
@@ -1578,7 +1578,7 @@ function confirmsInlineRead(command, path9) {
|
|
|
1578
1578
|
}
|
|
1579
1579
|
const readCall = expr.match(/^([\s\S]+)\.read\s*\(\s*\)$/);
|
|
1580
1580
|
if (readCall) expr = readCall[1];
|
|
1581
|
-
return isSimpleOpenCall(expr,
|
|
1581
|
+
return isSimpleOpenCall(expr, path10, binding);
|
|
1582
1582
|
}
|
|
1583
1583
|
function analyzeInlineScript(command) {
|
|
1584
1584
|
const code = extractInlineCode(command);
|
|
@@ -1733,7 +1733,7 @@ function _loadSensitivePathScope(scope, osType = "linux") {
|
|
|
1733
1733
|
os: String(sp.os || "linux").toLowerCase()
|
|
1734
1734
|
}));
|
|
1735
1735
|
}
|
|
1736
|
-
function _scopeOf(os6,
|
|
1736
|
+
function _scopeOf(os6, path10) {
|
|
1737
1737
|
if (!_scopeIndex) {
|
|
1738
1738
|
_scopeIndex = /* @__PURE__ */ new Map();
|
|
1739
1739
|
for (const sp of loadL1().sensitive_path_access || []) {
|
|
@@ -1741,7 +1741,7 @@ function _scopeOf(os6, path9) {
|
|
|
1741
1741
|
if (!_scopeIndex.has(key)) _scopeIndex.set(key, sp.scope);
|
|
1742
1742
|
}
|
|
1743
1743
|
}
|
|
1744
|
-
return _scopeIndex.get(`${String(os6 || "linux").toLowerCase()}|${
|
|
1744
|
+
return _scopeIndex.get(`${String(os6 || "linux").toLowerCase()}|${path10}`) || "root";
|
|
1745
1745
|
}
|
|
1746
1746
|
function getSensitivePathsForOs(osType) {
|
|
1747
1747
|
const effective = runtimeConfigBridge.current?.effectiveSensitivePaths(osType);
|
|
@@ -2559,36 +2559,36 @@ function checkReadBeforeWrite(actionType, actionDetailRaw, actionHistory, reason
|
|
|
2559
2559
|
}
|
|
2560
2560
|
const preciseEdit = isPreciseEditTool(actionType);
|
|
2561
2561
|
const unreadPaths = [];
|
|
2562
|
-
for (const
|
|
2563
|
-
if (isDirectoryTarget(
|
|
2562
|
+
for (const path10 of checkTargets) {
|
|
2563
|
+
if (isDirectoryTarget(path10)) continue;
|
|
2564
2564
|
let isFullRead = [...normalizedFullReads].some(
|
|
2565
|
-
(rp) => pathIsSameOrUnder(
|
|
2565
|
+
(rp) => pathIsSameOrUnder(path10, rp) || pathIsSameOrUnder(rp, path10)
|
|
2566
2566
|
);
|
|
2567
2567
|
if (!isFullRead && preciseEdit && [...normalizedWrittenPaths].some(
|
|
2568
|
-
(wp) => pathIsSameOrUnder(
|
|
2568
|
+
(wp) => pathIsSameOrUnder(path10, wp) || pathIsSameOrUnder(wp, path10)
|
|
2569
2569
|
)) {
|
|
2570
2570
|
isFullRead = true;
|
|
2571
2571
|
}
|
|
2572
|
-
if (!isFullRead && !isProtectedWritePath(
|
|
2572
|
+
if (!isFullRead && !isProtectedWritePath(path10) && isScriptGeneratedTarget(path10, historyWrittenScripts, shellRunActions)) {
|
|
2573
2573
|
isFullRead = true;
|
|
2574
2574
|
}
|
|
2575
2575
|
let isPartialCovered = false;
|
|
2576
2576
|
if (!isFullRead) {
|
|
2577
2577
|
for (const [pp, upto] of normalizedPartialReads) {
|
|
2578
|
-
if (!(pathIsSameOrUnder(
|
|
2579
|
-
if (preciseEdit || upto != null && fileHasAtMostLines(
|
|
2578
|
+
if (!(pathIsSameOrUnder(path10, pp) || pathIsSameOrUnder(pp, path10))) continue;
|
|
2579
|
+
if (preciseEdit || upto != null && fileHasAtMostLines(path10, upto)) {
|
|
2580
2580
|
isPartialCovered = true;
|
|
2581
2581
|
break;
|
|
2582
2582
|
}
|
|
2583
2583
|
}
|
|
2584
2584
|
}
|
|
2585
2585
|
if (!isFullRead && !isPartialCovered) {
|
|
2586
|
-
let isCreate = !fs.existsSync(
|
|
2586
|
+
let isCreate = !fs.existsSync(path10);
|
|
2587
2587
|
if (!isCreate) {
|
|
2588
2588
|
isCreate = CREATE_KEYWORDS.some((kw) => reason.toLowerCase().includes(kw) || actionDetail.includes(kw));
|
|
2589
2589
|
}
|
|
2590
2590
|
if (!isCreate) {
|
|
2591
|
-
unreadPaths.push(
|
|
2591
|
+
unreadPaths.push(path10);
|
|
2592
2592
|
}
|
|
2593
2593
|
}
|
|
2594
2594
|
}
|
|
@@ -2782,16 +2782,16 @@ var init_logic_rules = __esm({
|
|
|
2782
2782
|
ALL_QUOTES_RE = /'[^']*'|"[^"]*"/g;
|
|
2783
2783
|
ROOT_SENSITIVE_PATHS = _loadSensitivePathScope("root");
|
|
2784
2784
|
HOME_SENSITIVE_PATHS = _loadSensitivePathScope("home");
|
|
2785
|
-
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path:
|
|
2785
|
+
CREDENTIAL_PATHS = _loadSensitivePathScope("credential").map(({ path: path10, riskLevel, desc, dirDelOnly }) => ({ path: path10, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2786
2786
|
ROOT_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("root", "windows");
|
|
2787
2787
|
HOME_SENSITIVE_PATHS_WINDOWS = _loadSensitivePathScope("home", "windows");
|
|
2788
|
-
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path:
|
|
2788
|
+
CREDENTIAL_PATHS_WINDOWS = _loadSensitivePathScope("credential", "windows").map(({ path: path10, riskLevel, desc, dirDelOnly }) => ({ path: path10, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2789
2789
|
ROOT_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("root", "macos");
|
|
2790
2790
|
HOME_SENSITIVE_PATHS_MACOS = _loadSensitivePathScope("home", "macos");
|
|
2791
|
-
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path:
|
|
2791
|
+
CREDENTIAL_PATHS_MACOS = _loadSensitivePathScope("credential", "macos").map(({ path: path10, riskLevel, desc, dirDelOnly }) => ({ path: path10, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2792
2792
|
ROOT_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("root", "harmony");
|
|
2793
2793
|
HOME_SENSITIVE_PATHS_HARMONY = _loadSensitivePathScope("home", "harmony");
|
|
2794
|
-
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path:
|
|
2794
|
+
CREDENTIAL_PATHS_HARMONY = _loadSensitivePathScope("credential", "harmony").map(({ path: path10, riskLevel, desc, dirDelOnly }) => ({ path: path10, riskLevel, desc, credential: true, dirDelOnly }));
|
|
2795
2795
|
_scopeIndex = null;
|
|
2796
2796
|
NON_WRITE_TOOLS = /* @__PURE__ */ new Set([
|
|
2797
2797
|
"ask_user_question",
|
|
@@ -5159,24 +5159,24 @@ function extractWritePayload(actionType, actionDetailRaw) {
|
|
|
5159
5159
|
const detail = actionDetailRaw || "";
|
|
5160
5160
|
const m = detail.match(WRITE_PREFIX_RE);
|
|
5161
5161
|
if (m) {
|
|
5162
|
-
const
|
|
5162
|
+
const path10 = m[1];
|
|
5163
5163
|
let content = m[2] || "";
|
|
5164
|
-
if (!
|
|
5164
|
+
if (!path10 || path10 === "?" || path10 === "-" || !content.trim()) return null;
|
|
5165
5165
|
if ((actionType || "").toLowerCase().includes("editfile")) {
|
|
5166
5166
|
const nm = content.match(EDIT_NEW_RE);
|
|
5167
5167
|
if (nm) content = nm[1];
|
|
5168
5168
|
}
|
|
5169
|
-
return { path:
|
|
5169
|
+
return { path: path10, content };
|
|
5170
5170
|
}
|
|
5171
5171
|
const stripped = detail.trim();
|
|
5172
5172
|
if (stripped.startsWith("{")) {
|
|
5173
5173
|
try {
|
|
5174
5174
|
const obj = JSON.parse(stripped);
|
|
5175
5175
|
if (obj && typeof obj === "object") {
|
|
5176
|
-
const
|
|
5176
|
+
const path10 = obj.path || obj.file_path || obj.filePath;
|
|
5177
5177
|
const content = obj.content || obj.newString || obj.new_string;
|
|
5178
|
-
if (typeof
|
|
5179
|
-
return { path:
|
|
5178
|
+
if (typeof path10 === "string" && path10 !== "" && path10 !== "?" && path10 !== "-" && typeof content === "string" && content.trim()) {
|
|
5179
|
+
return { path: path10, content };
|
|
5180
5180
|
}
|
|
5181
5181
|
}
|
|
5182
5182
|
} catch {
|
|
@@ -5189,8 +5189,8 @@ function handlesWrittenContent(actionType, actionDetailRaw) {
|
|
|
5189
5189
|
if (extractWritePayload(actionType, actionDetailRaw) !== null) return true;
|
|
5190
5190
|
return /^(?:写入文件|编辑文件|应用补丁)\s*[::]/.test(actionDetailRaw || "");
|
|
5191
5191
|
}
|
|
5192
|
-
function detectLanguage(
|
|
5193
|
-
const ext =
|
|
5192
|
+
function detectLanguage(path10, content) {
|
|
5193
|
+
const ext = path10.slice(path10.lastIndexOf(".") >= 0 ? path10.lastIndexOf(".") : path10.length).toLowerCase();
|
|
5194
5194
|
if (SHELL_EXTS.has(ext)) return "shell";
|
|
5195
5195
|
if (PY_EXTS.has(ext)) return "python";
|
|
5196
5196
|
if (DATA_EXTS.has(ext)) return "data";
|
|
@@ -5204,8 +5204,8 @@ function detectLanguage(path9, content) {
|
|
|
5204
5204
|
}
|
|
5205
5205
|
return "other";
|
|
5206
5206
|
}
|
|
5207
|
-
function isInstructionTarget(
|
|
5208
|
-
const p = (
|
|
5207
|
+
function isInstructionTarget(path10) {
|
|
5208
|
+
const p = (path10 || "").replace(/\\/g, "/").toLowerCase();
|
|
5209
5209
|
if (!p) return false;
|
|
5210
5210
|
const base = p.split("/").pop() || "";
|
|
5211
5211
|
if (["agents.md", "claude.md", "system.md", "prompt.md", "instructions.md", ".cursorrules"].includes(base)) {
|
|
@@ -5363,8 +5363,8 @@ function extractDangerousSnippets(actionType, actionDetailRaw, literalStripper)
|
|
|
5363
5363
|
if (!handlesWrittenContent(actionType, actionDetailRaw)) return null;
|
|
5364
5364
|
const payload = extractWritePayload(actionType, actionDetailRaw);
|
|
5365
5365
|
if (!payload) return [];
|
|
5366
|
-
const { path:
|
|
5367
|
-
const language = detectLanguage(
|
|
5366
|
+
const { path: path10, content: rawContent } = payload;
|
|
5367
|
+
const language = detectLanguage(path10, rawContent);
|
|
5368
5368
|
if (language === "data") return [];
|
|
5369
5369
|
let content = rawContent.replace(/\\r\\n/g, "\n").replace(/\\n/g, "\n").replace(/\\t/g, " ").slice(0, MAX_CONTENT);
|
|
5370
5370
|
const started = Date.now();
|
|
@@ -6065,16 +6065,16 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6065
6065
|
if (String(osType || "").toLowerCase() === "windows") {
|
|
6066
6066
|
pathScanTexts.push(...pathScanTexts.map((t) => t.replace(/\//g, "\\")));
|
|
6067
6067
|
}
|
|
6068
|
-
const pathMatches = (text,
|
|
6069
|
-
const parts =
|
|
6068
|
+
const pathMatches = (text, path10) => {
|
|
6069
|
+
const parts = path10.split(/(\(\?!.*?\))/);
|
|
6070
6070
|
const escaped = parts.map((part) => {
|
|
6071
6071
|
if (part.startsWith("(?!")) return part;
|
|
6072
6072
|
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6073
6073
|
}).join("");
|
|
6074
|
-
const re =
|
|
6074
|
+
const re = path10.startsWith(".") || path10.startsWith("/") ? new RegExp(`(?:^|[\\s/\\\\'"])${escaped}\\b`, "i") : new RegExp(`\\b${escaped}\\b`, "i");
|
|
6075
6075
|
return re.test(text);
|
|
6076
6076
|
};
|
|
6077
|
-
const pathMatchesAny = (
|
|
6077
|
+
const pathMatchesAny = (path10) => pathScanTexts.some((t) => pathMatches(t, path10));
|
|
6078
6078
|
for (const sp of rootPaths) {
|
|
6079
6079
|
if (pathMatchesAny(sp.path.toLowerCase())) {
|
|
6080
6080
|
if (keygenGenerate) continue;
|
|
@@ -6222,8 +6222,8 @@ function checkSensitivePath(command, cwd, agentExt, osType) {
|
|
|
6222
6222
|
}
|
|
6223
6223
|
return null;
|
|
6224
6224
|
}
|
|
6225
|
-
function isHomeValue(
|
|
6226
|
-
let p =
|
|
6225
|
+
function isHomeValue(path10) {
|
|
6226
|
+
let p = path10.trim().toLowerCase();
|
|
6227
6227
|
if (p.startsWith("$(") && p.endsWith(")")) {
|
|
6228
6228
|
const inner = p.slice(2, -1).trim();
|
|
6229
6229
|
return HOME_TARGET_RE.test(" " + inner);
|
|
@@ -6291,15 +6291,15 @@ function checkHomeDeletion(actionType, actionDetail) {
|
|
|
6291
6291
|
nameRe.lastIndex = nm.index + nm[0].length;
|
|
6292
6292
|
}
|
|
6293
6293
|
}
|
|
6294
|
-
for (const [varName,
|
|
6295
|
-
if (!isHomeValue(
|
|
6294
|
+
for (const [varName, path10] of Object.entries(assigned)) {
|
|
6295
|
+
if (!isHomeValue(path10)) continue;
|
|
6296
6296
|
const varRefRe = new RegExp(`(?:${escapeRegExp(varName)}|\\$\\{${escapeRegExp(varName)}\\})`);
|
|
6297
6297
|
for (const seg of segs) {
|
|
6298
6298
|
if (!isDeleteCommand(seg)) continue;
|
|
6299
6299
|
if (varRefRe.test(seg)) {
|
|
6300
6300
|
return {
|
|
6301
6301
|
allowed: false,
|
|
6302
|
-
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${
|
|
6302
|
+
reason: `\u68C0\u6D4B\u5230\u901A\u8FC7\u53D8\u91CF ${varName}\uFF08=${path10}\uFF0C\u4E3B\u76EE\u5F55\uFF09\u6267\u884C\u5220\u9664`,
|
|
6303
6303
|
riskLevel: "high",
|
|
6304
6304
|
riskType: "script_execution",
|
|
6305
6305
|
confidence: 90,
|
|
@@ -6754,8 +6754,64 @@ var init_script_analyzer = __esm({
|
|
|
6754
6754
|
}
|
|
6755
6755
|
});
|
|
6756
6756
|
|
|
6757
|
+
// src/engine/script-engine/ir.ts
|
|
6758
|
+
import { createHash as createHash3 } from "crypto";
|
|
6759
|
+
function encodeUtf8SurrogatePass(content) {
|
|
6760
|
+
const bytes = [];
|
|
6761
|
+
for (let i = 0; i < content.length; i++) {
|
|
6762
|
+
let codePoint = content.charCodeAt(i);
|
|
6763
|
+
if (codePoint >= 55296 && codePoint <= 56319 && i + 1 < content.length) {
|
|
6764
|
+
const low = content.charCodeAt(i + 1);
|
|
6765
|
+
if (low >= 56320 && low <= 57343) {
|
|
6766
|
+
codePoint = 65536 + (codePoint - 55296 << 10) + (low - 56320);
|
|
6767
|
+
i += 1;
|
|
6768
|
+
}
|
|
6769
|
+
}
|
|
6770
|
+
if (codePoint < 128) {
|
|
6771
|
+
bytes.push(codePoint);
|
|
6772
|
+
} else if (codePoint < 2048) {
|
|
6773
|
+
bytes.push(192 | codePoint >> 6, 128 | codePoint & 63);
|
|
6774
|
+
} else if (codePoint < 65536) {
|
|
6775
|
+
bytes.push(
|
|
6776
|
+
224 | codePoint >> 12,
|
|
6777
|
+
128 | codePoint >> 6 & 63,
|
|
6778
|
+
128 | codePoint & 63
|
|
6779
|
+
);
|
|
6780
|
+
} else {
|
|
6781
|
+
bytes.push(
|
|
6782
|
+
240 | codePoint >> 18,
|
|
6783
|
+
128 | codePoint >> 12 & 63,
|
|
6784
|
+
128 | codePoint >> 6 & 63,
|
|
6785
|
+
128 | codePoint & 63
|
|
6786
|
+
);
|
|
6787
|
+
}
|
|
6788
|
+
}
|
|
6789
|
+
return Buffer.from(bytes);
|
|
6790
|
+
}
|
|
6791
|
+
function scanFingerprint(content) {
|
|
6792
|
+
const digest = createHash3("sha256");
|
|
6793
|
+
let length = 0;
|
|
6794
|
+
for (let start = 0; start < content.length; start += 4096) {
|
|
6795
|
+
const chunk = encodeUtf8SurrogatePass(content.slice(start, start + 4096));
|
|
6796
|
+
length += chunk.length;
|
|
6797
|
+
digest.update(chunk);
|
|
6798
|
+
}
|
|
6799
|
+
return { bytes: length, sha256: digest.digest("hex") };
|
|
6800
|
+
}
|
|
6801
|
+
var WORKING_DIRECTORY_UNKNOWN;
|
|
6802
|
+
var init_ir = __esm({
|
|
6803
|
+
"src/engine/script-engine/ir.ts"() {
|
|
6804
|
+
"use strict";
|
|
6805
|
+
init_esm_shims();
|
|
6806
|
+
WORKING_DIRECTORY_UNKNOWN = /* @__PURE__ */ Symbol.for(
|
|
6807
|
+
"agent-moss.script-engine.working-directory-unknown"
|
|
6808
|
+
);
|
|
6809
|
+
}
|
|
6810
|
+
});
|
|
6811
|
+
|
|
6757
6812
|
// src/engine/script-engine/backends/python-backend.ts
|
|
6758
6813
|
import { parser } from "@lezer/python";
|
|
6814
|
+
import * as path4 from "path";
|
|
6759
6815
|
function buildLineStarts(content) {
|
|
6760
6816
|
const starts = [0];
|
|
6761
6817
|
for (let i = 0; i < content.length; i++) {
|
|
@@ -6791,14 +6847,117 @@ function makeEnv(argv) {
|
|
|
6791
6847
|
function srcSlice(node) {
|
|
6792
6848
|
return SOURCE.slice(node.from, node.to);
|
|
6793
6849
|
}
|
|
6794
|
-
function
|
|
6795
|
-
|
|
6796
|
-
if (
|
|
6797
|
-
|
|
6798
|
-
|
|
6850
|
+
function decodePythonStringLiteral(raw) {
|
|
6851
|
+
const m = /^([rubfRUBF]*)(\"\"\"|'''|"|')/.exec(raw);
|
|
6852
|
+
if (m === null) return null;
|
|
6853
|
+
const prefix = m[1].toLowerCase();
|
|
6854
|
+
const quote = m[2];
|
|
6855
|
+
if (prefix.includes("b") && (prefix.includes("f") || prefix.includes("u"))) return null;
|
|
6856
|
+
if (prefix.includes("f")) return null;
|
|
6857
|
+
if (!raw.endsWith(quote) || raw.length < m[0].length + quote.length) return null;
|
|
6858
|
+
const inner = raw.slice(m[0].length, raw.length - quote.length);
|
|
6859
|
+
const isBytes = prefix.includes("b");
|
|
6860
|
+
if (prefix.includes("r")) {
|
|
6861
|
+
return { value: inner.replace(/\r\n/g, "\n"), bytes: isBytes };
|
|
6862
|
+
}
|
|
6863
|
+
const decoded = unescapePythonString(inner, isBytes);
|
|
6864
|
+
if (decoded === null) return null;
|
|
6865
|
+
return { value: decoded, bytes: isBytes };
|
|
6866
|
+
}
|
|
6867
|
+
function unescapePythonString(text, isBytes) {
|
|
6868
|
+
let out = "";
|
|
6869
|
+
for (let i = 0; i < text.length; i++) {
|
|
6870
|
+
const ch = text[i];
|
|
6871
|
+
if (ch !== "\\") {
|
|
6872
|
+
out += ch;
|
|
6873
|
+
continue;
|
|
6874
|
+
}
|
|
6875
|
+
const next = text[i + 1];
|
|
6876
|
+
if (next === void 0) return null;
|
|
6877
|
+
i += 1;
|
|
6878
|
+
switch (next) {
|
|
6879
|
+
case "\n":
|
|
6880
|
+
break;
|
|
6881
|
+
// line continuation
|
|
6882
|
+
case "\\":
|
|
6883
|
+
out += "\\";
|
|
6884
|
+
break;
|
|
6885
|
+
case "'":
|
|
6886
|
+
out += "'";
|
|
6887
|
+
break;
|
|
6888
|
+
case '"':
|
|
6889
|
+
out += '"';
|
|
6890
|
+
break;
|
|
6891
|
+
case "a":
|
|
6892
|
+
out += "\x07";
|
|
6893
|
+
break;
|
|
6894
|
+
case "b":
|
|
6895
|
+
out += "\b";
|
|
6896
|
+
break;
|
|
6897
|
+
case "f":
|
|
6898
|
+
out += "\f";
|
|
6899
|
+
break;
|
|
6900
|
+
case "n":
|
|
6901
|
+
out += "\n";
|
|
6902
|
+
break;
|
|
6903
|
+
case "r":
|
|
6904
|
+
out += "\r";
|
|
6905
|
+
break;
|
|
6906
|
+
case "t":
|
|
6907
|
+
out += " ";
|
|
6908
|
+
break;
|
|
6909
|
+
case "v":
|
|
6910
|
+
out += "\v";
|
|
6911
|
+
break;
|
|
6912
|
+
case "x": {
|
|
6913
|
+
const hex = text.slice(i + 1, i + 3);
|
|
6914
|
+
if (!/^[0-9a-fA-F]{2}$/.test(hex)) return null;
|
|
6915
|
+
out += String.fromCharCode(parseInt(hex, 16));
|
|
6916
|
+
i += 2;
|
|
6917
|
+
break;
|
|
6918
|
+
}
|
|
6919
|
+
case "u": {
|
|
6920
|
+
if (isBytes) return null;
|
|
6921
|
+
const hex = text.slice(i + 1, i + 5);
|
|
6922
|
+
if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null;
|
|
6923
|
+
out += String.fromCharCode(parseInt(hex, 16));
|
|
6924
|
+
i += 4;
|
|
6925
|
+
break;
|
|
6926
|
+
}
|
|
6927
|
+
case "U": {
|
|
6928
|
+
if (isBytes) return null;
|
|
6929
|
+
const hex = text.slice(i + 1, i + 9);
|
|
6930
|
+
if (!/^[0-9a-fA-F]{8}$/.test(hex)) return null;
|
|
6931
|
+
const cp = parseInt(hex, 16);
|
|
6932
|
+
if (cp > 1114111) return null;
|
|
6933
|
+
out += String.fromCodePoint(cp);
|
|
6934
|
+
i += 8;
|
|
6935
|
+
break;
|
|
6936
|
+
}
|
|
6937
|
+
case "0":
|
|
6938
|
+
case "1":
|
|
6939
|
+
case "2":
|
|
6940
|
+
case "3":
|
|
6941
|
+
case "4":
|
|
6942
|
+
case "5":
|
|
6943
|
+
case "6":
|
|
6944
|
+
case "7": {
|
|
6945
|
+
let oct = next;
|
|
6946
|
+
for (let k = 0; k < 2 && /[0-7]/.test(text[i + 1] ?? ""); k++) {
|
|
6947
|
+
oct += text[i + 1];
|
|
6948
|
+
i += 1;
|
|
6949
|
+
}
|
|
6950
|
+
out += String.fromCharCode(parseInt(oct, 8));
|
|
6951
|
+
break;
|
|
6952
|
+
}
|
|
6953
|
+
case "N":
|
|
6954
|
+
return null;
|
|
6955
|
+
default:
|
|
6956
|
+
out += "\\" + next;
|
|
6957
|
+
break;
|
|
6958
|
+
}
|
|
6799
6959
|
}
|
|
6800
|
-
|
|
6801
|
-
return s;
|
|
6960
|
+
return out;
|
|
6802
6961
|
}
|
|
6803
6962
|
function isSysArgv(node) {
|
|
6804
6963
|
if (!node || node.name !== "MemberExpression") return false;
|
|
@@ -6810,7 +6969,14 @@ function isSysArgv(node) {
|
|
|
6810
6969
|
function evalExpr(node, env2) {
|
|
6811
6970
|
if (!node) return null;
|
|
6812
6971
|
const name = node.name;
|
|
6813
|
-
if (name === "String")
|
|
6972
|
+
if (name === "String") {
|
|
6973
|
+
const decoded = decodePythonStringLiteral(srcSlice(node));
|
|
6974
|
+
return decoded !== null && !decoded.bytes ? decoded.value : null;
|
|
6975
|
+
}
|
|
6976
|
+
if (name === "ContinuedString") {
|
|
6977
|
+
const decoded = literalStringText(node);
|
|
6978
|
+
return decoded;
|
|
6979
|
+
}
|
|
6814
6980
|
if (name === "Number") return srcSlice(node);
|
|
6815
6981
|
if (name === "VariableName") {
|
|
6816
6982
|
const id = srcSlice(node);
|
|
@@ -6842,6 +7008,9 @@ function evalExpr(node, env2) {
|
|
|
6842
7008
|
}
|
|
6843
7009
|
return null;
|
|
6844
7010
|
}
|
|
7011
|
+
if (name === "ParenthesizedExpression") {
|
|
7012
|
+
return evalExpr(firstNamedChild(node), env2);
|
|
7013
|
+
}
|
|
6845
7014
|
if (name === "ConditionalExpression") {
|
|
6846
7015
|
const ifKw = node.getChild("if");
|
|
6847
7016
|
const elseKw = node.getChild("else");
|
|
@@ -6885,7 +7054,7 @@ function lastNamedChild(node) {
|
|
|
6885
7054
|
function findOp(node) {
|
|
6886
7055
|
let c = node.firstChild;
|
|
6887
7056
|
while (c) {
|
|
6888
|
-
if (c.name === "CompareOp" || c.name === "and" || c.name === "or" || c.name === "UpdateOp") {
|
|
7057
|
+
if (c.name === "CompareOp" || c.name === "and" || c.name === "or" || c.name === "UpdateOp" || c.name === "ArithOp") {
|
|
6889
7058
|
return srcSlice(c).trim();
|
|
6890
7059
|
}
|
|
6891
7060
|
c = c.nextSibling;
|
|
@@ -6895,6 +7064,9 @@ function findOp(node) {
|
|
|
6895
7064
|
function evalCondition(node, env2) {
|
|
6896
7065
|
if (!node) return null;
|
|
6897
7066
|
const name = node.name;
|
|
7067
|
+
if (name === "ParenthesizedExpression") {
|
|
7068
|
+
return evalCondition(firstNamedChild(node), env2);
|
|
7069
|
+
}
|
|
6898
7070
|
if (name === "Boolean") {
|
|
6899
7071
|
const t = srcSlice(node).trim();
|
|
6900
7072
|
return t === "True" ? true : t === "False" ? false : null;
|
|
@@ -6902,7 +7074,7 @@ function evalCondition(node, env2) {
|
|
|
6902
7074
|
if (name === "BinaryExpression") {
|
|
6903
7075
|
const op = findOp(node);
|
|
6904
7076
|
if (op === "and" || op === "or") {
|
|
6905
|
-
const parts2 = namedChildren(node);
|
|
7077
|
+
const parts2 = namedChildren(node).filter((p) => p.name !== "and" && p.name !== "or");
|
|
6906
7078
|
const vals = parts2.map((p) => evalCondition(p, env2));
|
|
6907
7079
|
if (op === "and") {
|
|
6908
7080
|
if (vals.some((v) => v === false)) return false;
|
|
@@ -6988,8 +7160,8 @@ function evalCompare(left, opText, right, env2) {
|
|
|
6988
7160
|
}
|
|
6989
7161
|
return null;
|
|
6990
7162
|
}
|
|
6991
|
-
function processStmts(stmts, env2, lineStarts, lines, branches) {
|
|
6992
|
-
for (const s of stmts) processStmt(s, env2, lineStarts, lines, branches);
|
|
7163
|
+
function processStmts(stmts, env2, lineStarts, lines, branches, ifDecisions) {
|
|
7164
|
+
for (const s of stmts) processStmt(s, env2, lineStarts, lines, branches, ifDecisions);
|
|
6993
7165
|
}
|
|
6994
7166
|
function invalidateEnvOnCalls(node, env2) {
|
|
6995
7167
|
const cursor = node.cursor();
|
|
@@ -7004,15 +7176,31 @@ function invalidateEnvOnCalls(node, env2) {
|
|
|
7004
7176
|
return true;
|
|
7005
7177
|
});
|
|
7006
7178
|
}
|
|
7007
|
-
function
|
|
7179
|
+
function assignmentParts(stmt) {
|
|
7180
|
+
const targets = [];
|
|
7181
|
+
let lastAssign = null;
|
|
7182
|
+
let c = stmt.firstChild;
|
|
7183
|
+
while (c) {
|
|
7184
|
+
if (c.name === "AssignOp") lastAssign = c;
|
|
7185
|
+
c = c.nextSibling;
|
|
7186
|
+
}
|
|
7187
|
+
if (lastAssign === null) return { targets, value: null };
|
|
7188
|
+
const value = lastAssign.nextSibling;
|
|
7189
|
+
c = stmt.firstChild;
|
|
7190
|
+
while (c && !sameNode(c, lastAssign)) {
|
|
7191
|
+
if (c.name === "VariableName") targets.push(c);
|
|
7192
|
+
c = c.nextSibling;
|
|
7193
|
+
}
|
|
7194
|
+
return { targets, value };
|
|
7195
|
+
}
|
|
7196
|
+
function processStmt(stmt, env2, lineStarts, lines, branches, ifDecisions) {
|
|
7008
7197
|
const name = stmt.name;
|
|
7198
|
+
if (name === "Comment") return;
|
|
7009
7199
|
if (name === "AssignStatement") {
|
|
7010
|
-
const
|
|
7011
|
-
if (
|
|
7012
|
-
const valNode = target.nextSibling ? target.nextSibling.nextSibling : null;
|
|
7200
|
+
const { targets, value } = assignmentParts(stmt);
|
|
7201
|
+
if (targets.length === 1) {
|
|
7013
7202
|
invalidateEnvOnCalls(stmt, env2);
|
|
7014
|
-
|
|
7015
|
-
env2.vars[srcSlice(target)] = val;
|
|
7203
|
+
env2.vars[srcSlice(targets[0])] = evalExpr(value, env2);
|
|
7016
7204
|
}
|
|
7017
7205
|
markNodeLines(stmt, lines, lineStarts);
|
|
7018
7206
|
return;
|
|
@@ -7025,34 +7213,34 @@ function processStmt(stmt, env2, lineStarts, lines, branches) {
|
|
|
7025
7213
|
return;
|
|
7026
7214
|
}
|
|
7027
7215
|
if (name === "IfStatement") {
|
|
7028
|
-
processIf(stmt, env2, lineStarts, lines, branches);
|
|
7216
|
+
processIf(stmt, env2, lineStarts, lines, branches, ifDecisions);
|
|
7029
7217
|
return;
|
|
7030
7218
|
}
|
|
7031
7219
|
if (name === "ForStatement" || name === "WhileStatement") {
|
|
7032
7220
|
markNodeLines(stmt, lines, lineStarts);
|
|
7033
7221
|
for (const body of stmt.getChildren("Body")) {
|
|
7034
|
-
processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
|
|
7222
|
+
processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
|
|
7035
7223
|
}
|
|
7036
7224
|
return;
|
|
7037
7225
|
}
|
|
7038
7226
|
if (name === "TryStatement") {
|
|
7039
7227
|
markNodeLines(stmt, lines, lineStarts);
|
|
7040
7228
|
for (const body of stmt.getChildren("Body")) {
|
|
7041
|
-
processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
|
|
7229
|
+
processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
|
|
7042
7230
|
}
|
|
7043
7231
|
return;
|
|
7044
7232
|
}
|
|
7045
7233
|
if (name === "WithStatement") {
|
|
7046
7234
|
markNodeLines(stmt, lines, lineStarts);
|
|
7047
7235
|
const body = stmt.getChild("Body");
|
|
7048
|
-
if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
|
|
7236
|
+
if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
|
|
7049
7237
|
return;
|
|
7050
7238
|
}
|
|
7051
7239
|
if (name === "MatchStatement") {
|
|
7052
7240
|
markNodeLines(stmt, lines, lineStarts);
|
|
7053
7241
|
for (const clause of stmt.getChildren("MatchClause")) {
|
|
7054
7242
|
const body = clause.getChild("Body");
|
|
7055
|
-
if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches);
|
|
7243
|
+
if (body) processStmts(bodyStmts(body), { argv: env2.argv, vars: { ...env2.vars } }, lineStarts, lines, branches, ifDecisions);
|
|
7056
7244
|
}
|
|
7057
7245
|
return;
|
|
7058
7246
|
}
|
|
@@ -7074,14 +7262,26 @@ function markDefTree(stmt, lines, lineStarts) {
|
|
|
7074
7262
|
}
|
|
7075
7263
|
function bodyStmts(body) {
|
|
7076
7264
|
const out = [];
|
|
7265
|
+
const append = (node) => {
|
|
7266
|
+
if (node.name === "StatementGroup") {
|
|
7267
|
+
let c2 = node.firstChild;
|
|
7268
|
+
while (c2) {
|
|
7269
|
+
append(c2);
|
|
7270
|
+
c2 = c2.nextSibling;
|
|
7271
|
+
}
|
|
7272
|
+
return;
|
|
7273
|
+
}
|
|
7274
|
+
if (node.name === ":" || node.name === ";" || node.name === "\n") return;
|
|
7275
|
+
out.push(node);
|
|
7276
|
+
};
|
|
7077
7277
|
let c = body.firstChild;
|
|
7078
7278
|
while (c) {
|
|
7079
|
-
|
|
7279
|
+
append(c);
|
|
7080
7280
|
c = c.nextSibling;
|
|
7081
7281
|
}
|
|
7082
7282
|
return out;
|
|
7083
7283
|
}
|
|
7084
|
-
function
|
|
7284
|
+
function collectIfSections(stmt) {
|
|
7085
7285
|
const sections = [];
|
|
7086
7286
|
let c = stmt.firstChild;
|
|
7087
7287
|
while (c) {
|
|
@@ -7096,17 +7296,24 @@ function processIf(stmt, env2, lineStarts, lines, branches) {
|
|
|
7096
7296
|
}
|
|
7097
7297
|
c = c.nextSibling;
|
|
7098
7298
|
}
|
|
7099
|
-
|
|
7299
|
+
return sections;
|
|
7100
7300
|
}
|
|
7101
|
-
function
|
|
7301
|
+
function processIf(stmt, env2, lineStarts, lines, branches, ifDecisions) {
|
|
7302
|
+
const sections = collectIfSections(stmt);
|
|
7303
|
+
const decisions = [];
|
|
7304
|
+
ifDecisions.set(stmt.from, decisions);
|
|
7305
|
+
processIfSections(sections, decisions, 0, env2, lineStarts, lines, branches, ifDecisions);
|
|
7306
|
+
}
|
|
7307
|
+
function processIfSections(sections, decisions, idx, env2, lineStarts, lines, branches, ifDecisions) {
|
|
7102
7308
|
if (idx >= sections.length) return;
|
|
7103
7309
|
const s = sections[idx];
|
|
7104
7310
|
if (s.cond) markNodeLines(s.cond, lines, lineStarts);
|
|
7105
7311
|
if (s.isElse) {
|
|
7106
|
-
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches);
|
|
7312
|
+
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches, ifDecisions);
|
|
7107
7313
|
return;
|
|
7108
7314
|
}
|
|
7109
7315
|
const cond = s.cond ? evalCondition(s.cond, env2) : null;
|
|
7316
|
+
decisions[idx] = cond;
|
|
7110
7317
|
branches.push({
|
|
7111
7318
|
kind: "if",
|
|
7112
7319
|
label: s.cond ? srcSlice(s.cond) : "",
|
|
@@ -7114,138 +7321,1107 @@ function processIfSections(_stmt, sections, idx, env2, lineStarts, lines, branch
|
|
|
7114
7321
|
reachable: cond !== false
|
|
7115
7322
|
});
|
|
7116
7323
|
if (cond === true) {
|
|
7117
|
-
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches);
|
|
7324
|
+
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches, ifDecisions);
|
|
7118
7325
|
return;
|
|
7119
7326
|
}
|
|
7120
7327
|
if (cond === false) {
|
|
7121
|
-
processIfSections(
|
|
7328
|
+
processIfSections(sections, decisions, idx + 1, env2, lineStarts, lines, branches, ifDecisions);
|
|
7122
7329
|
return;
|
|
7123
7330
|
}
|
|
7124
|
-
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches);
|
|
7331
|
+
if (s.body) processStmts(bodyStmts(s.body), env2, lineStarts, lines, branches, ifDecisions);
|
|
7125
7332
|
for (let j = idx + 1; j < sections.length; j++) {
|
|
7126
7333
|
const sj = sections[j];
|
|
7127
7334
|
if (sj.cond) markNodeLines(sj.cond, lines, lineStarts);
|
|
7128
|
-
if (sj.body) processStmts(bodyStmts(sj.body), env2, lineStarts, lines, branches);
|
|
7335
|
+
if (sj.body) processStmts(bodyStmts(sj.body), env2, lineStarts, lines, branches, ifDecisions);
|
|
7129
7336
|
}
|
|
7130
7337
|
}
|
|
7131
|
-
function
|
|
7132
|
-
|
|
7133
|
-
|
|
7134
|
-
|
|
7135
|
-
|
|
7136
|
-
|
|
7137
|
-
|
|
7138
|
-
|
|
7139
|
-
|
|
7140
|
-
|
|
7141
|
-
|
|
7142
|
-
|
|
7338
|
+
function basenameOf(p) {
|
|
7339
|
+
const index = p.lastIndexOf("/");
|
|
7340
|
+
return index < 0 ? p : p.slice(index + 1);
|
|
7341
|
+
}
|
|
7342
|
+
function callKey(call) {
|
|
7343
|
+
const cwd = call.launchCwd === WORKING_DIRECTORY_UNKNOWN ? "\0UNKNOWN" : call.launchCwd === void 0 || call.launchCwd === null ? "\0NONE" : call.launchCwd;
|
|
7344
|
+
return `${call.path}\0${call.args.join("\0")}\0${call.interpreter}\0${cwd}`;
|
|
7345
|
+
}
|
|
7346
|
+
function sameNode(a, b) {
|
|
7347
|
+
return a !== null && b !== null && a.from === b.from && a.to === b.to && a.name === b.name;
|
|
7348
|
+
}
|
|
7349
|
+
function firstInnerNode(node) {
|
|
7350
|
+
let c = node.firstChild;
|
|
7351
|
+
while (c) {
|
|
7352
|
+
if (!["(", ")", ",", ":", "[", "]", "{", "}"].includes(c.name)) return c;
|
|
7353
|
+
c = c.nextSibling;
|
|
7354
|
+
}
|
|
7355
|
+
return null;
|
|
7356
|
+
}
|
|
7357
|
+
function unwrapParens(node) {
|
|
7358
|
+
let current = node;
|
|
7359
|
+
while (current && current.name === "ParenthesizedExpression") {
|
|
7360
|
+
current = firstInnerNode(current);
|
|
7361
|
+
}
|
|
7362
|
+
return current;
|
|
7363
|
+
}
|
|
7364
|
+
function literalStringText(node) {
|
|
7365
|
+
if (!node) return null;
|
|
7366
|
+
if (node.name === "String") {
|
|
7367
|
+
const decoded = decodePythonStringLiteral(srcSlice(node));
|
|
7368
|
+
return decoded !== null && !decoded.bytes ? decoded.value : null;
|
|
7369
|
+
}
|
|
7370
|
+
if (node.name === "ContinuedString") {
|
|
7371
|
+
let out = "";
|
|
7372
|
+
let c = node.firstChild;
|
|
7373
|
+
while (c) {
|
|
7374
|
+
if (c.name === "String") {
|
|
7375
|
+
const decoded = decodePythonStringLiteral(srcSlice(c));
|
|
7376
|
+
if (decoded === null || decoded.bytes) return null;
|
|
7377
|
+
out += decoded.value;
|
|
7378
|
+
}
|
|
7379
|
+
c = c.nextSibling;
|
|
7143
7380
|
}
|
|
7144
|
-
return
|
|
7381
|
+
return out;
|
|
7382
|
+
}
|
|
7383
|
+
if (node.name === "ParenthesizedExpression") {
|
|
7384
|
+
return literalStringText(firstInnerNode(node));
|
|
7385
|
+
}
|
|
7386
|
+
if (node.name === "FormatString") {
|
|
7387
|
+
let hasReplacement = false;
|
|
7388
|
+
const cursor = node.cursor();
|
|
7389
|
+
cursor.iterate((n) => {
|
|
7390
|
+
if (n.node.name === "FormatReplacement") {
|
|
7391
|
+
hasReplacement = true;
|
|
7392
|
+
return false;
|
|
7393
|
+
}
|
|
7394
|
+
return true;
|
|
7395
|
+
});
|
|
7396
|
+
if (hasReplacement) return null;
|
|
7397
|
+
const raw = srcSlice(node);
|
|
7398
|
+
const m = /^([rRfF]*)(\"\"\"|'''|"|')/.exec(raw);
|
|
7399
|
+
if (m === null || !raw.endsWith(m[2]) || raw.length < m[0].length + m[2].length) return null;
|
|
7400
|
+
let inner = raw.slice(m[0].length, raw.length - m[2].length);
|
|
7401
|
+
inner = inner.replace(/\{\{/g, "{").replace(/\}\}/g, "}");
|
|
7402
|
+
return m[1].toLowerCase().includes("r") ? inner : unescapePythonString(inner, false);
|
|
7145
7403
|
}
|
|
7146
7404
|
return null;
|
|
7147
7405
|
}
|
|
7148
|
-
function
|
|
7406
|
+
function literalText(node, bindings) {
|
|
7407
|
+
if (!node) return null;
|
|
7408
|
+
if (node.name === "VariableName") return bindings.strings.get(srcSlice(node)) ?? null;
|
|
7409
|
+
if (node.name === "ParenthesizedExpression") return literalText(firstInnerNode(node), bindings);
|
|
7410
|
+
return literalStringText(node);
|
|
7411
|
+
}
|
|
7412
|
+
function* literalShellCommands(command) {
|
|
7413
|
+
let words = [];
|
|
7414
|
+
let assigned = false;
|
|
7415
|
+
let redirected = false;
|
|
7416
|
+
let redirectTarget = false;
|
|
7417
|
+
let index = 0;
|
|
7418
|
+
let statementStart = 0;
|
|
7419
|
+
while (index <= command.length) {
|
|
7420
|
+
const char = index < command.length ? command[index] : "\n";
|
|
7421
|
+
if (char === " " || char === " ") {
|
|
7422
|
+
index += 1;
|
|
7423
|
+
continue;
|
|
7424
|
+
}
|
|
7425
|
+
if (char === "#") {
|
|
7426
|
+
const newline = command.indexOf("\n", index);
|
|
7427
|
+
index = newline < 0 ? command.length : newline;
|
|
7428
|
+
continue;
|
|
7429
|
+
}
|
|
7430
|
+
if (char === "\n" || char === ";" || command.startsWith("&&", index) || command.startsWith("||", index)) {
|
|
7431
|
+
if (redirectTarget) return;
|
|
7432
|
+
const separator = char === "&" || char === "|" ? command.slice(index, index + 2) : char;
|
|
7433
|
+
if (words.length || redirected || assigned) {
|
|
7434
|
+
yield { words, separator, start: statementStart, redirected };
|
|
7435
|
+
}
|
|
7436
|
+
words = [];
|
|
7437
|
+
assigned = false;
|
|
7438
|
+
redirected = false;
|
|
7439
|
+
index += separator.length;
|
|
7440
|
+
statementStart = index;
|
|
7441
|
+
continue;
|
|
7442
|
+
}
|
|
7443
|
+
if ((char === "<" || char === ">") && !command.startsWith("<<", index)) {
|
|
7444
|
+
if (redirectTarget) return;
|
|
7445
|
+
FILE_REDIRECT_RE.lastIndex = index;
|
|
7446
|
+
const redirect = FILE_REDIRECT_RE.exec(command);
|
|
7447
|
+
if (!redirect || redirect.index !== index) return;
|
|
7448
|
+
index += redirect[0].length;
|
|
7449
|
+
redirected = true;
|
|
7450
|
+
redirectTarget = true;
|
|
7451
|
+
continue;
|
|
7452
|
+
}
|
|
7453
|
+
const start = index;
|
|
7454
|
+
const parts = [];
|
|
7455
|
+
if (char !== "~") {
|
|
7456
|
+
while (true) {
|
|
7457
|
+
LITERAL_PART_RE.lastIndex = index;
|
|
7458
|
+
const match = LITERAL_PART_RE.exec(command);
|
|
7459
|
+
if (!match || match.index !== index) break;
|
|
7460
|
+
const raw = match[0];
|
|
7461
|
+
if (raw.startsWith('"')) parts.push(raw.slice(1, -1).replace(SHELL_DOUBLE_ESCAPE_RE, "$1"));
|
|
7462
|
+
else if (raw.startsWith("'")) parts.push(raw.slice(1, -1));
|
|
7463
|
+
else if (raw.startsWith("\\")) parts.push(raw.slice(1));
|
|
7464
|
+
else parts.push(raw);
|
|
7465
|
+
index += raw.length;
|
|
7466
|
+
}
|
|
7467
|
+
}
|
|
7468
|
+
if (parts.length === 0 || index < command.length && !" \n;<>|&".includes(command[index])) {
|
|
7469
|
+
yield { words: null, separator: "", start: statementStart, redirected };
|
|
7470
|
+
return;
|
|
7471
|
+
}
|
|
7472
|
+
if (redirectTarget) {
|
|
7473
|
+
redirectTarget = false;
|
|
7474
|
+
} else if (words.length === 0 && SHELL_ASSIGNMENT.test(command.slice(start, index))) {
|
|
7475
|
+
assigned = true;
|
|
7476
|
+
} else if (!(index < command.length && "<>".includes(command[index]) && IO_NUMBER.test(command.slice(start, index)))) {
|
|
7477
|
+
words.push(parts.join(""));
|
|
7478
|
+
}
|
|
7479
|
+
}
|
|
7480
|
+
}
|
|
7481
|
+
function legacyLiteralCalls(command, source) {
|
|
7482
|
+
let calls = extractCallsRegex(command);
|
|
7483
|
+
if (calls.length && source !== null && command !== source) {
|
|
7484
|
+
const old = new Set(extractCallsRegex(source).map(callKey));
|
|
7485
|
+
calls = calls.filter((call) => old.has(callKey(call)));
|
|
7486
|
+
}
|
|
7487
|
+
return calls.filter((call) => !call.path.includes("\0"));
|
|
7488
|
+
}
|
|
7489
|
+
function shellProgramOperand(words) {
|
|
7490
|
+
if (!words.length) return null;
|
|
7491
|
+
const name = basenameOf(words[0]);
|
|
7492
|
+
if (!SHELL_INTERPRETERS.has(name)) return null;
|
|
7493
|
+
let kind = "script";
|
|
7494
|
+
for (let index = 1; index < words.length; index++) {
|
|
7495
|
+
const word = words[index];
|
|
7496
|
+
if (word === "--") {
|
|
7497
|
+
return index + 1 < words.length ? { kind, index: index + 1 } : null;
|
|
7498
|
+
}
|
|
7499
|
+
if (!word.startsWith("-") && !word.startsWith("+")) return { kind, index };
|
|
7500
|
+
if (word.length < 2 || [...word.slice(1)].some((flag) => !"acefuvx".includes(flag))) {
|
|
7501
|
+
return null;
|
|
7502
|
+
}
|
|
7503
|
+
if (word.slice(1).includes("c")) kind = "command";
|
|
7504
|
+
}
|
|
7505
|
+
return null;
|
|
7506
|
+
}
|
|
7507
|
+
function envCommand(words) {
|
|
7508
|
+
if (!words.length || !ENV_PROGRAMS.has(words[0])) return words;
|
|
7509
|
+
let index = words.length > 1 && words[1] === "--" ? 2 : 1;
|
|
7510
|
+
while (index < words.length && SHELL_ASSIGNMENT.test(words[index])) {
|
|
7511
|
+
if (words[index].includes("\0")) return [];
|
|
7512
|
+
index += 1;
|
|
7513
|
+
}
|
|
7514
|
+
return words.slice(index);
|
|
7515
|
+
}
|
|
7516
|
+
function literalScriptCall(words) {
|
|
7517
|
+
if (words.length < 2) return null;
|
|
7518
|
+
const interpreter = words[0];
|
|
7519
|
+
const name = basenameOf(interpreter);
|
|
7520
|
+
if (!SCRIPT_INTERPRETERS.has(name) && !VERSIONED_PYTHON.test(name)) return null;
|
|
7521
|
+
if (words.some((word) => word.includes("\0"))) return null;
|
|
7522
|
+
let index = 1;
|
|
7523
|
+
if (SHELL_INTERPRETERS.has(name)) {
|
|
7524
|
+
const operand = shellProgramOperand(words);
|
|
7525
|
+
if (operand === null || operand.kind !== "script") return null;
|
|
7526
|
+
index = operand.index;
|
|
7527
|
+
} else if (words[index].startsWith("-")) {
|
|
7528
|
+
return null;
|
|
7529
|
+
}
|
|
7530
|
+
const scriptPath = words[index];
|
|
7531
|
+
if (!scriptPath || scriptPath.startsWith("$") || scriptPath.startsWith("~") || scriptPath.includes("/dev/")) {
|
|
7532
|
+
return null;
|
|
7533
|
+
}
|
|
7534
|
+
return { path: scriptPath, args: words.slice(index + 1), interpreter };
|
|
7535
|
+
}
|
|
7536
|
+
function literalShellCalls(command, source) {
|
|
7149
7537
|
const calls = [];
|
|
7150
|
-
|
|
7151
|
-
const
|
|
7152
|
-
|
|
7153
|
-
|
|
7154
|
-
|
|
7155
|
-
calls.push(
|
|
7538
|
+
let eligible = null;
|
|
7539
|
+
const statuses = /* @__PURE__ */ new Set([true, false]);
|
|
7540
|
+
let required = null;
|
|
7541
|
+
for (const entry of literalShellCommands(command)) {
|
|
7542
|
+
if (entry.words === null) {
|
|
7543
|
+
calls.push(...legacyLiteralCalls(command.slice(entry.start), source));
|
|
7544
|
+
break;
|
|
7156
7545
|
}
|
|
7157
|
-
|
|
7158
|
-
|
|
7159
|
-
|
|
7160
|
-
|
|
7161
|
-
|
|
7162
|
-
|
|
7546
|
+
if (required === null || statuses.has(required)) {
|
|
7547
|
+
if (required === null) statuses.clear();
|
|
7548
|
+
else statuses.delete(required);
|
|
7549
|
+
const words = entry.words;
|
|
7550
|
+
const head = words.length ? words[0] : "";
|
|
7551
|
+
const replacesShell = head === "exec" && words.length > 1;
|
|
7552
|
+
const program = replacesShell ? words.slice(1) : words;
|
|
7553
|
+
const call = literalScriptCall(envCommand(program));
|
|
7554
|
+
if (call !== null) {
|
|
7555
|
+
if (eligible === null || eligible.has(callKey(call))) calls.push(call);
|
|
7556
|
+
} else if (head !== "" && !["echo", "printf", ":", "true", "false", "exit"].includes(head) && !ENV_PROGRAMS.has(head) && eligible === null) {
|
|
7557
|
+
eligible = new Set(legacyLiteralCalls(command, source).map(callKey));
|
|
7558
|
+
}
|
|
7559
|
+
const exits = head === "exit" && (words.length === 1 || words.length === 2 && /^[+-]?[0-9]+$/.test(words[1]));
|
|
7560
|
+
if (exits || call !== null && replacesShell) {
|
|
7561
|
+
if (entry.redirected) statuses.add(false);
|
|
7562
|
+
} else if (!entry.redirected && [":", "true", "false"].includes(head)) {
|
|
7563
|
+
statuses.add(head !== "false");
|
|
7564
|
+
} else {
|
|
7565
|
+
statuses.add(true);
|
|
7566
|
+
statuses.add(false);
|
|
7567
|
+
}
|
|
7568
|
+
if (statuses.size === 0) break;
|
|
7569
|
+
}
|
|
7570
|
+
required = entry.separator === "&&" ? true : entry.separator === "||" ? false : null;
|
|
7571
|
+
}
|
|
7572
|
+
return calls;
|
|
7573
|
+
}
|
|
7574
|
+
function mergeBindings(maps, same) {
|
|
7575
|
+
const out = /* @__PURE__ */ new Map();
|
|
7576
|
+
if (!maps.length) return out;
|
|
7577
|
+
for (const [key, value] of maps[0]) {
|
|
7578
|
+
if (maps.every((map) => map.has(key) && same(map.get(key), value))) {
|
|
7579
|
+
out.set(key, value);
|
|
7580
|
+
}
|
|
7581
|
+
}
|
|
7582
|
+
return out;
|
|
7583
|
+
}
|
|
7584
|
+
function sameTuple(a, b) {
|
|
7585
|
+
return a[0] === b[0] && a[1] === b[1];
|
|
7586
|
+
}
|
|
7587
|
+
function purePathNormalize(p) {
|
|
7588
|
+
const absolute = p.startsWith("/");
|
|
7589
|
+
const parts = p.split("/").filter((part) => part !== "" && part !== ".");
|
|
7590
|
+
if (absolute) return "/" + parts.join("/");
|
|
7591
|
+
return parts.length ? parts.join("/") : ".";
|
|
7592
|
+
}
|
|
7593
|
+
function directoryFor(bindings, directory) {
|
|
7594
|
+
if (directory && !directory.includes("\0")) {
|
|
7595
|
+
if (path4.isAbsolute(directory)) return purePathNormalize(directory);
|
|
7596
|
+
if (bindings.cwd !== WORKING_DIRECTORY_UNKNOWN) {
|
|
7597
|
+
return purePathNormalize(`${bindings.cwd === null ? "." : bindings.cwd}/${directory}`);
|
|
7598
|
+
}
|
|
7599
|
+
}
|
|
7600
|
+
return WORKING_DIRECTORY_UNKNOWN;
|
|
7601
|
+
}
|
|
7602
|
+
function recordImportText(node, bindings) {
|
|
7603
|
+
const text = srcSlice(node).trim();
|
|
7604
|
+
const fromMatch = /^from\s+([\s\S]*?)\s+import\s+([\s\S]+)$/.exec(text);
|
|
7605
|
+
if (fromMatch !== null) {
|
|
7606
|
+
const head = fromMatch[1].trim();
|
|
7607
|
+
const levelMatch = /^(\.+)([\s\S]*)$/.exec(head);
|
|
7608
|
+
const level = levelMatch === null ? 0 : levelMatch[1].length;
|
|
7609
|
+
const module = (levelMatch === null ? head : levelMatch[2]).trim();
|
|
7610
|
+
for (const part of fromMatch[2].replace(/[()]/g, " ").split(",")) {
|
|
7611
|
+
const trimmed = part.trim();
|
|
7612
|
+
if (trimmed === "*") {
|
|
7613
|
+
bindings.invalidate();
|
|
7614
|
+
continue;
|
|
7615
|
+
}
|
|
7616
|
+
const nameMatch = /^([A-Za-z_][\w.]*)(?:\s+as\s+([A-Za-z_][\w.]*))?$/.exec(trimmed);
|
|
7617
|
+
if (nameMatch === null) continue;
|
|
7618
|
+
const name = nameMatch[1];
|
|
7619
|
+
const bound = nameMatch[2] || name.split(".")[0];
|
|
7620
|
+
bindings.forget(bound);
|
|
7621
|
+
if (level === 0 && module && CALL_FUNCTIONS[module]?.has(name)) {
|
|
7622
|
+
bindings.functions.set(bound, [module, name]);
|
|
7623
|
+
}
|
|
7624
|
+
}
|
|
7625
|
+
return;
|
|
7626
|
+
}
|
|
7627
|
+
const importMatch = /^import\s+([\s\S]+)$/.exec(text);
|
|
7628
|
+
if (importMatch === null) return;
|
|
7629
|
+
for (const part of importMatch[1].split(",")) {
|
|
7630
|
+
const nameMatch = /^([A-Za-z_][\w.]*)(?:\s+as\s+([A-Za-z_][\w.]*))?$/.exec(part.trim());
|
|
7631
|
+
if (nameMatch === null) continue;
|
|
7632
|
+
const full = nameMatch[1];
|
|
7633
|
+
const alias = nameMatch[2];
|
|
7634
|
+
const name = alias || full;
|
|
7635
|
+
const bound = alias || full.split(".")[0];
|
|
7636
|
+
bindings.forget(bound);
|
|
7637
|
+
const module = alias ? full : full.split(".")[0];
|
|
7638
|
+
if (CALL_FUNCTIONS[module]) bindings.modules.set(bound, module);
|
|
7639
|
+
}
|
|
7640
|
+
}
|
|
7641
|
+
function sequenceElements(node) {
|
|
7642
|
+
if (node.name !== "ArrayExpression" && node.name !== "TupleExpression") return null;
|
|
7643
|
+
const out = [];
|
|
7644
|
+
let c = node.firstChild;
|
|
7645
|
+
while (c) {
|
|
7646
|
+
if (!["[", "]", "(", ")", ","].includes(c.name)) out.push(c);
|
|
7647
|
+
c = c.nextSibling;
|
|
7648
|
+
}
|
|
7649
|
+
return out;
|
|
7650
|
+
}
|
|
7651
|
+
function literalKeywordDict(node) {
|
|
7652
|
+
if (!node || node.name !== "DictionaryExpression") return null;
|
|
7653
|
+
const out = /* @__PURE__ */ new Map();
|
|
7654
|
+
let c = node.firstChild;
|
|
7655
|
+
while (c) {
|
|
7656
|
+
if (["{", "}", ","].includes(c.name)) {
|
|
7657
|
+
c = c.nextSibling;
|
|
7658
|
+
continue;
|
|
7659
|
+
}
|
|
7660
|
+
if (c.name === "**") {
|
|
7661
|
+
const nestedNode = c.nextSibling;
|
|
7662
|
+
const nested = nestedNode === null ? null : literalKeywordDict(nestedNode);
|
|
7663
|
+
if (nested === null) return null;
|
|
7664
|
+
for (const [key, value2] of nested) out.set(key, value2);
|
|
7665
|
+
c = nestedNode === null ? null : nestedNode.nextSibling;
|
|
7666
|
+
continue;
|
|
7667
|
+
}
|
|
7668
|
+
const keyNode = c;
|
|
7669
|
+
const colon = keyNode.nextSibling;
|
|
7670
|
+
const value = colon === null ? null : colon.nextSibling;
|
|
7671
|
+
if (colon === null || colon.name !== ":" || value === null) return null;
|
|
7672
|
+
const decoded = keyNode.name === "String" ? decodePythonStringLiteral(srcSlice(keyNode)) : null;
|
|
7673
|
+
if (decoded === null || decoded.bytes) return null;
|
|
7674
|
+
out.set(decoded.value, value);
|
|
7675
|
+
c = value.nextSibling;
|
|
7676
|
+
}
|
|
7677
|
+
return out;
|
|
7678
|
+
}
|
|
7679
|
+
function parseCallArgs(node) {
|
|
7680
|
+
const argList = node.getChild("ArgList");
|
|
7681
|
+
if (!argList) return { positional: [], keywords: /* @__PURE__ */ new Map(), hasStar: false };
|
|
7682
|
+
const positional = [];
|
|
7683
|
+
const keywords = /* @__PURE__ */ new Map();
|
|
7684
|
+
let hasStar = false;
|
|
7685
|
+
let keywordInvalid = false;
|
|
7686
|
+
let c = argList.firstChild;
|
|
7687
|
+
while (c) {
|
|
7688
|
+
const name = c.name;
|
|
7689
|
+
if (name === "(" || name === ")" || name === ",") {
|
|
7690
|
+
c = c.nextSibling;
|
|
7691
|
+
continue;
|
|
7692
|
+
}
|
|
7693
|
+
if (name === "**") {
|
|
7694
|
+
const value = c.nextSibling;
|
|
7695
|
+
const expansion = value === null ? null : literalKeywordDict(value);
|
|
7696
|
+
if (expansion === null) {
|
|
7697
|
+
keywordInvalid = true;
|
|
7698
|
+
} else {
|
|
7699
|
+
for (const [key, val] of expansion) {
|
|
7700
|
+
if (keywords.has(key)) keywordInvalid = true;
|
|
7701
|
+
else keywords.set(key, val);
|
|
7702
|
+
}
|
|
7703
|
+
}
|
|
7704
|
+
c = value === null ? null : value.nextSibling;
|
|
7705
|
+
continue;
|
|
7706
|
+
}
|
|
7707
|
+
if (name === "*") {
|
|
7708
|
+
hasStar = true;
|
|
7709
|
+
const value = c.nextSibling;
|
|
7710
|
+
c = value === null ? null : value.nextSibling;
|
|
7711
|
+
continue;
|
|
7712
|
+
}
|
|
7713
|
+
if (name === "VariableName" && c.nextSibling !== null && c.nextSibling.name === "AssignOp") {
|
|
7714
|
+
const key = srcSlice(c);
|
|
7715
|
+
const value = c.nextSibling.nextSibling;
|
|
7716
|
+
if (value === null || keywords.has(key)) keywordInvalid = true;
|
|
7717
|
+
else keywords.set(key, value);
|
|
7718
|
+
c = value === null ? null : value.nextSibling;
|
|
7719
|
+
continue;
|
|
7720
|
+
}
|
|
7721
|
+
positional.push(c);
|
|
7722
|
+
c = c.nextSibling;
|
|
7723
|
+
}
|
|
7724
|
+
return { positional, keywords: keywordInvalid ? null : keywords, hasStar };
|
|
7725
|
+
}
|
|
7726
|
+
function callIdentity(node, bindings) {
|
|
7727
|
+
const func = unwrapParens(node.firstChild);
|
|
7728
|
+
if (!func) return null;
|
|
7729
|
+
if (func.name === "MemberExpression") {
|
|
7730
|
+
const moduleNode = unwrapParens(func.firstChild);
|
|
7731
|
+
if (!moduleNode || moduleNode.name !== "VariableName") return null;
|
|
7732
|
+
const property = func.getChild("PropertyName");
|
|
7733
|
+
if (!property) return null;
|
|
7734
|
+
const module = bindings.modules.get(srcSlice(moduleNode));
|
|
7735
|
+
const method = srcSlice(property);
|
|
7736
|
+
if (module !== void 0 && CALL_FUNCTIONS[module]?.has(method)) return [module, method];
|
|
7737
|
+
return null;
|
|
7738
|
+
}
|
|
7739
|
+
if (func.name === "VariableName") {
|
|
7740
|
+
return bindings.functions.get(srcSlice(func)) ?? null;
|
|
7741
|
+
}
|
|
7742
|
+
return null;
|
|
7743
|
+
}
|
|
7744
|
+
function isConstantNode(node) {
|
|
7745
|
+
return ["String", "Number", "Boolean", "None"].includes(node.name);
|
|
7746
|
+
}
|
|
7747
|
+
function isLiteralPrint(node, bindings) {
|
|
7748
|
+
if (!bindings.builtinPrint) return false;
|
|
7749
|
+
const func = unwrapParens(node.firstChild);
|
|
7750
|
+
if (!func || func.name !== "VariableName" || srcSlice(func) !== "print") return false;
|
|
7751
|
+
const args = parseCallArgs(node);
|
|
7752
|
+
if (args === null || args.hasStar || args.keywords === null) return false;
|
|
7753
|
+
if (!args.positional.every(isConstantNode)) return false;
|
|
7754
|
+
for (const [key, value] of args.keywords) {
|
|
7755
|
+
if (!["sep", "end", "flush"].includes(key) || !isConstantNode(value)) return false;
|
|
7756
|
+
}
|
|
7757
|
+
return true;
|
|
7758
|
+
}
|
|
7759
|
+
function observeChdir(node, bindings, method, standalone) {
|
|
7760
|
+
let directory = null;
|
|
7761
|
+
if (standalone && method === "chdir") {
|
|
7762
|
+
const args = parseCallArgs(node);
|
|
7763
|
+
if (args !== null && !args.hasStar && args.keywords !== null) {
|
|
7764
|
+
if (args.positional.length === 1 && args.keywords.size === 0) {
|
|
7765
|
+
directory = literalText(args.positional[0], bindings);
|
|
7766
|
+
} else if (args.positional.length === 0 && args.keywords.size === 1 && args.keywords.has("path")) {
|
|
7767
|
+
directory = literalText(args.keywords.get("path"), bindings);
|
|
7768
|
+
}
|
|
7769
|
+
}
|
|
7770
|
+
}
|
|
7771
|
+
bindings.changeDirectory(directory);
|
|
7772
|
+
}
|
|
7773
|
+
function subprocessCalls(command, options, source, bindings) {
|
|
7774
|
+
const executableNode = options.get("executable");
|
|
7775
|
+
const shellNode = options.get("shell");
|
|
7776
|
+
let executable = null;
|
|
7777
|
+
if (executableNode !== void 0) {
|
|
7778
|
+
if (executableNode.name === "None") {
|
|
7779
|
+
executable = null;
|
|
7780
|
+
} else if (executableNode.name === "String") {
|
|
7781
|
+
const decoded = decodePythonStringLiteral(srcSlice(executableNode));
|
|
7782
|
+
if (decoded === null || decoded.bytes || decoded.value === "" || decoded.value.includes("\0")) {
|
|
7783
|
+
return [];
|
|
7784
|
+
}
|
|
7785
|
+
executable = decoded.value;
|
|
7786
|
+
} else {
|
|
7787
|
+
return [];
|
|
7788
|
+
}
|
|
7789
|
+
}
|
|
7790
|
+
let shell = false;
|
|
7791
|
+
if (shellNode !== void 0) {
|
|
7792
|
+
if (shellNode.name !== "Boolean") return [];
|
|
7793
|
+
shell = srcSlice(shellNode) === "True";
|
|
7794
|
+
}
|
|
7795
|
+
if (shell) {
|
|
7796
|
+
if (executable !== null && !SHELL_INTERPRETERS.has(basenameOf(executable))) return [];
|
|
7797
|
+
let commandNode = command;
|
|
7798
|
+
if (commandNode.name === "ArrayExpression" || commandNode.name === "TupleExpression") {
|
|
7799
|
+
const elements2 = sequenceElements(commandNode);
|
|
7800
|
+
if (elements2 !== null && elements2.length) commandNode = elements2[0];
|
|
7801
|
+
}
|
|
7802
|
+
const text = literalText(commandNode, bindings);
|
|
7803
|
+
return text !== null ? literalShellCalls(text, source) : [];
|
|
7804
|
+
}
|
|
7805
|
+
if (shell !== false) return [];
|
|
7806
|
+
const elements = sequenceElements(command);
|
|
7807
|
+
if (elements === null) return [];
|
|
7808
|
+
const words = [];
|
|
7809
|
+
for (const operand of elements) {
|
|
7810
|
+
const word = literalText(operand, bindings);
|
|
7811
|
+
if (word === null || word.includes("\0")) return [];
|
|
7812
|
+
words.push(word);
|
|
7813
|
+
}
|
|
7814
|
+
if (executable !== null && words.length) words[0] = executable;
|
|
7815
|
+
const resolved = envCommand(words);
|
|
7816
|
+
const program = shellProgramOperand(resolved);
|
|
7817
|
+
if (program !== null && program.kind === "command") {
|
|
7818
|
+
return literalShellCalls(resolved[program.index], source);
|
|
7819
|
+
}
|
|
7820
|
+
const call = literalScriptCall(resolved);
|
|
7821
|
+
return call === null ? [] : [call];
|
|
7822
|
+
}
|
|
7823
|
+
function decodeProcessCall(node, module, method, source, bindings) {
|
|
7824
|
+
if (module === "os" && !OS_FUNCS.has(method)) return [];
|
|
7825
|
+
const argumentName = module === "subprocess" ? "args" : method === "system" ? "command" : method === "popen" ? "cmd" : null;
|
|
7826
|
+
const args = parseCallArgs(node);
|
|
7827
|
+
if (args === null || args.hasStar || args.keywords === null) return [];
|
|
7828
|
+
const options = args.keywords;
|
|
7829
|
+
const named = argumentName === null ? void 0 : options.get(argumentName);
|
|
7830
|
+
if (named !== void 0 && args.positional.length) return [];
|
|
7831
|
+
const operand = args.positional.length ? args.positional[0] : named ?? null;
|
|
7832
|
+
if (!operand) return [];
|
|
7833
|
+
if (module === "subprocess") {
|
|
7834
|
+
for (const [name, index] of [["executable", 2], ["shell", 8], ["cwd", 9]]) {
|
|
7835
|
+
if (args.positional.length > index) {
|
|
7836
|
+
if (options.has(name)) return [];
|
|
7837
|
+
options.set(name, args.positional[index]);
|
|
7838
|
+
}
|
|
7839
|
+
}
|
|
7840
|
+
const calls = subprocessCalls(operand, options, source, bindings);
|
|
7841
|
+
const directoryNode = options.get("cwd");
|
|
7842
|
+
if (!calls.length || directoryNode === void 0) return calls;
|
|
7843
|
+
let directory;
|
|
7844
|
+
if (directoryNode.name === "None") {
|
|
7845
|
+
return calls;
|
|
7846
|
+
} else if (directoryNode.name === "String") {
|
|
7847
|
+
const decoded = decodePythonStringLiteral(srcSlice(directoryNode));
|
|
7848
|
+
if (decoded === null || decoded.value === "") return [];
|
|
7849
|
+
directory = decoded.value;
|
|
7850
|
+
} else if (isConstantNode(directoryNode)) {
|
|
7851
|
+
return [];
|
|
7852
|
+
} else {
|
|
7853
|
+
directory = literalText(directoryNode, bindings);
|
|
7854
|
+
}
|
|
7855
|
+
if (directory === "" || directory !== null && directory.includes("\0")) return [];
|
|
7856
|
+
const launchCwd = directoryFor(bindings, directory);
|
|
7857
|
+
for (const call of calls) call.launchCwd = launchCwd;
|
|
7858
|
+
return calls;
|
|
7859
|
+
}
|
|
7860
|
+
const text = literalText(operand, bindings);
|
|
7861
|
+
return text === null ? [] : literalShellCalls(text, source);
|
|
7862
|
+
}
|
|
7863
|
+
function isNodeReachable(node, ctx) {
|
|
7864
|
+
if (ctx.reachableLines === null) return true;
|
|
7865
|
+
return ctx.reachableLines.has(lineAt(ctx.lineStarts, node.from));
|
|
7866
|
+
}
|
|
7867
|
+
function forgetTarget(node, bindings) {
|
|
7868
|
+
const cursor = node.cursor();
|
|
7163
7869
|
cursor.iterate((n) => {
|
|
7164
|
-
|
|
7165
|
-
|
|
7166
|
-
|
|
7167
|
-
|
|
7168
|
-
|
|
7169
|
-
|
|
7170
|
-
|
|
7171
|
-
|
|
7172
|
-
|
|
7173
|
-
const
|
|
7174
|
-
const
|
|
7175
|
-
|
|
7176
|
-
|
|
7177
|
-
if (
|
|
7178
|
-
|
|
7179
|
-
|
|
7180
|
-
|
|
7181
|
-
|
|
7182
|
-
|
|
7183
|
-
|
|
7184
|
-
|
|
7185
|
-
|
|
7186
|
-
|
|
7870
|
+
if (n.node.name === "VariableName") bindings.forget(srcSlice(n.node));
|
|
7871
|
+
return true;
|
|
7872
|
+
});
|
|
7873
|
+
}
|
|
7874
|
+
function visitExpression(node, bindings, ctx, standaloneRoot = false) {
|
|
7875
|
+
const stack = [
|
|
7876
|
+
{ node, standalone: standaloneRoot }
|
|
7877
|
+
];
|
|
7878
|
+
while (stack.length) {
|
|
7879
|
+
const entry = stack.pop();
|
|
7880
|
+
const current = entry.node;
|
|
7881
|
+
if (current.name === "CallExpression") {
|
|
7882
|
+
handleCall(current, bindings, ctx, entry.standalone);
|
|
7883
|
+
} else if (current.name === "NamedExpression") {
|
|
7884
|
+
const target = current.firstChild;
|
|
7885
|
+
const value = current.lastChild;
|
|
7886
|
+
const literal = value === null || sameNode(value, target) ? null : literalText(value, bindings);
|
|
7887
|
+
if (target !== null && target.name === "VariableName") {
|
|
7888
|
+
bindings.forget(srcSlice(target));
|
|
7889
|
+
if (literal !== null) bindings.strings.set(srcSlice(target), literal);
|
|
7890
|
+
}
|
|
7891
|
+
} else if (current.name === "LambdaExpression") {
|
|
7892
|
+
const params = current.getChild("ParamList");
|
|
7893
|
+
const colon = current.getChild(":");
|
|
7894
|
+
if (params) {
|
|
7895
|
+
let c2 = params.firstChild;
|
|
7896
|
+
while (c2) {
|
|
7897
|
+
if (c2.name !== "ParamList") visitExpression(c2, bindings, ctx);
|
|
7898
|
+
c2 = c2.nextSibling;
|
|
7187
7899
|
}
|
|
7188
|
-
|
|
7189
|
-
|
|
7190
|
-
|
|
7191
|
-
|
|
7192
|
-
|
|
7193
|
-
|
|
7194
|
-
|
|
7900
|
+
}
|
|
7901
|
+
const local = bindings.fork();
|
|
7902
|
+
if (params) {
|
|
7903
|
+
let c2 = params.firstChild;
|
|
7904
|
+
while (c2) {
|
|
7905
|
+
if (c2.name === "VariableName") local.forget(srcSlice(c2));
|
|
7906
|
+
c2 = c2.nextSibling;
|
|
7195
7907
|
}
|
|
7196
7908
|
}
|
|
7197
|
-
if (
|
|
7198
|
-
|
|
7199
|
-
if (sc) add(sc);
|
|
7909
|
+
if (colon !== null && colon.nextSibling !== null) {
|
|
7910
|
+
visitExpression(colon.nextSibling, local, ctx);
|
|
7200
7911
|
}
|
|
7201
|
-
|
|
7202
|
-
|
|
7203
|
-
|
|
7204
|
-
|
|
7912
|
+
continue;
|
|
7913
|
+
}
|
|
7914
|
+
const children = [];
|
|
7915
|
+
let c = current.lastChild;
|
|
7916
|
+
while (c) {
|
|
7917
|
+
children.push(c);
|
|
7918
|
+
c = c.prevSibling;
|
|
7919
|
+
}
|
|
7920
|
+
for (const child of children) stack.push({ node: child, standalone: false });
|
|
7921
|
+
}
|
|
7922
|
+
}
|
|
7923
|
+
function functionNameNode(stmt) {
|
|
7924
|
+
let c = stmt.firstChild;
|
|
7925
|
+
while (c) {
|
|
7926
|
+
if (c.name === "VariableName") return c;
|
|
7927
|
+
if (c.name === "Body") return null;
|
|
7928
|
+
c = c.nextSibling;
|
|
7929
|
+
}
|
|
7930
|
+
return null;
|
|
7931
|
+
}
|
|
7932
|
+
function parameterNames(stmt) {
|
|
7933
|
+
const params = stmt.getChild("ParamList");
|
|
7934
|
+
if (!params) return [];
|
|
7935
|
+
const names = [];
|
|
7936
|
+
let c = params.firstChild;
|
|
7937
|
+
while (c) {
|
|
7938
|
+
if (c.name === "VariableName") names.push(srcSlice(c));
|
|
7939
|
+
c = c.nextSibling;
|
|
7940
|
+
}
|
|
7941
|
+
return names;
|
|
7942
|
+
}
|
|
7943
|
+
function isDocstringStatement(stmt) {
|
|
7944
|
+
if (stmt.name !== "ExpressionStatement") return false;
|
|
7945
|
+
const value = firstInnerNode(stmt);
|
|
7946
|
+
return value !== null && ["String", "ContinuedString", "FormatString"].includes(value.name);
|
|
7947
|
+
}
|
|
7948
|
+
function bodyStatements(body) {
|
|
7949
|
+
return body === null ? [] : bodyStmts(body);
|
|
7950
|
+
}
|
|
7951
|
+
function containsCallOrWalrus(node) {
|
|
7952
|
+
let found = false;
|
|
7953
|
+
const cursor = node.cursor();
|
|
7954
|
+
cursor.iterate((n) => {
|
|
7955
|
+
if (n.node.name === "CallExpression" || n.node.name === "NamedExpression") {
|
|
7956
|
+
found = true;
|
|
7957
|
+
return false;
|
|
7958
|
+
}
|
|
7959
|
+
return true;
|
|
7960
|
+
});
|
|
7961
|
+
return found;
|
|
7962
|
+
}
|
|
7963
|
+
function recordWrapper(stmt, bindings) {
|
|
7964
|
+
const params = stmt.getChild("ParamList");
|
|
7965
|
+
if (params !== null) {
|
|
7966
|
+
let c = params.firstChild;
|
|
7967
|
+
while (c) {
|
|
7968
|
+
if (c.name !== "(" && c.name !== ")") return false;
|
|
7969
|
+
c = c.nextSibling;
|
|
7970
|
+
}
|
|
7971
|
+
}
|
|
7972
|
+
const body = stmt.getChild("Body");
|
|
7973
|
+
if (body === null) return false;
|
|
7974
|
+
let statements = bodyStatements(body);
|
|
7975
|
+
if (statements.length && isDocstringStatement(statements[0])) statements = statements.slice(1);
|
|
7976
|
+
if (statements.length !== 1) return false;
|
|
7977
|
+
const only = statements[0];
|
|
7978
|
+
if (only.name !== "ExpressionStatement") return false;
|
|
7979
|
+
const value = firstInnerNode(only);
|
|
7980
|
+
if (value === null || value.name !== "CallExpression") return false;
|
|
7981
|
+
const func = unwrapParens(value.firstChild);
|
|
7982
|
+
if (func === null || func.name !== "VariableName" || !bindings.functions.has(srcSlice(func))) {
|
|
7983
|
+
return false;
|
|
7984
|
+
}
|
|
7985
|
+
const argList = value.getChild("ArgList");
|
|
7986
|
+
if (argList !== null && containsCallOrWalrus(argList)) return false;
|
|
7987
|
+
const nameNode = functionNameNode(stmt);
|
|
7988
|
+
if (nameNode === null) return false;
|
|
7989
|
+
bindings.forget(srcSlice(nameNode));
|
|
7990
|
+
bindings.wrappers.set(srcSlice(nameNode), value);
|
|
7991
|
+
return true;
|
|
7992
|
+
}
|
|
7993
|
+
function wrapperCalls(node, bindings, ctx) {
|
|
7994
|
+
const func = unwrapParens(node.firstChild);
|
|
7995
|
+
if (!func || func.name !== "VariableName") return null;
|
|
7996
|
+
const args = parseCallArgs(node);
|
|
7997
|
+
if (args === null || args.hasStar || args.positional.length || args.keywords !== null && args.keywords.size > 0) {
|
|
7998
|
+
return null;
|
|
7999
|
+
}
|
|
8000
|
+
const stored = bindings.wrappers.get(srcSlice(func));
|
|
8001
|
+
if (stored === void 0) return null;
|
|
8002
|
+
const identity = callIdentity(stored, bindings);
|
|
8003
|
+
if (identity === null) return [];
|
|
8004
|
+
const calls = decodeProcessCall(stored, identity[0], identity[1], ctx.source, bindings);
|
|
8005
|
+
for (const call of calls) {
|
|
8006
|
+
if (call.launchCwd === void 0 || call.launchCwd === null) {
|
|
8007
|
+
call.launchCwd = bindings.cwd === null ? "." : bindings.cwd;
|
|
8008
|
+
}
|
|
8009
|
+
}
|
|
8010
|
+
return calls;
|
|
8011
|
+
}
|
|
8012
|
+
function handleCall(node, bindings, ctx, standalone) {
|
|
8013
|
+
if (!isNodeReachable(node, ctx)) return;
|
|
8014
|
+
const identity = callIdentity(node, bindings);
|
|
8015
|
+
if (identity === null) {
|
|
8016
|
+
const forwarded = wrapperCalls(node, bindings, ctx);
|
|
8017
|
+
if (forwarded !== null) {
|
|
8018
|
+
ctx.found.set(node.from, forwarded);
|
|
8019
|
+
return;
|
|
8020
|
+
}
|
|
8021
|
+
if (!isLiteralPrint(node, bindings)) bindings.invalidate();
|
|
8022
|
+
return;
|
|
8023
|
+
}
|
|
8024
|
+
const [module, method] = identity;
|
|
8025
|
+
if (module === "os" && CWD_METHODS.has(method)) {
|
|
8026
|
+
observeChdir(node, bindings, method, standalone);
|
|
8027
|
+
return;
|
|
8028
|
+
}
|
|
8029
|
+
const calls = decodeProcessCall(node, module, method, ctx.source, bindings);
|
|
8030
|
+
if (!calls.length) return;
|
|
8031
|
+
let directory = bindings.cwd;
|
|
8032
|
+
if (directory === null) {
|
|
8033
|
+
const func = unwrapParens(node.firstChild);
|
|
8034
|
+
const isModuleAttribute = func !== null && func.name === "MemberExpression" && unwrapParens(func.firstChild)?.name === "VariableName" && srcSlice(unwrapParens(func.firstChild)) === module;
|
|
8035
|
+
let capturedArgument = false;
|
|
8036
|
+
const cursor = node.cursor();
|
|
8037
|
+
cursor.iterate((n) => {
|
|
8038
|
+
if (n.node.name === "VariableName" && bindings.strings.has(srcSlice(n.node))) {
|
|
8039
|
+
capturedArgument = true;
|
|
8040
|
+
return false;
|
|
7205
8041
|
}
|
|
8042
|
+
return true;
|
|
8043
|
+
});
|
|
8044
|
+
if (!isModuleAttribute || capturedArgument) directory = ".";
|
|
8045
|
+
}
|
|
8046
|
+
for (const call of calls) {
|
|
8047
|
+
if (call.launchCwd === void 0 || call.launchCwd === null) call.launchCwd = directory;
|
|
8048
|
+
}
|
|
8049
|
+
ctx.found.set(node.from, calls);
|
|
8050
|
+
}
|
|
8051
|
+
function assignedNamesInBody(body) {
|
|
8052
|
+
const assigned = /* @__PURE__ */ new Set();
|
|
8053
|
+
const external = /* @__PURE__ */ new Set();
|
|
8054
|
+
const walk = (node) => {
|
|
8055
|
+
if (node.name === "AssignStatement") {
|
|
8056
|
+
const { targets } = assignmentParts(node);
|
|
8057
|
+
for (const target of targets) assigned.add(srcSlice(target));
|
|
8058
|
+
} else if (node.name === "UpdateStatement") {
|
|
8059
|
+
const target = node.firstChild;
|
|
8060
|
+
if (target && target.name === "VariableName") assigned.add(srcSlice(target));
|
|
8061
|
+
} else if (node.name === "ForStatement") {
|
|
8062
|
+
const forToken = node.getChild("for");
|
|
8063
|
+
const target = forToken === null ? null : forToken.nextSibling;
|
|
8064
|
+
if (target) forgetTargetInto(target, assigned);
|
|
8065
|
+
} else if (node.name === "FunctionDefinition" || node.name === "ClassDefinition") {
|
|
8066
|
+
const name = functionNameNode(node);
|
|
8067
|
+
if (name) assigned.add(srcSlice(name));
|
|
8068
|
+
} else if (node.name === "ImportStatement") {
|
|
8069
|
+
const text = srcSlice(node);
|
|
8070
|
+
for (const part of text.split(",")) {
|
|
8071
|
+
const m = /([A-Za-z_][\w.]*)(?:\s+as\s+([A-Za-z_][\w.]*))?$/.exec(part.trim());
|
|
8072
|
+
if (m) assigned.add(m[2] || m[1].split(".")[0]);
|
|
8073
|
+
}
|
|
8074
|
+
} else if (node.name === "WithStatement" || node.name === "NamedExpression") {
|
|
8075
|
+
const cursor = node.cursor();
|
|
8076
|
+
let afterAs = false;
|
|
8077
|
+
cursor.iterate((n) => {
|
|
8078
|
+
if (n.node.name === "as") afterAs = true;
|
|
8079
|
+
else if (afterAs && n.node.name === "VariableName") assigned.add(srcSlice(n.node));
|
|
8080
|
+
return true;
|
|
8081
|
+
});
|
|
8082
|
+
} else if (node.name === "GlobalStatement" || node.name === "NonlocalStatement") {
|
|
8083
|
+
const cursor = node.cursor();
|
|
8084
|
+
cursor.iterate((n) => {
|
|
8085
|
+
if (n.node.name === "VariableName") external.add(srcSlice(n.node));
|
|
8086
|
+
return true;
|
|
8087
|
+
});
|
|
7206
8088
|
}
|
|
8089
|
+
let c = node.firstChild;
|
|
8090
|
+
while (c) {
|
|
8091
|
+
if (!(node.name === "FunctionDefinition" || node.name === "ClassDefinition")) walk(c);
|
|
8092
|
+
c = c.nextSibling;
|
|
8093
|
+
}
|
|
8094
|
+
};
|
|
8095
|
+
walk(body);
|
|
8096
|
+
return { assigned, external };
|
|
8097
|
+
}
|
|
8098
|
+
function forgetTargetInto(node, names) {
|
|
8099
|
+
const cursor = node.cursor();
|
|
8100
|
+
cursor.iterate((n) => {
|
|
8101
|
+
if (n.node.name === "VariableName") names.add(srcSlice(n.node));
|
|
7207
8102
|
return true;
|
|
7208
8103
|
});
|
|
7209
|
-
|
|
7210
|
-
|
|
8104
|
+
}
|
|
8105
|
+
function extractFunction(stmt, bindings, ctx) {
|
|
8106
|
+
const body = stmt.getChild("Body");
|
|
8107
|
+
let c = stmt.firstChild;
|
|
8108
|
+
while (c) {
|
|
8109
|
+
if (!sameNode(c, body) && c.name !== "def" && c.name !== "async") {
|
|
8110
|
+
visitExpression(c, bindings, ctx);
|
|
8111
|
+
}
|
|
8112
|
+
c = c.nextSibling;
|
|
8113
|
+
}
|
|
8114
|
+
if (recordWrapper(stmt, bindings)) return;
|
|
8115
|
+
const local = bindings.fork();
|
|
8116
|
+
for (const name of parameterNames(stmt)) local.forget(name);
|
|
8117
|
+
if (body !== null) {
|
|
8118
|
+
const { assigned, external } = assignedNamesInBody(body);
|
|
8119
|
+
for (const name of assigned) {
|
|
8120
|
+
if (!external.has(name)) local.forget(name);
|
|
8121
|
+
}
|
|
8122
|
+
extractBlock(bodyStatements(body), local, ctx);
|
|
8123
|
+
}
|
|
8124
|
+
if (stmt.name === "ClassDefinition") bindings.cwd = local.cwd;
|
|
8125
|
+
const nameNode = functionNameNode(stmt);
|
|
8126
|
+
if (nameNode) bindings.forget(srcSlice(nameNode));
|
|
8127
|
+
}
|
|
8128
|
+
function extractIfSections(sections, decisions, idx, bindings, ctx) {
|
|
8129
|
+
if (idx >= sections.length) return;
|
|
8130
|
+
const section = sections[idx];
|
|
8131
|
+
if (section.cond) visitExpression(section.cond, bindings, ctx);
|
|
8132
|
+
if (section.isElse) {
|
|
8133
|
+
if (section.body) extractBlock(bodyStatements(section.body), bindings, ctx);
|
|
8134
|
+
return;
|
|
8135
|
+
}
|
|
8136
|
+
const decision = decisions[idx] ?? null;
|
|
8137
|
+
if (decision === true) {
|
|
8138
|
+
if (section.body) extractBlock(bodyStatements(section.body), bindings, ctx);
|
|
8139
|
+
return;
|
|
8140
|
+
}
|
|
8141
|
+
if (decision === false) {
|
|
8142
|
+
extractIfSections(sections, decisions, idx + 1, bindings, ctx);
|
|
8143
|
+
return;
|
|
8144
|
+
}
|
|
8145
|
+
const left = bindings.fork();
|
|
8146
|
+
if (section.body) extractBlock(bodyStatements(section.body), left, ctx);
|
|
8147
|
+
const right = bindings.fork();
|
|
8148
|
+
extractIfSections(sections, decisions, idx + 1, right, ctx);
|
|
8149
|
+
bindings.merge([left, right]);
|
|
8150
|
+
}
|
|
8151
|
+
function extractBlock(stmts, bindings, ctx) {
|
|
8152
|
+
for (const stmt of stmts) {
|
|
8153
|
+
if (!isNodeReachable(stmt, ctx) && !(stmt.name === "IfStatement" && ctx.ifDecisions.has(stmt.from))) {
|
|
8154
|
+
continue;
|
|
8155
|
+
}
|
|
8156
|
+
extractStmt(stmt, bindings, ctx);
|
|
8157
|
+
}
|
|
8158
|
+
}
|
|
8159
|
+
function extractStatementExpression(stmt, bindings, ctx) {
|
|
8160
|
+
const value = firstInnerNode(stmt);
|
|
8161
|
+
if (value === null) return;
|
|
8162
|
+
visitExpression(value, bindings, ctx, true);
|
|
8163
|
+
}
|
|
8164
|
+
function extractStmt(stmt, bindings, ctx) {
|
|
8165
|
+
switch (stmt.name) {
|
|
8166
|
+
case "ImportStatement":
|
|
8167
|
+
recordImportText(stmt, bindings);
|
|
8168
|
+
return;
|
|
8169
|
+
case "DecoratedStatement": {
|
|
8170
|
+
let c = stmt.firstChild;
|
|
8171
|
+
while (c) {
|
|
8172
|
+
if (c.name === "Decorator") visitExpression(c, bindings, ctx);
|
|
8173
|
+
else if (c.name === "FunctionDefinition" || c.name === "ClassDefinition") {
|
|
8174
|
+
extractFunction(c, bindings, ctx);
|
|
8175
|
+
}
|
|
8176
|
+
c = c.nextSibling;
|
|
8177
|
+
}
|
|
8178
|
+
return;
|
|
8179
|
+
}
|
|
8180
|
+
case "FunctionDefinition":
|
|
8181
|
+
case "ClassDefinition":
|
|
8182
|
+
extractFunction(stmt, bindings, ctx);
|
|
8183
|
+
return;
|
|
8184
|
+
case "IfStatement": {
|
|
8185
|
+
const sections = collectIfSections(stmt);
|
|
8186
|
+
const decisions = ctx.ifDecisions.get(stmt.from) ?? [];
|
|
8187
|
+
extractIfSections(sections, decisions, 0, bindings, ctx);
|
|
8188
|
+
return;
|
|
8189
|
+
}
|
|
8190
|
+
case "ForStatement": {
|
|
8191
|
+
const forToken = stmt.getChild("for");
|
|
8192
|
+
const target = forToken === null ? null : forToken.nextSibling;
|
|
8193
|
+
const inToken = target === null ? null : target.nextSibling;
|
|
8194
|
+
const iter = inToken === null ? null : inToken.nextSibling;
|
|
8195
|
+
if (iter) visitExpression(iter, bindings, ctx);
|
|
8196
|
+
const bodies = stmt.getChildren("Body");
|
|
8197
|
+
if (bodies.length) {
|
|
8198
|
+
const bodyBindings = bindings.fork();
|
|
8199
|
+
if (target) forgetTarget(target, bodyBindings);
|
|
8200
|
+
extractBlock(bodyStatements(bodies[0]), bodyBindings, ctx);
|
|
8201
|
+
bindings.merge([bindings, bodyBindings]);
|
|
8202
|
+
}
|
|
8203
|
+
if (bodies.length > 1) {
|
|
8204
|
+
const elseBindings = bindings.fork();
|
|
8205
|
+
extractBlock(bodyStatements(bodies[1]), elseBindings, ctx);
|
|
8206
|
+
bindings.merge([bindings, elseBindings]);
|
|
8207
|
+
}
|
|
8208
|
+
return;
|
|
8209
|
+
}
|
|
8210
|
+
case "WhileStatement": {
|
|
8211
|
+
const whileToken = stmt.getChild("while");
|
|
8212
|
+
const body = stmt.getChild("Body");
|
|
8213
|
+
if (whileToken !== null) {
|
|
8214
|
+
const test = whileToken.nextSibling;
|
|
8215
|
+
if (test && !sameNode(test, body)) visitExpression(test, bindings, ctx);
|
|
8216
|
+
}
|
|
8217
|
+
const bodies = stmt.getChildren("Body");
|
|
8218
|
+
if (bodies.length) {
|
|
8219
|
+
const bodyBindings = bindings.fork();
|
|
8220
|
+
extractBlock(bodyStatements(bodies[0]), bodyBindings, ctx);
|
|
8221
|
+
bindings.merge([bindings, bodyBindings]);
|
|
8222
|
+
}
|
|
8223
|
+
if (bodies.length > 1) {
|
|
8224
|
+
const elseBindings = bindings.fork();
|
|
8225
|
+
extractBlock(bodyStatements(bodies[1]), elseBindings, ctx);
|
|
8226
|
+
bindings.merge([bindings, elseBindings]);
|
|
8227
|
+
}
|
|
8228
|
+
return;
|
|
8229
|
+
}
|
|
8230
|
+
case "WithStatement": {
|
|
8231
|
+
const body = stmt.getChild("Body");
|
|
8232
|
+
const bodyBindings = bindings.fork();
|
|
8233
|
+
let afterAs = false;
|
|
8234
|
+
let c = stmt.firstChild;
|
|
8235
|
+
while (c && !sameNode(c, body)) {
|
|
8236
|
+
if (c.name === "as") afterAs = true;
|
|
8237
|
+
else if (afterAs && c.name === "VariableName") {
|
|
8238
|
+
forgetTarget(c, bodyBindings);
|
|
8239
|
+
afterAs = false;
|
|
8240
|
+
} else if (!["with", ",", ":"].includes(c.name)) {
|
|
8241
|
+
visitExpression(c, bodyBindings, ctx);
|
|
8242
|
+
afterAs = false;
|
|
8243
|
+
}
|
|
8244
|
+
c = c.nextSibling;
|
|
8245
|
+
}
|
|
8246
|
+
if (body) extractBlock(bodyStatements(body), bodyBindings, ctx);
|
|
8247
|
+
bindings.merge([bindings, bodyBindings]);
|
|
8248
|
+
return;
|
|
8249
|
+
}
|
|
8250
|
+
case "TryStatement": {
|
|
8251
|
+
const bodies = stmt.getChildren("Body");
|
|
8252
|
+
let finallyToken = null;
|
|
8253
|
+
let c = stmt.firstChild;
|
|
8254
|
+
while (c) {
|
|
8255
|
+
if (c.name === "finally") finallyToken = c;
|
|
8256
|
+
c = c.nextSibling;
|
|
8257
|
+
}
|
|
8258
|
+
const finalBody = finallyToken === null ? null : finallyToken.nextSibling;
|
|
8259
|
+
const alternatives = [];
|
|
8260
|
+
let inExcept = false;
|
|
8261
|
+
const handlerNames = [];
|
|
8262
|
+
c = stmt.firstChild;
|
|
8263
|
+
while (c) {
|
|
8264
|
+
if (c.name === "except") {
|
|
8265
|
+
inExcept = true;
|
|
8266
|
+
handlerNames.length = 0;
|
|
8267
|
+
} else if (c.name === "as" && inExcept) {
|
|
8268
|
+
const nameNode = c.nextSibling;
|
|
8269
|
+
if (nameNode && nameNode.name === "VariableName") handlerNames.push(srcSlice(nameNode));
|
|
8270
|
+
} else if (c.name === "Body" && !sameNode(c, finalBody)) {
|
|
8271
|
+
const fork = bindings.fork();
|
|
8272
|
+
for (const name of handlerNames) fork.forget(name);
|
|
8273
|
+
handlerNames.length = 0;
|
|
8274
|
+
inExcept = false;
|
|
8275
|
+
extractBlock(bodyStatements(c), fork, ctx);
|
|
8276
|
+
alternatives.push(fork);
|
|
8277
|
+
} else if (c.name === "else" || c.name === "finally") {
|
|
8278
|
+
inExcept = false;
|
|
8279
|
+
}
|
|
8280
|
+
c = c.nextSibling;
|
|
8281
|
+
}
|
|
8282
|
+
bindings.merge([bindings, ...alternatives]);
|
|
8283
|
+
if (finalBody) extractBlock(bodyStatements(finalBody), bindings, ctx);
|
|
8284
|
+
return;
|
|
8285
|
+
}
|
|
8286
|
+
case "MatchStatement": {
|
|
8287
|
+
const matchToken = stmt.getChild("match");
|
|
8288
|
+
const matchBody = stmt.getChild("MatchBody");
|
|
8289
|
+
if (matchToken !== null && matchBody !== null) {
|
|
8290
|
+
const subject = matchToken.nextSibling;
|
|
8291
|
+
if (subject && !sameNode(subject, matchBody)) visitExpression(subject, bindings, ctx);
|
|
8292
|
+
}
|
|
8293
|
+
const alternatives = [];
|
|
8294
|
+
if (matchBody !== null) {
|
|
8295
|
+
for (const clause of matchBody.getChildren("MatchClause")) {
|
|
8296
|
+
const fork = bindings.fork();
|
|
8297
|
+
let c = clause.firstChild;
|
|
8298
|
+
const body = clause.getChild("Body");
|
|
8299
|
+
while (c && !sameNode(c, body)) {
|
|
8300
|
+
if (c.name !== "case") visitExpression(c, fork, ctx);
|
|
8301
|
+
c = c.nextSibling;
|
|
8302
|
+
}
|
|
8303
|
+
if (body) extractBlock(bodyStatements(body), fork, ctx);
|
|
8304
|
+
alternatives.push(fork);
|
|
8305
|
+
}
|
|
8306
|
+
}
|
|
8307
|
+
bindings.merge([bindings, ...alternatives]);
|
|
8308
|
+
return;
|
|
8309
|
+
}
|
|
8310
|
+
case "AssignStatement": {
|
|
8311
|
+
const { targets, value } = assignmentParts(stmt);
|
|
8312
|
+
if (value) visitExpression(value, bindings, ctx);
|
|
8313
|
+
if (targets.length === 1) {
|
|
8314
|
+
bindings.bindString(srcSlice(targets[0]), literalText(value, bindings));
|
|
8315
|
+
} else {
|
|
8316
|
+
for (const target of targets) forgetTarget(target, bindings);
|
|
8317
|
+
}
|
|
8318
|
+
return;
|
|
8319
|
+
}
|
|
8320
|
+
case "UpdateStatement": {
|
|
8321
|
+
const target = stmt.firstChild;
|
|
8322
|
+
const value = stmt.lastChild;
|
|
8323
|
+
if (value && value !== target) visitExpression(value, bindings, ctx);
|
|
8324
|
+
if (target && target.name === "VariableName") bindings.forget(srcSlice(target));
|
|
8325
|
+
return;
|
|
8326
|
+
}
|
|
8327
|
+
case "ExpressionStatement":
|
|
8328
|
+
extractStatementExpression(stmt, bindings, ctx);
|
|
8329
|
+
return;
|
|
8330
|
+
default: {
|
|
8331
|
+
let c = stmt.firstChild;
|
|
8332
|
+
while (c) {
|
|
8333
|
+
if (c.name !== "del") visitExpression(c, bindings, ctx);
|
|
8334
|
+
c = c.nextSibling;
|
|
8335
|
+
}
|
|
8336
|
+
}
|
|
8337
|
+
}
|
|
8338
|
+
}
|
|
8339
|
+
function relativeImportCalls(tree) {
|
|
8340
|
+
const calls = [];
|
|
8341
|
+
const cursor = tree.cursor();
|
|
8342
|
+
cursor.iterate((n) => {
|
|
7211
8343
|
const node = n.node;
|
|
7212
8344
|
if (node.name !== "ImportStatement") return true;
|
|
7213
|
-
const
|
|
7214
|
-
|
|
7215
|
-
|
|
7216
|
-
if (m) {
|
|
7217
|
-
|
|
7218
|
-
|
|
7219
|
-
|
|
8345
|
+
const text = srcSlice(node);
|
|
8346
|
+
const m = text.match(/^\s*from\s+(\.+)([A-Za-z_][\w.]*)?\s+import\s+([\s\S]+)$/);
|
|
8347
|
+
if (!m) return true;
|
|
8348
|
+
if (m[2]) {
|
|
8349
|
+
calls.push({
|
|
8350
|
+
path: m[2].replace(/\./g, "/") + ".py",
|
|
8351
|
+
args: [],
|
|
8352
|
+
interpreter: "python3",
|
|
8353
|
+
isImport: true
|
|
8354
|
+
});
|
|
8355
|
+
}
|
|
8356
|
+
for (const part of m[3].replace(/[()]/g, "").split(",")) {
|
|
8357
|
+
const name = part.trim().replace(/\s+as\s+\w+$/, "").trim();
|
|
8358
|
+
if (name && name !== "*" && /^[A-Za-z_][\w.]*$/.test(name)) {
|
|
8359
|
+
calls.push({ path: name.replace(/\./g, "/") + ".py", args: [], interpreter: "python3", isImport: true });
|
|
7220
8360
|
}
|
|
7221
8361
|
}
|
|
7222
8362
|
return true;
|
|
7223
8363
|
});
|
|
7224
8364
|
return calls;
|
|
7225
8365
|
}
|
|
8366
|
+
function extractCallsFromTree(tree, reachableLines, ifDecisions, lineStarts) {
|
|
8367
|
+
const ctx = {
|
|
8368
|
+
source: null,
|
|
8369
|
+
reachableLines,
|
|
8370
|
+
lineStarts,
|
|
8371
|
+
ifDecisions,
|
|
8372
|
+
found: /* @__PURE__ */ new Map()
|
|
8373
|
+
};
|
|
8374
|
+
const bindings = new CallBindings(null);
|
|
8375
|
+
extractBlock(bodyStmts(tree), bindings, ctx);
|
|
8376
|
+
const calls = [];
|
|
8377
|
+
const queue = [tree];
|
|
8378
|
+
for (let index = 0; index < queue.length; index++) {
|
|
8379
|
+
const node = queue[index];
|
|
8380
|
+
if (node.name === "CallExpression") {
|
|
8381
|
+
const found = ctx.found.get(node.from);
|
|
8382
|
+
if (found !== void 0) calls.push(...found);
|
|
8383
|
+
}
|
|
8384
|
+
let c = node.firstChild;
|
|
8385
|
+
while (c) {
|
|
8386
|
+
queue.push(c);
|
|
8387
|
+
c = c.nextSibling;
|
|
8388
|
+
}
|
|
8389
|
+
}
|
|
8390
|
+
calls.push(...relativeImportCalls(tree));
|
|
8391
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8392
|
+
const unique = [];
|
|
8393
|
+
for (const call of calls) {
|
|
8394
|
+
const key = callKey(call);
|
|
8395
|
+
if (seen.has(key)) continue;
|
|
8396
|
+
seen.add(key);
|
|
8397
|
+
unique.push(call);
|
|
8398
|
+
}
|
|
8399
|
+
return unique;
|
|
8400
|
+
}
|
|
7226
8401
|
function extractCallsRegex(content) {
|
|
7227
8402
|
const calls = [];
|
|
7228
8403
|
CHILD_CALL_RE.lastIndex = 0;
|
|
7229
8404
|
let m;
|
|
7230
8405
|
while ((m = CHILD_CALL_RE.exec(content)) !== null) {
|
|
7231
8406
|
const interp = m[1];
|
|
7232
|
-
const
|
|
8407
|
+
const path10 = m[2].trim();
|
|
7233
8408
|
let rest = m[3].trim();
|
|
7234
|
-
if (
|
|
8409
|
+
if (path10.startsWith("-") || path10.startsWith("$") || path10.includes("/dev/")) continue;
|
|
7235
8410
|
rest = rest.split(/[;|&<>]/)[0].trim();
|
|
7236
8411
|
const args = [];
|
|
7237
8412
|
for (const tm of rest.matchAll(/(["'])(.*?)\1|(\S+)/g)) {
|
|
7238
8413
|
args.push(tm[1] ? tm[2] : tm[3]);
|
|
7239
8414
|
}
|
|
7240
|
-
calls.push({ path:
|
|
8415
|
+
calls.push({ path: path10, args, interpreter: interp });
|
|
7241
8416
|
}
|
|
7242
8417
|
return calls;
|
|
7243
8418
|
}
|
|
7244
|
-
var MAX_LINES, PURE_BUILTINS, CHILD_CALL_RE, SUBPROCESS_FUNCS, OS_FUNCS, SOURCE, PythonBackend;
|
|
8419
|
+
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;
|
|
7245
8420
|
var init_python_backend = __esm({
|
|
7246
8421
|
"src/engine/script-engine/backends/python-backend.ts"() {
|
|
7247
8422
|
"use strict";
|
|
7248
8423
|
init_esm_shims();
|
|
8424
|
+
init_ir();
|
|
7249
8425
|
MAX_LINES = 500;
|
|
7250
8426
|
PURE_BUILTINS = /* @__PURE__ */ new Set([
|
|
7251
8427
|
"len",
|
|
@@ -7294,9 +8470,86 @@ var init_python_backend = __esm({
|
|
|
7294
8470
|
SUBPROCESS_FUNCS = /* @__PURE__ */ new Set(["run", "call", "Popen", "check_call", "check_output"]);
|
|
7295
8471
|
OS_FUNCS = /* @__PURE__ */ new Set(["system", "popen", "popen2", "popen3", "popen4"]);
|
|
7296
8472
|
SOURCE = "";
|
|
8473
|
+
CWD_METHODS = /* @__PURE__ */ new Set(["chdir", "fchdir"]);
|
|
8474
|
+
CALL_FUNCTIONS = {
|
|
8475
|
+
os: /* @__PURE__ */ new Set([...OS_FUNCS, ...CWD_METHODS]),
|
|
8476
|
+
subprocess: SUBPROCESS_FUNCS
|
|
8477
|
+
};
|
|
8478
|
+
SHELL_INTERPRETERS = /* @__PURE__ */ new Set(["bash", "dash", "sh", "zsh"]);
|
|
8479
|
+
SCRIPT_INTERPRETERS = /* @__PURE__ */ new Set([
|
|
8480
|
+
...SHELL_INTERPRETERS,
|
|
8481
|
+
"python",
|
|
8482
|
+
"python3",
|
|
8483
|
+
"node",
|
|
8484
|
+
"ruby",
|
|
8485
|
+
"perl",
|
|
8486
|
+
"php",
|
|
8487
|
+
"lua"
|
|
8488
|
+
]);
|
|
8489
|
+
VERSIONED_PYTHON = /^python3\.[0-9]+t?$/;
|
|
8490
|
+
ENV_PROGRAMS = /* @__PURE__ */ new Set(["env", "/bin/env", "/usr/bin/env"]);
|
|
8491
|
+
SHELL_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
8492
|
+
IO_NUMBER = /^[0-9]+$/;
|
|
8493
|
+
LITERAL_PART_RE = /[^\s'"\\$`*?\[\]{}();|&<>]+|'[^']*'|"(?:[^"\\$`]|\\.)*"|\\[^\n]/y;
|
|
8494
|
+
SHELL_DOUBLE_ESCAPE_RE = /\\(["\\$`])/g;
|
|
8495
|
+
FILE_REDIRECT_RE = />>|>\||>&|<>|<&|[<>]/y;
|
|
8496
|
+
CallBindings = class _CallBindings {
|
|
8497
|
+
cwd;
|
|
8498
|
+
modules = /* @__PURE__ */ new Map([["os", "os"], ["subprocess", "subprocess"]]);
|
|
8499
|
+
builtinPrint = true;
|
|
8500
|
+
functions = /* @__PURE__ */ new Map();
|
|
8501
|
+
wrappers = /* @__PURE__ */ new Map();
|
|
8502
|
+
strings = /* @__PURE__ */ new Map([["__name__", "__main__"]]);
|
|
8503
|
+
constructor(cwd = ".") {
|
|
8504
|
+
this.cwd = cwd;
|
|
8505
|
+
}
|
|
8506
|
+
fork() {
|
|
8507
|
+
const other = new _CallBindings(this.cwd);
|
|
8508
|
+
other.modules = new Map(this.modules);
|
|
8509
|
+
other.functions = new Map(this.functions);
|
|
8510
|
+
other.wrappers = new Map(this.wrappers);
|
|
8511
|
+
other.strings = new Map(this.strings);
|
|
8512
|
+
other.builtinPrint = this.builtinPrint;
|
|
8513
|
+
return other;
|
|
8514
|
+
}
|
|
8515
|
+
merge(paths) {
|
|
8516
|
+
this.modules = mergeBindings(paths.map((p) => p.modules), (a, b) => a === b);
|
|
8517
|
+
this.functions = mergeBindings(paths.map((p) => p.functions), sameTuple);
|
|
8518
|
+
this.strings = mergeBindings(paths.map((p) => p.strings), (a, b) => a === b);
|
|
8519
|
+
this.wrappers = mergeBindings(paths.map((p) => p.wrappers), (a, b) => a === b);
|
|
8520
|
+
const first = paths[0].cwd;
|
|
8521
|
+
this.cwd = paths.every((p) => p.cwd === first) ? first : WORKING_DIRECTORY_UNKNOWN;
|
|
8522
|
+
this.builtinPrint = paths.every((p) => p.builtinPrint);
|
|
8523
|
+
}
|
|
8524
|
+
invalidate() {
|
|
8525
|
+
this.builtinPrint = false;
|
|
8526
|
+
this.functions.clear();
|
|
8527
|
+
this.wrappers.clear();
|
|
8528
|
+
this.strings.clear();
|
|
8529
|
+
for (const [name, module] of [...this.modules]) {
|
|
8530
|
+
if (name !== module) this.modules.delete(name);
|
|
8531
|
+
}
|
|
8532
|
+
}
|
|
8533
|
+
forget(name) {
|
|
8534
|
+
if (name === "print") this.builtinPrint = false;
|
|
8535
|
+
this.functions.delete(name);
|
|
8536
|
+
this.strings.delete(name);
|
|
8537
|
+
this.modules.delete(name);
|
|
8538
|
+
this.wrappers.delete(name);
|
|
8539
|
+
}
|
|
8540
|
+
bindString(name, value) {
|
|
8541
|
+
this.forget(name);
|
|
8542
|
+
if (value !== null) this.strings.set(name, value);
|
|
8543
|
+
}
|
|
8544
|
+
changeDirectory(directory) {
|
|
8545
|
+
this.cwd = directoryFor(this, directory);
|
|
8546
|
+
}
|
|
8547
|
+
};
|
|
7297
8548
|
PythonBackend = class {
|
|
7298
8549
|
language = "python";
|
|
7299
|
-
parse(content, entryArgs) {
|
|
8550
|
+
parse(content, entryArgs, options = {}) {
|
|
8551
|
+
const diagnostics = options.diagnostics;
|
|
8552
|
+
const argsKnown = options.argsKnown !== false;
|
|
7300
8553
|
const c = content || "";
|
|
7301
8554
|
SOURCE = c;
|
|
7302
8555
|
const sourceLines = c.split("\n");
|
|
@@ -7304,7 +8557,16 @@ var init_python_backend = __esm({
|
|
|
7304
8557
|
const env2 = makeEnv(entryArgs || []);
|
|
7305
8558
|
const lines = /* @__PURE__ */ new Set();
|
|
7306
8559
|
const branches = [];
|
|
8560
|
+
const ifDecisions = /* @__PURE__ */ new Map();
|
|
8561
|
+
if (diagnostics) {
|
|
8562
|
+
diagnostics.physical_lines = sourceLines.length;
|
|
8563
|
+
diagnostics.line_limit = MAX_LINES;
|
|
8564
|
+
}
|
|
7307
8565
|
if (sourceLines.length > MAX_LINES) {
|
|
8566
|
+
if (diagnostics) {
|
|
8567
|
+
diagnostics.parser = "python_full";
|
|
8568
|
+
diagnostics.fallback_reason = "line_budget";
|
|
8569
|
+
}
|
|
7308
8570
|
return {
|
|
7309
8571
|
reachableContent: c,
|
|
7310
8572
|
controlFlowResolved: false,
|
|
@@ -7318,6 +8580,10 @@ var init_python_backend = __esm({
|
|
|
7318
8580
|
try {
|
|
7319
8581
|
tree = parser.parse(c).topNode;
|
|
7320
8582
|
} catch {
|
|
8583
|
+
if (diagnostics) {
|
|
8584
|
+
diagnostics.parser = "python_full";
|
|
8585
|
+
diagnostics.fallback_reason = "syntax_error";
|
|
8586
|
+
}
|
|
7321
8587
|
return {
|
|
7322
8588
|
reachableContent: c,
|
|
7323
8589
|
controlFlowResolved: false,
|
|
@@ -7327,11 +8593,32 @@ var init_python_backend = __esm({
|
|
|
7327
8593
|
language: this.language
|
|
7328
8594
|
};
|
|
7329
8595
|
}
|
|
8596
|
+
if (!argsKnown) {
|
|
8597
|
+
if (diagnostics) {
|
|
8598
|
+
diagnostics.parser = "python_full";
|
|
8599
|
+
diagnostics.fallback_reason = "unknown_args";
|
|
8600
|
+
diagnostics.child_extractor = "ast";
|
|
8601
|
+
}
|
|
8602
|
+
return {
|
|
8603
|
+
reachableContent: c,
|
|
8604
|
+
controlFlowResolved: false,
|
|
8605
|
+
calls: extractCallsFromTree(tree, null, /* @__PURE__ */ new Map(), lineStarts),
|
|
8606
|
+
branches: [],
|
|
8607
|
+
unresolvedSnippets: [],
|
|
8608
|
+
language: this.language
|
|
8609
|
+
};
|
|
8610
|
+
}
|
|
7330
8611
|
const stmts = bodyStmts(tree);
|
|
7331
|
-
processStmts(stmts, env2, lineStarts, lines, branches);
|
|
8612
|
+
processStmts(stmts, env2, lineStarts, lines, branches, ifDecisions);
|
|
7332
8613
|
const reachable = reconstruct(sourceLines, lines);
|
|
7333
|
-
|
|
7334
|
-
if (
|
|
8614
|
+
const calls = extractCallsFromTree(tree, lines, ifDecisions, lineStarts);
|
|
8615
|
+
if (diagnostics) {
|
|
8616
|
+
diagnostics.parser = "python_ast";
|
|
8617
|
+
diagnostics.child_extractor = "ast";
|
|
8618
|
+
diagnostics.retained_lines = lines.size;
|
|
8619
|
+
diagnostics.branch_count = branches.length;
|
|
8620
|
+
diagnostics.branch_reachable = branches.slice(0, 4).map((b) => b.reachable);
|
|
8621
|
+
}
|
|
7335
8622
|
const srcNonblank = sourceLines.filter((l) => l.trim().length > 0);
|
|
7336
8623
|
const rcNonblank = reachable.split("\n").filter((l) => l.trim().length > 0);
|
|
7337
8624
|
const resolved = rcNonblank.length !== srcNonblank.length || rcNonblank.some((l, i) => l !== srcNonblank[i]);
|
|
@@ -7374,6 +8661,23 @@ function fold(val) {
|
|
|
7374
8661
|
}
|
|
7375
8662
|
return svalConc(parts.join(""));
|
|
7376
8663
|
}
|
|
8664
|
+
function maskCaseLiteral(literal) {
|
|
8665
|
+
const unsupported = literal === "\\\n" || literal.startsWith('"') && (literal.includes("$(") || literal.includes("`"));
|
|
8666
|
+
const mask = unsupported ? "\0" : "x";
|
|
8667
|
+
return literal.replace(/[^\n]/g, mask);
|
|
8668
|
+
}
|
|
8669
|
+
function maskCaseWord(text) {
|
|
8670
|
+
if (text.startsWith("#")) return " ".repeat(text.length);
|
|
8671
|
+
if (text === "<<" || text === "'" || text === '"' || text === "\\" || text === "`") {
|
|
8672
|
+
return "\0".repeat(text.length);
|
|
8673
|
+
}
|
|
8674
|
+
CASE_QUOTED_RE.lastIndex = 0;
|
|
8675
|
+
return text.replace(CASE_QUOTED_RE, maskCaseLiteral);
|
|
8676
|
+
}
|
|
8677
|
+
function caseSyntaxLines(content) {
|
|
8678
|
+
const re = new RegExp(CASE_SYNTAX_TOKEN_SOURCE, "g");
|
|
8679
|
+
return content.replace(re, maskCaseWord).split("\n");
|
|
8680
|
+
}
|
|
7377
8681
|
function countMatches(re, s) {
|
|
7378
8682
|
const m = s.match(re);
|
|
7379
8683
|
return m ? m.length : 0;
|
|
@@ -7386,176 +8690,225 @@ function findBlockEnd(lines, startLine, openRe, closeRe) {
|
|
|
7386
8690
|
}
|
|
7387
8691
|
return -1;
|
|
7388
8692
|
}
|
|
7389
|
-
function
|
|
7390
|
-
return findBlockEnd(lines,
|
|
7391
|
-
}
|
|
7392
|
-
function findIfEnd(lines, start) {
|
|
7393
|
-
return findBlockEnd(lines, start, IF_OPEN_RE, IF_CLOSE_RE);
|
|
8693
|
+
function findIfEnd(lines, startLine) {
|
|
8694
|
+
return findBlockEnd(lines, startLine, IF_OPEN_RE, IF_CLOSE_RE);
|
|
7394
8695
|
}
|
|
7395
|
-
function findLoopEnd(lines,
|
|
8696
|
+
function findLoopEnd(lines, startLine) {
|
|
7396
8697
|
let depth = 0;
|
|
7397
|
-
for (let idx =
|
|
8698
|
+
for (let idx = startLine; idx < lines.length; idx++) {
|
|
7398
8699
|
depth += countMatches(LOOP_DO_RE, lines[idx]) - countMatches(LOOP_DONE_RE, lines[idx]);
|
|
7399
|
-
if (depth <= 0 && idx >
|
|
8700
|
+
if (depth <= 0 && idx > startLine) return idx;
|
|
7400
8701
|
}
|
|
7401
8702
|
return -1;
|
|
7402
8703
|
}
|
|
7403
|
-
function findFnEnd(lines,
|
|
8704
|
+
function findFnEnd(lines, startLine) {
|
|
7404
8705
|
let depth = 0;
|
|
7405
|
-
for (let idx =
|
|
8706
|
+
for (let idx = startLine; idx < lines.length; idx++) {
|
|
7406
8707
|
depth += (lines[idx].match(/\{/g) || []).length - (lines[idx].match(/\}/g) || []).length;
|
|
7407
|
-
if (depth <= 0 && idx >
|
|
8708
|
+
if (depth <= 0 && idx > startLine) return idx;
|
|
7408
8709
|
}
|
|
7409
8710
|
return -1;
|
|
7410
8711
|
}
|
|
7411
|
-
function
|
|
7412
|
-
|
|
7413
|
-
|
|
7414
|
-
|
|
7415
|
-
|
|
7416
|
-
|
|
7417
|
-
|
|
7418
|
-
|
|
7419
|
-
let headerLine = 0;
|
|
7420
|
-
for (let i = 0; i < lines.length; i++) {
|
|
7421
|
-
if (/\bin\b/.test(lines[i]) && /\bcase\b/.test(lines[i])) {
|
|
7422
|
-
headerLine = i;
|
|
7423
|
-
break;
|
|
7424
|
-
}
|
|
7425
|
-
}
|
|
7426
|
-
const bodyStartLine = headerLine + 1;
|
|
7427
|
-
const endLine = findCaseEnd(lines, 0);
|
|
7428
|
-
if (endLine === -1) return null;
|
|
7429
|
-
const branches = splitCaseBranchesDepthAware(lines.slice(bodyStartLine, endLine));
|
|
7430
|
-
if (!branches.length) return null;
|
|
7431
|
-
return { kind: "case", line: block, modelable: true, selector: sel, branches };
|
|
7432
|
-
}
|
|
7433
|
-
function splitCaseBranchesDepthAware(bodyLines) {
|
|
7434
|
-
let depth = 0;
|
|
7435
|
-
let curPat = null;
|
|
7436
|
-
let curBody = [];
|
|
7437
|
-
const branches = [];
|
|
7438
|
-
const flush = () => {
|
|
7439
|
-
if (curPat !== null) {
|
|
7440
|
-
branches.push({ pat: curPat, body: curBody.join("\n") });
|
|
8712
|
+
function caseDepthDelta(line, rawLine) {
|
|
8713
|
+
if (COPROC_GROUP_RE.test(line)) return null;
|
|
8714
|
+
CASE_FUNCTION_G.lastIndex = 0;
|
|
8715
|
+
let fn;
|
|
8716
|
+
while ((fn = CASE_FUNCTION_G.exec(line)) !== null) {
|
|
8717
|
+
if (fn[0] === "") {
|
|
8718
|
+
CASE_FUNCTION_G.lastIndex++;
|
|
8719
|
+
continue;
|
|
7441
8720
|
}
|
|
7442
|
-
|
|
7443
|
-
|
|
7444
|
-
|
|
7445
|
-
|
|
7446
|
-
const
|
|
7447
|
-
if (
|
|
7448
|
-
|
|
7449
|
-
if (bm) {
|
|
7450
|
-
if (curPat !== null) flush();
|
|
7451
|
-
curPat = bm[1].trim().replace(/^["']|["']$/g, "");
|
|
7452
|
-
curBody = bm[2].trim() ? [bm[2].trim()] : [];
|
|
7453
|
-
continue;
|
|
7454
|
-
}
|
|
8721
|
+
const name = fn.groups?.name;
|
|
8722
|
+
if (name === void 0) return null;
|
|
8723
|
+
const range = fn.indices?.groups?.name;
|
|
8724
|
+
if (!range) return null;
|
|
8725
|
+
const [startIdx, endIdx] = range;
|
|
8726
|
+
if (rawLine[endIdx] !== "(" || !CASE_ARRAY_ASSIGNMENT_RE.test(rawLine.slice(startIdx, endIdx))) {
|
|
8727
|
+
return null;
|
|
7455
8728
|
}
|
|
7456
|
-
|
|
7457
|
-
|
|
7458
|
-
|
|
7459
|
-
|
|
7460
|
-
|
|
8729
|
+
}
|
|
8730
|
+
const opens = countMatches(CASE_OPEN_G, line);
|
|
8731
|
+
const closes = [];
|
|
8732
|
+
CASE_CLOSE_G.lastIndex = 0;
|
|
8733
|
+
let cm;
|
|
8734
|
+
while ((cm = CASE_CLOSE_G.exec(line)) !== null) {
|
|
8735
|
+
if (cm[0] === "") {
|
|
8736
|
+
CASE_CLOSE_G.lastIndex++;
|
|
8737
|
+
continue;
|
|
7461
8738
|
}
|
|
8739
|
+
closes.push(cm.index);
|
|
7462
8740
|
}
|
|
7463
|
-
if (
|
|
7464
|
-
return
|
|
8741
|
+
if (opens + closes.length > 1 || closes.length > 0 && closes[0] !== 0) return null;
|
|
8742
|
+
return opens - closes.length;
|
|
7465
8743
|
}
|
|
7466
|
-
function
|
|
7467
|
-
|
|
7468
|
-
|
|
7469
|
-
|
|
7470
|
-
|
|
7471
|
-
|
|
7472
|
-
|
|
7473
|
-
const body = lines.slice(1, fiLine).join("\n");
|
|
7474
|
-
const elseM = /\belse\b/.exec(body);
|
|
7475
|
-
let thenBody;
|
|
7476
|
-
let elseBody;
|
|
7477
|
-
if (elseM) {
|
|
7478
|
-
thenBody = body.slice(0, elseM.index);
|
|
7479
|
-
elseBody = body.slice(elseM.index + 4);
|
|
7480
|
-
} else {
|
|
7481
|
-
thenBody = body;
|
|
7482
|
-
elseBody = null;
|
|
8744
|
+
function findCaseEnd(lines, syntaxLines, startLine) {
|
|
8745
|
+
let depth = 0;
|
|
8746
|
+
for (let index = startLine; index < lines.length; index++) {
|
|
8747
|
+
const delta = caseDepthDelta(syntaxLines[index], lines[index]);
|
|
8748
|
+
if (delta === null || index === startLine && delta !== 1) return -1;
|
|
8749
|
+
depth += delta;
|
|
8750
|
+
if (depth === 0) return index;
|
|
7483
8751
|
}
|
|
7484
|
-
return
|
|
8752
|
+
return -1;
|
|
7485
8753
|
}
|
|
7486
|
-
function
|
|
7487
|
-
|
|
8754
|
+
function containsCommandSubstitution(line) {
|
|
8755
|
+
return NOT_MODELED_RE.test(line);
|
|
8756
|
+
}
|
|
8757
|
+
function splitStatements(content) {
|
|
8758
|
+
const lines = content.split("\n");
|
|
8759
|
+
const syntaxLines = CASE_HEADER_RE.test(content) ? caseSyntaxLines(content) : lines;
|
|
7488
8760
|
const stmts = [];
|
|
7489
8761
|
let i = 0;
|
|
7490
|
-
|
|
8762
|
+
const n = lines.length;
|
|
8763
|
+
while (i < n) {
|
|
7491
8764
|
const ln = lines[i];
|
|
7492
8765
|
const stripped = ln.trim();
|
|
7493
|
-
if (!stripped) {
|
|
7494
|
-
i
|
|
8766
|
+
if (!syntaxLines[i].trim() || stripped.startsWith("#")) {
|
|
8767
|
+
i += 1;
|
|
7495
8768
|
continue;
|
|
7496
8769
|
}
|
|
7497
|
-
if (
|
|
8770
|
+
if (LOOP_OPEN_RE.test(stripped) && !/^\s*case\s+/.test(stripped) && !/^\s*if\s+/.test(stripped)) {
|
|
7498
8771
|
const endLine = findLoopEnd(lines, i);
|
|
7499
8772
|
if (endLine !== -1) {
|
|
7500
|
-
for (let k = i; k <= endLine; k++)
|
|
8773
|
+
for (let k = i; k <= endLine; k++) {
|
|
8774
|
+
stmts.push({ kind: "not_modeled", line: lines[k], modelable: false, reason: "loop" });
|
|
8775
|
+
}
|
|
7501
8776
|
i = endLine + 1;
|
|
7502
8777
|
continue;
|
|
7503
8778
|
}
|
|
7504
|
-
stmts.push({ kind: "
|
|
7505
|
-
i
|
|
8779
|
+
stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "loop" });
|
|
8780
|
+
i += 1;
|
|
7506
8781
|
continue;
|
|
7507
8782
|
}
|
|
7508
8783
|
if (FN_DEF_RE.test(stripped) || FN_DEF_KW_RE.test(stripped)) {
|
|
7509
8784
|
const endLine = findFnEnd(lines, i);
|
|
7510
8785
|
if (endLine !== -1) {
|
|
7511
|
-
for (let k = i; k <= endLine; k++)
|
|
8786
|
+
for (let k = i; k <= endLine; k++) {
|
|
8787
|
+
stmts.push({ kind: "not_modeled", line: lines[k], modelable: false, reason: "function" });
|
|
8788
|
+
}
|
|
7512
8789
|
i = endLine + 1;
|
|
7513
8790
|
continue;
|
|
7514
8791
|
}
|
|
7515
|
-
stmts.push({ kind: "
|
|
7516
|
-
i
|
|
8792
|
+
stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "function" });
|
|
8793
|
+
i += 1;
|
|
7517
8794
|
continue;
|
|
7518
8795
|
}
|
|
7519
|
-
if (
|
|
7520
|
-
const
|
|
7521
|
-
|
|
7522
|
-
|
|
7523
|
-
i++;
|
|
7524
|
-
continue;
|
|
7525
|
-
}
|
|
7526
|
-
const parsed = parseCaseStmt(lines.slice(i, endLine + 1).join("\n"));
|
|
7527
|
-
stmts.push(parsed || { kind: "plain", line: ln, modelable: false });
|
|
7528
|
-
i = endLine + 1;
|
|
8796
|
+
if (CASE_HEADER_RE.test(syntaxLines[i])) {
|
|
8797
|
+
const parsed = parseCaseStatement(lines, syntaxLines, i);
|
|
8798
|
+
stmts.push(parsed ?? { kind: "not_modeled", line: ln, modelable: false, reason: "case_syntax" });
|
|
8799
|
+
i += parsed === null ? 1 : parsed.line.split("\n").length;
|
|
7529
8800
|
continue;
|
|
7530
8801
|
}
|
|
7531
|
-
if (
|
|
8802
|
+
if (/^\s*if\s+/.test(stripped)) {
|
|
7532
8803
|
const endLine = findIfEnd(lines, i);
|
|
7533
8804
|
if (endLine === -1) {
|
|
7534
|
-
stmts.push({ kind: "
|
|
7535
|
-
i
|
|
8805
|
+
stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "if_syntax" });
|
|
8806
|
+
i += 1;
|
|
7536
8807
|
continue;
|
|
7537
8808
|
}
|
|
7538
|
-
const
|
|
7539
|
-
|
|
8809
|
+
const blockText = lines.slice(i, endLine + 1).join("\n");
|
|
8810
|
+
const parsed = parseIfStmt(blockText);
|
|
8811
|
+
stmts.push(parsed ?? { kind: "not_modeled", line: ln, modelable: false, reason: "if_syntax" });
|
|
7540
8812
|
i = endLine + 1;
|
|
7541
8813
|
continue;
|
|
7542
8814
|
}
|
|
7543
8815
|
if (/\bshift\b|\bset\s+--(?:\s|$)|[\s;|&]read\b|^\s*read\b/.test(stripped)) {
|
|
7544
|
-
stmts.push({ kind: "
|
|
7545
|
-
i
|
|
8816
|
+
stmts.push({ kind: "not_modeled", line: ln, modelable: false, reason: "positional_mutation" });
|
|
8817
|
+
i += 1;
|
|
7546
8818
|
continue;
|
|
7547
8819
|
}
|
|
7548
|
-
const am =
|
|
7549
|
-
if (am && !
|
|
8820
|
+
const am = ASGN_RE.exec(stripped);
|
|
8821
|
+
if (am && !containsCommandSubstitution(stripped)) {
|
|
7550
8822
|
stmts.push({ kind: "assign", line: stripped, modelable: true, name: am[1], rhs: am[2].trim() });
|
|
7551
|
-
i
|
|
8823
|
+
i += 1;
|
|
7552
8824
|
continue;
|
|
7553
8825
|
}
|
|
7554
|
-
stmts.push(
|
|
7555
|
-
i
|
|
8826
|
+
stmts.push(containsCommandSubstitution(stripped) ? { kind: "not_modeled", line: ln, modelable: false, reason: "command_substitution" } : { kind: "plain", line: ln, modelable: true });
|
|
8827
|
+
i += 1;
|
|
7556
8828
|
}
|
|
7557
8829
|
return stmts;
|
|
7558
8830
|
}
|
|
8831
|
+
function parseCaseStatement(lines, syntaxLines, start) {
|
|
8832
|
+
const header = CASE_HEADER_LINE_RE.exec(syntaxLines[start]);
|
|
8833
|
+
if (header === null) return null;
|
|
8834
|
+
let bodyStart = start + 1;
|
|
8835
|
+
if (header[2] === void 0) {
|
|
8836
|
+
while (bodyStart < syntaxLines.length && !syntaxLines[bodyStart].trim()) bodyStart += 1;
|
|
8837
|
+
if (bodyStart === syntaxLines.length || syntaxLines[bodyStart].trim() !== "in") return null;
|
|
8838
|
+
bodyStart += 1;
|
|
8839
|
+
}
|
|
8840
|
+
const end = findCaseEnd(lines, syntaxLines, start);
|
|
8841
|
+
if (end < bodyStart || !/^\s*esac\s*;?\s*$/.test(syntaxLines[end])) return null;
|
|
8842
|
+
for (let i = start; i <= end; i++) {
|
|
8843
|
+
if (syntaxLines[i].includes("\0") || syntaxLines[i].includes("$(")) return null;
|
|
8844
|
+
}
|
|
8845
|
+
const selectorRange = header.indices?.[1];
|
|
8846
|
+
if (!selectorRange) return null;
|
|
8847
|
+
const selector = lines[start].slice(selectorRange[0], selectorRange[1]);
|
|
8848
|
+
const branches = [];
|
|
8849
|
+
let label = null;
|
|
8850
|
+
let body = [];
|
|
8851
|
+
let depth = 0;
|
|
8852
|
+
for (let index = bodyStart; index < end; index++) {
|
|
8853
|
+
let line = lines[index];
|
|
8854
|
+
let syntax = syntaxLines[index];
|
|
8855
|
+
if (label === null) {
|
|
8856
|
+
if (!syntax.trim()) continue;
|
|
8857
|
+
const branch = CASE_LABEL_END_RE.exec(syntax);
|
|
8858
|
+
if (branch === null) return null;
|
|
8859
|
+
const labelRange = branch.indices?.[1];
|
|
8860
|
+
if (!labelRange) return null;
|
|
8861
|
+
label = line.slice(labelRange[0], labelRange[1]).trim();
|
|
8862
|
+
const consumed = branch[0].length;
|
|
8863
|
+
line = line.slice(consumed);
|
|
8864
|
+
syntax = syntax.slice(consumed);
|
|
8865
|
+
}
|
|
8866
|
+
const delta = caseDepthDelta(syntax, line);
|
|
8867
|
+
if (delta === null || depth + delta < 0) return null;
|
|
8868
|
+
depth += delta;
|
|
8869
|
+
body.push(line);
|
|
8870
|
+
if (depth === 0) {
|
|
8871
|
+
const terminator = CASE_TERMINATOR_RE.exec(syntax);
|
|
8872
|
+
if (terminator !== null) {
|
|
8873
|
+
if (terminator[0] !== ";;" || syntax.slice(terminator.index + terminator[0].length).trim()) {
|
|
8874
|
+
return null;
|
|
8875
|
+
}
|
|
8876
|
+
branches.push({ label, body: body.join("\n") });
|
|
8877
|
+
label = null;
|
|
8878
|
+
body = [];
|
|
8879
|
+
}
|
|
8880
|
+
}
|
|
8881
|
+
}
|
|
8882
|
+
if (depth) return null;
|
|
8883
|
+
if (label !== null) branches.push({ label, body: body.join("\n") });
|
|
8884
|
+
return {
|
|
8885
|
+
kind: "case",
|
|
8886
|
+
line: lines.slice(start, end + 1).join("\n"),
|
|
8887
|
+
modelable: true,
|
|
8888
|
+
selector,
|
|
8889
|
+
branches
|
|
8890
|
+
};
|
|
8891
|
+
}
|
|
8892
|
+
function parseIfStmt(block) {
|
|
8893
|
+
const m = /^\s*if\s+([^\n;]+?)\s*;\s*then/.exec(block);
|
|
8894
|
+
if (!m) return null;
|
|
8895
|
+
const cond = m[1].trim();
|
|
8896
|
+
const blockLines = block.split("\n");
|
|
8897
|
+
const fiLine = findIfEnd(blockLines, 0);
|
|
8898
|
+
if (fiLine === -1) return null;
|
|
8899
|
+
const body = blockLines.slice(1, fiLine).join("\n");
|
|
8900
|
+
const elseM = /\belse\b/.exec(body);
|
|
8901
|
+
let thenBody;
|
|
8902
|
+
let elseBody;
|
|
8903
|
+
if (elseM) {
|
|
8904
|
+
thenBody = body.slice(0, elseM.index);
|
|
8905
|
+
elseBody = body.slice(elseM.index + 4);
|
|
8906
|
+
} else {
|
|
8907
|
+
thenBody = body;
|
|
8908
|
+
elseBody = null;
|
|
8909
|
+
}
|
|
8910
|
+
return { kind: "if", line: block, modelable: true, cond, thenBody, elseBody };
|
|
8911
|
+
}
|
|
7559
8912
|
function evalExpr2(text, env2) {
|
|
7560
8913
|
const isSingleQuoted = text.length >= 2 && text[0] === "'" && text[text.length - 1] === "'";
|
|
7561
8914
|
if (text.length >= 2 && (text[0] === '"' || text[0] === "'") && text[text.length - 1] === text[0]) {
|
|
@@ -7642,16 +8995,71 @@ function globToRegex(pattern) {
|
|
|
7642
8995
|
i++;
|
|
7643
8996
|
}
|
|
7644
8997
|
out += "$";
|
|
7645
|
-
return new RegExp(out,
|
|
8998
|
+
return new RegExp(out, "s");
|
|
7646
8999
|
}
|
|
7647
|
-
function
|
|
9000
|
+
function fnmatchCase(value, pattern) {
|
|
7648
9001
|
if (!HAS_GLOB.test(pattern)) return pattern === value;
|
|
7649
9002
|
return globToRegex(pattern).test(value);
|
|
7650
9003
|
}
|
|
9004
|
+
function matchGlobStrict(pattern, value) {
|
|
9005
|
+
if (!CASE_PATTERN_FULL_RE.test(pattern)) return null;
|
|
9006
|
+
if (pattern.startsWith("'") || pattern.startsWith('"')) {
|
|
9007
|
+
return pattern.slice(1, -1) === value;
|
|
9008
|
+
}
|
|
9009
|
+
if (!/^[\x00-\x7F]*$/.test(value) && (pattern.includes("?") || pattern.includes("["))) {
|
|
9010
|
+
return null;
|
|
9011
|
+
}
|
|
9012
|
+
return fnmatchCase(value, pattern);
|
|
9013
|
+
}
|
|
9014
|
+
function selectCaseBranch(caseStmt, value) {
|
|
9015
|
+
for (let index = 0; index < caseStmt.branches.length; index++) {
|
|
9016
|
+
const label = caseStmt.branches[index].label;
|
|
9017
|
+
if (!CASE_LABEL_FULL_RE.test(label)) return null;
|
|
9018
|
+
CASE_PATTERN_ITER_RE.lastIndex = 0;
|
|
9019
|
+
let m;
|
|
9020
|
+
while ((m = CASE_PATTERN_ITER_RE.exec(label)) !== null) {
|
|
9021
|
+
if (m[0] === "") {
|
|
9022
|
+
CASE_PATTERN_ITER_RE.lastIndex++;
|
|
9023
|
+
continue;
|
|
9024
|
+
}
|
|
9025
|
+
const pattern = m[0];
|
|
9026
|
+
const matched = matchGlobStrict(pattern, value);
|
|
9027
|
+
if (matched === null) return null;
|
|
9028
|
+
if (matched) return [index, pattern === "*" ? "default" : "match"];
|
|
9029
|
+
}
|
|
9030
|
+
}
|
|
9031
|
+
return null;
|
|
9032
|
+
}
|
|
9033
|
+
function unicodeDigitValue(codePoint) {
|
|
9034
|
+
for (const [start, end] of DECIMAL_DIGIT_RANGES) {
|
|
9035
|
+
if (codePoint >= start && codePoint <= end) {
|
|
9036
|
+
return start === 120782 ? (codePoint - start) % 10 : codePoint - start;
|
|
9037
|
+
}
|
|
9038
|
+
}
|
|
9039
|
+
return null;
|
|
9040
|
+
}
|
|
9041
|
+
function normalizeDecimalDigits(text) {
|
|
9042
|
+
let out = "";
|
|
9043
|
+
for (const ch of text) {
|
|
9044
|
+
const codePoint = ch.codePointAt(0);
|
|
9045
|
+
const digit = unicodeDigitValue(codePoint);
|
|
9046
|
+
out += digit === null ? ch : String(digit);
|
|
9047
|
+
}
|
|
9048
|
+
return out;
|
|
9049
|
+
}
|
|
9050
|
+
function parsePythonInt(text) {
|
|
9051
|
+
const t = normalizeDecimalDigits(text.trim());
|
|
9052
|
+
if (!/^[+-]?\d(?:_?\d)*$/.test(t)) return null;
|
|
9053
|
+
try {
|
|
9054
|
+
return BigInt(t.replace(/_/g, ""));
|
|
9055
|
+
} catch {
|
|
9056
|
+
return null;
|
|
9057
|
+
}
|
|
9058
|
+
}
|
|
7651
9059
|
function evalNumericCompare(op, left, right) {
|
|
7652
|
-
const li =
|
|
7653
|
-
const ri =
|
|
7654
|
-
if (
|
|
9060
|
+
const li = parsePythonInt(left);
|
|
9061
|
+
const ri = parsePythonInt(right);
|
|
9062
|
+
if (li === null || ri === null) return null;
|
|
7655
9063
|
switch (op) {
|
|
7656
9064
|
case "-gt":
|
|
7657
9065
|
return li > ri;
|
|
@@ -7672,99 +9080,203 @@ function resolveVarSide(tok, env2) {
|
|
|
7672
9080
|
const ev = evalExpr2(tok, env2);
|
|
7673
9081
|
return ev.kind === "concrete" ? ev.value : null;
|
|
7674
9082
|
}
|
|
7675
|
-
function
|
|
7676
|
-
|
|
7677
|
-
|
|
9083
|
+
function unquoteConditionToken(tok) {
|
|
9084
|
+
tok = tok.trim();
|
|
9085
|
+
let quoted = false;
|
|
9086
|
+
if (tok.length >= 2 && (tok[0] === '"' || tok[0] === "'") && tok[tok.length - 1] === tok[0]) {
|
|
9087
|
+
tok = tok.slice(1, -1);
|
|
9088
|
+
quoted = true;
|
|
9089
|
+
}
|
|
9090
|
+
if (tok.includes('"') || tok.includes("'") || tok.includes("\\")) return null;
|
|
9091
|
+
return [tok, quoted];
|
|
9092
|
+
}
|
|
9093
|
+
function evalCondition2(cond, env2, diagnostics) {
|
|
9094
|
+
if (diagnostics) {
|
|
9095
|
+
delete diagnostics.condition_operator;
|
|
9096
|
+
delete diagnostics.condition_failure;
|
|
9097
|
+
}
|
|
9098
|
+
const doubleBracket = cond.trim().startsWith("[[");
|
|
9099
|
+
const inner = cond.replace(/^\[\[?|\]\]?$/g, "").trim();
|
|
9100
|
+
if (/^-[A-Za-z]\s/.test(inner) || inner.startsWith("-d") || inner.startsWith("-f")) {
|
|
9101
|
+
if (diagnostics) diagnostics.condition_failure = "unsupported_predicate";
|
|
9102
|
+
return null;
|
|
9103
|
+
}
|
|
7678
9104
|
const innerQ = inner.replace(/"/g, "").replace(/'/g, "");
|
|
7679
9105
|
for (const op2 of ["-gt", "-lt", "-eq", "-ge", "-le"]) {
|
|
7680
|
-
const
|
|
7681
|
-
const opm = re.exec(innerQ);
|
|
9106
|
+
const opm = new RegExp("\\s" + op2 + "\\s").exec(innerQ);
|
|
7682
9107
|
if (!opm) continue;
|
|
7683
9108
|
const left2 = innerQ.slice(0, opm.index).trim();
|
|
7684
9109
|
const right2 = innerQ.slice(opm.index + opm[0].length).trim();
|
|
9110
|
+
if (diagnostics) diagnostics.condition_operator = op2;
|
|
7685
9111
|
const lv2 = resolveVarSide(left2, env2);
|
|
7686
9112
|
const rv2 = resolveVarSide(right2, env2);
|
|
7687
|
-
if (lv2 === null || rv2 === null)
|
|
7688
|
-
|
|
9113
|
+
if (lv2 === null || rv2 === null) {
|
|
9114
|
+
if (diagnostics) diagnostics.condition_failure = "unbound_operand";
|
|
9115
|
+
return null;
|
|
9116
|
+
}
|
|
9117
|
+
const result = evalNumericCompare(op2, lv2, rv2);
|
|
9118
|
+
if (result === null && diagnostics) diagnostics.condition_failure = "not_integer";
|
|
9119
|
+
return result;
|
|
9120
|
+
}
|
|
9121
|
+
const sm = /(.*?)\s*(=~|==|!=|=)\s*(.*)/.exec(inner);
|
|
9122
|
+
if (!sm) {
|
|
9123
|
+
if (diagnostics) diagnostics.condition_failure = "unsupported_comparison";
|
|
9124
|
+
return null;
|
|
9125
|
+
}
|
|
9126
|
+
const op = sm[2];
|
|
9127
|
+
if (diagnostics) diagnostics.condition_operator = op;
|
|
9128
|
+
const leftPair = unquoteConditionToken(sm[1]);
|
|
9129
|
+
const rightPair = unquoteConditionToken(sm[3]);
|
|
9130
|
+
if (leftPair === null || rightPair === null) {
|
|
9131
|
+
if (diagnostics) diagnostics.condition_failure = "unsupported_quoting";
|
|
9132
|
+
return null;
|
|
9133
|
+
}
|
|
9134
|
+
const [left] = leftPair;
|
|
9135
|
+
const [right, rightQuoted] = rightPair;
|
|
9136
|
+
const lv = resolveVarSide(left, env2);
|
|
9137
|
+
if (lv === null) {
|
|
9138
|
+
if (diagnostics) diagnostics.condition_failure = "unbound_operand";
|
|
9139
|
+
return null;
|
|
7689
9140
|
}
|
|
7690
|
-
const sm = innerQ.match(/(.*?)\s*(=~|==|!=|=)\s*(.*)/);
|
|
7691
|
-
if (!sm) return null;
|
|
7692
|
-
const op = sm[2];
|
|
7693
|
-
let left = sm[1].trim();
|
|
7694
|
-
let right = sm[3].trim();
|
|
7695
9141
|
if (op === "=~") {
|
|
7696
|
-
if (
|
|
7697
|
-
|
|
7698
|
-
|
|
9142
|
+
if (!doubleBracket) {
|
|
9143
|
+
if (diagnostics) diagnostics.condition_failure = "unsupported_operator";
|
|
9144
|
+
return null;
|
|
9145
|
+
}
|
|
9146
|
+
let rv2 = resolveVarSide(right, env2);
|
|
9147
|
+
if (rv2 === null) {
|
|
9148
|
+
if (diagnostics) diagnostics.condition_failure = "unbound_operand";
|
|
9149
|
+
return null;
|
|
9150
|
+
}
|
|
9151
|
+
if (rv2.startsWith("/") && rv2.endsWith("/") && rv2.length > 1) rv2 = rv2.slice(1, -1);
|
|
9152
|
+
const pattern = rightQuoted || right.startsWith("$") ? reescape(rv2) : rv2;
|
|
7699
9153
|
try {
|
|
7700
|
-
return new RegExp(
|
|
9154
|
+
return new RegExp(pattern).test(lv);
|
|
7701
9155
|
} catch {
|
|
9156
|
+
if (diagnostics) diagnostics.condition_failure = "invalid_regex";
|
|
7702
9157
|
return null;
|
|
7703
9158
|
}
|
|
7704
9159
|
}
|
|
7705
|
-
const lv = resolveVarSide(left, env2);
|
|
7706
9160
|
const rv = resolveVarSide(right, env2);
|
|
7707
|
-
if (
|
|
7708
|
-
|
|
9161
|
+
if (rv === null) {
|
|
9162
|
+
if (diagnostics) diagnostics.condition_failure = "unbound_operand";
|
|
9163
|
+
return null;
|
|
9164
|
+
}
|
|
9165
|
+
const glob = rv.includes("*") || rv.includes("?") || rv.includes("[");
|
|
9166
|
+
let matched;
|
|
9167
|
+
if (!rightQuoted && (glob || right.startsWith("$"))) {
|
|
9168
|
+
if (!doubleBracket) {
|
|
9169
|
+
if (diagnostics) diagnostics.condition_failure = "pathname_expansion";
|
|
9170
|
+
return null;
|
|
9171
|
+
}
|
|
9172
|
+
matched = glob ? fnmatchCase(lv, rv) : lv === rv;
|
|
9173
|
+
} else {
|
|
9174
|
+
matched = lv === rv;
|
|
9175
|
+
}
|
|
7709
9176
|
return op === "!=" ? !matched : matched;
|
|
7710
9177
|
}
|
|
7711
|
-
function symbolicProcess(content, entryArgs) {
|
|
7712
|
-
|
|
7713
|
-
|
|
7714
|
-
|
|
7715
|
-
|
|
9178
|
+
function symbolicProcess(content, entryArgs, diagnostics) {
|
|
9179
|
+
const recordResult = (reason, budget2 = null, variables = 0) => {
|
|
9180
|
+
if (!diagnostics) return;
|
|
9181
|
+
diagnostics.result = reason ? "none" : "text";
|
|
9182
|
+
diagnostics.fallback_reason = reason;
|
|
9183
|
+
diagnostics.lines = budget2 ? budget2.lines : 0;
|
|
9184
|
+
diagnostics.branches = budget2 ? budget2.branches : 0;
|
|
9185
|
+
diagnostics.variables = variables;
|
|
9186
|
+
};
|
|
9187
|
+
if (diagnostics) {
|
|
9188
|
+
diagnostics.line_limit = MAX_LINES2;
|
|
9189
|
+
diagnostics.branch_limit = MAX_BRANCHES;
|
|
9190
|
+
diagnostics.variable_limit = MAX_VARS;
|
|
9191
|
+
}
|
|
9192
|
+
if (content === null || content === void 0) {
|
|
9193
|
+
recordResult("empty");
|
|
9194
|
+
return null;
|
|
9195
|
+
}
|
|
9196
|
+
const stmts = splitStatements(content);
|
|
9197
|
+
if (diagnostics) {
|
|
9198
|
+
diagnostics.statement_count = stmts.length;
|
|
9199
|
+
const unsupported = stmts.find((s) => s.kind === "not_modeled");
|
|
9200
|
+
if (unsupported !== void 0) diagnostics.unsupported = unsupported.reason;
|
|
9201
|
+
}
|
|
9202
|
+
if (!stmts.some((s) => s.kind === "case" || s.kind === "if" || s.kind === "assign")) {
|
|
9203
|
+
recordResult(stmts.length ? "no_modeled_statements" : "empty");
|
|
9204
|
+
return null;
|
|
9205
|
+
}
|
|
9206
|
+
if (stmts.some((s) => !s.modelable)) {
|
|
9207
|
+
recordResult("unsupported_statement");
|
|
9208
|
+
return null;
|
|
9209
|
+
}
|
|
9210
|
+
const budget = { lines: 0, branches: 0 };
|
|
7716
9211
|
const env2 = initEnv(entryArgs);
|
|
7717
|
-
if (env2.size > MAX_VARS)
|
|
7718
|
-
|
|
7719
|
-
|
|
7720
|
-
|
|
9212
|
+
if (env2.size > MAX_VARS) {
|
|
9213
|
+
recordResult("variable_budget", budget, env2.size);
|
|
9214
|
+
return null;
|
|
9215
|
+
}
|
|
7721
9216
|
const out = [];
|
|
9217
|
+
let modelableEncountered = false;
|
|
9218
|
+
const choices = diagnostics ? [] : null;
|
|
9219
|
+
if (diagnostics) diagnostics.choices = choices;
|
|
7722
9220
|
for (const s of stmts) {
|
|
7723
|
-
|
|
7724
|
-
if (
|
|
9221
|
+
budget.lines += 1;
|
|
9222
|
+
if (budget.lines > MAX_LINES2 || budget.branches > MAX_BRANCHES) {
|
|
9223
|
+
recordResult("line_budget", budget, env2.size);
|
|
9224
|
+
return null;
|
|
9225
|
+
}
|
|
7725
9226
|
if (s.kind === "assign") {
|
|
7726
|
-
|
|
7727
|
-
|
|
7728
|
-
|
|
7729
|
-
|
|
9227
|
+
if (!env2.has(s.name) && env2.size >= MAX_VARS) {
|
|
9228
|
+
recordResult("variable_budget", budget, env2.size);
|
|
9229
|
+
return null;
|
|
9230
|
+
}
|
|
9231
|
+
modelableEncountered = true;
|
|
9232
|
+
env2.set(s.name, fold(evalExpr2(s.rhs, env2)));
|
|
7730
9233
|
out.push(s.line);
|
|
7731
9234
|
continue;
|
|
7732
9235
|
}
|
|
7733
9236
|
if (s.kind === "case") {
|
|
7734
|
-
|
|
7735
|
-
|
|
7736
|
-
if (
|
|
9237
|
+
modelableEncountered = true;
|
|
9238
|
+
budget.branches += s.branches.length;
|
|
9239
|
+
if (budget.branches > MAX_BRANCHES) {
|
|
9240
|
+
recordResult("branch_budget", budget, env2.size);
|
|
9241
|
+
return null;
|
|
9242
|
+
}
|
|
7737
9243
|
const selVal = fold(evalExpr2(s.selector, env2));
|
|
7738
|
-
if (selVal.kind !== "concrete")
|
|
7739
|
-
|
|
7740
|
-
|
|
7741
|
-
|
|
7742
|
-
|
|
7743
|
-
|
|
7744
|
-
|
|
7745
|
-
|
|
7746
|
-
|
|
7747
|
-
|
|
7748
|
-
|
|
7749
|
-
|
|
7750
|
-
break;
|
|
7751
|
-
}
|
|
9244
|
+
if (selVal.kind !== "concrete") {
|
|
9245
|
+
recordResult("unbound_selector", budget, env2.size);
|
|
9246
|
+
return null;
|
|
9247
|
+
}
|
|
9248
|
+
const selection = selectCaseBranch(s, selVal.value || "");
|
|
9249
|
+
if (selection === null) {
|
|
9250
|
+
recordResult("case_unresolved", budget, env2.size);
|
|
9251
|
+
return null;
|
|
9252
|
+
}
|
|
9253
|
+
const [index, kind] = selection;
|
|
9254
|
+
if (choices !== null && choices.length < 4) {
|
|
9255
|
+
choices.push(`${kind === "default" ? "case_default" : "case"}:${index + 1}`);
|
|
7752
9256
|
}
|
|
7753
|
-
const final = selected !== null ? selected : fallback || null;
|
|
7754
|
-
if (final === null) return null;
|
|
7755
9257
|
out.push(`case ${s.selector} in
|
|
7756
|
-
${
|
|
9258
|
+
${s.branches[index].body}
|
|
7757
9259
|
esac`);
|
|
7758
9260
|
continue;
|
|
7759
9261
|
}
|
|
7760
9262
|
if (s.kind === "if") {
|
|
7761
|
-
|
|
7762
|
-
|
|
7763
|
-
if (
|
|
7764
|
-
|
|
7765
|
-
|
|
9263
|
+
modelableEncountered = true;
|
|
9264
|
+
budget.branches += 1;
|
|
9265
|
+
if (budget.branches > MAX_BRANCHES) {
|
|
9266
|
+
recordResult("branch_budget", budget, env2.size);
|
|
9267
|
+
return null;
|
|
9268
|
+
}
|
|
9269
|
+
const truth = evalCondition2(s.cond, env2, diagnostics);
|
|
9270
|
+
if (truth === null) {
|
|
9271
|
+
recordResult("condition_unresolved", budget, env2.size);
|
|
9272
|
+
return null;
|
|
9273
|
+
}
|
|
7766
9274
|
const chosen = truth ? s.thenBody : s.elseBody;
|
|
7767
|
-
if (chosen === null)
|
|
9275
|
+
if (chosen === null) {
|
|
9276
|
+
recordResult("missing_else", budget, env2.size);
|
|
9277
|
+
return null;
|
|
9278
|
+
}
|
|
9279
|
+
if (choices !== null && choices.length < 4) choices.push(truth ? "then" : "else");
|
|
7768
9280
|
out.push(`if ${s.cond}; then
|
|
7769
9281
|
${chosen}
|
|
7770
9282
|
fi`);
|
|
@@ -7772,231 +9284,547 @@ fi`);
|
|
|
7772
9284
|
}
|
|
7773
9285
|
out.push(s.line);
|
|
7774
9286
|
}
|
|
7775
|
-
if (!
|
|
9287
|
+
if (!modelableEncountered) {
|
|
9288
|
+
recordResult("no_modeled_statements", budget, env2.size);
|
|
9289
|
+
return null;
|
|
9290
|
+
}
|
|
9291
|
+
recordResult("", budget, env2.size);
|
|
7776
9292
|
return out.join("\n");
|
|
7777
9293
|
}
|
|
7778
|
-
var
|
|
9294
|
+
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;
|
|
7779
9295
|
var init_symbolic = __esm({
|
|
7780
9296
|
"src/engine/script-engine/symbolic.ts"() {
|
|
7781
9297
|
"use strict";
|
|
7782
9298
|
init_esm_shims();
|
|
7783
|
-
RE_DOTALL = "s";
|
|
7784
9299
|
MAX_LINES2 = 500;
|
|
7785
9300
|
MAX_BRANCHES = 50;
|
|
7786
9301
|
MAX_VARS = 200;
|
|
7787
|
-
|
|
7788
|
-
|
|
7789
|
-
|
|
7790
|
-
|
|
7791
|
-
|
|
7792
|
-
|
|
7793
|
-
|
|
7794
|
-
|
|
9302
|
+
CASE_QUOTED_PART = String.raw`'[^']*'|"(?:\\[\s\S]|[^"\\])*"|\\[\s\S]`;
|
|
9303
|
+
CASE_SYNTAX_TOKEN_SOURCE = String.raw`\#[^\n]*` + String.raw`|(?:` + CASE_QUOTED_PART + String.raw`|[^\s;&|()<>'"\\\x60])+` + String.raw`|<<|['"\\\x60]`;
|
|
9304
|
+
CASE_QUOTED_RE = new RegExp(CASE_QUOTED_PART, "g");
|
|
9305
|
+
CASE_COMMAND_START = String.raw`(?:^|(?<=[;|&()]))[ \t]*` + String.raw`(?:(?:if|then|elif|else|while|until|do|\{|!|time(?:[ \t]+-p)?(?:[ \t]+--)?)[ \t]+)*`;
|
|
9306
|
+
COPROC_PREFIX = String.raw`coproc[ \t]+(?:[^\s;&|()<>]+[ \t]+)?`;
|
|
9307
|
+
CASE_OPEN_SOURCE = CASE_COMMAND_START + String.raw`(?:` + COPROC_PREFIX + String.raw`)?case[ \t]+(?=[^\s;&|()<>])`;
|
|
9308
|
+
COPROC_GROUP_SOURCE = CASE_COMMAND_START + COPROC_PREFIX + String.raw`(?:(?:\{|if|for|while|until|select)(?=$|[\s;&|()<>])|\()`;
|
|
9309
|
+
CASE_FUNCTION_SOURCE = CASE_COMMAND_START + String.raw`(?:function[ \t]+[^\s;&|()<>]+|(?<name>[^\s;&|()<>]+)[ \t]*\([ \t]*)`;
|
|
9310
|
+
CASE_ARRAY_ASSIGNMENT_SOURCE = String.raw`[A-Za-z_][A-Za-z0-9_]*(?:\[.+\])?\+?=`;
|
|
9311
|
+
CASE_CLOSE_SOURCE = String.raw`(?:^|(?<=[;&]))[ \t]*esac(?=$|[ \t;&|])`;
|
|
9312
|
+
CASE_HEADER_LINE_SOURCE = String.raw`[ \t]*case[ \t]+([^\s;&|()<>]+)(?:[ \t]+(in))?[ \t]*`;
|
|
9313
|
+
CASE_HEADER_RE = /^[ \t]*case[ \t]+/m;
|
|
9314
|
+
CASE_OPEN_G = new RegExp(CASE_OPEN_SOURCE, "g");
|
|
9315
|
+
COPROC_GROUP_RE = new RegExp(COPROC_GROUP_SOURCE);
|
|
9316
|
+
CASE_FUNCTION_G = new RegExp(CASE_FUNCTION_SOURCE, "gd");
|
|
9317
|
+
CASE_ARRAY_ASSIGNMENT_RE = new RegExp("^(?:" + CASE_ARRAY_ASSIGNMENT_SOURCE + ")$");
|
|
9318
|
+
CASE_CLOSE_G = new RegExp(CASE_CLOSE_SOURCE, "g");
|
|
9319
|
+
CASE_HEADER_LINE_RE = new RegExp("^(?:" + CASE_HEADER_LINE_SOURCE + ")$", "d");
|
|
9320
|
+
CASE_TERMINATOR_RE = /;;&|;&|;;/;
|
|
9321
|
+
CASE_LABEL_END_RE = new RegExp(String.raw`^\s*\(?([^()]+)\)\s*`, "d");
|
|
9322
|
+
IF_OPEN_RE = /\bif\b/g;
|
|
9323
|
+
IF_CLOSE_RE = /\bfi\b/g;
|
|
9324
|
+
LOOP_OPEN_RE = /\b(?:while|for|until)\b/;
|
|
7795
9325
|
LOOP_DO_RE = /\bdo\b/g;
|
|
7796
9326
|
LOOP_DONE_RE = /\bdone\b/g;
|
|
7797
9327
|
FN_DEF_RE = /^\s*(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*\s*\(\s*\)\s*\{/;
|
|
7798
9328
|
FN_DEF_KW_RE = /^\s*function\s+[A-Za-z_][A-Za-z0-9_]*\s*\{?/;
|
|
9329
|
+
ASGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/;
|
|
9330
|
+
NOT_MODELED_RE = /\$\(|`[^`]*`/;
|
|
7799
9331
|
EXPR_SPLIT_RE = /(\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*|\$\d+)/;
|
|
7800
9332
|
HAS_GLOB = /[*?[]/;
|
|
9333
|
+
CASE_BARE_PATTERN = String.raw`(?:[A-Za-z0-9_./:+,@%=-]|\*|\?|\[!?(?:[0-9]-[0-9]|[A-Za-z0-9_.])+\])+`;
|
|
9334
|
+
CASE_PATTERN = String.raw`(?:` + CASE_BARE_PATTERN + String.raw`|'[^']*'|"[^"\\$\x60]*")`;
|
|
9335
|
+
CASE_PATTERN_FULL_RE = new RegExp("^(?:" + CASE_PATTERN + ")$");
|
|
9336
|
+
CASE_PATTERN_ITER_RE = new RegExp(CASE_PATTERN, "g");
|
|
9337
|
+
CASE_LABEL_FULL_RE = new RegExp(
|
|
9338
|
+
"^(?:" + CASE_PATTERN + String.raw`)(?:[ \t]*\|[ \t]*(?:` + CASE_PATTERN + "))*$"
|
|
9339
|
+
);
|
|
9340
|
+
DECIMAL_DIGIT_RANGES = [
|
|
9341
|
+
[48, 57],
|
|
9342
|
+
[1632, 1641],
|
|
9343
|
+
[1776, 1785],
|
|
9344
|
+
[1984, 1993],
|
|
9345
|
+
[2406, 2415],
|
|
9346
|
+
[2534, 2543],
|
|
9347
|
+
[2662, 2671],
|
|
9348
|
+
[2790, 2799],
|
|
9349
|
+
[2918, 2927],
|
|
9350
|
+
[3046, 3055],
|
|
9351
|
+
[3174, 3183],
|
|
9352
|
+
[3302, 3311],
|
|
9353
|
+
[3430, 3439],
|
|
9354
|
+
[3558, 3567],
|
|
9355
|
+
[3664, 3673],
|
|
9356
|
+
[3792, 3801],
|
|
9357
|
+
[3872, 3881],
|
|
9358
|
+
[4160, 4169],
|
|
9359
|
+
[4240, 4249],
|
|
9360
|
+
[6112, 6121],
|
|
9361
|
+
[6160, 6169],
|
|
9362
|
+
[6470, 6479],
|
|
9363
|
+
[6608, 6617],
|
|
9364
|
+
[6784, 6793],
|
|
9365
|
+
[6800, 6809],
|
|
9366
|
+
[6992, 7001],
|
|
9367
|
+
[7088, 7097],
|
|
9368
|
+
[7232, 7241],
|
|
9369
|
+
[7248, 7257],
|
|
9370
|
+
[42528, 42537],
|
|
9371
|
+
[43216, 43225],
|
|
9372
|
+
[43264, 43273],
|
|
9373
|
+
[43472, 43481],
|
|
9374
|
+
[43504, 43513],
|
|
9375
|
+
[43600, 43609],
|
|
9376
|
+
[44016, 44025],
|
|
9377
|
+
[65296, 65305],
|
|
9378
|
+
[66720, 66729],
|
|
9379
|
+
[68912, 68921],
|
|
9380
|
+
[69734, 69743],
|
|
9381
|
+
[69872, 69881],
|
|
9382
|
+
[69942, 69951],
|
|
9383
|
+
[70096, 70105],
|
|
9384
|
+
[70384, 70393],
|
|
9385
|
+
[70736, 70745],
|
|
9386
|
+
[70864, 70873],
|
|
9387
|
+
[71248, 71257],
|
|
9388
|
+
[71360, 71369],
|
|
9389
|
+
[71472, 71481],
|
|
9390
|
+
[71904, 71913],
|
|
9391
|
+
[72016, 72025],
|
|
9392
|
+
[72784, 72793],
|
|
9393
|
+
[73040, 73049],
|
|
9394
|
+
[73120, 73129],
|
|
9395
|
+
[92768, 92777],
|
|
9396
|
+
[93008, 93017],
|
|
9397
|
+
[120782, 120831],
|
|
9398
|
+
[123200, 123209],
|
|
9399
|
+
[123632, 123641],
|
|
9400
|
+
[125264, 125273],
|
|
9401
|
+
[130032, 130041]
|
|
9402
|
+
];
|
|
7801
9403
|
}
|
|
7802
9404
|
});
|
|
7803
9405
|
|
|
7804
9406
|
// src/engine/script-engine/backends/shell-backend.ts
|
|
7805
|
-
function
|
|
7806
|
-
|
|
7807
|
-
|
|
7808
|
-
|
|
7809
|
-
|
|
7810
|
-
|
|
7811
|
-
|
|
7812
|
-
|
|
7813
|
-
return
|
|
7814
|
-
}
|
|
7815
|
-
|
|
7816
|
-
|
|
7817
|
-
|
|
7818
|
-
|
|
7819
|
-
|
|
7820
|
-
|
|
7821
|
-
|
|
7822
|
-
|
|
7823
|
-
|
|
7824
|
-
|
|
7825
|
-
|
|
7826
|
-
|
|
9407
|
+
function positionalMatch(token) {
|
|
9408
|
+
const m = POSITIONAL_RE.exec(token);
|
|
9409
|
+
return m !== null && m.index === 0 ? m : null;
|
|
9410
|
+
}
|
|
9411
|
+
function substitutionEnd(text, startPos, opening, level) {
|
|
9412
|
+
if (level >= MAX_DEFAULT_DEPTH) return null;
|
|
9413
|
+
if (opening === "`") {
|
|
9414
|
+
const m = BACKTICK_ANCHORED_RE.exec(text.slice(startPos - 1));
|
|
9415
|
+
return m ? startPos - 1 + m[0].length : null;
|
|
9416
|
+
}
|
|
9417
|
+
let depth = 1;
|
|
9418
|
+
let start = startPos;
|
|
9419
|
+
const boundary = new RegExp(SUBSTITUTION_BOUNDARY_PART, "g");
|
|
9420
|
+
while (start !== null) {
|
|
9421
|
+
boundary.lastIndex = start;
|
|
9422
|
+
const token = boundary.exec(text);
|
|
9423
|
+
if (!token) return null;
|
|
9424
|
+
const part = token[0];
|
|
9425
|
+
start = token.index + part.length;
|
|
9426
|
+
if (part === "(" || part === "$(") {
|
|
9427
|
+
depth += 1;
|
|
9428
|
+
} else if (part === ")") {
|
|
9429
|
+
depth -= 1;
|
|
9430
|
+
if (!depth) return start;
|
|
9431
|
+
} else if (part === '"') {
|
|
9432
|
+
start = doubleQuoteEnd(text, start, level + 1);
|
|
9433
|
+
} else if (part === "${") {
|
|
9434
|
+
start = bracedWordEnd(text, start, level + 1);
|
|
9435
|
+
} else if (part === "`") {
|
|
9436
|
+
start = substitutionEnd(text, start, part, level + 1);
|
|
9437
|
+
} else if (part === "'" || part === "<<" || part === "case") {
|
|
9438
|
+
return null;
|
|
9439
|
+
}
|
|
9440
|
+
}
|
|
9441
|
+
return null;
|
|
7827
9442
|
}
|
|
7828
|
-
function
|
|
7829
|
-
if (
|
|
7830
|
-
|
|
7831
|
-
|
|
7832
|
-
|
|
7833
|
-
|
|
7834
|
-
|
|
9443
|
+
function bracedWordEnd(text, startPos, level = 0) {
|
|
9444
|
+
if (level >= MAX_DEFAULT_DEPTH) return null;
|
|
9445
|
+
let depth = 1;
|
|
9446
|
+
let start = startPos;
|
|
9447
|
+
const boundary = new RegExp(DEFAULT_BOUNDARY_PART, "g");
|
|
9448
|
+
while (start !== null) {
|
|
9449
|
+
boundary.lastIndex = start;
|
|
9450
|
+
const token = boundary.exec(text);
|
|
9451
|
+
if (!token) return null;
|
|
9452
|
+
const part = token[0];
|
|
9453
|
+
start = token.index + part.length;
|
|
9454
|
+
if (part === "${") {
|
|
9455
|
+
depth += 1;
|
|
9456
|
+
} else if (part === "}") {
|
|
9457
|
+
depth -= 1;
|
|
9458
|
+
if (!depth) return start;
|
|
9459
|
+
} else if (part === "$(" || part === "`") {
|
|
9460
|
+
start = substitutionEnd(text, start, part, level + 1);
|
|
9461
|
+
} else if (part === '"') {
|
|
9462
|
+
start = doubleQuoteEnd(text, start, level + 1);
|
|
9463
|
+
} else if (part === "'") {
|
|
9464
|
+
return null;
|
|
9465
|
+
}
|
|
7835
9466
|
}
|
|
7836
9467
|
return null;
|
|
7837
9468
|
}
|
|
7838
|
-
function
|
|
7839
|
-
|
|
7840
|
-
|
|
7841
|
-
|
|
7842
|
-
|
|
7843
|
-
|
|
7844
|
-
|
|
7845
|
-
|
|
7846
|
-
|
|
7847
|
-
|
|
7848
|
-
|
|
7849
|
-
|
|
7850
|
-
|
|
7851
|
-
|
|
7852
|
-
|
|
9469
|
+
function doubleQuoteEnd(text, startPos, level = 0) {
|
|
9470
|
+
if (level >= MAX_DEFAULT_DEPTH) return null;
|
|
9471
|
+
let start = startPos;
|
|
9472
|
+
const boundary = new RegExp(DOUBLE_QUOTE_END_PART, "g");
|
|
9473
|
+
while (start !== null) {
|
|
9474
|
+
boundary.lastIndex = start;
|
|
9475
|
+
const token = boundary.exec(text);
|
|
9476
|
+
if (!token) return null;
|
|
9477
|
+
const part = token[0];
|
|
9478
|
+
if (part === '"') return token.index + part.length;
|
|
9479
|
+
start = token.index + part.length;
|
|
9480
|
+
if (part === "${") {
|
|
9481
|
+
start = bracedWordEnd(text, start, level + 1);
|
|
9482
|
+
} else if (part === "$(" || part === "`") {
|
|
9483
|
+
start = substitutionEnd(text, start, part, level + 1);
|
|
9484
|
+
}
|
|
9485
|
+
}
|
|
9486
|
+
return null;
|
|
9487
|
+
}
|
|
9488
|
+
function* shellWordParts(text, quoted = false, opts = {}) {
|
|
9489
|
+
const syntax = opts.syntax === void 0 ? null : opts.syntax;
|
|
9490
|
+
const defaultText = opts.defaultText === true;
|
|
9491
|
+
let patternSource;
|
|
9492
|
+
if (defaultText) {
|
|
9493
|
+
patternSource = quoted ? QUOTED_DEFAULT_PART : DEFAULT_WORD_PART;
|
|
9494
|
+
} else if (quoted) {
|
|
9495
|
+
patternSource = QUOTED_WORD_PART;
|
|
9496
|
+
} else {
|
|
9497
|
+
patternSource = syntax !== null ? SHELL_SOURCE_PART : SHELL_WORD_PART;
|
|
9498
|
+
}
|
|
9499
|
+
const pattern = new RegExp(patternSource, "g");
|
|
9500
|
+
let offset = 0;
|
|
9501
|
+
while (true) {
|
|
9502
|
+
pattern.lastIndex = offset;
|
|
9503
|
+
const token = pattern.exec(text);
|
|
9504
|
+
if (!token) return;
|
|
9505
|
+
const part = token[0];
|
|
9506
|
+
let end = token.index + part.length;
|
|
9507
|
+
if (part === "#" && syntax !== null && syntax[token.index] === " ") {
|
|
9508
|
+
const newline = text.indexOf("\n", end);
|
|
9509
|
+
if (newline < 0) return;
|
|
9510
|
+
offset = newline + 1;
|
|
9511
|
+
continue;
|
|
9512
|
+
}
|
|
9513
|
+
if (part === "${") {
|
|
9514
|
+
end = bracedWordEnd(text, end);
|
|
9515
|
+
} else if (part === '"') {
|
|
9516
|
+
end = doubleQuoteEnd(text, end);
|
|
9517
|
+
} else if (part === "$(" || part === "`") {
|
|
9518
|
+
end = substitutionEnd(text, end, part, 0);
|
|
9519
|
+
}
|
|
9520
|
+
if (end === null) {
|
|
9521
|
+
if (syntax === null) return;
|
|
9522
|
+
const newline = text.indexOf("\n", token.index + part.length);
|
|
9523
|
+
if (newline < 0) return;
|
|
9524
|
+
offset = newline + 1;
|
|
7853
9525
|
continue;
|
|
7854
9526
|
}
|
|
7855
|
-
|
|
7856
|
-
|
|
7857
|
-
|
|
7858
|
-
|
|
7859
|
-
|
|
9527
|
+
yield [token.index, end];
|
|
9528
|
+
offset = end;
|
|
9529
|
+
}
|
|
9530
|
+
}
|
|
9531
|
+
function* splitFields(text) {
|
|
9532
|
+
const parts = text.split(SHELL_IFS_RE);
|
|
9533
|
+
for (let index = 0; index < parts.length; index++) {
|
|
9534
|
+
if (index % 2) yield null;
|
|
9535
|
+
else if (parts[index]) yield parts[index];
|
|
9536
|
+
}
|
|
9537
|
+
}
|
|
9538
|
+
function positionalValue(token, args) {
|
|
9539
|
+
const part = positionalMatch(token);
|
|
9540
|
+
if (part === null) return [token, false];
|
|
9541
|
+
const name = part[1] || part[2];
|
|
9542
|
+
const operator = part[3];
|
|
9543
|
+
if (name === "@") return [args, false];
|
|
9544
|
+
if (name === "*") return [args.join(" "), false];
|
|
9545
|
+
const index = name.length <= String(args.length).length ? parseInt(name, 10) - 1 : args.length;
|
|
9546
|
+
if (index < args.length && (operator !== ":-" || args[index])) {
|
|
9547
|
+
return [args[index], false];
|
|
9548
|
+
}
|
|
9549
|
+
return operator ? [token.slice(part[0].length, -1), true] : ["", false];
|
|
9550
|
+
}
|
|
9551
|
+
function defaultHasSubstitution(text, quoted) {
|
|
9552
|
+
for (const [start, end] of shellWordParts(text, quoted, { defaultText: true })) {
|
|
9553
|
+
const part = text.slice(start, end);
|
|
9554
|
+
if (part.startsWith("$(") || part.startsWith("`")) return true;
|
|
9555
|
+
if (part.startsWith('"') && defaultHasSubstitution(part.slice(1, -1), true)) return true;
|
|
9556
|
+
}
|
|
9557
|
+
return false;
|
|
9558
|
+
}
|
|
9559
|
+
function* argumentParts(word, args, opts = {}) {
|
|
9560
|
+
const quoted = opts.quoted === true;
|
|
9561
|
+
const defaultText = opts.defaultText === true;
|
|
9562
|
+
const defaultDepth = opts.defaultDepth ?? 0;
|
|
9563
|
+
const fieldSplit = !quoted;
|
|
9564
|
+
let offset = 0;
|
|
9565
|
+
for (const [start, end] of shellWordParts(word, quoted, { defaultText })) {
|
|
9566
|
+
if (start > offset) {
|
|
9567
|
+
const literal = word.slice(offset, start);
|
|
9568
|
+
if (fieldSplit) yield* splitFields(literal);
|
|
9569
|
+
else yield literal;
|
|
9570
|
+
}
|
|
9571
|
+
offset = end;
|
|
9572
|
+
const text = word.slice(start, end);
|
|
9573
|
+
if (!quoted && text.startsWith("'")) {
|
|
9574
|
+
yield text.slice(1, -1);
|
|
9575
|
+
} else if (text.startsWith('"')) {
|
|
9576
|
+
if (text === '""') {
|
|
9577
|
+
yield "";
|
|
9578
|
+
} else {
|
|
9579
|
+
yield* argumentParts(text.slice(1, -1), args, { quoted: true, defaultDepth });
|
|
9580
|
+
}
|
|
9581
|
+
} else if (text.startsWith("\\")) {
|
|
9582
|
+
const escaped = text.slice(1);
|
|
9583
|
+
if (escaped !== "\n") {
|
|
9584
|
+
const specials = defaultText ? '$"\\`}' : '$"\\`';
|
|
9585
|
+
yield !quoted || specials.includes(escaped) ? escaped : text;
|
|
9586
|
+
}
|
|
9587
|
+
} else if (positionalMatch(text) === null) {
|
|
9588
|
+
yield text;
|
|
9589
|
+
} else if (args === null) {
|
|
9590
|
+
yield UNRESOLVED;
|
|
9591
|
+
} else {
|
|
9592
|
+
const [value, useDefault] = positionalValue(text, args);
|
|
9593
|
+
if (useDefault) {
|
|
9594
|
+
if (defaultDepth >= MAX_DEFAULT_DEPTH || defaultHasSubstitution(value, quoted)) {
|
|
9595
|
+
yield UNRESOLVED;
|
|
9596
|
+
continue;
|
|
9597
|
+
}
|
|
9598
|
+
yield* argumentParts(value, args, {
|
|
9599
|
+
quoted,
|
|
9600
|
+
defaultText: true,
|
|
9601
|
+
defaultDepth: defaultDepth + 1
|
|
9602
|
+
});
|
|
9603
|
+
if (!value && !fieldSplit) yield "";
|
|
9604
|
+
} else if (!fieldSplit && Array.isArray(value)) {
|
|
9605
|
+
for (let index = 0; index < value.length; index++) {
|
|
9606
|
+
if (index) yield null;
|
|
9607
|
+
yield value[index];
|
|
9608
|
+
}
|
|
9609
|
+
} else if (!fieldSplit) {
|
|
9610
|
+
yield value;
|
|
9611
|
+
} else {
|
|
9612
|
+
yield* splitFields(Array.isArray(value) ? value.join(" ") : value);
|
|
7860
9613
|
}
|
|
7861
9614
|
}
|
|
7862
9615
|
}
|
|
7863
|
-
if (
|
|
7864
|
-
|
|
9616
|
+
if (offset < word.length) {
|
|
9617
|
+
const literal = word.slice(offset);
|
|
9618
|
+
if (fieldSplit) yield* splitFields(literal);
|
|
9619
|
+
else yield literal;
|
|
7865
9620
|
}
|
|
7866
|
-
return branches;
|
|
7867
9621
|
}
|
|
7868
|
-
function
|
|
7869
|
-
const
|
|
7870
|
-
|
|
7871
|
-
|
|
7872
|
-
const
|
|
7873
|
-
|
|
7874
|
-
|
|
7875
|
-
|
|
7876
|
-
|
|
7877
|
-
|
|
7878
|
-
|
|
7879
|
-
|
|
7880
|
-
|
|
7881
|
-
|
|
7882
|
-
|
|
7883
|
-
if (final === null) return null;
|
|
7884
|
-
} else {
|
|
7885
|
-
const branches = splitCaseBody(body);
|
|
7886
|
-
let selected = null;
|
|
7887
|
-
let fallback = "";
|
|
7888
|
-
for (const b of branches) {
|
|
7889
|
-
const values = b.label.split("|").map((v) => v.trim()).filter(Boolean);
|
|
7890
|
-
if (values.includes("*")) fallback = b.body;
|
|
7891
|
-
else if (values.includes(val)) selected = b.body;
|
|
7892
|
-
}
|
|
7893
|
-
final = selected !== null ? selected : fallback || null;
|
|
7894
|
-
if (final === null) return null;
|
|
7895
|
-
}
|
|
7896
|
-
const prefix = content.slice(0, m.index ?? 0);
|
|
7897
|
-
const suffix = lines.slice(endMatch + 1).join("\n");
|
|
7898
|
-
return `${prefix}
|
|
7899
|
-
${final}
|
|
7900
|
-
${suffix}`;
|
|
7901
|
-
}
|
|
7902
|
-
function findCaseEndInLines(lines, headerLine) {
|
|
7903
|
-
let depth = 0;
|
|
7904
|
-
for (let idx = headerLine; idx < lines.length; idx++) {
|
|
7905
|
-
const ln = lines[idx];
|
|
7906
|
-
const opens = (ln.match(/\bcase\b/g) || []).length;
|
|
7907
|
-
const closes = (ln.match(/\besac\b/g) || []).length;
|
|
7908
|
-
depth += opens - closes;
|
|
7909
|
-
if (depth <= 0 && idx > headerLine) return idx;
|
|
9622
|
+
function expandShellWord(word, args, opts = {}) {
|
|
9623
|
+
const quotedDefault = opts.quotedDefault === true;
|
|
9624
|
+
const fields = [];
|
|
9625
|
+
let pieces = [];
|
|
9626
|
+
for (const part of argumentParts(word, args, {
|
|
9627
|
+
quoted: quotedDefault,
|
|
9628
|
+
defaultText: quotedDefault
|
|
9629
|
+
})) {
|
|
9630
|
+
if (part === UNRESOLVED) return null;
|
|
9631
|
+
if (part !== null) {
|
|
9632
|
+
pieces.push(part);
|
|
9633
|
+
} else if (pieces.length) {
|
|
9634
|
+
fields.push(pieces.join(""));
|
|
9635
|
+
pieces = [];
|
|
9636
|
+
}
|
|
7910
9637
|
}
|
|
7911
|
-
|
|
9638
|
+
if (pieces.length) fields.push(pieces.join(""));
|
|
9639
|
+
return fields;
|
|
7912
9640
|
}
|
|
7913
|
-
function
|
|
7914
|
-
|
|
7915
|
-
|
|
7916
|
-
|
|
7917
|
-
|
|
7918
|
-
|
|
7919
|
-
|
|
7920
|
-
|
|
7921
|
-
|
|
7922
|
-
|
|
7923
|
-
|
|
7924
|
-
if (
|
|
7925
|
-
|
|
7926
|
-
|
|
7927
|
-
|
|
7928
|
-
|
|
7929
|
-
|
|
7930
|
-
|
|
7931
|
-
|
|
7932
|
-
|
|
7933
|
-
|
|
7934
|
-
|
|
7935
|
-
|
|
7936
|
-
|
|
7937
|
-
|
|
7938
|
-
|
|
7939
|
-
|
|
9641
|
+
function bindPositionalArgs(content, args) {
|
|
9642
|
+
if (!args.length || !content.includes("$")) return content;
|
|
9643
|
+
const bindText = (text, quoted = false) => {
|
|
9644
|
+
const out = [];
|
|
9645
|
+
let offset = 0;
|
|
9646
|
+
let syntax = null;
|
|
9647
|
+
if (!quoted) syntax = text.includes("#") ? caseSyntaxLines(text).join("\n") : text;
|
|
9648
|
+
for (const [start, end] of shellWordParts(text, quoted, { syntax })) {
|
|
9649
|
+
const token = text.slice(start, end);
|
|
9650
|
+
out.push(text.slice(offset, start));
|
|
9651
|
+
offset = end;
|
|
9652
|
+
if (token.startsWith('"')) {
|
|
9653
|
+
out.push('"' + bindText(token.slice(1, -1), true) + '"');
|
|
9654
|
+
} else if (positionalMatch(token)) {
|
|
9655
|
+
const [value, useDefault] = positionalValue(token, args);
|
|
9656
|
+
let values = Array.isArray(value) ? value : [value];
|
|
9657
|
+
if (useDefault) {
|
|
9658
|
+
if (defaultHasSubstitution(values[0], quoted)) {
|
|
9659
|
+
out.push(token);
|
|
9660
|
+
continue;
|
|
9661
|
+
}
|
|
9662
|
+
const expanded = expandShellWord(values[0], args, { quotedDefault: quoted });
|
|
9663
|
+
if (expanded === null) {
|
|
9664
|
+
out.push(token);
|
|
9665
|
+
continue;
|
|
9666
|
+
}
|
|
9667
|
+
values = expanded;
|
|
9668
|
+
}
|
|
9669
|
+
if (quoted) values = values.map((item) => item.replace(/([\\$"`])/g, "\\$1"));
|
|
9670
|
+
out.push(values.join(quoted ? '" "' : " "));
|
|
9671
|
+
} else {
|
|
9672
|
+
out.push(token);
|
|
7940
9673
|
}
|
|
7941
9674
|
}
|
|
7942
|
-
|
|
7943
|
-
|
|
7944
|
-
|
|
7945
|
-
|
|
7946
|
-
|
|
9675
|
+
out.push(text.slice(offset));
|
|
9676
|
+
return out.join("");
|
|
9677
|
+
};
|
|
9678
|
+
return bindText(content);
|
|
9679
|
+
}
|
|
9680
|
+
function findSelectorValue(selector, args) {
|
|
9681
|
+
if (!args || !args.length) return null;
|
|
9682
|
+
const m = selector.match(/^\$\{?(\d+)\}?$/);
|
|
9683
|
+
if (m) {
|
|
9684
|
+
const idx = parseInt(m[1], 10);
|
|
9685
|
+
if (1 <= idx && idx <= args.length) return args[idx - 1];
|
|
9686
|
+
return null;
|
|
9687
|
+
}
|
|
9688
|
+
return null;
|
|
9689
|
+
}
|
|
9690
|
+
function parseCase(content, args, diagnostics) {
|
|
9691
|
+
if (!args || !args.length || !CASE_HEADER_RE.test(content)) return null;
|
|
9692
|
+
const lines = content.split("\n");
|
|
9693
|
+
const syntaxLines = caseSyntaxLines(content);
|
|
9694
|
+
let index = -1;
|
|
9695
|
+
for (let i = 0; i < syntaxLines.length; i++) {
|
|
9696
|
+
if (CASE_HEADER_RE.test(syntaxLines[i])) {
|
|
9697
|
+
index = i;
|
|
9698
|
+
break;
|
|
7947
9699
|
}
|
|
7948
9700
|
}
|
|
7949
|
-
if (
|
|
7950
|
-
|
|
9701
|
+
if (index < 0) return null;
|
|
9702
|
+
const caseStmt = parseCaseStatement(lines, syntaxLines, index);
|
|
9703
|
+
if (caseStmt === null) return null;
|
|
9704
|
+
const value = findSelectorValue(caseStmt.selector, args);
|
|
9705
|
+
if (value === null) return null;
|
|
9706
|
+
const selection = selectCaseBranch(caseStmt, value);
|
|
9707
|
+
if (selection === null) return null;
|
|
9708
|
+
const [branch, kind] = selection;
|
|
9709
|
+
if (diagnostics) diagnostics.p1_case = kind;
|
|
9710
|
+
const end = index + caseStmt.line.split("\n").length;
|
|
9711
|
+
return [...lines.slice(0, index), caseStmt.branches[branch].body, ...lines.slice(end)].join("\n");
|
|
9712
|
+
}
|
|
9713
|
+
function unquoteIfToken(tok) {
|
|
9714
|
+
tok = tok.trim();
|
|
9715
|
+
let quoted = false;
|
|
9716
|
+
if (tok.length >= 2 && (tok[0] === '"' || tok[0] === "'") && tok[tok.length - 1] === tok[0]) {
|
|
9717
|
+
tok = tok.slice(1, -1);
|
|
9718
|
+
quoted = true;
|
|
9719
|
+
}
|
|
9720
|
+
if (tok.includes('"') || tok.includes("'") || tok.includes("\\")) return null;
|
|
9721
|
+
return [tok, quoted];
|
|
7951
9722
|
}
|
|
7952
9723
|
function evalIfCondition(cond, args) {
|
|
7953
9724
|
if (!args || !args.length) return null;
|
|
7954
|
-
const
|
|
7955
|
-
const
|
|
9725
|
+
const doubleBracket = cond.trimStart().startsWith("[[");
|
|
9726
|
+
const inner = cond.replace(/^\[\[?|\]\]?$/g, "").trim();
|
|
9727
|
+
const m = /(.*?)\s*(=~|==|!=|=)\s*(.*)/.exec(inner);
|
|
7956
9728
|
if (!m) return null;
|
|
7957
9729
|
const op = m[2];
|
|
7958
|
-
|
|
7959
|
-
|
|
9730
|
+
const leftPair = unquoteIfToken(m[1]);
|
|
9731
|
+
const rightPair = unquoteIfToken(m[3]);
|
|
9732
|
+
if (leftPair === null || rightPair === null) return null;
|
|
9733
|
+
const [left] = leftPair;
|
|
9734
|
+
const [right, rightQuoted] = rightPair;
|
|
7960
9735
|
const resolve13 = (tok) => {
|
|
7961
9736
|
const rm = tok.match(/^\$(\d+)$/);
|
|
7962
9737
|
if (rm) {
|
|
7963
9738
|
const idx = parseInt(rm[1], 10);
|
|
7964
9739
|
return 1 <= idx && idx <= args.length ? args[idx - 1] : null;
|
|
7965
9740
|
}
|
|
7966
|
-
|
|
9741
|
+
if (tok.startsWith("$")) return null;
|
|
9742
|
+
return tok;
|
|
7967
9743
|
};
|
|
7968
9744
|
const lv = resolve13(left);
|
|
7969
9745
|
const rv = resolve13(right);
|
|
7970
9746
|
if (lv === null || rv === null) return null;
|
|
7971
9747
|
if (op === "=~") {
|
|
7972
|
-
|
|
7973
|
-
|
|
9748
|
+
if (!doubleBracket) return null;
|
|
9749
|
+
let pattern = rv;
|
|
9750
|
+
if (pattern.startsWith("/") && pattern.endsWith("/") && pattern.length > 1) {
|
|
9751
|
+
pattern = pattern.slice(1, -1);
|
|
9752
|
+
}
|
|
9753
|
+
const source = rightQuoted ? escapeRegex(pattern) : pattern;
|
|
7974
9754
|
try {
|
|
7975
|
-
return new RegExp(
|
|
9755
|
+
return new RegExp(source).test(lv);
|
|
7976
9756
|
} catch {
|
|
7977
9757
|
return null;
|
|
7978
9758
|
}
|
|
7979
9759
|
}
|
|
7980
|
-
|
|
9760
|
+
let matched;
|
|
9761
|
+
if (!rightQuoted && (rv.includes("*") || rv.includes("?") || rv.includes("["))) {
|
|
9762
|
+
if (!doubleBracket) {
|
|
9763
|
+
return null;
|
|
9764
|
+
}
|
|
9765
|
+
matched = fnmatchCase2(lv, rv);
|
|
9766
|
+
} else {
|
|
9767
|
+
matched = lv === rv;
|
|
9768
|
+
}
|
|
7981
9769
|
return op === "!=" ? !matched : matched;
|
|
7982
9770
|
}
|
|
7983
|
-
function
|
|
7984
|
-
|
|
9771
|
+
function escapeRegex(s) {
|
|
9772
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
9773
|
+
}
|
|
9774
|
+
function fnmatchCase2(value, pattern) {
|
|
9775
|
+
if (!/[*?[]/.test(pattern)) return pattern === value;
|
|
9776
|
+
let out = "^";
|
|
9777
|
+
let i = 0;
|
|
9778
|
+
while (i < pattern.length) {
|
|
9779
|
+
const c = pattern[i];
|
|
9780
|
+
if (c === "*") out += ".*";
|
|
9781
|
+
else if (c === "?") out += ".";
|
|
9782
|
+
else if (c === "[") {
|
|
9783
|
+
let j = i + 1;
|
|
9784
|
+
let neg = false;
|
|
9785
|
+
if (j < pattern.length && (pattern[j] === "!" || pattern[j] === "^")) {
|
|
9786
|
+
neg = true;
|
|
9787
|
+
j++;
|
|
9788
|
+
}
|
|
9789
|
+
let cls = "";
|
|
9790
|
+
while (j < pattern.length && pattern[j] !== "]") {
|
|
9791
|
+
cls += pattern[j];
|
|
9792
|
+
j++;
|
|
9793
|
+
}
|
|
9794
|
+
if (j >= pattern.length) {
|
|
9795
|
+
out += escapeRegex(pattern.slice(i));
|
|
9796
|
+
break;
|
|
9797
|
+
}
|
|
9798
|
+
out += "[" + (neg ? "^" : "") + escapeRegex(cls) + "]";
|
|
9799
|
+
i = j;
|
|
9800
|
+
} else {
|
|
9801
|
+
out += escapeRegex(c);
|
|
9802
|
+
}
|
|
9803
|
+
i++;
|
|
9804
|
+
}
|
|
9805
|
+
out += "$";
|
|
9806
|
+
return new RegExp(out, "s").test(value);
|
|
9807
|
+
}
|
|
9808
|
+
function parseIf(content, args, diagnostics) {
|
|
9809
|
+
const m = /\bif\s+([^\n;]+?)\s*;\s*then/.exec(content);
|
|
7985
9810
|
if (!m) return null;
|
|
7986
|
-
const
|
|
9811
|
+
const cond = m[1].trim();
|
|
9812
|
+
const truth = evalIfCondition(cond, args);
|
|
7987
9813
|
if (truth === null) return null;
|
|
7988
|
-
const start = m.index
|
|
9814
|
+
const start = m.index;
|
|
7989
9815
|
const thenBodyStart = start + m[0].length;
|
|
7990
9816
|
const fiPos = content.indexOf("fi", thenBodyStart);
|
|
7991
9817
|
if (fiPos === -1) return null;
|
|
7992
9818
|
const segment = content.slice(thenBodyStart, fiPos);
|
|
7993
|
-
const elseM =
|
|
9819
|
+
const elseM = /\belse\b/.exec(segment);
|
|
7994
9820
|
let chosen;
|
|
7995
|
-
if (truth)
|
|
7996
|
-
|
|
9821
|
+
if (truth) {
|
|
9822
|
+
chosen = elseM ? segment.slice(0, elseM.index) : segment;
|
|
9823
|
+
} else {
|
|
7997
9824
|
if (!elseM) return null;
|
|
7998
|
-
chosen = segment.slice(
|
|
9825
|
+
chosen = segment.slice(elseM.index + 4);
|
|
7999
9826
|
}
|
|
9827
|
+
if (diagnostics) diagnostics.p1_if = truth ? "then" : "else";
|
|
8000
9828
|
return `${content.slice(0, start)}
|
|
8001
9829
|
${chosen}
|
|
8002
9830
|
${content.slice(fiPos + 2)}`;
|
|
@@ -8025,63 +9853,153 @@ function stripNonExecutableLines(content) {
|
|
|
8025
9853
|
function markLoopsReachable(content) {
|
|
8026
9854
|
return content;
|
|
8027
9855
|
}
|
|
8028
|
-
function extractCallsFromContent(content) {
|
|
9856
|
+
function extractCallsFromContent(content, entryArgs = null) {
|
|
9857
|
+
if (!CHILD_INTERPRETER_RE.test(content)) return [];
|
|
9858
|
+
let syntax = caseSyntaxLines(content).join("\n");
|
|
9859
|
+
if (content.includes("${")) {
|
|
9860
|
+
const parts = [];
|
|
9861
|
+
let offset = 0;
|
|
9862
|
+
for (const [start, end] of shellWordParts(content, false, { syntax })) {
|
|
9863
|
+
const token = content.slice(start, end);
|
|
9864
|
+
if (!token.includes("${") || syntax[start] === " ") continue;
|
|
9865
|
+
if (token.startsWith('"') && defaultHasSubstitution(token.slice(1, -1), true)) continue;
|
|
9866
|
+
parts.push(syntax.slice(offset, start));
|
|
9867
|
+
parts.push(token.replace(/[^\n]/g, "x"));
|
|
9868
|
+
offset = end;
|
|
9869
|
+
}
|
|
9870
|
+
parts.push(syntax.slice(offset));
|
|
9871
|
+
syntax = parts.join("");
|
|
9872
|
+
}
|
|
8029
9873
|
const calls = [];
|
|
8030
|
-
|
|
8031
|
-
|
|
8032
|
-
while ((
|
|
8033
|
-
|
|
8034
|
-
|
|
8035
|
-
|
|
8036
|
-
|
|
8037
|
-
|
|
8038
|
-
|
|
8039
|
-
|
|
8040
|
-
|
|
9874
|
+
const re = new RegExp(CHILD_CALL_SOURCE, "gmd");
|
|
9875
|
+
let match;
|
|
9876
|
+
while ((match = re.exec(syntax)) !== null) {
|
|
9877
|
+
if (match[0] === "") {
|
|
9878
|
+
re.lastIndex += 1;
|
|
9879
|
+
continue;
|
|
9880
|
+
}
|
|
9881
|
+
const range = match.indices?.[2];
|
|
9882
|
+
if (!range) continue;
|
|
9883
|
+
const [start, end] = range;
|
|
9884
|
+
const words = [...syntax.slice(start, end).matchAll(/[^ \t]+/g)];
|
|
9885
|
+
const truncated = syntax.slice(end, end + 1) === "\0" && !content.startsWith("<<", end) || syntax.startsWith("$(", end - 1);
|
|
9886
|
+
if (truncated && words.length && words[words.length - 1].index + words[words.length - 1][0].length === end - start) {
|
|
9887
|
+
words.pop();
|
|
9888
|
+
}
|
|
9889
|
+
const argv = [];
|
|
9890
|
+
let argsKnown = !truncated;
|
|
9891
|
+
for (const word of words) {
|
|
9892
|
+
const fields = expandShellWord(
|
|
9893
|
+
content.slice(start + word.index, start + word.index + word[0].length),
|
|
9894
|
+
entryArgs
|
|
9895
|
+
);
|
|
9896
|
+
if (fields === null) {
|
|
9897
|
+
argsKnown = false;
|
|
9898
|
+
break;
|
|
9899
|
+
}
|
|
9900
|
+
argv.push(...fields);
|
|
9901
|
+
}
|
|
9902
|
+
if (argv.length && argv[0] && !argv[0].startsWith("-") && !argv[0].startsWith("$") && !argv[0].includes("/dev/")) {
|
|
9903
|
+
calls.push({
|
|
9904
|
+
path: argv[0],
|
|
9905
|
+
args: argsKnown ? argv.slice(1) : [],
|
|
9906
|
+
interpreter: match[1],
|
|
9907
|
+
argsKnown
|
|
9908
|
+
});
|
|
8041
9909
|
}
|
|
8042
|
-
calls.push({ path: path9, args, interpreter: interp });
|
|
8043
9910
|
}
|
|
8044
9911
|
return calls;
|
|
8045
9912
|
}
|
|
8046
|
-
var HEREDOC_RE,
|
|
9913
|
+
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;
|
|
8047
9914
|
var init_shell_backend = __esm({
|
|
8048
9915
|
"src/engine/script-engine/backends/shell-backend.ts"() {
|
|
8049
9916
|
"use strict";
|
|
8050
9917
|
init_esm_shims();
|
|
9918
|
+
init_ir();
|
|
8051
9919
|
init_symbolic();
|
|
9920
|
+
POSITIONAL_RE = /\$(?:([1-9@*])|\{([1-9][0-9]*|[@*])(?:(:-|-)|\}))/;
|
|
9921
|
+
QUOTED_WORD_PART = String.raw`\$\{|\\[\s\S]|\$[1-9@*]`;
|
|
9922
|
+
SHELL_WORD_PART = String.raw`'[^']*'|"|` + QUOTED_WORD_PART;
|
|
9923
|
+
SHELL_SOURCE_PART = String.raw`\#|` + SHELL_WORD_PART;
|
|
9924
|
+
SUBSTITUTION_START = String.raw`\$\(|\x60`;
|
|
9925
|
+
DEFAULT_WORD_PART = SUBSTITUTION_START + "|" + SHELL_WORD_PART;
|
|
9926
|
+
QUOTED_DEFAULT_PART = SUBSTITUTION_START + String.raw`|"|` + QUOTED_WORD_PART;
|
|
9927
|
+
DOUBLE_QUOTE_END_PART = String.raw`\\[\s\S]|\$\{|` + SUBSTITUTION_START + String.raw`|"`;
|
|
9928
|
+
DEFAULT_BOUNDARY_PART = String.raw`\\[\s\S]|'[^']*'|"|\$\{|` + SUBSTITUTION_START + String.raw`|[}']`;
|
|
9929
|
+
SUBSTITUTION_BOUNDARY_PART = String.raw`\\[\s\S]|'[^']*'|"|\$\{|` + SUBSTITUTION_START + String.raw`|[()']|<<` + String.raw`|(?<![^\s;&|()<>])(?:\#[^\n]*|case(?=[ \t]))`;
|
|
9930
|
+
BACKTICK_PART = String.raw`\x60(?:\\[\s\S]|[^\x60\\])*\x60`;
|
|
9931
|
+
BACKTICK_ANCHORED_RE = new RegExp("^(?:" + BACKTICK_PART + ")");
|
|
9932
|
+
SHELL_IFS_RE = /([ \t\n]+)/;
|
|
9933
|
+
UNRESOLVED = /* @__PURE__ */ Symbol("unresolved");
|
|
9934
|
+
MAX_DEFAULT_DEPTH = 32;
|
|
8052
9935
|
HEREDOC_RE = /<<-?\s*['"]?(\w+)['"]?/;
|
|
8053
|
-
|
|
9936
|
+
CHILD_INTERPRETER_RE = /\b(?:bash|sh|zsh|python(?:3(?:\.[0-9]+)?)?|node|ruby|perl|php|lua)\b/;
|
|
9937
|
+
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]+)`;
|
|
8054
9938
|
ShellBackend = class {
|
|
8055
9939
|
language = "shell";
|
|
8056
|
-
|
|
8057
|
-
|
|
8058
|
-
|
|
8059
|
-
|
|
9940
|
+
ENTRY_PATTERNS = [
|
|
9941
|
+
String.raw`(?:^|\s|&&|\|\|)\s*bash\s+(\S+)`,
|
|
9942
|
+
String.raw`(?:^|\s|&&|\|\|)\s*(?:/bin/)?sh\s+(\S+)`,
|
|
9943
|
+
String.raw`(?:^|\s|&&|\|\|)\s*zsh\s+(\S+)`,
|
|
9944
|
+
String.raw`\./(\S+)`,
|
|
9945
|
+
String.raw`(?:^|\s|&&|\|\|)\s*source\s+(\S+)`
|
|
9946
|
+
];
|
|
9947
|
+
parse(content, entryArgs, options = {}) {
|
|
9948
|
+
const diagnostics = options.diagnostics;
|
|
9949
|
+
const argsKnown = options.argsKnown !== false;
|
|
9950
|
+
let candidate = content || "";
|
|
8060
9951
|
let resolved = false;
|
|
8061
|
-
const
|
|
9952
|
+
const P1_UNSAFE_RE = /\bshift\b|\bset\s+--(?:\s|$)|[\s;|&]read\b|^\s*read\b|\(\)\s*\{|function\s+\w+/;
|
|
9953
|
+
const p1Safe = argsKnown && !P1_UNSAFE_RE.test(candidate);
|
|
8062
9954
|
if (p1Safe) {
|
|
8063
|
-
const caseOut = parseCase(candidate, entryArgs);
|
|
9955
|
+
const caseOut = parseCase(candidate, entryArgs, diagnostics);
|
|
8064
9956
|
if (caseOut !== null && caseOut !== candidate) {
|
|
8065
9957
|
resolved = true;
|
|
8066
9958
|
candidate = caseOut;
|
|
8067
9959
|
}
|
|
8068
|
-
|
|
8069
|
-
|
|
8070
|
-
|
|
8071
|
-
|
|
9960
|
+
if (!CASE_HEADER_RE.test(candidate)) {
|
|
9961
|
+
const ifOut = parseIf(candidate, entryArgs, diagnostics);
|
|
9962
|
+
if (ifOut !== null && ifOut !== candidate) {
|
|
9963
|
+
resolved = true;
|
|
9964
|
+
candidate = ifOut;
|
|
9965
|
+
}
|
|
8072
9966
|
}
|
|
8073
9967
|
}
|
|
8074
|
-
|
|
8075
|
-
|
|
8076
|
-
|
|
8077
|
-
|
|
9968
|
+
if (diagnostics) {
|
|
9969
|
+
diagnostics.parser = "shell_p1";
|
|
9970
|
+
diagnostics.p1_safe = p1Safe;
|
|
9971
|
+
diagnostics.child_extractor = "regex";
|
|
9972
|
+
}
|
|
9973
|
+
if (!argsKnown) {
|
|
9974
|
+
if (diagnostics) {
|
|
9975
|
+
diagnostics.parser = "shell_full";
|
|
9976
|
+
diagnostics.fallback_reason = "unknown_args";
|
|
9977
|
+
}
|
|
9978
|
+
} else if (!resolved) {
|
|
9979
|
+
const symbolicDiagnostics = diagnostics ? {} : void 0;
|
|
9980
|
+
const symOut = symbolicProcess(content ?? "", entryArgs, symbolicDiagnostics);
|
|
9981
|
+
if (symOut !== null && symOut !== content) {
|
|
8078
9982
|
resolved = true;
|
|
8079
|
-
|
|
9983
|
+
candidate = symOut;
|
|
9984
|
+
}
|
|
9985
|
+
if (diagnostics && symbolicDiagnostics) {
|
|
9986
|
+
diagnostics.parser = resolved ? "shell_litese" : "shell_full";
|
|
9987
|
+
diagnostics.symbolic = symbolicDiagnostics;
|
|
9988
|
+
if (!resolved) {
|
|
9989
|
+
diagnostics.fallback_reason = symbolicDiagnostics.fallback_reason || "no_pruning";
|
|
9990
|
+
}
|
|
9991
|
+
if (symOut !== null && symOut !== void 0) {
|
|
9992
|
+
const fingerprint2 = scanFingerprint(symOut);
|
|
9993
|
+
symbolicDiagnostics.output_bytes = fingerprint2.bytes;
|
|
9994
|
+
symbolicDiagnostics.output_sha256 = fingerprint2.sha256;
|
|
9995
|
+
}
|
|
8080
9996
|
}
|
|
8081
9997
|
}
|
|
8082
|
-
|
|
9998
|
+
candidate = stripNonExecutableLines(candidate);
|
|
9999
|
+
const bindArgs = p1Safe ? entryArgs : null;
|
|
10000
|
+
const calls = extractCallsFromContent(candidate, bindArgs);
|
|
10001
|
+
const bound = bindPositionalArgs(candidate, bindArgs || []);
|
|
8083
10002
|
const loopMarked = markLoopsReachable(bound);
|
|
8084
|
-
const calls = extractCallsFromContent(loopMarked);
|
|
8085
10003
|
return {
|
|
8086
10004
|
reachableContent: loopMarked,
|
|
8087
10005
|
controlFlowResolved: resolved,
|
|
@@ -8108,7 +10026,7 @@ var init_backends = __esm({
|
|
|
8108
10026
|
|
|
8109
10027
|
// src/engine/script-engine/tracker.ts
|
|
8110
10028
|
import * as fs3 from "fs";
|
|
8111
|
-
import * as
|
|
10029
|
+
import * as path5 from "path";
|
|
8112
10030
|
import * as os2 from "os";
|
|
8113
10031
|
function maxFileSizeFromEnv() {
|
|
8114
10032
|
const raw = (process.env.AGENT_MOSS_SCRIPT_MAX_FILE_SIZE || "").trim();
|
|
@@ -8125,14 +10043,44 @@ function pickBackend(pathStr) {
|
|
|
8125
10043
|
}
|
|
8126
10044
|
return DEFAULT_BACKEND;
|
|
8127
10045
|
}
|
|
10046
|
+
function realpathBestEffort(absolutePath) {
|
|
10047
|
+
try {
|
|
10048
|
+
return fs3.realpathSync.native(absolutePath);
|
|
10049
|
+
} catch {
|
|
10050
|
+
}
|
|
10051
|
+
try {
|
|
10052
|
+
return fs3.realpathSync(absolutePath);
|
|
10053
|
+
} catch {
|
|
10054
|
+
}
|
|
10055
|
+
const tail = [];
|
|
10056
|
+
let current = absolutePath;
|
|
10057
|
+
while (true) {
|
|
10058
|
+
const parent = path5.dirname(current);
|
|
10059
|
+
if (parent === current) break;
|
|
10060
|
+
tail.unshift(path5.basename(current));
|
|
10061
|
+
current = parent;
|
|
10062
|
+
if (fs3.existsSync(current)) {
|
|
10063
|
+
try {
|
|
10064
|
+
return path5.join(realpathBestEffort(current), ...tail);
|
|
10065
|
+
} catch {
|
|
10066
|
+
break;
|
|
10067
|
+
}
|
|
10068
|
+
}
|
|
10069
|
+
}
|
|
10070
|
+
return absolutePath;
|
|
10071
|
+
}
|
|
10072
|
+
function isAbsoluteExpanded(p) {
|
|
10073
|
+
if (p === "~" || p.startsWith("~/")) return true;
|
|
10074
|
+
return path5.isAbsolute(p);
|
|
10075
|
+
}
|
|
8128
10076
|
function resolvePath(p, baseDir) {
|
|
8129
10077
|
let expanded = p;
|
|
8130
10078
|
if (expanded.startsWith("~/") || expanded === "~") {
|
|
8131
|
-
expanded =
|
|
8132
|
-
} else if (!
|
|
8133
|
-
expanded =
|
|
10079
|
+
expanded = path5.join(os2.homedir(), expanded.slice(1));
|
|
10080
|
+
} else if (!path5.isAbsolute(expanded) && baseDir) {
|
|
10081
|
+
expanded = path5.join(baseDir, expanded);
|
|
8134
10082
|
}
|
|
8135
|
-
return
|
|
10083
|
+
return realpathBestEffort(path5.resolve(expanded));
|
|
8136
10084
|
}
|
|
8137
10085
|
function readScript(pathStr, maxFileSize) {
|
|
8138
10086
|
try {
|
|
@@ -8177,28 +10125,41 @@ function emptyNode(pathStr, depth) {
|
|
|
8177
10125
|
keywordRiskReason: ""
|
|
8178
10126
|
};
|
|
8179
10127
|
}
|
|
8180
|
-
|
|
10128
|
+
function captureReachableContent(details, source, reachable) {
|
|
10129
|
+
details.reachable_content_matches_source = reachable === source;
|
|
10130
|
+
if ([...reachable].length <= MAX_DIAGNOSTIC_CONTENT_BYTES) {
|
|
10131
|
+
details.reachable_content = reachable;
|
|
10132
|
+
} else {
|
|
10133
|
+
details.reachable_content_omitted = true;
|
|
10134
|
+
}
|
|
10135
|
+
}
|
|
10136
|
+
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;
|
|
8181
10137
|
var init_tracker = __esm({
|
|
8182
10138
|
"src/engine/script-engine/tracker.ts"() {
|
|
8183
10139
|
"use strict";
|
|
8184
10140
|
init_esm_shims();
|
|
10141
|
+
init_ir();
|
|
8185
10142
|
init_python_backend();
|
|
8186
10143
|
init_backends();
|
|
8187
10144
|
DEFAULT_MAX_DEPTH = 14;
|
|
8188
10145
|
DEFAULT_MAX_NODES = 64;
|
|
8189
10146
|
DEFAULT_MAX_FILE_SIZE = maxFileSizeFromEnv();
|
|
8190
10147
|
DEFAULT_MAX_TOTAL_SIZE = 8 * 1024 * 1024;
|
|
10148
|
+
DIAGNOSTIC_NODE_LIMIT = 8;
|
|
10149
|
+
DIAGNOSTIC_CHILD_LIMIT = 4;
|
|
10150
|
+
MAX_DIAGNOSTIC_CONTENT_BYTES = 8 * 1024;
|
|
8191
10151
|
BACKENDS = {
|
|
8192
10152
|
".py": new PythonBackend()
|
|
8193
10153
|
};
|
|
8194
10154
|
DEFAULT_BACKEND = new ShellBackend();
|
|
8195
10155
|
RecursiveTracker = class {
|
|
8196
|
-
constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true) {
|
|
10156
|
+
constructor(commandScanner, maxDepth = DEFAULT_MAX_DEPTH, maxNodes = DEFAULT_MAX_NODES, maxFileSize = DEFAULT_MAX_FILE_SIZE, maxTotalSize = DEFAULT_MAX_TOTAL_SIZE, stopOnCritical = true, diagnostics = null) {
|
|
8197
10157
|
this.maxDepth = maxDepth;
|
|
8198
10158
|
this.maxNodes = maxNodes;
|
|
8199
10159
|
this.maxFileSize = maxFileSize;
|
|
8200
10160
|
this.maxTotalSize = maxTotalSize;
|
|
8201
10161
|
this.stopOnCritical = stopOnCritical;
|
|
10162
|
+
this.diagnostics = diagnostics;
|
|
8202
10163
|
this._scanner = commandScanner;
|
|
8203
10164
|
this.result = {
|
|
8204
10165
|
nodes: [],
|
|
@@ -8220,39 +10181,78 @@ var init_tracker = __esm({
|
|
|
8220
10181
|
maxFileSize;
|
|
8221
10182
|
maxTotalSize;
|
|
8222
10183
|
stopOnCritical;
|
|
10184
|
+
diagnostics;
|
|
8223
10185
|
result;
|
|
8224
10186
|
visiting = /* @__PURE__ */ new Set();
|
|
8225
|
-
|
|
10187
|
+
/**
|
|
10188
|
+
* 已处理集合:按 (路径 → 调用上下文) 去重。
|
|
10189
|
+
* 同一脚本可能先以带参直接调用扫描过,再被 import / 另一组参数调用;
|
|
10190
|
+
* sys.argv 分支完全不同,不能因为"路径访问过"就跳过(会漏掉危险分支)。
|
|
10191
|
+
*/
|
|
10192
|
+
visited = /* @__PURE__ */ new Map();
|
|
8226
10193
|
_scanner;
|
|
10194
|
+
_diagnosticNodes = [];
|
|
10195
|
+
_budgetSkips = { depth: 0, nodes: 0, total_bytes: 0 };
|
|
8227
10196
|
track(entryPath, entryArgs, cwd = "") {
|
|
8228
|
-
const
|
|
8229
|
-
const resolved = resolvePath(entryPath);
|
|
10197
|
+
const processCwd = resolvePath(cwd || ".");
|
|
10198
|
+
const resolved = resolvePath(entryPath, processCwd);
|
|
8230
10199
|
this.result.entryPath = resolved;
|
|
8231
|
-
this.visitScript(resolved, 0,
|
|
10200
|
+
this.visitScript(resolved, 0, processCwd, entryArgs);
|
|
8232
10201
|
const nodes = this.result.nodes;
|
|
8233
10202
|
this.result.hasCritical = nodes.some((n) => n.l1RiskLevel === "critical" || n.l2RiskLevel === "critical" || n.keywordRiskLevel === "critical") || this.result.hasCritical;
|
|
8234
10203
|
this.result.hasHigh = nodes.some((n) => ["high", "critical"].includes(n.l1RiskLevel) || ["high", "critical"].includes(n.l2RiskLevel) || ["high", "critical"].includes(n.keywordRiskLevel));
|
|
8235
10204
|
this.result.firstHitNode = nodes.find((n) => n.l1Hit || n.l2Hit || n.isSuspicious) || null;
|
|
10205
|
+
if (this.diagnostics !== null) {
|
|
10206
|
+
const maxVisitedDepth = nodes.reduce((max, node) => Math.max(max, node.depth), 0);
|
|
10207
|
+
this.diagnostics.nodes = this._diagnosticNodes;
|
|
10208
|
+
this.diagnostics.node_count = nodes.length;
|
|
10209
|
+
this.diagnostics.omitted_nodes = nodes.length - this._diagnosticNodes.length;
|
|
10210
|
+
this.diagnostics.max_visited_depth = maxVisitedDepth;
|
|
10211
|
+
this.diagnostics.total_bytes = this.result.totalSize;
|
|
10212
|
+
this.diagnostics.budget_skips = this._budgetSkips;
|
|
10213
|
+
this.diagnostics.limits = {
|
|
10214
|
+
depth: this.maxDepth,
|
|
10215
|
+
nodes: this.maxNodes,
|
|
10216
|
+
file_bytes: this.maxFileSize,
|
|
10217
|
+
total_bytes: this.maxTotalSize
|
|
10218
|
+
};
|
|
10219
|
+
}
|
|
8236
10220
|
return this.result;
|
|
8237
10221
|
}
|
|
8238
|
-
visitScript(pathStr, depth,
|
|
10222
|
+
visitScript(pathStr, depth, processCwd, args, isImport = false, argsKnown = true) {
|
|
8239
10223
|
pathStr = resolvePath(pathStr);
|
|
8240
10224
|
if (this.visiting.has(pathStr)) return;
|
|
8241
|
-
|
|
10225
|
+
const effectiveArgs = argsKnown ? args : null;
|
|
10226
|
+
const invocation = `${argsKnown ? "1" : "0"}\0${effectiveArgs === null ? "" : JSON.stringify(effectiveArgs)}\0${processCwd === null ? "\0UNKNOWN" : processCwd}`;
|
|
10227
|
+
const seen = this.visited.get(pathStr);
|
|
10228
|
+
if (seen !== void 0 && seen.has(invocation)) return;
|
|
8242
10229
|
if (depth > this.maxDepth) {
|
|
10230
|
+
if (this.diagnostics !== null) this._budgetSkips.depth += 1;
|
|
8243
10231
|
this.result.maxDepthReached = true;
|
|
8244
10232
|
return;
|
|
8245
10233
|
}
|
|
8246
10234
|
if (this.result.nodes.length >= this.maxNodes) {
|
|
10235
|
+
if (this.diagnostics !== null) this._budgetSkips.nodes += 1;
|
|
8247
10236
|
this.result.maxNodesReached = true;
|
|
8248
10237
|
return;
|
|
8249
10238
|
}
|
|
8250
10239
|
if (this.result.totalSize >= this.maxTotalSize) {
|
|
10240
|
+
if (this.diagnostics !== null) this._budgetSkips.total_bytes += 1;
|
|
8251
10241
|
this.result.maxSizeReached = true;
|
|
8252
10242
|
return;
|
|
8253
10243
|
}
|
|
8254
10244
|
this.visiting.add(pathStr);
|
|
8255
|
-
this.
|
|
10245
|
+
let seenSet = this.visited.get(pathStr);
|
|
10246
|
+
if (seenSet === void 0) {
|
|
10247
|
+
seenSet = /* @__PURE__ */ new Set();
|
|
10248
|
+
this.visited.set(pathStr, seenSet);
|
|
10249
|
+
}
|
|
10250
|
+
seenSet.add(invocation);
|
|
10251
|
+
let details = null;
|
|
10252
|
+
if (this.diagnostics !== null && this._diagnosticNodes.length < DIAGNOSTIC_NODE_LIMIT) {
|
|
10253
|
+
details = { depth };
|
|
10254
|
+
this._diagnosticNodes.push(details);
|
|
10255
|
+
}
|
|
8256
10256
|
const { content, lineCount, fileSize, error } = readScript(pathStr, this.maxFileSize);
|
|
8257
10257
|
if (error) {
|
|
8258
10258
|
const node2 = emptyNode(pathStr, depth);
|
|
@@ -8261,12 +10261,20 @@ var init_tracker = __esm({
|
|
|
8261
10261
|
node2.lineCount = lineCount;
|
|
8262
10262
|
node2.unanalyzable = error.startsWith("\u811A\u672C\u6587\u4EF6\u8FC7\u5927");
|
|
8263
10263
|
this.result.nodes.push(node2);
|
|
10264
|
+
if (details !== null) {
|
|
10265
|
+
details.read_status = node2.unanalyzable ? "file_size_limit" : "read_error";
|
|
10266
|
+
details.file_bytes = fileSize;
|
|
10267
|
+
}
|
|
8264
10268
|
this.visiting.delete(pathStr);
|
|
8265
10269
|
return;
|
|
8266
10270
|
}
|
|
8267
10271
|
this.result.totalSize += fileSize;
|
|
8268
10272
|
this.result.totalLines += lineCount;
|
|
8269
|
-
const ir = pickBackend(pathStr).parse(
|
|
10273
|
+
const ir = pickBackend(pathStr).parse(
|
|
10274
|
+
content,
|
|
10275
|
+
effectiveArgs,
|
|
10276
|
+
details === null ? { argsKnown } : { argsKnown, diagnostics: details }
|
|
10277
|
+
);
|
|
8270
10278
|
const node = emptyNode(pathStr, depth);
|
|
8271
10279
|
node.rawContent = content;
|
|
8272
10280
|
node.preprocessedContent = ir.reachableContent;
|
|
@@ -8274,8 +10282,24 @@ var init_tracker = __esm({
|
|
|
8274
10282
|
node.fileSize = fileSize;
|
|
8275
10283
|
this.result.nodes.push(node);
|
|
8276
10284
|
this.result.totalNodes = this.result.nodes.length;
|
|
10285
|
+
if (details !== null) {
|
|
10286
|
+
const fingerprint2 = scanFingerprint(ir.reachableContent);
|
|
10287
|
+
details.language = ir.language;
|
|
10288
|
+
details.control_flow_resolved = ir.controlFlowResolved;
|
|
10289
|
+
details.file_bytes = fileSize;
|
|
10290
|
+
details.scan_bytes = fingerprint2.bytes;
|
|
10291
|
+
details.scan_sha256 = fingerprint2.sha256;
|
|
10292
|
+
details.child_count = ir.calls.length;
|
|
10293
|
+
details.child_arg_counts = ir.calls.slice(0, DIAGNOSTIC_CHILD_LIMIT).map((call) => call.args.length);
|
|
10294
|
+
details.inline_l1_scan = false;
|
|
10295
|
+
captureReachableContent(details, content, ir.reachableContent);
|
|
10296
|
+
}
|
|
8277
10297
|
if (this._scanner && ir.reachableContent) {
|
|
8278
10298
|
const l1 = this._scanner(ir.reachableContent);
|
|
10299
|
+
if (details !== null) {
|
|
10300
|
+
details.inline_l1_scan = true;
|
|
10301
|
+
details.inline_l1_hit = l1.hit;
|
|
10302
|
+
}
|
|
8279
10303
|
if (l1.hit) {
|
|
8280
10304
|
node.l1Hit = true;
|
|
8281
10305
|
node.l1RiskLevel = l1.riskLevel;
|
|
@@ -8292,12 +10316,38 @@ var init_tracker = __esm({
|
|
|
8292
10316
|
}
|
|
8293
10317
|
}
|
|
8294
10318
|
}
|
|
8295
|
-
const parentDir =
|
|
10319
|
+
const parentDir = path5.dirname(pathStr);
|
|
8296
10320
|
const childPaths = [];
|
|
8297
10321
|
for (const call of ir.calls) {
|
|
8298
|
-
|
|
10322
|
+
let childCwd = processCwd;
|
|
10323
|
+
let pathBase = parentDir;
|
|
10324
|
+
const launchCwd = call.launchCwd;
|
|
10325
|
+
if (launchCwd === WORKING_DIRECTORY_UNKNOWN) {
|
|
10326
|
+
childCwd = null;
|
|
10327
|
+
} else if (launchCwd !== void 0 && launchCwd !== null) {
|
|
10328
|
+
if (path5.isAbsolute(launchCwd)) {
|
|
10329
|
+
childCwd = path5.resolve(launchCwd);
|
|
10330
|
+
} else if (processCwd !== null) {
|
|
10331
|
+
childCwd = path5.resolve(processCwd, launchCwd);
|
|
10332
|
+
}
|
|
10333
|
+
}
|
|
10334
|
+
if (launchCwd !== void 0 && launchCwd !== null) {
|
|
10335
|
+
if (childCwd !== null) {
|
|
10336
|
+
pathBase = childCwd;
|
|
10337
|
+
} else if (!isAbsoluteExpanded(call.path)) {
|
|
10338
|
+
continue;
|
|
10339
|
+
}
|
|
10340
|
+
}
|
|
10341
|
+
const child = resolvePath(call.path, pathBase);
|
|
8299
10342
|
childPaths.push(child);
|
|
8300
|
-
this.visitScript(
|
|
10343
|
+
this.visitScript(
|
|
10344
|
+
child,
|
|
10345
|
+
depth + 1,
|
|
10346
|
+
childCwd,
|
|
10347
|
+
call.args,
|
|
10348
|
+
call.isImport === true,
|
|
10349
|
+
call.argsKnown !== false
|
|
10350
|
+
);
|
|
8301
10351
|
if (this.stopOnCritical && this.result.hasCritical) break;
|
|
8302
10352
|
}
|
|
8303
10353
|
node.childPaths = childPaths;
|
|
@@ -8309,7 +10359,7 @@ var init_tracker = __esm({
|
|
|
8309
10359
|
|
|
8310
10360
|
// src/engine/script-content-analyzer.ts
|
|
8311
10361
|
import { statSync as statSync6, existsSync as existsSync13 } from "fs";
|
|
8312
|
-
import { resolve as resolve11, join as join13, isAbsolute as
|
|
10362
|
+
import { resolve as resolve11, join as join13, isAbsolute as isAbsolute5 } from "path";
|
|
8313
10363
|
import { homedir as homedir5 } from "os";
|
|
8314
10364
|
function emptyChain() {
|
|
8315
10365
|
return {
|
|
@@ -8580,7 +10630,7 @@ function analyzeScriptContent2(input, ext, stopOnCritical = true) {
|
|
|
8580
10630
|
resolvedPath = inline;
|
|
8581
10631
|
isInline = true;
|
|
8582
10632
|
}
|
|
8583
|
-
if (resolvedPath && !
|
|
10633
|
+
if (resolvedPath && !isAbsolute5(resolvedPath) && !resolvedPath.startsWith("~/")) {
|
|
8584
10634
|
resolvedPath = join13(input.cwd || process.cwd(), resolvedPath);
|
|
8585
10635
|
}
|
|
8586
10636
|
const l1Adapter = (content) => {
|
|
@@ -8715,7 +10765,7 @@ var init_script_content_analyzer = __esm({
|
|
|
8715
10765
|
|
|
8716
10766
|
// src/infra/trace-log.ts
|
|
8717
10767
|
import fs4 from "fs";
|
|
8718
|
-
import
|
|
10768
|
+
import path6 from "path";
|
|
8719
10769
|
function traceLevel() {
|
|
8720
10770
|
if (_levelCache !== null) return _levelCache;
|
|
8721
10771
|
const raw = (process.env.AGENT_MOSS_TRACE_LEVEL || "off").trim().toLowerCase();
|
|
@@ -8742,7 +10792,7 @@ function tracePath() {
|
|
|
8742
10792
|
const explicit = (process.env.AGENT_MOSS_TRACE_PATH || "").trim();
|
|
8743
10793
|
if (explicit) return explicit;
|
|
8744
10794
|
try {
|
|
8745
|
-
return
|
|
10795
|
+
return path6.join(getDataRoot(), "agent_moss_trace.log");
|
|
8746
10796
|
} catch {
|
|
8747
10797
|
return "agent_moss_trace.log";
|
|
8748
10798
|
}
|
|
@@ -8781,7 +10831,7 @@ function trace(event, level = LEVEL_SUMMARY, fields = {}) {
|
|
|
8781
10831
|
`;
|
|
8782
10832
|
const file = tracePath();
|
|
8783
10833
|
try {
|
|
8784
|
-
const dir =
|
|
10834
|
+
const dir = path6.dirname(file);
|
|
8785
10835
|
if (dir && dir !== ".") fs4.mkdirSync(dir, { recursive: true });
|
|
8786
10836
|
try {
|
|
8787
10837
|
const st = fs4.statSync(file);
|
|
@@ -9385,7 +11435,7 @@ var init_token_stats = __esm({
|
|
|
9385
11435
|
});
|
|
9386
11436
|
|
|
9387
11437
|
// src/engine/llm-analyzer.ts
|
|
9388
|
-
import { createHash as
|
|
11438
|
+
import { createHash as createHash4 } from "crypto";
|
|
9389
11439
|
import { openSync as openSync3, writeSync as writeSync2, closeSync as closeSync3, constants as fsConstants2 } from "fs";
|
|
9390
11440
|
import OpenAI from "openai";
|
|
9391
11441
|
function reasoningTextFallback(raw) {
|
|
@@ -9464,7 +11514,7 @@ async function runLLMAnalysis(input, previous) {
|
|
|
9464
11514
|
}
|
|
9465
11515
|
const config = perRequest?.apiKey ? { ...globalConfig, ...perRequest } : globalConfig;
|
|
9466
11516
|
const rawDetail = input.aNext.actionDetail.replace(/^terminal-\w+:\s*command=([^,]+).*/, "$1").trim();
|
|
9467
|
-
const cacheKey2 = `${input.aNext.actionType}:${
|
|
11517
|
+
const cacheKey2 = `${input.aNext.actionType}:${createHash4("sha256").update(rawDetail || input.aNext.actionDetail).digest("hex")}`;
|
|
9468
11518
|
const cached2 = llmCache.get(cacheKey2);
|
|
9469
11519
|
if (cached2) {
|
|
9470
11520
|
console.log("[AgentMoss] LLM cache hit");
|
|
@@ -9479,7 +11529,7 @@ async function runLLMAnalysis(input, previous) {
|
|
|
9479
11529
|
} else {
|
|
9480
11530
|
scriptAnalysis = analyzeScriptContent(input.aNext.actionType, input.aNext.actionDetail);
|
|
9481
11531
|
}
|
|
9482
|
-
const maxPromptTokens =
|
|
11532
|
+
const maxPromptTokens = getMaxPromptTokens();
|
|
9483
11533
|
const budgetMode = getAgentMossSetting("AGENT_MOSS_LLM_BUDGET_MODE", "hard").trim().toLowerCase() === "soft" ? "soft" : "hard";
|
|
9484
11534
|
const budgetActive = maxPromptTokens > 0;
|
|
9485
11535
|
const tokenLimit = budgetActive && budgetMode === "hard" ? Math.floor(maxPromptTokens * 100 / 115) : maxPromptTokens;
|
|
@@ -9586,6 +11636,10 @@ function getNumSetting(key, def) {
|
|
|
9586
11636
|
const v = parseInt(getAgentMossSetting(key, String(def)), 10);
|
|
9587
11637
|
return Number.isFinite(v) ? v : def;
|
|
9588
11638
|
}
|
|
11639
|
+
function getMaxPromptTokens() {
|
|
11640
|
+
const configured = getNumSetting("AGENT_MOSS_LLM_MAX_PROMPT_TOKENS", 0);
|
|
11641
|
+
return configured > 0 ? Math.max(1200, configured) : 0;
|
|
11642
|
+
}
|
|
9589
11643
|
function truncateDetail(detail, maxChars) {
|
|
9590
11644
|
if (maxChars <= 0 || detail.length <= maxChars) return detail;
|
|
9591
11645
|
const head = Math.max(1, Math.floor(maxChars * 0.6));
|
|
@@ -9980,8 +12034,8 @@ var init_rule_store = __esm({
|
|
|
9980
12034
|
BrainRuleStore = class {
|
|
9981
12035
|
path;
|
|
9982
12036
|
data;
|
|
9983
|
-
constructor(
|
|
9984
|
-
this.path =
|
|
12037
|
+
constructor(path10) {
|
|
12038
|
+
this.path = path10 || getRulesPath();
|
|
9985
12039
|
this.data = this.load();
|
|
9986
12040
|
}
|
|
9987
12041
|
load() {
|
|
@@ -10434,10 +12488,10 @@ ${reason.slice(0, 500)}
|
|
|
10434
12488
|
const pathRe = new RegExp(pathPrefix + pathBody + pathSuffix, "g");
|
|
10435
12489
|
let mm;
|
|
10436
12490
|
while ((mm = pathRe.exec(src)) !== null) {
|
|
10437
|
-
const
|
|
10438
|
-
if (
|
|
10439
|
-
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(
|
|
10440
|
-
const gen = this.generalizePath(
|
|
12491
|
+
const path10 = mm[1];
|
|
12492
|
+
if (path10.split("/").length < 3) continue;
|
|
12493
|
+
if (["/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"].includes(path10)) continue;
|
|
12494
|
+
const gen = this.generalizePath(path10);
|
|
10441
12495
|
if (seen.has(gen)) continue;
|
|
10442
12496
|
seen.add(gen);
|
|
10443
12497
|
patterns.push({ pattern: gen, layer: 1, scope: "openat", ruleType: "deny_path" });
|
|
@@ -10456,8 +12510,8 @@ ${reason.slice(0, 500)}
|
|
|
10456
12510
|
}
|
|
10457
12511
|
return false;
|
|
10458
12512
|
}
|
|
10459
|
-
generalizePath(
|
|
10460
|
-
const p =
|
|
12513
|
+
generalizePath(path10) {
|
|
12514
|
+
const p = path10.toLowerCase();
|
|
10461
12515
|
if (/\/etc\/(shadow|passwd|sudoers|security|ssh)/.test(p)) {
|
|
10462
12516
|
return "(?:^|[^a-z0-9_-])etc/(?:shadow|passwd|sudoers|security/|ssh/)";
|
|
10463
12517
|
}
|
|
@@ -11018,7 +13072,7 @@ function allEdges(mg) {
|
|
|
11018
13072
|
function emptyVerificationResult() {
|
|
11019
13073
|
return { verified: true, violations: [] };
|
|
11020
13074
|
}
|
|
11021
|
-
var
|
|
13075
|
+
var init_ir2 = __esm({
|
|
11022
13076
|
"src/engine/formal-engine/ir.ts"() {
|
|
11023
13077
|
"use strict";
|
|
11024
13078
|
init_esm_shims();
|
|
@@ -11114,7 +13168,7 @@ function checkMCRules(graph) {
|
|
|
11114
13168
|
if (rule?.type !== "ltl" || !(rule.enabled !== false)) continue;
|
|
11115
13169
|
if (ruleViolates(rule, trace2, witnessMode)) {
|
|
11116
13170
|
const pathNodes = nodes.filter((n) => labelEvent(n.actionDetail).size > 0).slice(-3);
|
|
11117
|
-
const
|
|
13171
|
+
const path10 = pathNodes.map((n) => ({
|
|
11118
13172
|
sessionId: n.sessionId,
|
|
11119
13173
|
seq: n.seq,
|
|
11120
13174
|
detail: n.actionDetail.slice(0, 60)
|
|
@@ -11123,7 +13177,7 @@ function checkMCRules(graph) {
|
|
|
11123
13177
|
propertyId: String(rule.id || "mc-ltl"),
|
|
11124
13178
|
reason: String(rule.reason || "L2.2 \u6A21\u578B\u68C0\u6D4B\u89C4\u5219\u547D\u4E2D"),
|
|
11125
13179
|
riskLevel: String(rule.risk_level || "high"),
|
|
11126
|
-
path:
|
|
13180
|
+
path: path10,
|
|
11127
13181
|
graph: {
|
|
11128
13182
|
property_id: String(rule.id || "mc-ltl"),
|
|
11129
13183
|
property_short: "P6",
|
|
@@ -11154,7 +13208,7 @@ var init_ltl = __esm({
|
|
|
11154
13208
|
"use strict";
|
|
11155
13209
|
init_esm_shims();
|
|
11156
13210
|
init_rules_loader();
|
|
11157
|
-
|
|
13211
|
+
init_ir2();
|
|
11158
13212
|
init_decode();
|
|
11159
13213
|
AP_RE = null;
|
|
11160
13214
|
}
|
|
@@ -11341,12 +13395,12 @@ var init_builder = __esm({
|
|
|
11341
13395
|
});
|
|
11342
13396
|
|
|
11343
13397
|
// src/engine/formal-engine/properties.ts
|
|
11344
|
-
function graphFromPath(nodes,
|
|
13398
|
+
function graphFromPath(nodes, path10, edgeType = "next", propertyMeta, roles, witnessLast = true, propertyExpression) {
|
|
11345
13399
|
const byKey = /* @__PURE__ */ new Map();
|
|
11346
13400
|
for (const n of nodes) byKey.set(`${n.sessionId}#${n.seq}`, n);
|
|
11347
13401
|
const gNodes = [];
|
|
11348
13402
|
const gEdges = [];
|
|
11349
|
-
for (const item of
|
|
13403
|
+
for (const item of path10) {
|
|
11350
13404
|
const n = byKey.get(`${item.sessionId}#${item.seq}`);
|
|
11351
13405
|
gNodes.push({
|
|
11352
13406
|
session_id: item.sessionId,
|
|
@@ -11412,22 +13466,22 @@ function checkCrossSessionChain(graph) {
|
|
|
11412
13466
|
if (witness !== void 0) {
|
|
11413
13467
|
if (nodes[witness].stage !== stages[stages.length - 1]) continue;
|
|
11414
13468
|
let matched = 0;
|
|
11415
|
-
const
|
|
13469
|
+
const path10 = [];
|
|
11416
13470
|
for (let k = 0; k < witness; k++) {
|
|
11417
13471
|
const n = nodes[k];
|
|
11418
13472
|
if (matched < stages.length - 1 && n.stage === stages[matched]) {
|
|
11419
13473
|
matched += 1;
|
|
11420
|
-
|
|
13474
|
+
path10.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
11421
13475
|
}
|
|
11422
13476
|
}
|
|
11423
13477
|
if (matched < stages.length - 1) continue;
|
|
11424
|
-
|
|
13478
|
+
path10.push({ sessionId: nodes[witness].sessionId, seq: nodes[witness].seq, detail: nodes[witness].actionDetail.slice(0, 60) });
|
|
11425
13479
|
violations.push({
|
|
11426
13480
|
propertyId: "cross-" + chain.id,
|
|
11427
13481
|
reason: chain.reason,
|
|
11428
13482
|
riskLevel: chain.riskLevel,
|
|
11429
|
-
path:
|
|
11430
|
-
graph: graphFromPath(nodes,
|
|
13483
|
+
path: path10,
|
|
13484
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
11431
13485
|
property_id: "cross-" + chain.id,
|
|
11432
13486
|
property_short: "P1",
|
|
11433
13487
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -11437,11 +13491,11 @@ function checkCrossSessionChain(graph) {
|
|
|
11437
13491
|
} else {
|
|
11438
13492
|
let matched = 0;
|
|
11439
13493
|
let stageIdx = 0;
|
|
11440
|
-
const
|
|
13494
|
+
const path10 = [];
|
|
11441
13495
|
for (const n of nodes) {
|
|
11442
13496
|
if (stageIdx < stages.length && n.stage === stages[stageIdx]) {
|
|
11443
13497
|
matched += 1;
|
|
11444
|
-
|
|
13498
|
+
path10.push({ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) });
|
|
11445
13499
|
stageIdx += 1;
|
|
11446
13500
|
if (matched >= stages.length) break;
|
|
11447
13501
|
}
|
|
@@ -11451,8 +13505,8 @@ function checkCrossSessionChain(graph) {
|
|
|
11451
13505
|
propertyId: "cross-" + chain.id,
|
|
11452
13506
|
reason: chain.reason,
|
|
11453
13507
|
riskLevel: chain.riskLevel,
|
|
11454
|
-
path:
|
|
11455
|
-
graph: graphFromPath(nodes,
|
|
13508
|
+
path: path10,
|
|
13509
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
11456
13510
|
property_id: "cross-" + chain.id,
|
|
11457
13511
|
property_short: "P1",
|
|
11458
13512
|
property_name: "\u8DE8\u4F1A\u8BDD\u7EC4\u5408\u94FE"
|
|
@@ -11673,7 +13727,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
11673
13727
|
if (candidates.length > 0) {
|
|
11674
13728
|
const pre = nodes[candidates[candidates.length - 1]];
|
|
11675
13729
|
const post = nodes[firstEv];
|
|
11676
|
-
const
|
|
13730
|
+
const path10 = [
|
|
11677
13731
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
11678
13732
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
11679
13733
|
];
|
|
@@ -11681,8 +13735,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
11681
13735
|
propertyId: "no-exfil-after-privesc",
|
|
11682
13736
|
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",
|
|
11683
13737
|
riskLevel: "critical",
|
|
11684
|
-
path:
|
|
11685
|
-
graph: graphFromPath(nodes,
|
|
13738
|
+
path: path10,
|
|
13739
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
11686
13740
|
property_id: "no-exfil-after-privesc",
|
|
11687
13741
|
property_short: "P4",
|
|
11688
13742
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -11699,7 +13753,7 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
11699
13753
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
11700
13754
|
if (!isExfilNode(nodes[j])) continue;
|
|
11701
13755
|
if (privescInWindow(nodes, [i], j, windowSec).length === 0) continue;
|
|
11702
|
-
const
|
|
13756
|
+
const path10 = [
|
|
11703
13757
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
11704
13758
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
11705
13759
|
];
|
|
@@ -11707,8 +13761,8 @@ function checkNeverExfilAfterPrivesc(graph) {
|
|
|
11707
13761
|
propertyId: "no-exfil-after-privesc",
|
|
11708
13762
|
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",
|
|
11709
13763
|
riskLevel: "critical",
|
|
11710
|
-
path:
|
|
11711
|
-
graph: graphFromPath(nodes,
|
|
13764
|
+
path: path10,
|
|
13765
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
11712
13766
|
property_id: "no-exfil-after-privesc",
|
|
11713
13767
|
property_short: "P4",
|
|
11714
13768
|
property_name: "\u63D0\u6743\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -11740,7 +13794,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
11740
13794
|
}
|
|
11741
13795
|
if (pre) {
|
|
11742
13796
|
const post = nodes[firstEv];
|
|
11743
|
-
const
|
|
13797
|
+
const path10 = [
|
|
11744
13798
|
{ sessionId: pre.sessionId, seq: pre.seq, detail: pre.actionDetail.slice(0, 60) },
|
|
11745
13799
|
{ sessionId: post.sessionId, seq: post.seq, detail: post.actionDetail.slice(0, 60) }
|
|
11746
13800
|
];
|
|
@@ -11748,8 +13802,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
11748
13802
|
propertyId: "no-exfil-after-credential",
|
|
11749
13803
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
11750
13804
|
riskLevel: "critical",
|
|
11751
|
-
path:
|
|
11752
|
-
graph: graphFromPath(nodes,
|
|
13805
|
+
path: path10,
|
|
13806
|
+
graph: graphFromPath(nodes, path10, "data", {
|
|
11753
13807
|
property_id: "no-exfil-after-credential",
|
|
11754
13808
|
property_short: "P5",
|
|
11755
13809
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -11765,7 +13819,7 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
11765
13819
|
if (!isCredNode(nodes[i])) continue;
|
|
11766
13820
|
for (let j = i + 1; j < nodes.length; j++) {
|
|
11767
13821
|
if (isExfilNode(nodes[j])) {
|
|
11768
|
-
const
|
|
13822
|
+
const path10 = [
|
|
11769
13823
|
{ sessionId: nodes[i].sessionId, seq: nodes[i].seq, detail: nodes[i].actionDetail.slice(0, 60) },
|
|
11770
13824
|
{ sessionId: nodes[j].sessionId, seq: nodes[j].seq, detail: nodes[j].actionDetail.slice(0, 60) }
|
|
11771
13825
|
];
|
|
@@ -11773,8 +13827,8 @@ function checkNeverExfilAfterCred(graph) {
|
|
|
11773
13827
|
propertyId: "no-exfil-after-credential",
|
|
11774
13828
|
reason: "\u8BFB\u53D6\u51ED\u636E\u540E\u51FA\u73B0\u5916\u4F20\uFF0C\u8FDD\u53CD \u25A1(CRED\u2192\xAC\u25C7EXFIL)",
|
|
11775
13829
|
riskLevel: "critical",
|
|
11776
|
-
path:
|
|
11777
|
-
graph: graphFromPath(nodes,
|
|
13830
|
+
path: path10,
|
|
13831
|
+
graph: graphFromPath(nodes, path10, "data", {
|
|
11778
13832
|
property_id: "no-exfil-after-credential",
|
|
11779
13833
|
property_short: "P5",
|
|
11780
13834
|
property_name: "\u8BFB\u53D6\u51ED\u636E\u540E\u7981\u6B62\u5916\u4F20"
|
|
@@ -11841,13 +13895,13 @@ function checkLowIntegrityCommandExec(graph) {
|
|
|
11841
13895
|
for (const i of candidates) {
|
|
11842
13896
|
const n = nodes[i];
|
|
11843
13897
|
if (lowAt.has(i) && isComputeNode(n)) {
|
|
11844
|
-
const
|
|
13898
|
+
const path10 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
11845
13899
|
violations.push({
|
|
11846
13900
|
propertyId: "low-integrity-command-exec",
|
|
11847
13901
|
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`,
|
|
11848
13902
|
riskLevel: "critical",
|
|
11849
|
-
path:
|
|
11850
|
-
graph: graphFromPath(nodes,
|
|
13903
|
+
path: path10,
|
|
13904
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
11851
13905
|
property_id: "low-integrity-command-exec",
|
|
11852
13906
|
property_short: "P7",
|
|
11853
13907
|
property_name: "\u4F4E\u5B8C\u6574\u6027\u547D\u4EE4\u6267\u884C"
|
|
@@ -11893,7 +13947,7 @@ function checkCrossSessionReachability(graph) {
|
|
|
11893
13947
|
if (reached.has(i)) {
|
|
11894
13948
|
const srcIdx = Math.min(...sources);
|
|
11895
13949
|
const srcDesc = nodes[srcIdx].actionDetail.slice(0, 40);
|
|
11896
|
-
const
|
|
13950
|
+
const path10 = nodes.slice(-3).map((m) => ({
|
|
11897
13951
|
sessionId: m.sessionId,
|
|
11898
13952
|
seq: m.seq,
|
|
11899
13953
|
detail: m.actionDetail.slice(0, 60)
|
|
@@ -11902,8 +13956,8 @@ function checkCrossSessionReachability(graph) {
|
|
|
11902
13956
|
propertyId: "low-integrity-reachability",
|
|
11903
13957
|
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`,
|
|
11904
13958
|
riskLevel: "high",
|
|
11905
|
-
path:
|
|
11906
|
-
graph: graphFromPath(nodes,
|
|
13959
|
+
path: path10,
|
|
13960
|
+
graph: graphFromPath(nodes, path10, "data", {
|
|
11907
13961
|
property_id: "low-integrity-reachability",
|
|
11908
13962
|
property_short: "P3",
|
|
11909
13963
|
property_name: "\u4F4E\u5B8C\u6574\u6027\u6570\u636E\u6D41\u53EF\u8FBE"
|
|
@@ -11949,13 +14003,13 @@ function checkSensitiveDataAggregation(graph) {
|
|
|
11949
14003
|
if (!isExfilNode(n)) continue;
|
|
11950
14004
|
const srcs = sourcesFor(i);
|
|
11951
14005
|
if (srcs.size >= 2) {
|
|
11952
|
-
const
|
|
14006
|
+
const path10 = [{ sessionId: n.sessionId, seq: n.seq, detail: n.actionDetail.slice(0, 60) }];
|
|
11953
14007
|
violations.push({
|
|
11954
14008
|
propertyId: "sensitive-data-aggregation",
|
|
11955
14009
|
reason: `\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20\uFF1Aegress \u805A\u5408 ${srcs.size} \u4E2A\u4E8B\u4EF6\u6E90\u6570\u636E\uFF08Rule 12\uFF09`,
|
|
11956
14010
|
riskLevel: "critical",
|
|
11957
|
-
path:
|
|
11958
|
-
graph: graphFromPath(nodes,
|
|
14011
|
+
path: path10,
|
|
14012
|
+
graph: graphFromPath(nodes, path10, "next", {
|
|
11959
14013
|
property_id: "sensitive-data-aggregation",
|
|
11960
14014
|
property_short: "P8",
|
|
11961
14015
|
property_name: "\u654F\u611F\u6570\u636E\u805A\u5408\u5916\u4F20"
|
|
@@ -11974,7 +14028,7 @@ var init_properties = __esm({
|
|
|
11974
14028
|
"use strict";
|
|
11975
14029
|
init_esm_shims();
|
|
11976
14030
|
init_rules_loader();
|
|
11977
|
-
|
|
14031
|
+
init_ir2();
|
|
11978
14032
|
init_ltl();
|
|
11979
14033
|
init_decode();
|
|
11980
14034
|
CROSS_SESSION_CHAINS = null;
|
|
@@ -12027,7 +14081,7 @@ var init_engine = __esm({
|
|
|
12027
14081
|
"use strict";
|
|
12028
14082
|
init_esm_shims();
|
|
12029
14083
|
init_builder();
|
|
12030
|
-
|
|
14084
|
+
init_ir2();
|
|
12031
14085
|
init_properties();
|
|
12032
14086
|
FormalEngine = class {
|
|
12033
14087
|
properties;
|
|
@@ -12077,10 +14131,10 @@ var init_engine = __esm({
|
|
|
12077
14131
|
});
|
|
12078
14132
|
|
|
12079
14133
|
// src/engine/formal-engine/stateful.ts
|
|
12080
|
-
import { createHash as
|
|
14134
|
+
import { createHash as createHash5 } from "crypto";
|
|
12081
14135
|
import * as fs5 from "fs";
|
|
12082
14136
|
import * as os3 from "os";
|
|
12083
|
-
import * as
|
|
14137
|
+
import * as path7 from "path";
|
|
12084
14138
|
import { gzipSync } from "zlib";
|
|
12085
14139
|
function extractInstances(actionDetail, stage) {
|
|
12086
14140
|
const out = [];
|
|
@@ -12166,7 +14220,7 @@ function envInt3(name, def) {
|
|
|
12166
14220
|
function cleanupChainArchives(dir, maxBytes = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_MAX_MB", 512) * 1024 * 1024, maxAgeDays = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_MAX_AGE_DAYS", 0)) {
|
|
12167
14221
|
let files = [];
|
|
12168
14222
|
try {
|
|
12169
|
-
files = fs5.readdirSync(dir).filter((f) => f.startsWith("chain-nodes-") && f.endsWith(".jsonl.gz")).map((f) =>
|
|
14223
|
+
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);
|
|
12170
14224
|
} catch {
|
|
12171
14225
|
return { deleted: 0, files: 0, bytes: 0 };
|
|
12172
14226
|
}
|
|
@@ -12212,7 +14266,7 @@ function cleanupChainArchives(dir, maxBytes = envInt3("AGENT_MOSS_CHAIN_ARCHIVE_
|
|
|
12212
14266
|
for (const f of fs5.readdirSync(dir)) {
|
|
12213
14267
|
if (!f.startsWith("chain-nodes-") || !f.endsWith(".jsonl.gz")) continue;
|
|
12214
14268
|
remainFiles += 1;
|
|
12215
|
-
remainBytes += fs5.statSync(
|
|
14269
|
+
remainBytes += fs5.statSync(path7.join(dir, f)).size;
|
|
12216
14270
|
}
|
|
12217
14271
|
} catch {
|
|
12218
14272
|
}
|
|
@@ -12225,7 +14279,7 @@ function canonicalActionType(actionType) {
|
|
|
12225
14279
|
function canonicalDetail(actionDetail) {
|
|
12226
14280
|
const detail = String(actionDetail || "");
|
|
12227
14281
|
const m = TRUNCATED_DETAIL_RE.exec(detail);
|
|
12228
|
-
const digest = m ? m[1] :
|
|
14282
|
+
const digest = m ? m[1] : createHash5("sha256").update(detail).digest("hex").slice(0, 16);
|
|
12229
14283
|
return `sha256:${digest}`;
|
|
12230
14284
|
}
|
|
12231
14285
|
function canonicalCalledAt(calledAt) {
|
|
@@ -12245,7 +14299,7 @@ function fingerprint(sessionId, actionType, actionDetail, calledAt) {
|
|
|
12245
14299
|
canonicalDetail(actionDetail),
|
|
12246
14300
|
canonicalCalledAt(calledAt)
|
|
12247
14301
|
].join("\0");
|
|
12248
|
-
return
|
|
14302
|
+
return createHash5("blake2b512").update(raw).digest("hex").slice(0, 16);
|
|
12249
14303
|
}
|
|
12250
14304
|
function gateOrder(action) {
|
|
12251
14305
|
const callId = String(action?.gateCallId ?? "");
|
|
@@ -12262,7 +14316,7 @@ function gateFingerprint(action, isError, agentId, instanceId, order) {
|
|
|
12262
14316
|
Boolean(isError),
|
|
12263
14317
|
order.callTimeUs
|
|
12264
14318
|
];
|
|
12265
|
-
return
|
|
14319
|
+
return createHash5("sha256").update(JSON.stringify(values)).digest("hex");
|
|
12266
14320
|
}
|
|
12267
14321
|
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;
|
|
12268
14322
|
var init_stateful = __esm({
|
|
@@ -12467,10 +14521,10 @@ var init_stateful = __esm({
|
|
|
12467
14521
|
if (this.nodes_.length <= keep) return { archived: 0, file: "" };
|
|
12468
14522
|
const old = this.nodes_.slice(0, this.nodes_.length - keep);
|
|
12469
14523
|
const kept = this.nodes_.slice(-keep);
|
|
12470
|
-
const dir = archiveDir || process.env.AGENT_MOSS_CHAIN_ARCHIVE_DIR ||
|
|
14524
|
+
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");
|
|
12471
14525
|
fs5.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
12472
14526
|
const safeAgent = (this.agentId || "default").replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
12473
|
-
const file =
|
|
14527
|
+
const file = path7.join(dir, `chain-nodes-${safeAgent}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.jsonl.gz`);
|
|
12474
14528
|
const payload = old.map((n) => JSON.stringify(n)).join("\n") + "\n";
|
|
12475
14529
|
fs5.writeFileSync(file, gzipSync(Buffer.from(payload, "utf-8")), { mode: 384 });
|
|
12476
14530
|
try {
|
|
@@ -12694,11 +14748,11 @@ var init_stateful = __esm({
|
|
|
12694
14748
|
}
|
|
12695
14749
|
}
|
|
12696
14750
|
chainPath(stages) {
|
|
12697
|
-
const
|
|
14751
|
+
const path10 = [];
|
|
12698
14752
|
let want = stages[0];
|
|
12699
14753
|
for (const n of this.nodes_) {
|
|
12700
14754
|
if (n.stage === want) {
|
|
12701
|
-
|
|
14755
|
+
path10.push({
|
|
12702
14756
|
sessionId: n.sessionId,
|
|
12703
14757
|
seq: n.seq,
|
|
12704
14758
|
stage: n.stage,
|
|
@@ -12714,12 +14768,12 @@ var init_stateful = __esm({
|
|
|
12714
14768
|
}
|
|
12715
14769
|
}
|
|
12716
14770
|
}
|
|
12717
|
-
return
|
|
14771
|
+
return path10;
|
|
12718
14772
|
}
|
|
12719
14773
|
/** 把链路径转成前端可画的结构化图(相邻节点 next 边)。 */
|
|
12720
14774
|
buildChainGraph(stages, chainId) {
|
|
12721
|
-
const
|
|
12722
|
-
const gNodes =
|
|
14775
|
+
const path10 = this.chainPath(stages);
|
|
14776
|
+
const gNodes = path10.map((p, i) => {
|
|
12723
14777
|
const n = this.nodes_.find((x) => x.sessionId === p.sessionId && x.seq === p.seq);
|
|
12724
14778
|
return {
|
|
12725
14779
|
session_id: p.sessionId,
|
|
@@ -12987,16 +15041,16 @@ var init_stateful = __esm({
|
|
|
12987
15041
|
// src/engine/formal-engine/chain_state.ts
|
|
12988
15042
|
import * as fs6 from "fs";
|
|
12989
15043
|
import * as os4 from "os";
|
|
12990
|
-
import * as
|
|
12991
|
-
import { createHash as
|
|
15044
|
+
import * as path8 from "path";
|
|
15045
|
+
import { createHash as createHash6 } from "crypto";
|
|
12992
15046
|
function defaultStateDbPath() {
|
|
12993
|
-
const base = process.env.AGENT_MOSS_STATE_DIR ||
|
|
15047
|
+
const base = process.env.AGENT_MOSS_STATE_DIR || path8.join(os4.homedir(), ".agentmoss");
|
|
12994
15048
|
const instance = (process.env.AGENT_MOSS_INSTANCE || "").trim().replace(/^[/\\]+|[/\\]+$/g, "");
|
|
12995
|
-
const dir = instance ?
|
|
12996
|
-
const tag =
|
|
12997
|
-
const target =
|
|
15049
|
+
const dir = instance ? path8.join(base, instance) : base;
|
|
15050
|
+
const tag = createHash6("sha1").update("agentmoss-stateful").digest("hex").slice(0, 8);
|
|
15051
|
+
const target = path8.join(dir, `stateful_chains_${tag}.json`);
|
|
12998
15052
|
if (instance) {
|
|
12999
|
-
const legacy =
|
|
15053
|
+
const legacy = path8.join(base, `stateful_chains_${tag}.json`);
|
|
13000
15054
|
if (!fs6.existsSync(target) && fs6.existsSync(legacy)) {
|
|
13001
15055
|
try {
|
|
13002
15056
|
fs6.mkdirSync(dir, { recursive: true });
|
|
@@ -13093,7 +15147,7 @@ var init_chain_state = __esm({
|
|
|
13093
15147
|
this._timer = null;
|
|
13094
15148
|
try {
|
|
13095
15149
|
this._syncDirtyToData();
|
|
13096
|
-
ensurePrivateDir(
|
|
15150
|
+
ensurePrivateDir(path8.dirname(this.filePath));
|
|
13097
15151
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
13098
15152
|
} catch {
|
|
13099
15153
|
}
|
|
@@ -13116,7 +15170,7 @@ var init_chain_state = __esm({
|
|
|
13116
15170
|
}
|
|
13117
15171
|
try {
|
|
13118
15172
|
this._syncDirtyToData();
|
|
13119
|
-
ensurePrivateDir(
|
|
15173
|
+
ensurePrivateDir(path8.dirname(this.filePath));
|
|
13120
15174
|
writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
13121
15175
|
} catch {
|
|
13122
15176
|
}
|
|
@@ -13184,7 +15238,7 @@ var init_chain_state = __esm({
|
|
|
13184
15238
|
_flushNow() {
|
|
13185
15239
|
this._syncDirtyToData();
|
|
13186
15240
|
try {
|
|
13187
|
-
const _dirOk = ensurePrivateDir(
|
|
15241
|
+
const _dirOk = ensurePrivateDir(path8.dirname(this.filePath));
|
|
13188
15242
|
const _wOk = writePrivateText(this.filePath, JSON.stringify(this.data, null, 2));
|
|
13189
15243
|
if (!_wOk) console.error("[AgentMoss] chain state flush failed:", this.filePath, "dirOk=", _dirOk);
|
|
13190
15244
|
} catch (e) {
|
|
@@ -13233,7 +15287,7 @@ var init_formal_engine = __esm({
|
|
|
13233
15287
|
"use strict";
|
|
13234
15288
|
init_esm_shims();
|
|
13235
15289
|
init_engine();
|
|
13236
|
-
|
|
15290
|
+
init_ir2();
|
|
13237
15291
|
init_builder();
|
|
13238
15292
|
init_properties();
|
|
13239
15293
|
init_stateful();
|
|
@@ -14155,7 +16209,7 @@ init_esm_shims();
|
|
|
14155
16209
|
init_security_policy();
|
|
14156
16210
|
init_paths();
|
|
14157
16211
|
init_config();
|
|
14158
|
-
import { createHash as
|
|
16212
|
+
import { createHash as createHash7 } from "crypto";
|
|
14159
16213
|
import { existsSync as existsSync18, lstatSync as lstatSync2, readdirSync as readdirSync6, readFileSync as readFileSync18, rmdirSync, unlinkSync as unlinkSync5 } from "fs";
|
|
14160
16214
|
import { tmpdir as tmpdir2 } from "os";
|
|
14161
16215
|
import { join as join18 } from "path";
|
|
@@ -14188,7 +16242,7 @@ var PolicyCache = class {
|
|
|
14188
16242
|
return `${sessionId}::${promptSession}`;
|
|
14189
16243
|
}
|
|
14190
16244
|
cacheFilePath(sessionId, promptSession) {
|
|
14191
|
-
const promptHash =
|
|
16245
|
+
const promptHash = createHash7("md5").update(promptSession).digest("hex").slice(0, 12);
|
|
14192
16246
|
const safeSessionId = sessionId.replace(/\//g, "_").replace(/\\/g, "_").replace(/\.\./g, "__");
|
|
14193
16247
|
return join18(safeCacheDir(), safeSessionId, `${promptHash}.toml`);
|
|
14194
16248
|
}
|
|
@@ -14803,8 +16857,8 @@ function mineDangerousPatterns(sessions, minSup = 2, maxLen = 4) {
|
|
|
14803
16857
|
init_esm_shims();
|
|
14804
16858
|
import * as fs8 from "fs";
|
|
14805
16859
|
import * as os5 from "os";
|
|
14806
|
-
import * as
|
|
14807
|
-
var DEFAULT_AGENTGATE_SQLITE =
|
|
16860
|
+
import * as path9 from "path";
|
|
16861
|
+
var DEFAULT_AGENTGATE_SQLITE = path9.join(
|
|
14808
16862
|
os5.homedir(),
|
|
14809
16863
|
".local",
|
|
14810
16864
|
"share",
|
|
@@ -14835,7 +16889,7 @@ function readJsonDir(dirPath, limit = 1e5, strict = false) {
|
|
|
14835
16889
|
const files = fs8.readdirSync(dirPath).filter((f) => f.endsWith(".json")).sort();
|
|
14836
16890
|
for (const f of files.slice(-200)) {
|
|
14837
16891
|
const sid = f.replace(/\.json$/, "");
|
|
14838
|
-
const raw = fs8.readFileSync(
|
|
16892
|
+
const raw = fs8.readFileSync(path9.join(dirPath, f), "utf-8");
|
|
14839
16893
|
const arr = JSON.parse(raw);
|
|
14840
16894
|
if (!Array.isArray(arr)) continue;
|
|
14841
16895
|
for (const item of arr) {
|
|
@@ -14909,7 +16963,7 @@ function loadAgentGateSessions(dbPath = "") {
|
|
|
14909
16963
|
}
|
|
14910
16964
|
const sql = readSqlite(DEFAULT_AGENTGATE_SQLITE);
|
|
14911
16965
|
if (sql.length > 0) return sql;
|
|
14912
|
-
const jsonDefault =
|
|
16966
|
+
const jsonDefault = path9.join(os5.homedir(), ".local", "share", "agent_gate", "tool_calls");
|
|
14913
16967
|
return readJsonDir(jsonDefault);
|
|
14914
16968
|
}
|
|
14915
16969
|
|
|
@@ -16237,7 +18291,7 @@ function createApp() {
|
|
|
16237
18291
|
startLoopMonitor();
|
|
16238
18292
|
const limiter = new RateLimiter(rateLimitQps());
|
|
16239
18293
|
app.use("*", async (c, next) => {
|
|
16240
|
-
const
|
|
18294
|
+
const path10 = new URL(c.req.url).pathname;
|
|
16241
18295
|
const method = c.req.method.toUpperCase();
|
|
16242
18296
|
if (method === "OPTIONS") return next();
|
|
16243
18297
|
const maxBody = maxBodyBytes();
|
|
@@ -16251,18 +18305,18 @@ function createApp() {
|
|
|
16251
18305
|
if (originCheckEnabled()) {
|
|
16252
18306
|
const origin = c.req.header("origin") || "";
|
|
16253
18307
|
if (origin && !originAllowed(origin, c.req.header("host") || "")) {
|
|
16254
|
-
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${
|
|
18308
|
+
console.warn(`[AgentMoss] \u5DF2\u62E6\u622A\u8DE8\u6E90\u8BF7\u6C42: origin=${origin} path=${path10}`);
|
|
16255
18309
|
return c.json({ detail: `\u8DE8\u6E90\u6765\u6E90\u672A\u88AB\u5141\u8BB8: ${origin}` }, 403);
|
|
16256
18310
|
}
|
|
16257
18311
|
}
|
|
16258
|
-
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers,
|
|
16259
|
-
const isPublicPage = !
|
|
18312
|
+
const [okAuth, principal] = checkRequestAuth(c.req.raw.headers, path10);
|
|
18313
|
+
const isPublicPage = !path10.startsWith("/console/api") && (path10 === "/console" || path10.startsWith("/console/"));
|
|
16260
18314
|
if (!okAuth && !isPublicPage) {
|
|
16261
18315
|
return c.json({ detail: "Unauthorized: invalid or missing Bearer token" }, 401);
|
|
16262
18316
|
}
|
|
16263
18317
|
let gateCallId = null;
|
|
16264
18318
|
const gateRequired = c.req.header(GATE_IDENTITY_HEADER);
|
|
16265
|
-
const gatePath =
|
|
18319
|
+
const gatePath = path10.replace(/\/+$/, "");
|
|
16266
18320
|
if (method === "POST" && gateRequired !== void 0 && (gatePath === "/api/v1/analyze" || gatePath === "/api/v1/review")) {
|
|
16267
18321
|
if (principal !== GATE_PRINCIPAL) {
|
|
16268
18322
|
return c.json({ detail: "AgentGate \u4E13\u7528\u8EAB\u4EFD\u6821\u9A8C\u5931\u8D25" }, 403);
|
|
@@ -16279,7 +18333,7 @@ function createApp() {
|
|
|
16279
18333
|
gateCallId = id;
|
|
16280
18334
|
c.set("gateCallId", id);
|
|
16281
18335
|
}
|
|
16282
|
-
if (limiter.enabled &&
|
|
18336
|
+
if (limiter.enabled && path10.startsWith("/api/")) {
|
|
16283
18337
|
const key = principal ? "p:" + principalHash(principal) : "c:" + (c.req.header("x-forwarded-for") || "local");
|
|
16284
18338
|
if (!limiter.allow(key)) {
|
|
16285
18339
|
if (gateCallId) c.header(GATE_RATE_LIMIT_HEADER, gateCallId);
|
|
@@ -16315,7 +18369,7 @@ function createApp() {
|
|
|
16315
18369
|
return busy(`agent '${bound}' \u7684\u5E76\u53D1\u8D85\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5`, 429);
|
|
16316
18370
|
}
|
|
16317
18371
|
}
|
|
16318
|
-
const pool = poolOf(
|
|
18372
|
+
const pool = poolOf(path10);
|
|
16319
18373
|
if (!take(`pool:${pool}`, poolLimit(pool))) {
|
|
16320
18374
|
const qkey = principal ? "p:" + principalHash(principal) : "c:local";
|
|
16321
18375
|
const [qn, abusive] = noteQueueReject(qkey);
|
|
@@ -16415,8 +18469,8 @@ async function warmUpEngine() {
|
|
|
16415
18469
|
}
|
|
16416
18470
|
function writePortFile(port) {
|
|
16417
18471
|
try {
|
|
16418
|
-
const
|
|
16419
|
-
mkdirSync10(dirname16(
|
|
18472
|
+
const path10 = getPortFilePath();
|
|
18473
|
+
mkdirSync10(dirname16(path10), { recursive: true });
|
|
16420
18474
|
const payload = JSON.stringify({
|
|
16421
18475
|
port,
|
|
16422
18476
|
pid: process.pid,
|
|
@@ -16425,10 +18479,10 @@ function writePortFile(port) {
|
|
|
16425
18479
|
version,
|
|
16426
18480
|
started_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
16427
18481
|
});
|
|
16428
|
-
const tmp = `${
|
|
18482
|
+
const tmp = `${path10}.tmp`;
|
|
16429
18483
|
writeFileSync7(tmp, payload, "utf-8");
|
|
16430
|
-
renameSync3(tmp,
|
|
16431
|
-
console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${
|
|
18484
|
+
renameSync3(tmp, path10);
|
|
18485
|
+
console.log(`[AgentMoss] \u7AEF\u53E3\u6587\u4EF6\u5DF2\u5199\u5165: ${path10} (port=${port})`);
|
|
16432
18486
|
} catch (err) {
|
|
16433
18487
|
console.warn("[AgentMoss] \u5199\u7AEF\u53E3\u6587\u4EF6\u5931\u8D25\uFF08\u8C03\u7528\u65B9\u9700\u81EA\u884C\u914D\u7F6E\u7AEF\u53E3\uFF09:", err);
|
|
16434
18488
|
}
|