Files
reverse-engineering-anything/src/cli/modelCommands.ts
T
Eliran Zachandmorluto d28ee2b639 feat(model): inspect PyTorch checkpoints and pickle opcodes statically (#16257)
* feat(model): inspect PyTorch checkpoints and pickle opcodes statically

inspect_model_artifact now reads PyTorch ZIP checkpoints, legacy torch.save
files and protocol 2-5 pickle streams without unpickling. A bounded static
walker (protocols 0-5) reports each stream's protocol and opcode counts and
every GLOBAL, STACK_GLOBAL, INST, OBJ, REDUCE, NEWOBJ, BUILD and EXT reference
with its offset, marking callables outside PyTorch's tensor-rebuild allow-list
as observations of what loading would import or call.

ZIP checkpoints report their archive prefix, version, byteorder and
serialization records and each referenced data/<key> storage; legacy files
locate every storage in the file. State-dict tensors get dtype, shape, byte
span and parameter counts, and names when one unshared key path reaches them.
Malformed opcodes, truncation and memo misuse are target failures with their
offset; max_pickle_opcodes and max_pickle_memo_entries bound the walk.

Refs #3652

* fix(model): address pickle walker and PyTorch interpretation review findings

- push APPENDS/ADDITEMS values one at a time instead of spreading them
- replace an equal key on SETITEM(S), as unpickling does
- refuse a FRAME longer than the remaining stream as truncated
- decode BINUNICODE with surrogatepass and validate raw-unicode-escape text
- unwrap _rebuild_parameter chains iteratively
- resolve tensor key paths once per node and charge names before building them
- inventory every storage persistent ID and require its storage bytes
- bound archive records in the MCP summary with record_count and records_omitted

* fix(model): bound pickle integers, ZIP names and keep partial facts

- validate but do not convert protocol 0 integers beyond an exact long; refuse inexact memo keys
- decode STRING with Python's escape rules, keeping unknown escapes
- fill the format peek before classifying the file
- read PyTorch ZIPs under the session member count with a bounded metadata read, charging names as they are listed
- retain completed pickle facts before full-file hashing
- mark tensor coverage partial when a rebuild call cannot be read

* fix(model): keep Python string identity and bound dict-key work

- record the exact code point sequence of strings holding Python surrogates, so distinct keys stay distinct
- build each key's identity once per node, so a reused memoized key is not rebuilt per write
- decode raw-unicode-escape text in bounded batches instead of one fragment per backslash run
- keep the first equal key when SETITEM replaces its value

* fix(model): scan raw-unicode-escape text in one pass

Measure each backslash run once instead of retrying a regular expression from every backslash, and build output without a per-escape list.

* fix(model): keep GGUF partial tensor data offsets non-null

* fix(model): bound pickle tensor counts and validate FLOAT operands

* fix(model): bound shared tensor work and read expanded views

* fix(model): format the pickle changes and drop the unused ModelFormat type

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-12-04 17:10:56 +00:00

49 lines
1.7 KiB
TypeScript

import type { Logger } from "pino";
import { createModelArtifactService } from "../composition/model.js";
import { INSPECT_MODEL_ARTIFACT_CONTRACT } from "../contracts/model/modelToolContracts.js";
import { registerContractCommand } from "./contractCommand.js";
import { deliverWithService } from "./contractCommandRunners.js";
import type { CliInstance } from "./types.js";
/** One-shot summaries export the same complete observations used by MCP retained pages. */
export const registerModelCommands = (
cli: CliInstance,
logger: Logger,
): void => {
const deliver = deliverWithService(
createModelArtifactService,
"model-artifact",
);
registerContractCommand(
cli,
logger,
INSPECT_MODEL_ARTIFACT_CONTRACT,
{
description:
"Inspect GGUF, safetensors, PyTorch checkpoint or pickle declarations without loading weights or unpickling",
positionals: ["path"],
callerPaths: ["path"],
evidenceDelivery: true,
viewDelivery: {
invalidJson: "view must be a JSON model page selection",
kind: "model-artifact",
},
fields: {
path: { description: "Local model file, detected by content" },
hash: {
description:
"header reads declarations only; full additionally streams all bytes for SHA-256",
},
view: {
description:
"JSON model page selection; requires --detail summary and --evidence_output",
},
},
},
// The CLI delivers the summary itself, so the service returns complete
// Evidence; the contract's own default would retain a summary instead.
(input, context) => deliver({ ...input, detail: "complete" }, context),
);
};