@kevlns/art-workshop 0.4.2 → 0.5.1

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.
Files changed (68) hide show
  1. package/AGENTS.md +25 -105
  2. package/LICENSE +21 -21
  3. package/README.md +63 -63
  4. package/art-workshop.mjs +174 -167
  5. package/docs/commands.md +116 -8
  6. package/docs/configuration.md +82 -82
  7. package/docs/core-guidance.md +50 -50
  8. package/docs/data-formats.md +85 -79
  9. package/docs/deployment.md +32 -32
  10. package/docs/local-models/qwen-image-2.1.json +73 -73
  11. package/docs/local-models/qwen-image-2.1.md +33 -33
  12. package/docs/model-architecture.md +78 -78
  13. package/docs/modes.md +67 -67
  14. package/lib/agent.mjs +32 -47
  15. package/lib/analysis-worker.mjs +32 -29
  16. package/lib/analyze.mjs +85 -78
  17. package/lib/asset-profile.mjs +23 -0
  18. package/lib/candidates.mjs +103 -101
  19. package/lib/comfy-recovery.mjs +17 -17
  20. package/lib/conversation.mjs +77 -0
  21. package/lib/core.mjs +75 -89
  22. package/lib/deployment-guide.mjs +12 -12
  23. package/lib/design.mjs +29 -29
  24. package/lib/dimensions.mjs +22 -22
  25. package/lib/edit.mjs +41 -38
  26. package/lib/environment-operations.mjs +49 -49
  27. package/lib/environment-runtime.mjs +99 -99
  28. package/lib/environments.mjs +55 -55
  29. package/lib/errors.mjs +32 -0
  30. package/lib/executor.mjs +107 -107
  31. package/lib/generate.mjs +58 -59
  32. package/lib/heartbeat.mjs +16 -16
  33. package/lib/images.mjs +1 -1
  34. package/lib/lifecycle.mjs +53 -53
  35. package/lib/migration.mjs +154 -154
  36. package/lib/object-format.mjs +112 -0
  37. package/lib/presentation.mjs +18 -2
  38. package/lib/process-identity.mjs +14 -14
  39. package/lib/project.mjs +39 -39
  40. package/lib/prompt-structure.mjs +7 -3
  41. package/lib/refs.mjs +26 -26
  42. package/lib/runtime.mjs +25 -25
  43. package/lib/service.mjs +126 -126
  44. package/lib/settings.mjs +50 -50
  45. package/lib/shared.mjs +67 -66
  46. package/lib/style-bundle.mjs +85 -85
  47. package/lib/style-contract.mjs +74 -35
  48. package/lib/style-evidence.mjs +39 -0
  49. package/lib/style-lifecycle.mjs +125 -120
  50. package/lib/style-report.mjs +201 -0
  51. package/lib/style-review.mjs +14 -75
  52. package/lib/task-contract.mjs +93 -59
  53. package/lib/tasks.mjs +497 -495
  54. package/lib/templates.mjs +80 -70
  55. package/lib/vision.mjs +56 -46
  56. package/lib/workspace.mjs +292 -238
  57. package/package.json +3 -5
  58. package/rules/core-guidance.json +22 -22
  59. package/skills/art-workshop/SKILL.md +17 -112
  60. package/skills/art-workshop/references/conversation.md +11 -0
  61. package/skills/art-workshop/references/expression.md +27 -0
  62. package/skills/art-workshop/references/getty.md +76 -0
  63. package/skills/art-workshop/references/project.md +109 -0
  64. package/skills/art-workshop/references/style-discussion.md +27 -0
  65. package/skills/art-workshop/scripts/getty.py +269 -0
  66. package/v-cli.plugin.json +2747 -2491
  67. package/scripts/sync-skill.mjs +0 -6
  68. /package/{skills/art-workshop → adapters/codex}/agents/openai.yaml +0 -0
@@ -0,0 +1,269 @@
1
+ #!/usr/bin/env python3
2
+ """Getty AAT JSON adapter; Python 3.9+, standard library only."""
3
+
4
+ import argparse
5
+ import hashlib
6
+ import http.client
7
+ import json
8
+ import math
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import socket
13
+ import sys
14
+ import tempfile
15
+ import time
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+
20
+ ENDPOINT = "https://services.getty.edu/vocab/reconcile/"
21
+ SCHEMA = "art-workshop/getty-v1"
22
+ CORE_FIELDS = {"preferredTerms": "/aat_prefterm", "variantTerms": "/aat_varterms",
23
+ "scopeNotes": "/aat_notes"}
24
+ HIERARCHY_FIELD = "/aat_hier"
25
+ MAX_BYTES = 5 * 1024 * 1024
26
+ MAX_ERROR_BYTES = 4096
27
+
28
+
29
+ class GettyError(Exception):
30
+ def __init__(self, code, message, *, http_status=None, details=None):
31
+ super().__init__(message)
32
+ self.code = code
33
+ self.http_status, self.details = http_status, details
34
+
35
+ def to_dict(self):
36
+ return {"code": self.code, "message": str(self),
37
+ **({"httpStatus": self.http_status} if self.http_status is not None else {}),
38
+ **({"details": self.details} if self.details else {})}
39
+
40
+
41
+ def encoded(value):
42
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
43
+
44
+
45
+ def read_json(text):
46
+ return json.loads(text, parse_constant=lambda value: (_ for _ in ()).throw(ValueError(value)))
47
+
48
+
49
+ def validate(value):
50
+ if not isinstance(value, dict) or set(value) - {"queries", "limit"}:
51
+ raise GettyError("INVALID_INPUT", "Expected {queries:[{id?,query,context,properties?}],limit?}")
52
+ limit = value.get("limit", 5)
53
+ if type(limit) is not int or not 1 <= limit <= 10:
54
+ raise GettyError("INVALID_INPUT", "limit must be an integer from 1 to 10")
55
+ queries = value.get("queries")
56
+ if not isinstance(queries, list) or not 1 <= len(queries) <= 10:
57
+ raise GettyError("INVALID_INPUT", "queries must contain 1 to 10 items; split larger batches")
58
+ result, ids = [], set()
59
+ for index, item in enumerate(queries):
60
+ if not isinstance(item, dict) or set(item) - {"id", "query", "context", "properties"}:
61
+ raise GettyError("INVALID_INPUT", "Unknown query fields")
62
+ identifier, query = item.get("id", "q" + str(index)), item.get("query")
63
+ if not isinstance(identifier, str) or not identifier or identifier in ids:
64
+ raise GettyError("INVALID_INPUT", "Query IDs must be nonempty and unique")
65
+ if not isinstance(query, str) or not query.strip():
66
+ raise GettyError("INVALID_INPUT", "query must be a nonempty string")
67
+ context = item.get("context")
68
+ if (not isinstance(context, dict) or not isinstance(context.get("original"), str)
69
+ or not context["original"] or ("target" in context and not isinstance(context["target"], str))):
70
+ raise GettyError("INVALID_INPUT", "context requires original text and an optional target string")
71
+ properties = item.get("properties", {})
72
+ if (not isinstance(properties, dict) or set(properties) - {"note", "broaderExt", "label"}
73
+ or any(not isinstance(v, str) or not v.strip() for v in properties.values())):
74
+ raise GettyError("INVALID_INPUT", "properties accepts nonempty note, broaderExt and label strings")
75
+ ids.add(identifier)
76
+ result.append({**item, "id": identifier, "properties": properties})
77
+ return {"queries": result, "limit": limit}
78
+
79
+
80
+ def transport(params, timeout):
81
+ request = urllib.request.Request(ENDPOINT, data=urllib.parse.urlencode(params).encode("utf-8"), headers={
82
+ "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
83
+ "User-Agent": "Vant-Art-Workshop-Getty/1"})
84
+ try:
85
+ with urllib.request.urlopen(request, timeout=timeout) as response:
86
+ data = response.read(MAX_BYTES + 1)
87
+ if len(data) > MAX_BYTES:
88
+ raise GettyError("RESPONSE_TOO_LARGE", "Getty response exceeds 5 MiB")
89
+ return read_json(data.decode("utf-8-sig"))
90
+ except urllib.error.HTTPError as error:
91
+ try:
92
+ details = error.read(MAX_ERROR_BYTES).decode("utf-8", errors="replace")
93
+ except OSError:
94
+ details = None
95
+ finally:
96
+ error.close()
97
+ raise GettyError("HTTP_ERROR", "Getty returned HTTP " + str(error.code),
98
+ http_status=error.code, details=details) from error
99
+ except (TimeoutError, socket.timeout) as error:
100
+ raise GettyError("TIMEOUT", "Getty request timed out") from error
101
+ except urllib.error.URLError as error:
102
+ if isinstance(error.reason, (TimeoutError, socket.timeout)):
103
+ raise GettyError("TIMEOUT", "Getty request timed out") from error
104
+ raise GettyError("NETWORK_ERROR", "Getty connection failed: " + str(error.reason)) from error
105
+ except (OSError, http.client.HTTPException) as error:
106
+ raise GettyError("NETWORK_ERROR", "Getty connection failed: " + str(error)) from error
107
+ except (ValueError, UnicodeError) as error:
108
+ raise GettyError("INVALID_RESPONSE", "Getty did not return valid UTF-8 JSON") from error
109
+
110
+
111
+ class Client:
112
+ def __init__(self, cache_dir, timeout=15, ttl=86400, refresh=False, fetch=transport):
113
+ self.cache_dir, self.timeout, self.ttl = Path(cache_dir), timeout, ttl
114
+ self.refresh, self.fetch, self.warnings = refresh, fetch, []
115
+
116
+ def request(self, params, check):
117
+ # 完整请求精确命中,不裁剪、翻译或归一化检索文字。
118
+ key = hashlib.sha256(encoded({"schema": SCHEMA, "endpoint": ENDPOINT,
119
+ "method": "POST", "params": params}).encode("utf-8")).hexdigest()
120
+ path = self.cache_dir / (key + ".json")
121
+ if not self.refresh and self.ttl > 0:
122
+ try:
123
+ cached = read_json(path.read_text(encoding="utf-8"))
124
+ age = time.time() - cached["fetchedAt"]
125
+ if cached["key"] == key and 0 <= age < self.ttl:
126
+ check(cached["data"])
127
+ return cached["data"], "hit"
128
+ except (OSError, ValueError, KeyError, TypeError, GettyError):
129
+ pass
130
+ data = self.fetch(params, self.timeout)
131
+ check(data)
132
+ if self.ttl > 0:
133
+ temporary = None
134
+ try:
135
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
136
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=self.cache_dir,
137
+ suffix=".tmp", delete=False) as output:
138
+ temporary = output.name
139
+ output.write(encoded({"key": key, "fetchedAt": time.time(), "data": data}))
140
+ os.replace(temporary, path)
141
+ except OSError:
142
+ self.warnings.append("Cache write failed; live result retained")
143
+ finally:
144
+ if temporary:
145
+ try:
146
+ Path(temporary).unlink(missing_ok=True)
147
+ except OSError:
148
+ pass
149
+ return data, "miss"
150
+
151
+
152
+ def check_candidates(data, keys):
153
+ if not isinstance(data, dict):
154
+ raise GettyError("INVALID_RESPONSE", "Expected Getty reconciliation object")
155
+ for key in keys:
156
+ group = data.get(key)
157
+ if not isinstance(group, dict) or not isinstance(group.get("result"), list):
158
+ raise GettyError("INVALID_RESPONSE", "Missing reconciliation results for " + key)
159
+ for candidate in group["result"]:
160
+ if (not isinstance(candidate, dict)
161
+ or not isinstance(candidate.get("id"), str)
162
+ or not re.fullmatch(r"aat/[0-9]+", candidate["id"])
163
+ or not isinstance(candidate.get("name"), str)
164
+ or type(candidate.get("score")) not in (int, float)
165
+ or not math.isfinite(candidate["score"])
166
+ or type(candidate.get("match")) is not bool):
167
+ raise GettyError("INVALID_RESPONSE", "Malformed AAT candidate")
168
+
169
+
170
+ def check_details(data, ids, fields):
171
+ if not isinstance(data, dict) or not isinstance(data.get("rows"), dict):
172
+ raise GettyError("INVALID_RESPONSE", "Missing Getty detail rows")
173
+ for identifier in ids:
174
+ row = data["rows"].get(identifier)
175
+ if not isinstance(row, dict):
176
+ raise GettyError("INVALID_RESPONSE", "Missing detail row for " + identifier)
177
+ for field in fields:
178
+ if (field not in row or not isinstance(row[field], list)
179
+ or any(not isinstance(v, dict) or not isinstance(v.get("str"), str) for v in row[field])):
180
+ raise GettyError("INVALID_RESPONSE", "Malformed Getty detail field " + field)
181
+
182
+
183
+ def execute(value, client):
184
+ request = validate(value)
185
+ wire = {"q" + str(i): {"query": item["query"], "type": "/aat", "limit": request["limit"],
186
+ "properties": [{"pid": k, "v": v} for k, v in sorted(item["properties"].items())]}
187
+ for i, item in enumerate(request["queries"])}
188
+ data, search_cache = client.request({"queries": encoded(wire)}, lambda d: check_candidates(d, wire))
189
+ ids = sorted({c["id"] for key in wire for c in data[key]["result"]})
190
+ details, detail_cache, detail_error = {}, None, None
191
+ hierarchy, hierarchy_cache = {}, None
192
+ enrichment = {"status": "not_requested"}
193
+ if ids:
194
+ try:
195
+ extended, detail_cache = client.request({"extend": encoded({"ids": ids,
196
+ "properties": [{"id": field} for field in CORE_FIELDS.values()]})},
197
+ lambda d: check_details(d, ids, CORE_FIELDS.values()))
198
+ details = extended["rows"]
199
+ except GettyError as error:
200
+ detail_error = error.to_dict()
201
+ if detail_error is None:
202
+ try:
203
+ extended, hierarchy_cache = client.request({"extend": encoded({"ids": ids,
204
+ "properties": [{"id": HIERARCHY_FIELD}]})},
205
+ lambda d: check_details(d, ids, [HIERARCHY_FIELD]))
206
+ hierarchy = extended["rows"]
207
+ enrichment = {"status": "succeeded"}
208
+ except GettyError as error:
209
+ enrichment = {"status": "failed", "error": error.to_dict()}
210
+ groups = []
211
+ for index, item in enumerate(request["queries"]):
212
+ candidates = []
213
+ for candidate in sorted(data["q" + str(index)]["result"], key=lambda c: -c["score"]):
214
+ identifier = candidate["id"]
215
+ row = details.get(identifier, {})
216
+ candidates.append({"id": identifier, "uri": "http://vocab.getty.edu/" + identifier,
217
+ "label": candidate["name"], "serviceScore": candidate["score"],
218
+ "serviceMatch": candidate["match"], "detailsAvailable": identifier in details,
219
+ "hierarchyAvailable": identifier in hierarchy,
220
+ "hierarchy": [v["str"] for v in hierarchy.get(identifier, {}).get(HIERARCHY_FIELD, [])],
221
+ **{name: [v["str"] for v in row.get(field, [])] for name, field in CORE_FIELDS.items()}})
222
+ groups.append({**item, "status": "candidates" if candidates else "no_match", "candidates": candidates})
223
+ status = "partial" if detail_error else "candidates" if ids else "no_match"
224
+ return {"schema": SCHEMA, "ok": not detail_error, "status": status, "request": request,
225
+ "source": {"endpoint": ENDPOINT, "vocabulary": "aat", "license": "ODC-By-1.0",
226
+ "attribution": "J. Paul Getty Trust, Getty Research Institute, Art & Architecture Thesaurus"},
227
+ "cache": {"search": search_cache, "details": detail_cache, "hierarchy": hierarchy_cache}, "queries": groups,
228
+ "enrichment": {"hierarchy": enrichment},
229
+ "warnings": client.warnings + (["Candidates retained; core concept details could not be verified"] if detail_error else [])
230
+ + (["Core concept details verified; hierarchy unavailable"] if enrichment["status"] == "failed" else []),
231
+ "error": detail_error}
232
+
233
+
234
+ class Parser(argparse.ArgumentParser):
235
+ def error(self, message):
236
+ raise GettyError("INVALID_INPUT", message)
237
+
238
+
239
+ def main():
240
+ for stream in (sys.stdin, sys.stdout, sys.stderr):
241
+ if hasattr(stream, "reconfigure"):
242
+ stream.reconfigure(encoding="utf-8")
243
+ parser = Parser(description=__doc__)
244
+ parser.add_argument("--input", default="-", help="UTF-8 JSON file, or - for stdin")
245
+ parser.add_argument("--cache-dir", default=str(Path(os.environ.get("VANT_HOME", str(Path.home() / ".vant")))
246
+ / "tools/art-workshop/cache/getty"))
247
+ parser.add_argument("--timeout", type=float, default=15, help="Seconds per request; no automatic retries")
248
+ parser.add_argument("--cache-ttl", type=float, default=86400, help="Seconds; 0 disables cache")
249
+ parser.add_argument("--refresh", action="store_true", help="Bypass existing cache")
250
+ result = None
251
+ try:
252
+ args = parser.parse_args()
253
+ if not math.isfinite(args.timeout) or not 0 < args.timeout <= 60:
254
+ raise GettyError("INVALID_INPUT", "timeout must be greater than 0 and at most 60 seconds")
255
+ if not math.isfinite(args.cache_ttl) or args.cache_ttl < 0:
256
+ raise GettyError("INVALID_INPUT", "cache-ttl must be finite and nonnegative")
257
+ text = sys.stdin.read() if args.input == "-" else Path(args.input).read_text(encoding="utf-8-sig")
258
+ value = read_json(text)
259
+ result = execute(value, Client(args.cache_dir, args.timeout, args.cache_ttl, args.refresh))
260
+ except (GettyError, OSError, ValueError) as error:
261
+ result = {"schema": SCHEMA, "ok": False, "status": "error", "queries": [],
262
+ "error": error.to_dict() if isinstance(error, GettyError)
263
+ else {"code": "INVALID_INPUT", "message": str(error)}}
264
+ sys.stdout.write(encoded(result) + "\n")
265
+ return 0 if result["ok"] else 1
266
+
267
+
268
+ if __name__ == "__main__":
269
+ sys.exit(main())