dsh-plugin-opc 0.1.28 → 0.1.30

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-opc",
3
- "version": "0.1.28",
3
+ "version": "0.1.30",
4
4
  "description": "OPC Enterprise Plugin for DeepSeek Harness (DSH)",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -31,7 +31,7 @@ def valid_origin(value):
31
31
 
32
32
  def read_json(value, filename):
33
33
  if filename:
34
- return json.load(sys.stdin) if filename == "-" else json.loads(Path(filename).read_text())
34
+ return json.load(sys.stdin) if filename == "-" else json.loads(Path(filename).read_text(encoding="utf-8"))
35
35
  return json.loads(value)
36
36
 
37
37
 
@@ -280,6 +280,12 @@ def execute(contract, operation, params, body=None, approve_write=False, credent
280
280
 
281
281
 
282
282
  def main():
283
+ for stream in (sys.stdin, sys.stdout, sys.stderr):
284
+ if hasattr(stream, "reconfigure"):
285
+ try:
286
+ stream.reconfigure(encoding="utf-8", errors="replace")
287
+ except Exception:
288
+ pass
283
289
  parser = argparse.ArgumentParser(description=__doc__)
284
290
  parser.add_argument("--operation", required=True)
285
291
  group = parser.add_mutually_exclusive_group()
@@ -292,7 +298,7 @@ def main():
292
298
  root = Path(__file__).resolve().parents[1]
293
299
  if (root / ".work-delivery-pending").exists():
294
300
  raise ValueError("Work application deployment has not passed verification; this skill is disabled")
295
- contract = json.loads((root / "references/operations.json").read_text())
301
+ contract = json.loads((root / "references/operations.json").read_text(encoding="utf-8"))
296
302
  params = read_json(args.params, args.params_file)
297
303
  body = read_json("null", args.body_file)
298
304
  md = root / "SKILL.md"
@@ -2,6 +2,7 @@
2
2
  """Deterministic application delivery helpers; analysis and source edits belong to the Agent."""
3
3
 
4
4
  import argparse
5
+ import errno
5
6
  from glob import escape as escape_glob
6
7
  import hashlib
7
8
  import io
@@ -48,8 +49,39 @@ def load(path):
48
49
  return json.loads(Path(path).read_text(encoding="utf-8"))
49
50
 
50
51
 
52
+ def atomic_replace(tmp_path, target):
53
+ """Replace target with brief retries for transient Windows sharing/AV locks (WinError 5/32)."""
54
+ tmp = Path(tmp_path)
55
+ dst = Path(target)
56
+ for attempt in range(8):
57
+ try:
58
+ tmp.replace(dst)
59
+ return
60
+ except PermissionError as exc:
61
+ winerr = getattr(exc, "winerror", None)
62
+ if os.name == "nt" and (winerr in (5, 32) or exc.errno in (errno.EACCES, errno.EBUSY)) and attempt < 7:
63
+ time.sleep(0.02 * (attempt + 1))
64
+ continue
65
+ raise
66
+ except OSError as exc:
67
+ if os.name == "nt" and exc.errno in (errno.EACCES, errno.EBUSY) and attempt < 7:
68
+ time.sleep(0.02 * (attempt + 1))
69
+ continue
70
+ raise
71
+
72
+
51
73
  def save(path, data):
52
- Path(path).write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
74
+ target = Path(path)
75
+ target.parent.mkdir(parents=True, exist_ok=True)
76
+ tmp_path = None
77
+ try:
78
+ with tempfile.NamedTemporaryFile(dir=target.parent, prefix=target.name + "-", suffix=".tmp", mode="w", encoding="utf-8", delete=False) as tmp:
79
+ tmp_path = Path(tmp.name)
80
+ tmp.write(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
81
+ atomic_replace(tmp_path, target)
82
+ finally:
83
+ if tmp_path is not None:
84
+ tmp_path.unlink(missing_ok=True)
53
85
 
54
86
 
55
87
  def sha(data):
@@ -402,7 +434,7 @@ def read_environment(env_file=None):
402
434
  if env_file:
403
435
  path = Path(env_file).resolve()
404
436
  require(path.is_file() and not (path.stat().st_mode & 0o077), "env-file must exist with user-only permissions (chmod 600)")
405
- for line in path.read_text().splitlines():
437
+ for line in path.read_text(encoding="utf-8").splitlines():
406
438
  if not line.strip() or line.lstrip().startswith("#"):
407
439
  continue
408
440
  key, sep, value = line.partition("=")
@@ -497,13 +529,13 @@ def bundle_work(work, out, admin_login=None):
497
529
 
498
530
 
499
531
  def docker(*args, timeout=60):
500
- p = subprocess.run(["docker", *args], capture_output=True, text=True, timeout=timeout)
532
+ p = subprocess.run(["docker", *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout)
501
533
  require(p.returncode == 0, "Docker command failed: " + args[0] + "; " + "\n".join("[REDACTED]" if secret_lines(line) else line for line in p.stderr.splitlines()[-12:]))
502
534
  return p.stdout.strip()
503
535
 
504
536
 
505
537
  def owned_remove(kind, name, run_id):
506
- raw = subprocess.run(["docker", kind, "inspect", name], capture_output=True, text=True)
538
+ raw = subprocess.run(["docker", kind, "inspect", name], capture_output=True, text=True, encoding="utf-8", errors="replace")
507
539
  if raw.returncode != 0:
508
540
  return
509
541
  item = json.loads(raw.stdout)[0]
@@ -538,7 +570,7 @@ def smoke(args):
538
570
  run_id = load(work / "inventory.json")["run_id"]
539
571
  require(args.container.startswith("opc-adapter-") and re.fullmatch(r"[a-z0-9-]+", args.container), "use an exclusive opc-adapter-* container name")
540
572
  require(args.image.startswith("opc-adapter/"), "use an opc-adapter/ image tag")
541
- existing_image = subprocess.run(["docker", "image", "inspect", args.image], capture_output=True, text=True)
573
+ existing_image = subprocess.run(["docker", "image", "inspect", args.image], capture_output=True, text=True, encoding="utf-8", errors="replace")
542
574
  if existing_image.returncode == 0:
543
575
  labels = json.loads(existing_image.stdout)[0].get("Config", {}).get("Labels", {})
544
576
  require(labels.get(LABEL) == run_id, "image tag belongs to another run; choose a fresh tag")
@@ -631,6 +663,12 @@ def cleanup(args):
631
663
 
632
664
 
633
665
  def main():
666
+ for stream in (sys.stdin, sys.stdout, sys.stderr):
667
+ if hasattr(stream, "reconfigure"):
668
+ try:
669
+ stream.reconfigure(encoding="utf-8")
670
+ except Exception:
671
+ pass
634
672
  parser = argparse.ArgumentParser(description=__doc__)
635
673
  sub = parser.add_subparsers(dest="command", required=True)
636
674
  p = sub.add_parser("prepare")
@@ -31,7 +31,7 @@ def valid_origin(value):
31
31
 
32
32
  def read_json(value, filename):
33
33
  if filename:
34
- return json.load(sys.stdin) if filename == "-" else json.loads(Path(filename).read_text())
34
+ return json.load(sys.stdin) if filename == "-" else json.loads(Path(filename).read_text(encoding="utf-8"))
35
35
  return json.loads(value)
36
36
 
37
37
 
@@ -280,6 +280,12 @@ def execute(contract, operation, params, body=None, approve_write=False, credent
280
280
 
281
281
 
282
282
  def main():
283
+ for stream in (sys.stdin, sys.stdout, sys.stderr):
284
+ if hasattr(stream, "reconfigure"):
285
+ try:
286
+ stream.reconfigure(encoding="utf-8", errors="replace")
287
+ except Exception:
288
+ pass
283
289
  parser = argparse.ArgumentParser(description=__doc__)
284
290
  parser.add_argument("--operation", required=True)
285
291
  group = parser.add_mutually_exclusive_group()
@@ -292,7 +298,7 @@ def main():
292
298
  root = Path(__file__).resolve().parents[1]
293
299
  if (root / ".work-delivery-pending").exists():
294
300
  raise ValueError("Work application deployment has not passed verification; this skill is disabled")
295
- contract = json.loads((root / "references/operations.json").read_text())
301
+ contract = json.loads((root / "references/operations.json").read_text(encoding="utf-8"))
296
302
  params = read_json(args.params, args.params_file)
297
303
  body = read_json("null", args.body_file)
298
304
  md = root / "SKILL.md"
@@ -184,7 +184,7 @@ def scrypt_digest(password_bytes, salt, n, r, p, length):
184
184
  payload = json.dumps({"p": password_bytes.hex(), "s": salt.hex(), "n": n, "r": r, "p_par": p, "len": length})
185
185
  proc = subprocess.run(
186
186
  [node_bin, "-e", "const fs=require('fs'),c=require('crypto');const d=JSON.parse(fs.readFileSync(0,'utf8'));process.stdout.write(c.scryptSync(Buffer.from(d.p,'hex'),Buffer.from(d.s,'hex'),d.len,{N:d.n,r:d.r,p:d.p_par,maxmem:96*1024*1024}).toString('hex'))"],
187
- input=payload, text=True, capture_output=True, timeout=30,
187
+ input=payload, text=True, encoding="utf-8", capture_output=True, timeout=30,
188
188
  )
189
189
  if proc.returncode == 0 and len(proc.stdout.strip()) == length * 2:
190
190
  return proc.stdout.strip()
@@ -6,31 +6,50 @@ from app_delivery.scripts import delivery
6
6
 
7
7
 
8
8
  def resolve_authentication(contract):
9
+ errors = []
9
10
  rules = contract.get('auth_rules', [])
11
+ valid_rules = []
10
12
  if not isinstance(rules, list):
11
- raise ValueError('auth_rules 必须是数组')
12
- for index, rule in enumerate(rules):
13
- field = f'auth_rules[{index}]'
14
- if not isinstance(rule, dict):
15
- raise ValueError(f'{field} 必须是对象')
16
- if rule.get('target') not in ('api', 'page'):
17
- raise ValueError(f'{field}.target 必须填写 api 或 page')
18
- if not rule.get('evidence'):
19
- raise ValueError(f'{field}.evidence 缺少源码证据,请引用读取工具返回的 文件:行号')
20
- if not isinstance(rule.get('auth'), dict) or rule['auth'].get('type') not in ('none', 'header', 'bearer'):
21
- raise ValueError(f'{field}.auth.type 必须使用已确认的 none/header/bearer 方式')
22
- if not isinstance(rule.get('evidence'), list) or not all(isinstance(e, str) and e for e in rule['evidence']):
23
- raise ValueError(f'{field}.evidence 必须是源码位置数组')
24
- for key in ('path', 'prefix'):
25
- if key in rule and (not isinstance(rule[key], str) or not rule[key].startswith('/')):
26
- raise ValueError(f'{field}.{key} 必须是以 / 开头的路径')
27
- if bool(rule.get('path')) == bool(rule.get('prefix')):
28
- raise ValueError(f'{field} 必须选择精确 path 或路径 prefix')
29
- if 'method' in rule and not isinstance(rule['method'], str):
30
- raise ValueError(f'{field}.method 必须是字符串')
13
+ errors.append('auth_rules 必须是数组')
14
+ else:
15
+ for index, rule in enumerate(rules):
16
+ field = f'auth_rules[{index}]'
17
+ if not isinstance(rule, dict):
18
+ errors.append(f'{field} 必须是对象')
19
+ continue
20
+ rule_ok = True
21
+ if rule.get('target') not in ('api', 'page'):
22
+ errors.append(f'{field}.target 必须填写 api 或 page')
23
+ rule_ok = False
24
+ if not rule.get('evidence'):
25
+ errors.append(f'{field}.evidence 缺少源码证据,请引用读取工具返回的 文件:行号')
26
+ rule_ok = False
27
+ elif not isinstance(rule.get('evidence'), list) or not all(isinstance(e, str) and e for e in rule['evidence']):
28
+ errors.append(f'{field}.evidence 必须是源码位置数组')
29
+ rule_ok = False
30
+ if not isinstance(rule.get('auth'), dict) or rule['auth'].get('type') not in ('none', 'header', 'bearer'):
31
+ errors.append(f'{field}.auth.type 必须使用已确认的 none/header/bearer 方式')
32
+ rule_ok = False
33
+ for key in ('path', 'prefix'):
34
+ if key in rule and (not isinstance(rule[key], str) or not rule[key].startswith('/')):
35
+ errors.append(f'{field}.{key} 必须是以 / 开头的路径')
36
+ rule_ok = False
37
+ if bool(rule.get('path')) == bool(rule.get('prefix')):
38
+ errors.append(f'{field} 必须选择精确 path 或路径 prefix')
39
+ rule_ok = False
40
+ if 'method' in rule and not isinstance(rule['method'], str):
41
+ errors.append(f'{field}.method 必须是字符串')
42
+ rule_ok = False
43
+ if rule_ok:
44
+ valid_rules.append(rule)
31
45
  for target, key in [('api', 'apis'), ('page', 'pages')]:
32
- for item in contract.get(key, []):
33
- matches = [r for r in rules if r['target'] == target
46
+ items = contract.get(key, [])
47
+ if not isinstance(items, list):
48
+ continue
49
+ for item in items:
50
+ if not isinstance(item, dict):
51
+ continue
52
+ matches = [r for r in valid_rules if r['target'] == target
34
53
  and (not r.get('method') or r['method'].upper() == item.get('method', '').upper())
35
54
  and (r.get('path') == item['path'] or
36
55
  (r.get('prefix') and item['path'].startswith(r['prefix'])))]
@@ -39,7 +58,8 @@ def resolve_authentication(contract):
39
58
  best = ranked[0]
40
59
  rank = lambda r: (bool(r.get('path')), len(r.get('prefix', '')), bool(r.get('method')))
41
60
  if any(rank(r) == rank(best) and r.get('auth') != best.get('auth') for r in ranked[1:]):
42
- raise ValueError('存在互相冲突的认证规则:' + item['path'])
61
+ errors.append('存在互相冲突的认证规则:' + item['path'])
62
+ continue
43
63
  item['auth'] = {**copy.deepcopy(best.get('auth', {})), 'evidence': best['evidence']}
44
64
  auth = item.get('auth', {'type': 'unknown'})
45
65
  if auth.get('type') == 'unknown':
@@ -47,10 +67,12 @@ def resolve_authentication(contract):
47
67
  location = evidence[0] if isinstance(evidence, list) and evidence else ''
48
68
  origin = f"。源码位置:{location}" if isinstance(location, str) and location else ""
49
69
  label = item.get('method') if target == 'api' else '页面'
50
- raise ValueError(
70
+ errors.append(
51
71
  f"认证尚未分析({key} 项,需匹配 target='{target}'):{label or '接口'} {item['path']}{origin}。"
52
72
  f"请读取该条目的实际登录、会话或权限代码,并在 auth_rules 中补充 target='{target}' 且 path='{item['path']}'(或覆盖它的 prefix)的规则,或直接补齐该条目的 auth 与 evidence。"
53
73
  )
74
+ if errors:
75
+ raise ValueError("\n".join(dict.fromkeys(errors)))
54
76
  return contract
55
77
 
56
78
 
@@ -61,41 +83,64 @@ def validate_auth_evidence(source, proposal):
61
83
  delivery.relative(source, change["path"]): change["content"]
62
84
  for change in proposal.get("changes", [])
63
85
  }
64
- entries = [entry.get("evidence") if isinstance(entry, dict) else None
65
- for entry in [*contract.get("auth_rules", []), *contract.get("auth_blockers", [])]]
86
+ auth_rules = contract.get("auth_rules", [])
87
+ auth_blockers = contract.get("auth_blockers", [])
88
+ entries = [
89
+ entry.get("evidence") if isinstance(entry, dict) else None
90
+ for entry in [
91
+ *(auth_rules if isinstance(auth_rules, list) else []),
92
+ *(auth_blockers if isinstance(auth_blockers, list) else []),
93
+ ]
94
+ ]
66
95
  account = contract.get("admin_account")
67
96
  if account is not None:
68
97
  entries.append(account.get("evidence") if isinstance(account, dict) else None)
69
98
  # Older contracts put source citations on the route itself. When an
70
99
  # explicit authentication citation is supplied, check that citation.
71
100
  for collection in ("apis", "pages"):
72
- for item in contract.get(collection, []):
73
- entries.append(item.get("auth", {}).get("evidence", item.get("evidence")))
101
+ items = contract.get(collection, [])
102
+ if not isinstance(items, list):
103
+ continue
104
+ for item in items:
105
+ if not isinstance(item, dict):
106
+ continue
107
+ auth = item.get("auth")
108
+ entries.append(auth.get("evidence", item.get("evidence")) if isinstance(auth, dict) else item.get("evidence"))
74
109
 
110
+ errors = []
75
111
  line_counts = {}
76
112
  for citations in entries:
77
113
  if not isinstance(citations, list) or not citations:
78
- raise ValueError("认证证据必须是非空的 文件:行号 数组")
114
+ errors.append("认证证据必须是非空的 文件:行号 数组")
115
+ continue
79
116
  for evidence in citations:
80
117
  match = re.fullmatch(r"(.+):(\d+)(?:-(\d+))?", evidence) if isinstance(evidence, str) else None
81
118
  if not match:
82
- raise ValueError("认证证据必须引用源码读取工具返回的 文件:行号")
119
+ errors.append("认证证据必须引用源码读取工具返回的 文件:行号")
120
+ continue
83
121
  path, start, end = match.groups()
84
- source_path = delivery.relative(source, path)
122
+ try:
123
+ source_path = delivery.relative(source, path)
124
+ except ValueError as exc:
125
+ errors.append(str(exc))
126
+ continue
85
127
  if source_path not in line_counts:
86
128
  content = changes.get(source_path)
87
129
  if content is None:
88
130
  if not source_path.is_file():
89
- raise ValueError(f"认证证据位置不存在:{evidence}。找不到文件 {path}" + delivery.source_path_hint(source, path))
131
+ errors.append(f"认证证据位置不存在:{evidence}。找不到文件 {path}" + delivery.source_path_hint(source, path))
132
+ continue
90
133
  content = delivery.text_of(source_path)
91
134
  line_counts[source_path] = len(content.splitlines()) if content is not None else 0
92
135
  count = line_counts[source_path]
93
136
  if not 1 <= int(start) <= int(end or start) <= count:
94
137
  location = "拟提交文件" if source_path in changes else "当前导入源码"
95
- raise ValueError(
138
+ errors.append(
96
139
  f"认证证据位置不存在:{evidence}。{location} {path} 共 {count} 行。"
97
140
  "请只重读该文件的登录处理、会话读取或权限检查,用实际行号修正证据后重新提交。"
98
141
  )
142
+ if errors:
143
+ raise ValueError("\n".join(dict.fromkeys(errors)))
99
144
 
100
145
 
101
146
  def verification_credential_fields(contract):
@@ -114,11 +159,13 @@ def verification_credential_fields(contract):
114
159
 
115
160
  def validate_auth_questions(proposal):
116
161
  """Technical uncertainty is returned to the model, not turned into a user prompt."""
162
+ errors = []
117
163
  contract = proposal.get('contract', {})
118
164
  questions = [q for q in [*proposal.get('unresolved', []), *contract.get('unresolved', [])] if isinstance(q, str) and q.strip()]
119
165
  blockers = contract.get('auth_blockers', [])
120
166
  if not isinstance(blockers, list):
121
- raise ValueError('auth_blockers 必须是数组')
167
+ errors.append('auth_blockers 必须是数组')
168
+ blockers = []
122
169
  valid_reasons = {'external_authorization', 'missing_credential', 'role_change'}
123
170
  for question in dict.fromkeys(questions):
124
171
  if re.search(r'令牌|token|登录|账密|凭据|授权码', question, re.I):
@@ -131,7 +178,9 @@ def validate_auth_questions(proposal):
131
178
  detail = 'contract.auth_blockers[].question 必须与 unresolved 中的问题文本完全一致'
132
179
  else:
133
180
  detail = '如运行时账号/令牌可在第 3 步部署配置填写,请从 unresolved 移除;若确实阻塞改造,请在 contract.auth_blockers 中用完全相同的 question 提供 evidence/affected/action/reason'
134
- raise ValueError(f'认证提问缺少证据(unresolved 条目「{q_trimmed}」):{detail}。')
181
+ errors.append(f'认证提问缺少证据(unresolved 条目「{q_trimmed}」):{detail}。')
182
+ if errors:
183
+ raise ValueError("\n".join(dict.fromkeys(errors)))
135
184
 
136
185
 
137
186
  def validate_auth_probe_coverage(contract):
@@ -42,7 +42,7 @@ def check_archive_syntax(archive):
42
42
  raise ValueError(f'语法检查超时:{member.name}') from exc
43
43
  if result.returncode:
44
44
  # Do not expose source lines or embedded credentials in parser output.
45
- error = next((s.strip() for s in result.stderr.decode(errors='replace').splitlines() if 'SyntaxError:' in s), 'Node.js 解析失败')
45
+ error = next((s.strip() for s in result.stderr.decode('utf-8', errors='replace').splitlines() if 'SyntaxError:' in s), 'Node.js 解析失败')
46
46
  raise ValueError(f'交付包语法检查失败:{member.name}:{error};请修复完整文件后重新打包')
47
47
  checked += 1
48
48
  return {'label': '交付包 JavaScript 语法', 'status': 'passed' if checked else 'pending', 'detail': f'已检查 {checked} 个 .mjs/.cjs 文件;不代表目标版本兼容、启动或业务验证通过' if checked else '没有可用此检查器验证的 .mjs/.cjs 文件;其他语言及 .js/TS/JSX 未检查'}
@@ -11,7 +11,7 @@ def dependency_path(source: Path, module: str = "", name: str = ""):
11
11
  mod = source / "go.mod"
12
12
  if not mod.is_file():
13
13
  raise ValueError("当前源码没有 go.mod;请提供缺失依赖的源码或接口说明")
14
- contents = mod.read_text()
14
+ contents = mod.read_text(encoding="utf-8")
15
15
  declarations = re.findall(r"^\s*(?:require\s+)?([A-Za-z0-9_.!/-]+)\s+(v[0-9][A-Za-z0-9.+-]*)\s*(?://[^\n]*)?$", contents, re.M)
16
16
  replaced = set(re.findall(r"^\s*(?:replace\s+)?([A-Za-z0-9_.!/-]+)(?:\s+v[^\s]+)?\s*=>", contents, re.M))
17
17
  cache = Path(os.environ.get("GOMODCACHE") or str(Path(os.environ.get("GOPATH", str(Path.home() / "go")).split(os.pathsep)[0]) / "pkg/mod"))