omnius 1.0.923 → 1.0.925

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 (239) hide show
  1. package/dist/{providerRegistry.d.ts → _types/backend-vllm/providerRegistry.d.ts} +0 -1
  2. package/dist/_types/backend-vllm/types.d.ts +209 -0
  3. package/dist/_types/execution/av/media-capability.d.ts +94 -0
  4. package/dist/_types/execution/delegation-contract.d.ts +102 -0
  5. package/dist/_types/execution/evidence.d.ts +68 -0
  6. package/dist/_types/execution/html-source-evidence.d.ts +65 -0
  7. package/dist/_types/execution/mcp/types.d.ts +169 -0
  8. package/dist/_types/execution/mutation-contract.d.ts +102 -0
  9. package/dist/_types/execution/nol/artifacts.d.ts +39 -0
  10. package/dist/_types/execution/nol/checkpoint-edits.d.ts +98 -0
  11. package/dist/_types/execution/nol/distributions.d.ts +128 -0
  12. package/dist/_types/execution/nol/gguf-checkpoint-edits.d.ts +194 -0
  13. package/dist/_types/execution/nol/gguf-control-reader.d.ts +224 -0
  14. package/dist/_types/execution/nol/lora-exports.d.ts +129 -0
  15. package/dist/_types/execution/nol/neuronary.d.ts +212 -0
  16. package/dist/_types/execution/nol/pytorch-control-reader.d.ts +143 -0
  17. package/dist/_types/execution/nol/qwen35-head-sites.d.ts +61 -0
  18. package/dist/_types/execution/nol/worker-assets.d.ts +82 -0
  19. package/dist/_types/execution/nol/worker-protocol.d.ts +94 -0
  20. package/dist/_types/execution/page-content-source.d.ts +40 -0
  21. package/dist/_types/execution/rapid-computer-use/artifact-store.d.ts +21 -0
  22. package/dist/_types/execution/rapid-computer-use/contracts.d.ts +320 -0
  23. package/dist/_types/execution/rapid-computer-use/decision.d.ts +70 -0
  24. package/dist/_types/execution/rapid-computer-use/desktop-verification.d.ts +23 -0
  25. package/dist/_types/execution/rapid-computer-use/geometry.d.ts +57 -0
  26. package/dist/_types/execution/rapid-computer-use/planner.d.ts +78 -0
  27. package/dist/_types/execution/rapid-computer-use/trace.d.ts +80 -0
  28. package/dist/_types/execution/rapid-computer-use/visual.d.ts +48 -0
  29. package/dist/_types/execution/shell-runs.d.ts +78 -0
  30. package/dist/_types/execution/streamed-web-source.d.ts +64 -0
  31. package/dist/_types/execution/tools/browser-page-fallback.d.ts +25 -0
  32. package/dist/_types/execution/tools/network-egress-policy.d.ts +30 -0
  33. package/dist/_types/execution/tools/pdf-native-tables.d.ts +46 -0
  34. package/dist/_types/execution/tools/todo-store.d.ts +133 -0
  35. package/dist/_types/execution/tools/web-fetch.d.ts +57 -0
  36. package/dist/_types/execution/tools/workboard.d.ts +1223 -0
  37. package/dist/_types/execution/types.d.ts +549 -0
  38. package/dist/_types/execution/web-source.d.ts +14 -0
  39. package/dist/_types/memory/artifactReviewSourceIndex.d.ts +133 -0
  40. package/dist/_types/memory/contextMemoryLedger.d.ts +213 -0
  41. package/dist/_types/memory/db.d.ts +12 -0
  42. package/dist/_types/memory/embeddings.d.ts +36 -0
  43. package/dist/_types/memory/immutableEvidenceStore.d.ts +165 -0
  44. package/dist/_types/memory/memoryIngestion.d.ts +65 -0
  45. package/dist/_types/memory/memoryTypes.d.ts +312 -0
  46. package/dist/_types/memory/sourceCorpusStore.d.ts +331 -0
  47. package/dist/_types/memory/structuredMemoryStore.d.ts +105 -0
  48. package/dist/_types/memory/unifiedMemoryStore.d.ts +127 -0
  49. package/dist/_types/memory/virtualMemory.d.ts +187 -0
  50. package/dist/_types/orchestrator/agentic-page-content-receipt.d.ts +20 -0
  51. package/dist/_types/orchestrator/agentic-web-fetch-receipt.d.ts +20 -0
  52. package/dist/_types/orchestrator/agenticRunner.d.ts +5219 -0
  53. package/dist/_types/orchestrator/app-state.d.ts +171 -0
  54. package/dist/_types/orchestrator/artifactClaimCritic.d.ts +63 -0
  55. package/dist/_types/orchestrator/artifactQuality.d.ts +15 -0
  56. package/dist/_types/orchestrator/artifactSemanticIntegrity.d.ts +203 -0
  57. package/dist/_types/orchestrator/canonical-context-projection.d.ts +254 -0
  58. package/dist/_types/orchestrator/canonical-source-body-projection.d.ts +51 -0
  59. package/dist/_types/orchestrator/completion-review-pending.d.ts +24 -0
  60. package/dist/_types/orchestrator/completionContract.d.ts +103 -0
  61. package/dist/_types/orchestrator/completionFinalization.d.ts +224 -0
  62. package/dist/_types/orchestrator/completionLedger.d.ts +429 -0
  63. package/dist/_types/orchestrator/completionReadiness.d.ts +234 -0
  64. package/dist/_types/orchestrator/context-admission.d.ts +93 -0
  65. package/dist/_types/orchestrator/context-dump-retention.d.ts +25 -0
  66. package/dist/_types/orchestrator/context-fabric.d.ts +133 -0
  67. package/dist/_types/orchestrator/contextEngine.d.ts +68 -0
  68. package/dist/_types/orchestrator/contextWindowDump.d.ts +327 -0
  69. package/dist/_types/orchestrator/convergence-breaker.d.ts +225 -0
  70. package/dist/_types/orchestrator/convergence-progress.d.ts +66 -0
  71. package/dist/_types/orchestrator/deliveryCoverage.d.ts +181 -0
  72. package/dist/_types/orchestrator/document-persistence-goal-binding.d.ts +106 -0
  73. package/dist/_types/orchestrator/durable-document-worker.d.ts +85 -0
  74. package/dist/_types/orchestrator/evidenceBranch.d.ts +291 -0
  75. package/dist/_types/orchestrator/expected-inference-response.d.ts +55 -0
  76. package/dist/_types/orchestrator/expectedOutcomeContract.d.ts +58 -0
  77. package/dist/_types/orchestrator/failure-taxonomy.d.ts +36 -0
  78. package/dist/_types/orchestrator/focusSupervisor.d.ts +436 -0
  79. package/dist/_types/orchestrator/forced-update-requirement-recovery.d.ts +105 -0
  80. package/dist/_types/orchestrator/hooks.d.ts +100 -0
  81. package/dist/_types/orchestrator/inference-pressure.d.ts +61 -0
  82. package/dist/_types/orchestrator/integrationClosure.d.ts +89 -0
  83. package/dist/_types/orchestrator/interruption-lifecycle.d.ts +154 -0
  84. package/dist/_types/orchestrator/live-memory-passages.d.ts +51 -0
  85. package/dist/_types/orchestrator/liveVirtualContext.d.ts +84 -0
  86. package/dist/_types/orchestrator/memory-compiler.d.ts +254 -0
  87. package/dist/_types/orchestrator/memory-consolidation.d.ts +134 -0
  88. package/dist/_types/orchestrator/model-router.d.ts +17 -0
  89. package/dist/_types/orchestrator/modelResponseDiagnostics.d.ts +71 -0
  90. package/dist/_types/orchestrator/nativeRequirementAmendment.d.ts +63 -0
  91. package/dist/_types/orchestrator/nol/coordinator.d.ts +204 -0
  92. package/dist/_types/orchestrator/nol/datasets.d.ts +58 -0
  93. package/dist/_types/orchestrator/nol/discovery.d.ts +286 -0
  94. package/dist/_types/orchestrator/nol/evaluation.d.ts +59 -0
  95. package/dist/_types/orchestrator/nol/model-validation.d.ts +198 -0
  96. package/dist/_types/orchestrator/nol/statistics.d.ts +142 -0
  97. package/dist/_types/orchestrator/nol/store.d.ts +133 -0
  98. package/dist/_types/orchestrator/nol/variant-registry.d.ts +292 -0
  99. package/dist/_types/orchestrator/ollama-context-policy.d.ts +34 -0
  100. package/dist/_types/orchestrator/personality.d.ts +66 -0
  101. package/dist/_types/orchestrator/prompt-cache.d.ts +24 -0
  102. package/dist/_types/orchestrator/remote-inference-fallback.d.ts +224 -0
  103. package/dist/_types/orchestrator/remote-inference-policy.d.ts +58 -0
  104. package/dist/_types/orchestrator/request-budget.d.ts +75 -0
  105. package/dist/_types/orchestrator/requirementCoverage.d.ts +69 -0
  106. package/dist/_types/orchestrator/reviewedInterpretation.d.ts +111 -0
  107. package/dist/_types/orchestrator/runEvents.d.ts +115 -0
  108. package/dist/_types/orchestrator/runtime-rollout.d.ts +63 -0
  109. package/dist/_types/orchestrator/semanticVerification.d.ts +135 -0
  110. package/dist/_types/orchestrator/source-wide-extraction.d.ts +202 -0
  111. package/dist/_types/orchestrator/steeringIntake.d.ts +123 -0
  112. package/dist/_types/orchestrator/structured-memory-extraction-worker.d.ts +89 -0
  113. package/dist/_types/orchestrator/structuredMemoryInference.d.ts +62 -0
  114. package/dist/_types/orchestrator/successful-procedure-memory.d.ts +127 -0
  115. package/dist/_types/orchestrator/supportedAnswer.d.ts +68 -0
  116. package/dist/_types/orchestrator/taskEffectEvidence.d.ts +38 -0
  117. package/dist/_types/orchestrator/taskExecutionSnapshot.d.ts +67 -0
  118. package/dist/_types/orchestrator/taskObjective.d.ts +310 -0
  119. package/dist/_types/orchestrator/taskObjectiveContinuation.d.ts +134 -0
  120. package/dist/_types/orchestrator/taskRequirementReview.d.ts +246 -0
  121. package/dist/_types/orchestrator/taskRequirements.d.ts +80 -0
  122. package/dist/_types/orchestrator/taskSemanticAdmission.d.ts +159 -0
  123. package/dist/_types/orchestrator/taskWorkDelegation.d.ts +147 -0
  124. package/dist/_types/orchestrator/taskWorkPlan.d.ts +177 -0
  125. package/dist/_types/orchestrator/telegram-passive-history.d.ts +42 -0
  126. package/dist/_types/orchestrator/terminalTaskReport.d.ts +91 -0
  127. package/dist/_types/orchestrator/todoObservability.d.ts +147 -0
  128. package/dist/_types/orchestrator/tool-exposure-policy.d.ts +100 -0
  129. package/dist/_types/orchestrator/trajectory-checkpoint.d.ts +159 -0
  130. package/dist/_types/orchestrator/types.d.ts +185 -0
  131. package/dist/_types/schemas/dispatch.d.ts +53 -0
  132. package/dist/_types/schemas/feature-workflow.d.ts +362 -0
  133. package/dist/_types/schemas/messages.d.ts +15 -0
  134. package/dist/_types/schemas/nol-assets.d.ts +955 -0
  135. package/dist/_types/schemas/nol-json.d.ts +2 -0
  136. package/dist/_types/schemas/nol.d.ts +3995 -0
  137. package/dist/_types/schemas/patch.d.ts +47 -0
  138. package/dist/_types/schemas/plan.d.ts +47 -0
  139. package/dist/_types/schemas/repoProfile.d.ts +116 -0
  140. package/dist/_types/schemas/retrieval.d.ts +44 -0
  141. package/dist/_types/schemas/task.d.ts +57 -0
  142. package/dist/_types/schemas/tools.d.ts +16 -0
  143. package/dist/_types/schemas/verification.d.ts +31 -0
  144. package/dist/api/py-embed.js +3353 -1829
  145. package/dist/assets/nol-checkpoint-editor.py +701 -0
  146. package/dist/assets/nol-gguf-checkpoint-editor.py +785 -0
  147. package/dist/assets/nol-gguf-control-reader.py +428 -0
  148. package/dist/assets/nol-gne-tools-worker.py +425 -0
  149. package/dist/assets/nol-gne-worker.py +1081 -0
  150. package/dist/assets/nol-lora-exporter.py +349 -0
  151. package/dist/assets/nol-pytorch-control-reader.py +470 -0
  152. package/dist/assets/nol-transformers-nnsight-worker.py +512 -0
  153. package/dist/assets/nol-transformers-peft-validation-worker.py +385 -0
  154. package/dist/assets/nol-transformers-peft-worker.py +488 -0
  155. package/dist/assets/nol-transformers-research-worker.py +472 -0
  156. package/dist/assets/nol-transformers-worker.py +920 -0
  157. package/dist/assets/nol-vllm-owned-worker.py +803 -0
  158. package/dist/assets/nol-vllm-runtime.py +695 -0
  159. package/dist/assets/nol-vllm-tokenizer.py +93 -0
  160. package/dist/assets/nol-vllm-worker.py +201 -0
  161. package/dist/computer-use/configured-planner.d.ts +37 -0
  162. package/dist/computer-use/configured-point.d.ts +35 -0
  163. package/dist/computer-use/host-session.d.ts +60 -0
  164. package/dist/computer-use/runner-ui-port.d.ts +37 -0
  165. package/dist/computer-use/session-review.d.ts +14 -0
  166. package/dist/computer-use/task-spec.d.ts +84 -0
  167. package/dist/discovery.d.ts +16 -2
  168. package/dist/index.js +2 -2
  169. package/dist/library.d.ts +94 -10
  170. package/dist/library.js +144003 -87414
  171. package/dist/memory-maintenance-worker.js +1676 -511
  172. package/dist/nol/cpu-control-reader-profile.d.ts +93 -0
  173. package/dist/nol/cpu-control-reader-service.d.ts +87 -0
  174. package/dist/nol/cuda-lease.d.ts +111 -0
  175. package/dist/nol/cuda-mutations.d.ts +34 -0
  176. package/dist/nol/export-runtime-config.d.ts +114 -0
  177. package/dist/nol/export-service.d.ts +143 -0
  178. package/dist/nol/facade.d.ts +147 -0
  179. package/dist/nol/gguf-cpu-control-reader-profile.d.ts +106 -0
  180. package/dist/nol/gguf-cpu-control-reader-service.d.ts +91 -0
  181. package/dist/nol/gguf-model-control-verifier.d.ts +120 -0
  182. package/dist/nol/gguf-parameter-inventory.d.ts +28 -0
  183. package/dist/nol/gne-adapter.d.ts +134 -0
  184. package/dist/nol/gne-agent-evaluation.d.ts +84 -0
  185. package/dist/nol/gne-profile.d.ts +124 -0
  186. package/dist/nol/gne-tools-profile.d.ts +148 -0
  187. package/dist/nol/gne-tools-transport.d.ts +194 -0
  188. package/dist/nol/model-actions.d.ts +662 -0
  189. package/dist/nol/model-control-verifier.d.ts +135 -0
  190. package/dist/nol/model-json-scorer.d.ts +13 -0
  191. package/dist/nol/model-runtime-config.d.ts +830 -0
  192. package/dist/nol/model-serving.d.ts +130 -0
  193. package/dist/nol/model-subject-adapter.d.ts +72 -0
  194. package/dist/nol/model-validation-factory.d.ts +113 -0
  195. package/dist/nol/neuronary-catalog.d.ts +130 -0
  196. package/dist/nol/orphan-custody.d.ts +72 -0
  197. package/dist/nol/peft-conformance.d.ts +48 -0
  198. package/dist/nol/peft-control-types.d.ts +137 -0
  199. package/dist/nol/peft-control-verifier.d.ts +8 -0
  200. package/dist/nol/peft-model-actions.d.ts +41 -0
  201. package/dist/nol/peft-model-authority.d.ts +146 -0
  202. package/dist/nol/peft-model-controls.d.ts +20 -0
  203. package/dist/nol/peft-model-host.d.ts +47 -0
  204. package/dist/nol/peft-model-profile.d.ts +161 -0
  205. package/dist/nol/peft-model-runtime-config.d.ts +174 -0
  206. package/dist/nol/peft-model-subject-adapter.d.ts +36 -0
  207. package/dist/nol/peft-validation.d.ts +105 -0
  208. package/dist/nol/persistent-parameter-inventory.d.ts +32 -0
  209. package/dist/nol/runtime.d.ts +100 -0
  210. package/dist/nol/sqlite-store.d.ts +80 -0
  211. package/dist/nol/transformers-adapter.d.ts +119 -0
  212. package/dist/nol/transformers-nnsight.d.ts +87 -0
  213. package/dist/nol/transformers-peft.d.ts +107 -0
  214. package/dist/nol/transformers-research.d.ts +114 -0
  215. package/dist/nol/variant-service.d.ts +143 -0
  216. package/dist/nol/variant-store.d.ts +51 -0
  217. package/dist/nol/vllm-actions.d.ts +774 -0
  218. package/dist/nol/vllm-adapter.d.ts +1473 -0
  219. package/dist/nol/vllm-authority.d.ts +55 -0
  220. package/dist/nol/vllm-conformance.d.ts +662 -0
  221. package/dist/nol/vllm-profile.d.ts +850 -0
  222. package/dist/nol/vllm-protocol.d.ts +1505 -0
  223. package/dist/nol/vllm-runtime-config.d.ts +120 -0
  224. package/dist/nol/vllm-runtime.d.ts +34 -0
  225. package/dist/nol/vllm-startup.d.ts +235 -0
  226. package/dist/omni-setup-worker.js +3433 -1909
  227. package/dist/service-version.d.ts +0 -1
  228. package/dist/tui/async-process.d.ts +27 -0
  229. package/dist/tui/native/worker.js +3 -1
  230. package/dist/tui/telegram-action-session-registry.d.ts +136 -0
  231. package/dist/tui/telegram-cognition-queue.d.ts +154 -0
  232. package/dist/tui/telegram-context-packet-v2.d.ts +99 -0
  233. package/dist/tui/telegram-input-ownership.d.ts +78 -0
  234. package/dist/tui/telegram-turn-contract-v2.d.ts +62 -0
  235. package/dist/update-worker-runtime.js +4216 -2603
  236. package/docs/DISCOVERY.json +389 -0
  237. package/docs/DISCOVERY.md +4 -0
  238. package/npm-shrinkwrap.json +28 -12
  239. package/package.json +3 -2
@@ -0,0 +1,701 @@
1
+ #!/usr/bin/env python3
2
+ """Offline NOL parameter editor. No model construction, tokenization or CUDA.
3
+
4
+ Imports are stdlib-only until the explicit edit request has passed file/hash,
5
+ format and bounded ZIP/header admission. Numerical tensor work is CPU-only.
6
+ The separate --publish action is stdlib-only and uses atomic no-replace rename.
7
+ """
8
+ import ctypes
9
+ import hashlib
10
+ import importlib.metadata
11
+ import io
12
+ import json
13
+ import math
14
+ import os
15
+ from pathlib import Path
16
+ import platform
17
+ import pickle
18
+ from collections import OrderedDict
19
+ import signal
20
+ import stat
21
+ import struct
22
+ import sys
23
+ import time
24
+ import zipfile
25
+
26
+ SCHEMA = "omnius.nol.checkpoint-edit.v1"
27
+ OPS = {"WEIGHT_ADD", "WEIGHT_GAIN", "WEIGHT_REPLACE", "WEIGHT_PROJECT", "LOW_RANK_UPDATE", "WEIGHT_MERGE"}
28
+ SIZES = {"BOOL": 1, "I8": 1, "U8": 1, "I16": 2, "U16": 2, "I32": 4, "U32": 4,
29
+ "I64": 8, "U64": 8, "F16": 2, "BF16": 2, "F32": 4, "F64": 8}
30
+ ALIASES = {"F16": "f16", "BF16": "bf16", "F32": "f32", "F64": "f64"}
31
+
32
+
33
+ def need(ok, message):
34
+ if not ok:
35
+ raise ValueError(message)
36
+
37
+
38
+ def fields(value, required, optional=()):
39
+ need(type(value) is dict and set(required) <= value.keys() and not value.keys() - set(required) - set(optional), "Unknown/missing request fields")
40
+
41
+
42
+ def unique(pairs):
43
+ result = {}
44
+ for key, value in pairs:
45
+ need(key not in result, "Duplicate JSON property")
46
+ result[key] = value
47
+ return result
48
+
49
+
50
+ def parse(raw):
51
+ return json.loads(raw, object_pairs_hook=unique, parse_constant=lambda _: (_ for _ in ()).throw(ValueError("Nonfinite JSON")),
52
+ parse_int=lambda text: -0.0 if text == "-0" else int(text))
53
+
54
+
55
+ def encoded(value):
56
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
57
+
58
+
59
+ def same(a, b):
60
+ if type(a) in (int, float) and type(b) in (int, float):
61
+ return a == b and (a != 0 or math.copysign(1, a) == math.copysign(1, b))
62
+ if type(a) is not type(b):
63
+ return False
64
+ if type(a) is dict:
65
+ return a.keys() == b.keys() and all(same(a[key], b[key]) for key in a)
66
+ if type(a) is list:
67
+ return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
68
+ return a == b
69
+
70
+
71
+ def digest(raw):
72
+ return hashlib.sha256(raw).hexdigest()
73
+
74
+
75
+ def integer(value, minimum=0):
76
+ need(type(value) is int and minimum <= value <= 9007199254740991, "Invalid bounded integer")
77
+ return value
78
+
79
+
80
+ def finite(value):
81
+ need(type(value) in (int, float) and math.isfinite(value), "Nonfinite coefficient")
82
+ return value
83
+
84
+
85
+ def shape_size(shape, allow_zero=False):
86
+ need(type(shape) is list and len(shape) <= 8, "Unsupported tensor rank")
87
+ result = 1
88
+ for dimension in shape:
89
+ result *= integer(dimension, 0 if allow_zero else 1)
90
+ integer(result)
91
+ return result
92
+
93
+
94
+ def safe(root, name, exists=True):
95
+ need(type(name) is str and name and "\\" not in name and "\0" not in name and not name.startswith("/"), "Unsafe relative path")
96
+ need(all(part not in ("", ".", "..") for part in name.split("/")), "Unsafe relative path component")
97
+ current = root
98
+ for part in name.split("/"):
99
+ current /= part
100
+ need(not current.is_symlink(), "Symlink input/output refused")
101
+ if exists:
102
+ need(current.is_file(), "Missing regular input file")
103
+ return current
104
+
105
+
106
+ class Budget:
107
+ def __init__(self, limits):
108
+ self.limits = limits
109
+ for value in limits.values():
110
+ integer(value, 1)
111
+ self.deadline = time.monotonic() + limits["maxDurationMs"] / 1000
112
+ self.started = time.monotonic()
113
+ self.working = self.arithmetic = self.input = self.artifacts = 0
114
+ self.reserve(131072) # two bounded 64 KiB comparison/copy/hash blocks
115
+
116
+ def check(self):
117
+ need(time.monotonic() <= self.deadline, "Checkpoint edit time budget exceeded")
118
+
119
+ def reserve(self, count):
120
+ self.check()
121
+ self.working += integer(count)
122
+ need(self.working <= self.limits["maxWorkingBytes"], "Tensor/workspace byte budget exceeded")
123
+
124
+ def work(self, count):
125
+ self.check()
126
+ self.arithmetic += integer(count)
127
+ need(self.arithmetic <= self.limits["maxArithmeticUnits"], "Arithmetic budget exceeded")
128
+
129
+
130
+ def hash_file(path, budget=None):
131
+ before = path.lstat()
132
+ need(stat.S_ISREG(before.st_mode) and not path.is_symlink(), "Hash source is not a nonsymlink regular file")
133
+ value, size = hashlib.sha256(), 0
134
+ with path.open("rb") as stream:
135
+ opened = os.fstat(stream.fileno())
136
+ need((opened.st_dev, opened.st_ino) == (before.st_dev, before.st_ino), "Input identity changed")
137
+ while True:
138
+ if budget:
139
+ budget.check()
140
+ block = stream.read(65536)
141
+ if not block:
142
+ break
143
+ size += len(block)
144
+ value.update(block)
145
+ after = os.fstat(stream.fileno())
146
+ need((before.st_size, before.st_mtime_ns, before.st_ctime_ns) == (size, after.st_mtime_ns, after.st_ctime_ns), "Input changed while hashing")
147
+ return {"sha256": value.hexdigest(), "sizeBytes": size}
148
+
149
+
150
+ def verify_identity(raw, expected, sha):
151
+ need(type(raw) is str and digest(raw.encode()) == sha and same(parse(raw), expected), "Canonical identity body/hash mismatch")
152
+
153
+
154
+ def header(path, budget):
155
+ with path.open("rb") as stream:
156
+ raw = stream.read(8)
157
+ need(len(raw) == 8, "Truncated safetensors header")
158
+ size = struct.unpack("<Q", raw)[0]
159
+ need(1 <= size <= min(16 * 1024 * 1024, budget.limits["maxProtocolBytes"] * 16), "Safetensors header budget exceeded")
160
+ budget.reserve(size * 8)
161
+ raw = stream.read(size)
162
+ need(len(raw) == size, "Truncated safetensors header")
163
+ meta = parse(raw)
164
+ need(type(meta) is dict, "Invalid safetensors inventory")
165
+ metadata = meta.get("__metadata__", {})
166
+ need(type(metadata) is dict and all(type(k) is str and type(v) is str for k, v in metadata.items()), "Invalid safetensors metadata")
167
+ intervals = []
168
+ for name, info in meta.items():
169
+ if name == "__metadata__":
170
+ continue
171
+ fields(info, ("dtype", "shape", "data_offsets"))
172
+ need(info["dtype"] in SIZES and type(name) is str and name, "Unsupported safetensors dtype/name")
173
+ need(type(info["data_offsets"]) is list and len(info["data_offsets"]) == 2, "Invalid tensor offsets")
174
+ first, last = [integer(value) for value in info["data_offsets"]]
175
+ need(last >= first and last - first == shape_size(info["shape"], True) * SIZES[info["dtype"]], "Tensor shape/offset byte mismatch")
176
+ intervals.append((first, last))
177
+ cursor = 0
178
+ for first, last in sorted(intervals):
179
+ need(first == cursor, "Safetensors overlapping tensors or data gaps")
180
+ cursor = last
181
+ need(8 + size + cursor == path.stat().st_size, "Safetensors offsets exceed/trail file")
182
+ return {"header": meta, "dataStart": 8 + size, "dataBytes": cursor}
183
+
184
+
185
+ def zip_admission(path, budget):
186
+ need(zipfile.is_zipfile(path), "Legacy/non-ZIP PyTorch checkpoints are unsupported")
187
+ with zipfile.ZipFile(path) as archive:
188
+ entries = archive.infolist()
189
+ need(len(entries) <= 100000 and len({entry.filename for entry in entries}) == len(entries), "Duplicate/oversized PyTorch ZIP inventory")
190
+ total = 0
191
+ for entry in entries:
192
+ need(entry.compress_type == zipfile.ZIP_STORED and not entry.flag_bits & 1, "Compressed/encrypted PyTorch ZIP rejected before allocation")
193
+ need(not entry.filename.startswith("/") and all(part not in ("", ".", "..") for part in entry.filename.split("/")), "Unsafe PyTorch ZIP entry")
194
+ total += integer(entry.file_size)
195
+ need(total <= budget.limits["maxWorkingBytes"], "PyTorch declared storage exceeds working byte budget")
196
+ if entry.filename.endswith("/data.pkl"):
197
+ need(entry.file_size <= budget.limits["maxProtocolBytes"], "PyTorch pickle metadata exceeds protocol cap")
198
+ need(any(entry.filename.endswith("/data.pkl") for entry in entries), "Missing PyTorch tensor-state metadata")
199
+ pickle_entries = [entry for entry in entries if entry.filename.endswith("/data.pkl")]
200
+ need(len(pickle_entries) == 1, "Ambiguous PyTorch pickle root")
201
+ pickle_entry = pickle_entries[0]
202
+ prefix = pickle_entry.filename[:-len("data.pkl")]
203
+ storage_files = {entry.filename[len(prefix + "data/"):]: entry.file_size for entry in entries if entry.filename.startswith(prefix + "data/")}
204
+ budget.reserve(pickle_entry.file_size * 128)
205
+ declared = {}
206
+
207
+ class TensorMetadataReader(pickle.Unpickler):
208
+ # No Torch import, builtin eval, model class or arbitrary reducer.
209
+ # This tiny symbolic allowlist validates actual storage extents
210
+ # BEFORE weights_only/mmap can honor attacker-declared sizes.
211
+ def find_class(self, module, name):
212
+ widths = {"ByteStorage": 1, "CharStorage": 1, "BoolStorage": 1, "ShortStorage": 2,
213
+ "HalfStorage": 2, "BFloat16Storage": 2, "IntStorage": 4, "FloatStorage": 4,
214
+ "LongStorage": 8, "DoubleStorage": 8}
215
+ if module == "torch" and name in widths:
216
+ return ("storage_type", widths[name])
217
+ if module == "collections" and name == "OrderedDict":
218
+ return OrderedDict
219
+ if module == "torch._utils" and name in ("_rebuild_tensor_v2", "_rebuild_tensor"):
220
+ return self.tensor
221
+ raise ValueError("Unsupported PyTorch metadata reducer before load")
222
+
223
+ def persistent_load(self, value):
224
+ need(type(value) is tuple and len(value) == 5 and value[0] == "storage" and
225
+ type(value[1]) is tuple and len(value[1]) == 2 and value[1][0] == "storage_type" and
226
+ type(value[2]) is str and type(value[3]) is str, "Unsupported PyTorch storage descriptor")
227
+ width, key, count = value[1][1], value[2], integer(value[4])
228
+ need(key in storage_files and count * width == storage_files[key] and count * width <= budget.limits["maxWorkingBytes"],
229
+ "PyTorch declared storage extent differs from bounded ZIP payload")
230
+ descriptor = ("storage", key, count, width)
231
+ need(key not in declared or declared[key] == descriptor, "Conflicting PyTorch storage descriptors")
232
+ declared[key] = descriptor
233
+ return descriptor
234
+
235
+ @staticmethod
236
+ def tensor(storage, offset, size, stride, requires_grad=False, hooks=None, metadata=None):
237
+ need(type(storage) is tuple and len(storage) == 4 and storage[0] == "storage" and
238
+ type(size) is tuple and type(stride) is tuple and len(size) == len(stride) <= 8,
239
+ "Invalid symbolic tensor geometry")
240
+ offset = integer(offset)
241
+ count = shape_size(list(size), True)
242
+ extent = offset + sum(max(0, integer(dimension) - 1) * integer(step) for dimension, step in zip(size, stride))
243
+ need((count == 0 and offset <= storage[2]) or (count > 0 and extent < storage[2]), "PyTorch tensor view exceeds admitted storage")
244
+ need(count * storage[3] <= budget.limits["maxWorkingBytes"] and metadata in (None, {}) and not hooks,
245
+ "Tensor metadata/logical payload exceeds admission")
246
+ return {"__nol_tensor_descriptor__": True, "elements": count}
247
+
248
+ metadata = TensorMetadataReader(io.BytesIO(archive.read(pickle_entry))).load()
249
+ need(isinstance(metadata, dict) and metadata and all(type(key) is str and type(value) is dict and value.get("__nol_tensor_descriptor__") is True for key, value in metadata.items()),
250
+ "PyTorch requires flat tensor-only metadata before load")
251
+ need(set(declared) == set(storage_files), "PyTorch unreferenced/missing storage payload")
252
+ # ZIP storage maps plus a conservative decode/copy allowance, admitted
253
+ # before torch.load; arbitrary optimizer/nested objects are never accepted.
254
+ budget.reserve(total * 3)
255
+
256
+
257
+ class Checkpoint:
258
+ def __init__(self, value, root, identity, budget):
259
+ self.model, self.root, self.budget = value, Path(root).resolve(strict=True), budget
260
+ need(value["schema"] == "omnius.nol.model.v1" and value["format"] in ("hf", "safetensors", "pytorch") and value["quantization"]["method"] == "none", "Unsupported checkpoint model")
261
+ verify_identity(identity["modelJson"], {key: v for key, v in value.items() if key not in ("id", "modelDigest")}, value["modelDigest"])
262
+ verify_identity(identity["tensorSitesJson"], value["tensorSites"], value["architectureMapDigest"])
263
+ self.files = {file["path"]: file for file in value["files"]}
264
+ need(len(self.files) == len(value["files"]), "Duplicate checkpoint path")
265
+ actual = []
266
+ for path in self.root.rglob("*"):
267
+ budget.check()
268
+ need(not path.is_symlink(), "Checkpoint symlink refused")
269
+ if path.is_file():
270
+ actual.append(path.relative_to(self.root).as_posix())
271
+ need(set(actual) == self.files.keys(), "Complete checkpoint file inventory mismatch")
272
+ self.before = {}
273
+ for name, file in self.files.items():
274
+ budget.input += integer(file["artifact"]["sizeBytes"])
275
+ need(budget.input <= budget.limits["maxInputBytes"], "Aggregate checkpoint input bytes exceeded")
276
+ fact = hash_file(safe(self.root, name), budget)
277
+ need(fact == {"sha256": file["artifact"]["sha256"], "sizeBytes": file["artifact"]["sizeBytes"]}, "Complete checkpoint file hash mismatch")
278
+ self.before[name] = fact
279
+ self.weights = [name for name, file in self.files.items() if file["role"] == "weights"]
280
+ need(self.weights, "Missing weight shards")
281
+ kinds = {"safe" if name.endswith(".safetensors") else "torch" if name.endswith((".bin", ".pt", ".pth")) else "unknown" for name in self.weights}
282
+ need(len(kinds) == 1 and "unknown" not in kinds, "Unsupported/mixed native weight formats")
283
+ self.kind = kinds.pop()
284
+ need(value["format"] == "hf" or (value["format"] == "safetensors" and self.kind == "safe") or
285
+ (value["format"] == "pytorch" and self.kind == "torch"), "Declared checkpoint format differs from actual shard codec")
286
+ self.shards, self.locations, self.states = {}, {}, {}
287
+ for name in self.weights:
288
+ if self.kind == "safe":
289
+ self.shards[name] = header(safe(self.root, name), budget)
290
+ for parameter in self.shards[name]["header"]:
291
+ if parameter == "__metadata__":
292
+ continue
293
+ need(parameter not in self.locations, "Duplicate tensor across weight shards")
294
+ self.locations[parameter] = name
295
+ else:
296
+ zip_admission(safe(self.root, name), budget)
297
+ self.sites = {site["id"]: site for site in value["tensorSites"] if site["kind"] == "parameter"}
298
+ need(len(self.sites) == len([site for site in value["tensorSites"] if site["kind"] == "parameter"]), "Duplicate parameter site ID")
299
+
300
+ def load_torch(self, torch):
301
+ self.torch = torch
302
+ if self.kind == "torch":
303
+ for name in self.weights:
304
+ state = torch.load(str(safe(self.root, name)), weights_only=True, map_location="cpu", mmap=True)
305
+ need(isinstance(state, dict) and state and all(type(key) is str and type(value) is torch.Tensor for key, value in state.items()), "PyTorch requires a flat tensor-only state_dict")
306
+ payload = 0
307
+ for parameter, tensor in state.items():
308
+ need(tensor.device.type == "cpu" and tensor.layout == torch.strided and tensor.is_contiguous() and not tensor.is_quantized, "Unsupported PyTorch tensor storage/layout")
309
+ need(parameter not in self.locations, "Duplicate tensor across PyTorch shards")
310
+ self.locations[parameter] = name
311
+ payload += tensor.numel() * tensor.element_size()
312
+ self.budget.reserve(payload)
313
+ self.states[name] = state
314
+ for name, file in self.files.items():
315
+ if name.endswith(".index.json"):
316
+ need(file["artifact"]["sizeBytes"] <= self.budget.limits["maxProtocolBytes"], "Shard index exceeds metadata cap")
317
+ data = parse(safe(self.root, name).read_bytes())
318
+ need(type(data) is dict and type(data.get("weight_map")) is dict, "Invalid checkpoint shard index")
319
+ need(data["weight_map"] == self.locations, "Shard index misses/misbinds actual tensors")
320
+ for site in self.sites.values():
321
+ need(site["name"] in self.locations, "Parameter site absent from actual checkpoint")
322
+ shape, dtype = self.geometry(site["name"])
323
+ need(shape == site["shape"] and dtype == site["dtype"], "Actual parameter shape/dtype differs from frozen site")
324
+
325
+ def geometry(self, name):
326
+ shard = self.locations[name]
327
+ if self.kind == "safe":
328
+ info = self.shards[shard]["header"][name]
329
+ return info["shape"], ALIASES.get(info["dtype"], info["dtype"].lower())
330
+ tensor = self.states[shard][name]
331
+ return list(tensor.shape), {self.torch.float16: "f16", self.torch.bfloat16: "bf16", self.torch.float32: "f32", self.torch.float64: "f64"}.get(tensor.dtype, str(tensor.dtype))
332
+
333
+ def tensor(self, site):
334
+ name, torch = site["name"], self.torch
335
+ shape, dtype = self.geometry(name)
336
+ need(shape == site["shape"] and dtype == site["dtype"] and dtype in DTYPES, "Target tensor geometry/dtype mismatch")
337
+ n = shape_size(shape)
338
+ self.budget.reserve(n * 32)
339
+ shard = self.locations[name]
340
+ if self.kind == "safe":
341
+ info, data_start = self.shards[shard]["header"][name], self.shards[shard]["dataStart"]
342
+ first, last = info["data_offsets"]
343
+ with safe(self.root, shard).open("rb") as stream:
344
+ stream.seek(data_start + first)
345
+ raw = stream.read(last - first)
346
+ need(len(raw) == last - first, "Truncated source tensor")
347
+ return torch.frombuffer(bytearray(raw), dtype=DTYPES[dtype]).reshape(shape).clone()
348
+ tensor = self.states[shard][name]
349
+ for other_name, other in self.states[shard].items():
350
+ if other_name != name:
351
+ need(other.untyped_storage().data_ptr() != tensor.untyped_storage().data_ptr(), "Aliased PyTorch parameter target requires explicit tied-weight semantics")
352
+ return tensor.detach().clone()
353
+
354
+
355
+ def tensor_bytes(tensor):
356
+ return tensor.detach().contiguous().view(torch.uint8).numpy().tobytes()
357
+
358
+
359
+ class Editor:
360
+ def __init__(self, payload, budget, base, sources):
361
+ self.payload, self.budget, self.base, self.sources = payload, budget, base, sources
362
+ self.artifacts = set()
363
+
364
+ def operand(self, ref):
365
+ fields(ref, ("artifact", "shape", "dtype"))
366
+ spec, shape, dtype = ref["artifact"], ref["shape"], ref["dtype"]
367
+ need(dtype in DTYPES and len(shape) >= 1, "Unsupported operand dtype/shape")
368
+ n = shape_size(shape)
369
+ need(spec["uri"] == "omnius-artifact://sha256/" + spec["sha256"], "Artifact URI identity mismatch")
370
+ if spec["sha256"] not in self.artifacts:
371
+ self.budget.artifacts += integer(spec["sizeBytes"])
372
+ need(self.budget.artifacts <= self.budget.limits["maxArtifactBytes"], "Aggregate operand artifact cap exceeded")
373
+ self.artifacts.add(spec["sha256"])
374
+ self.budget.reserve(n * 64 + spec["sizeBytes"] * 4)
375
+ root = Path(self.payload["artifactRoot"]).resolve(strict=True)
376
+ path = safe(root, spec["sha256"][:2] + "/" + spec["sha256"])
377
+ need(hash_file(path, self.budget) == {"sha256": spec["sha256"], "sizeBytes": spec["sizeBytes"]}, "Operand full hash mismatch")
378
+ raw = path.read_bytes()
379
+ if spec["mediaType"] == "application/json":
380
+ value = parse(raw)
381
+ fields(value, ("schema", "shape", "dtype", "data"))
382
+ need(value["schema"] == "omnius.nol.tensor.v1" and value["shape"] == shape and value["dtype"] == dtype and type(value["data"]) is list and len(value["data"]) == n, "Operand JSON descriptor mismatch")
383
+ values = [finite(value) for value in value["data"]]
384
+ tensor = torch.tensor(values, dtype=DTYPES[dtype]).reshape(shape)
385
+ elif spec["mediaType"] == "application/octet-stream":
386
+ need(len(raw) == n * torch.empty((), dtype=DTYPES[dtype]).element_size(), "Operand binary length mismatch")
387
+ tensor = torch.frombuffer(bytearray(raw), dtype=DTYPES[dtype]).reshape(shape).clone()
388
+ else:
389
+ raise ValueError("Unsupported operand codec")
390
+ need(bool(torch.isfinite(tensor).all()), "Operand overflows actual declared dtype")
391
+ return tensor
392
+
393
+ def apply(self, op, current, site):
394
+ n, shape, kind = current.numel(), list(current.shape), op["operation"]
395
+ need(op["tokenScope"] == {"kind": "all"} and kind in OPS, "Unsupported static operation/scope")
396
+ self.budget.reserve(n * 160) # explicit float64 products/copies/casts/masks/serialization; not full process RSS
397
+ old_raw = tensor_bytes(current)
398
+ ideal, replacement = None, None
399
+ if kind == "WEIGHT_ADD":
400
+ delta = op["delta"]
401
+ value = finite(delta["value"]) if delta["kind"] == "scalar" else self.operand(delta["tensor"]).to(torch.float64)
402
+ need(isinstance(value, (int, float)) or list(value.shape) == shape, "Addition operand geometry mismatch")
403
+ self.budget.work(n)
404
+ if isinstance(value, (int, float)) and value == 0:
405
+ return current, 0, 0.0
406
+ ideal = current.to(torch.float64) + value
407
+ if not isinstance(value, (int, float)):
408
+ ideal = torch.where(value == 0, current.to(torch.float64), ideal)
409
+ elif kind == "WEIGHT_GAIN":
410
+ gain = op["gain"]
411
+ if gain["kind"] == "scalar":
412
+ value = finite(gain["factor"])
413
+ if value == 1:
414
+ return current, 0, 0.0
415
+ else:
416
+ axis = integer(gain["axis"])
417
+ need(axis < len(shape), "Gain axis outside tensor")
418
+ value = self.operand(gain["factors"]).to(torch.float64)
419
+ need(list(value.shape) == [shape[axis]], "Axis gain factor shape mismatch")
420
+ broadcast = [1] * len(shape)
421
+ broadcast[axis] = shape[axis]
422
+ value = value.reshape(broadcast)
423
+ self.budget.work(n)
424
+ ideal = current.to(torch.float64) * value
425
+ elif kind == "WEIGHT_REPLACE":
426
+ replacement = self.operand(op["replacement"])
427
+ need(list(replacement.shape) == shape and replacement.dtype == current.dtype, "Replacement shape/dtype mismatch")
428
+ self.budget.work(n)
429
+ elif kind == "WEIGHT_PROJECT":
430
+ need(len(shape) == 2 and op["side"] in ("left", "right") and op["normalization"] == "orthonormal", "Invalid projection semantics")
431
+ basis = self.operand(op["basis"]).to(torch.float64)
432
+ if basis.ndim == 1:
433
+ basis = basis.unsqueeze(0)
434
+ dimension = shape[0 if op["side"] == "left" else 1]
435
+ need(basis.ndim == 2 and basis.shape[1] == dimension and 0 < basis.shape[0] <= dimension, "Canonical projection row-basis shape mismatch")
436
+ rank = basis.shape[0]
437
+ self.budget.reserve(rank * rank * 32)
438
+ self.budget.work((2 * dimension + 1) * rank * rank)
439
+ need(float((basis @ basis.T - torch.eye(rank, dtype=torch.float64)).abs().max()) <= self.payload["orthogonalityTolerance"], "Projection basis is not orthonormal")
440
+ strength = finite(op["strength"])
441
+ if strength == 0:
442
+ return current, 0, 0.0
443
+ self.budget.work(5 * n * rank)
444
+ value = current.to(torch.float64)
445
+ projected = basis.T @ (basis @ value) if op["side"] == "left" else (value @ basis.T) @ basis
446
+ ideal = value - strength * projected
447
+ elif kind == "LOW_RANK_UPDATE":
448
+ need(len(shape) == 2 and op["scaling"] == "alpha_over_rank", "Invalid low-rank semantics")
449
+ rank = integer(op["rank"], 1)
450
+ a, b = self.operand(op["a"]).to(torch.float64), self.operand(op["b"]).to(torch.float64)
451
+ need(list(a.shape) == [rank, shape[1]] and list(b.shape) == [shape[0], rank], "Low-rank A/B geometry mismatch")
452
+ factor = finite(finite(op["scale"]) * (finite(op["alpha"]) / rank))
453
+ self.budget.work(2)
454
+ if factor == 0:
455
+ return current, 0, 0.0
456
+ self.budget.work(2 * n * rank + 2 * n)
457
+ delta = b @ a
458
+ ideal = torch.where(delta == 0, current.to(torch.float64), current.to(torch.float64) + factor * delta)
459
+ elif kind == "WEIGHT_MERGE":
460
+ terms, seen = [], set()
461
+ for source in op["sources"]:
462
+ key = (source["modelDigest"], source["siteId"])
463
+ need(key not in seen and source["modelDigest"] in self.payload["recipe"]["parentModelDigests"], "Duplicate/undeclared merge parent")
464
+ seen.add(key)
465
+ parent = self.sources.get(source["modelDigest"])
466
+ source_site = parent.sites.get(source["siteId"]) if parent else None
467
+ need(source_site and source_site["shape"] == site["shape"] and source_site["dtype"] == site["dtype"], "Merge source exact site geometry/dtype mismatch")
468
+ weight = finite(source["weight"])
469
+ value = parent.tensor(source_site)
470
+ need(bool(torch.isfinite(value).all()), "Merge source contains nonfinite values")
471
+ if weight != 0:
472
+ terms.append((value, weight))
473
+ self.budget.work(2 * n * len(terms))
474
+ if len(terms) == 1 and terms[0][1] == 1:
475
+ replacement = terms[0][0]
476
+ else:
477
+ ideal = torch.zeros(shape, dtype=torch.float64)
478
+ for value, weight in terms:
479
+ ideal = ideal + weight * value.to(torch.float64)
480
+ if replacement is not None:
481
+ result, rounding = replacement.clone(), 0.0
482
+ else:
483
+ need(ideal is not None and bool(torch.isfinite(ideal).all()), "Nonfinite float64 edit result")
484
+ result = ideal.to(current.dtype)
485
+ need(bool(torch.isfinite(result).all()), "Edited value overflows checkpoint storage dtype")
486
+ rounding = float((ideal - result.to(torch.float64)).abs().max())
487
+ new_raw = tensor_bytes(result)
488
+ width = current.element_size()
489
+ changed = sum(old_raw[i:i + width] != new_raw[i:i + width] for i in range(0, len(old_raw), width))
490
+ return result, changed, rounding
491
+
492
+
493
+ def copy_file(source, destination, budget):
494
+ destination.parent.mkdir(parents=True, exist_ok=True)
495
+ with source.open("rb") as incoming, destination.open("xb") as outgoing:
496
+ while True:
497
+ budget.check()
498
+ block = incoming.read(65536)
499
+ if not block:
500
+ break
501
+ outgoing.write(block)
502
+ outgoing.flush()
503
+ os.fsync(outgoing.fileno())
504
+
505
+
506
+ def save_safetensors(base, name, destination, edits, payload, budget, remaining_output_bytes):
507
+ shard = base.shards[name]
508
+ metadata = dict(shard["header"])
509
+ metadata["__metadata__"] = {**metadata.get("__metadata__", {}), "omnius.nol.parent_model_digest": base.model["modelDigest"],
510
+ "omnius.nol.recipe_digest": payload["recipe"]["recipeDigest"], "omnius.nol.edit_schema": SCHEMA}
511
+ raw_header = encoded(metadata)
512
+ raw_header += b" " * ((-len(raw_header)) % 8)
513
+ expected_size = 8 + len(raw_header) + shard["dataBytes"]
514
+ need(expected_size <= remaining_output_bytes, "Changed shard exceeds remaining output cap")
515
+ destination.parent.mkdir(parents=True, exist_ok=True)
516
+ with safe(base.root, name).open("rb") as incoming, destination.open("xb") as outgoing:
517
+ outgoing.write(struct.pack("<Q", len(raw_header)))
518
+ outgoing.write(raw_header)
519
+ incoming.seek(shard["dataStart"])
520
+ while True:
521
+ budget.check()
522
+ block = incoming.read(65536)
523
+ if not block:
524
+ break
525
+ outgoing.write(block)
526
+ for parameter, value in edits.items():
527
+ first, last = metadata[parameter]["data_offsets"]
528
+ raw = tensor_bytes(value)
529
+ need(len(raw) == last - first, "Edited tensor changes native byte geometry")
530
+ outgoing.seek(8 + len(raw_header) + first)
531
+ outgoing.write(raw)
532
+ outgoing.flush()
533
+ os.fsync(outgoing.fileno())
534
+ # Verify exact copied payload of every untouched tensor independently.
535
+ with safe(base.root, name).open("rb") as incoming, destination.open("rb") as outgoing:
536
+ for parameter, info in metadata.items():
537
+ if parameter == "__metadata__" or parameter in edits:
538
+ continue
539
+ first, last = info["data_offsets"]
540
+ incoming.seek(shard["dataStart"] + first)
541
+ outgoing.seek(8 + len(raw_header) + first)
542
+ remaining = last - first
543
+ while remaining:
544
+ budget.check()
545
+ count = min(65536, remaining)
546
+ need(incoming.read(count) == outgoing.read(count), "Untouched safetensors payload changed")
547
+ remaining -= count
548
+
549
+
550
+ def edit(payload):
551
+ fields(payload, ("schema", "exportId", "editorSha256", "checkpointRoot", "model", "identity", "recipe", "recipeIdentityJson", "sources", "artifactRoot", "stageDirectory", "limits", "orthogonalityTolerance"))
552
+ need(payload["schema"] == "omnius.nol.checkpoint-edit-request.v1", "Unsupported edit request schema")
553
+ need(sys.byteorder == "little", "Native little-endian tensor editor required")
554
+ need(hash_file(Path(__file__))["sha256"] == payload["editorSha256"], "Editor source identity mismatch")
555
+ limits = payload["limits"]
556
+ fields(limits, ("maxInputBytes", "maxArtifactBytes", "maxOutputBytes", "maxWorkingBytes", "maxArithmeticUnits", "maxOperations", "maxDurationMs", "maxProtocolBytes"))
557
+ budget = Budget(limits)
558
+ need(len(encoded(payload)) <= limits["maxProtocolBytes"], "Request exceeds protocol cap")
559
+ need(0 < finite(payload["orthogonalityTolerance"]) <= 0.01, "Invalid orthonormality tolerance")
560
+ recipe, model = payload["recipe"], payload["model"]
561
+ receipt_name = ".omnius-nol-edit." + payload["exportId"] + ".json"
562
+ need(type(payload["exportId"]) is str and len(payload["exportId"]) == 36 and all(c in "0123456789abcdef-" for c in payload["exportId"]) and
563
+ receipt_name not in {file["path"] for file in model["files"]}, "Invalid/colliding export receipt identity")
564
+ verify_identity(payload["recipeIdentityJson"], {key: value for key, value in recipe.items() if key != "recipeDigest"}, recipe["recipeDigest"])
565
+ need(recipe["schema"] == "omnius.nol.recipe.v1" and recipe["modelDigest"] == model["modelDigest"] and recipe["architectureMapDigest"] == model["architectureMapDigest"] and not recipe["calibrations"], "Recipe model/calibration mismatch")
566
+ operations = recipe["operations"]
567
+ need(0 < len(operations) <= limits["maxOperations"] and len({op["id"] for op in operations}) == len(operations), "Operation budget/ID mismatch")
568
+ need(all(op["operation"] in OPS and op["tokenScope"] == {"kind": "all"} for op in operations), "Activation/token-masked edits cannot be serialized as weights")
569
+ stage = Path(payload["stageDirectory"])
570
+ need(stage.is_dir() and not stage.is_symlink() and not any(stage.iterdir()), "Editor requires a new empty private stage")
571
+ stage = stage.resolve(strict=True)
572
+ roots = [Path(payload["checkpointRoot"]).resolve(strict=True), Path(payload["artifactRoot"]).resolve(strict=True)] + [Path(source["root"]).resolve(strict=True) for source in payload["sources"]]
573
+ need(all(not stage.is_relative_to(root) and not root.is_relative_to(stage) for root in roots), "Stage overlaps an immutable source")
574
+ base = Checkpoint(model, payload["checkpointRoot"], payload["identity"], budget)
575
+ sources = {model["modelDigest"]: base}
576
+ for source in payload["sources"]:
577
+ value = source["model"]
578
+ need(value["modelDigest"] not in sources and value["modelDigest"] in recipe["parentModelDigests"], "Duplicate/undeclared source model")
579
+ sources[value["modelDigest"]] = Checkpoint(value, source["root"], source["identity"], budget)
580
+ # All explicit hashes, safe header/ZIP storage admission precede this import.
581
+ global torch, DTYPES
582
+ import torch
583
+ torch.set_num_threads(1)
584
+ torch.use_deterministic_algorithms(True)
585
+ DTYPES = {"f16": torch.float16, "bf16": torch.bfloat16, "f32": torch.float32, "f64": torch.float64}
586
+ for source in sources.values():
587
+ source.load_torch(torch)
588
+ editor, changed, logs = Editor(payload, budget, base, sources), {}, []
589
+ for op in operations:
590
+ budget.check()
591
+ site = base.sites.get(op["siteId"])
592
+ need(site is not None and site["dtype"] in DTYPES, "Unknown/nonfloating parameter target")
593
+ name = site["name"]
594
+ current = changed.get(name)
595
+ if current is None:
596
+ current = base.tensor(site)
597
+ need(bool(torch.isfinite(current).all()), "Parent target contains nonfinite values")
598
+ before = digest(tensor_bytes(current))
599
+ result, count, rounding = editor.apply(op, current, site)
600
+ changed[name] = result
601
+ logs.append({"operationId": op["id"], "operation": op["operation"], "siteId": op["siteId"], "name": name,
602
+ "beforeTensorSha256": before, "afterTensorSha256": digest(tensor_bytes(result)),
603
+ "changedElements": count, "maxAbsRoundingError": rounding})
604
+ # Do not rewrite a shard when every admitted edit was byte-neutral.
605
+ effective = {}
606
+ for name, tensor in changed.items():
607
+ site = next(site for site in base.sites.values() if site["name"] == name)
608
+ if tensor_bytes(tensor) != tensor_bytes(base.tensor(site)):
609
+ effective.setdefault(base.locations[name], {})[name] = tensor
610
+ files, output_bytes = [], 0
611
+ for name in base.files:
612
+ destination = safe(stage, name, False)
613
+ if name not in effective:
614
+ need(output_bytes + base.before[name]["sizeBytes"] <= limits["maxOutputBytes"], "Output byte budget exceeded before copy")
615
+ copy_file(safe(base.root, name), destination, budget)
616
+ representation = "copied_exact_file"
617
+ elif base.kind == "safe":
618
+ save_safetensors(base, name, destination, effective[name], payload, budget, limits["maxOutputBytes"] - output_bytes)
619
+ representation = "safetensors_preserved_untouched_tensor_bytes"
620
+ else:
621
+ state = dict(base.states[name])
622
+ state.update(effective[name])
623
+ need(base.before[name]["sizeBytes"] * 2 + output_bytes + 65536 <= limits["maxOutputBytes"], "Conservative PyTorch serialization storage budget exceeded")
624
+ destination.parent.mkdir(parents=True, exist_ok=True)
625
+ torch.save(state, str(destination))
626
+ zip_admission(destination, budget)
627
+ check = torch.load(str(destination), weights_only=True, map_location="cpu", mmap=True)
628
+ need(check.keys() == state.keys(), "PyTorch roundtrip tensor inventory mismatch")
629
+ for parameter, value in state.items():
630
+ need(check[parameter].dtype == value.dtype and list(check[parameter].shape) == list(value.shape) and tensor_bytes(check[parameter]) == tensor_bytes(value), "PyTorch roundtrip changed tensor bytes")
631
+ representation = "pytorch_reencoded_verified_tensor_bytes"
632
+ after = hash_file(destination, budget)
633
+ output_bytes += after["sizeBytes"]
634
+ need(output_bytes <= limits["maxOutputBytes"], "Aggregate output byte budget exceeded")
635
+ files.append({"path": name, "before": base.before[name], "after": after,
636
+ "changed": after != base.before[name], "representation": representation})
637
+ for source in sources.values():
638
+ for name, before in source.before.items():
639
+ need(hash_file(safe(source.root, name), budget) == before, "Parent/source changed during edit")
640
+ receipt = {"schema": SCHEMA, "exportId": payload["exportId"], "parentModelDigest": model["modelDigest"], "recipeDigest": recipe["recipeDigest"],
641
+ "sourceModelDigests": sorted(key for key in sources if key != model["modelDigest"]), "editorSha256": payload["editorSha256"],
642
+ "runtime": {"python": platform.python_version(), "torch": str(torch.__version__), "safetensors": importlib.metadata.version("safetensors")},
643
+ "numericalPolicy": "cpu_float64_operation_then_cast_original_dtype_each_operation; canonical_row_basis; scale_times_alpha_over_rank; explicit_linear_merge; native_blas_reassociation_possible",
644
+ "inferencePerformed": False, "cudaUsed": False, "files": files, "operations": logs,
645
+ "usage": {"inputBytes": budget.input, "artifactBytes": budget.artifacts, "outputBytes": output_bytes,
646
+ "reservedWorkingBytes": budget.working, "arithmeticUnits": budget.arithmetic, "durationMs": int((time.monotonic() - budget.started) * 1000)}}
647
+ # Fixed-point includes receipt bytes in the declared storage total.
648
+ for _ in range(8):
649
+ raw = encoded(receipt)
650
+ total = output_bytes + len(raw)
651
+ if receipt["usage"]["outputBytes"] == total:
652
+ break
653
+ receipt["usage"]["outputBytes"] = total
654
+ raw = encoded(receipt)
655
+ need(len(raw) <= limits["maxProtocolBytes"] and output_bytes + len(raw) <= limits["maxOutputBytes"], "Receipt exceeds protocol/storage byte budget")
656
+ with (stage / receipt_name).open("xb") as stream:
657
+ stream.write(raw)
658
+ stream.flush()
659
+ os.fsync(stream.fileno())
660
+ budget.check()
661
+ return {"schema": "omnius.nol.checkpoint-edit-ready.v1", "exportId": payload["exportId"]}
662
+
663
+
664
+ def publish(payload):
665
+ fields(payload, ("stageDirectory", "outputDirectory", "exportId", "receiptSha256", "receiptPath"))
666
+ need(sys.platform.startswith("linux"), "Atomic no-replace directory publish unsupported on this platform")
667
+ stage, target = Path(payload["stageDirectory"]), Path(payload["outputDirectory"])
668
+ need(stage.is_dir() and not stage.is_symlink() and stage.parent.resolve(strict=True) == target.parent.resolve(strict=True), "Publish stage/parent mismatch")
669
+ need(payload["receiptPath"] == ".omnius-nol-edit." + payload["exportId"] + ".json", "Publish receipt path binding mismatch")
670
+ receipt = safe(stage, payload["receiptPath"])
671
+ need(hash_file(receipt)["sha256"] == payload["receiptSha256"] and parse(receipt.read_bytes())["exportId"] == payload["exportId"], "Publish receipt custody mismatch")
672
+ libc = ctypes.CDLL(None, use_errno=True)
673
+ rename = getattr(libc, "renameat2", None)
674
+ need(rename is not None, "Atomic no-replace rename unavailable; no unsafe fallback")
675
+ rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]
676
+ rename.restype = ctypes.c_int
677
+ if rename(-100, os.fsencode(stage), -100, os.fsencode(target), 1) != 0:
678
+ code = ctypes.get_errno()
679
+ raise OSError(code, os.strerror(code))
680
+ directory = os.open(target.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
681
+ try:
682
+ os.fsync(directory)
683
+ finally:
684
+ os.close(directory)
685
+ return {"published": True, "exportId": payload["exportId"]}
686
+
687
+
688
+ if __name__ == "__main__":
689
+ try:
690
+ signal.signal(signal.SIGTERM, lambda *_: (_ for _ in ()).throw(InterruptedError("Checkpoint edit cancelled")))
691
+ raw = sys.stdin.buffer.read(16 * 1024 * 1024 + 1)
692
+ need(len(raw) <= 16 * 1024 * 1024, "Absolute request frame cap exceeded")
693
+ payload = parse(raw)
694
+ result = publish(payload) if sys.argv[1:] == ["--publish"] else edit(payload) if not sys.argv[1:] else (_ for _ in ()).throw(ValueError("Unknown editor command"))
695
+ sys.stdout.buffer.write(encoded(result))
696
+ sys.stdout.flush()
697
+ except BaseException as error:
698
+ # Diagnostics stay on the bounded private subprocess channel.
699
+ sys.stderr.write((type(error).__name__ + ": " + str(error))[-4000:] +
700
+ "; torchImported=" + str("torch" in sys.modules).lower() + "\n")
701
+ sys.exit(1)