Skip to content

The server

modelmap.serve

modelmap serve: the map from a web server on this machine.

The server listens on 127.0.0.1 only. Every request must name the server by the address it listens on (Host), may come only from the server's own page (Origin), and must carry the run's token: in the address for the page, in the X-Modelmap-Token header for the API. A page on another site can therefore neither read the map nor make the server act, even though the server is reachable from the browser it runs in.

Routes:

  • GET /?t=TOKEN: the page, drawn by :func:render_html with served.
  • GET /api/state: when the scan ran and what it found, in totals.
  • POST /api/rescan: scan again and redraw the page.
  • POST /api/plan {"view"}: what removing that record would do, as :func:modelmap.removal.plan works it out, with a digest of the plan.
  • POST /api/remove {"view", "digest"}: scan again, plan again, and remove the record only if the new plan's digest is the one the person was shown. Then scan again and redraw.

Removal is what modelmap rm does, through the same functions; one runs at a time. The page is drawn once per scan and kept, so loading it does not scan.

App(scan, scanner, *, use_disk=False, token=None, env=None, home='~', read_only=False)

What every request shares: the scan, its page, the token and a lock.

Parameters:

Name Type Description Default
scan Scan

The first scan, already made.

required
scanner Callable[[], Scan]

Makes a new scan; called by a rescan.

required
use_disk bool

Size tiles by bytes allocated on disk.

False
token str | None

The run's token; a random one by default.

None
env Mapping[str, str] | None

Environment whose PATH finds hf, ollama and the Trash command; the process's own by default.

None
home str

The home folder of the machine scanned.

'~'
read_only bool

Offer no removal: for an inventory, or on request.

False
Source code in src/modelmap/serve.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def __init__(
    self,
    scan: Scan,
    scanner: Callable[[], Scan],
    *,
    use_disk: bool = False,
    token: str | None = None,
    env: Mapping[str, str] | None = None,
    home: str = "~",
    read_only: bool = False,
) -> None:
    self.scanner = scanner
    self.use_disk = use_disk
    self.token = token or secrets.token_urlsafe(32)
    self.env = os.environ if env is None else env
    self.home = home
    self.read_only = read_only
    #: Held while the scan changes; a second request is told to wait.
    self.lock = threading.Lock()
    self._set(scan)

find(view)

The record a view id names in the current scan, if exactly one.

Source code in src/modelmap/serve.py
124
125
126
127
def find(self, view: str) -> ModelRecord | None:
    """The record a view id names in the current scan, if exactly one."""
    found = [r for r in self.scan.records if record_view(r) == view]
    return found[0] if len(found) == 1 else None

plan(record)

How modelmap rm would remove the record, looking at the disk.

Source code in src/modelmap/serve.py
129
130
131
132
133
134
135
def plan(self, record: ModelRecord) -> Plan:
    """How ``modelmap rm`` would remove the record, looking at the disk."""
    # `ollama rm` acts on the running Ollama's store only.
    live = [
        r.resolved for r in self.scan.roots if r.provider == "ollama" and r.source != "layout"
    ]
    return plan(record, live, env=self.env, home=self.home)

remove(view, digest, log)

Remove a record if it would go as shown. The caller holds :attr:lock.

Returns:

Type Description
tuple[int, dict]

HTTP status and the reply.

Source code in src/modelmap/serve.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def remove(self, view: str, digest: str, log: Callable[[str], None]) -> tuple[int, dict]:
    """Remove a record if it would go as shown. The caller holds :attr:`lock`.

    :return: HTTP status and the reply.
    """
    self.rescan()
    record = self.find(view)
    if record is None:
        return 409, {"error": "It is no longer in the scan.", "gone": True}
    step = self.plan(record)
    shown = plan_json(step, view)
    if step.action == "refuse":
        return 409, {"error": step.note, "plan": shown}
    if plan_digest(step) != digest:
        return 409, {
            "error": "What would be removed has changed since it was shown. "
            "Check the list again.",
            "plan": shown,
        }
    what = shown["command"] or ", ".join(step.paths)
    log(f"removing {record.provider}:{record.name}: {what}")
    done, problem = execute(step, self.env)
    log(f"removed {record.provider}:{record.name}" if done else f"failed: {problem}")
    self.rescan()  # whatever happened, show the disk as it is now
    if not done:
        return 500, {
            "error": f"Could not remove {record.name}: {problem}",
            "state": self.state(),
        }
    message = f"Removed {record.name}."
    if step.action == "trash":
        message += " " + TRASH_NOTE
    return 200, {"removed": True, "message": message, "state": self.state()}

rescan()

Scan again and redraw. The caller holds :attr:lock.

Source code in src/modelmap/serve.py
105
106
107
def rescan(self) -> None:
    """Scan again and redraw. The caller holds :attr:`lock`."""
    self._set(self.scanner())

state()

The scan in totals, as the API returns it.

Source code in src/modelmap/serve.py
109
110
111
112
113
114
115
116
117
118
119
def state(self) -> dict[str, Any]:
    """The scan in totals, as the API returns it."""
    scan = self.scan
    return {
        "scanned_at": round(self.scanned_at, 3),
        "elapsed_s": scan.elapsed_s,
        "records": len(scan.records),
        "size_bytes": scan.size_bytes,
        "disk_bytes": scan.disk_bytes,
        "warnings": len(scan.warnings),
    }

Handler

Bases: BaseHTTPRequestHandler

Server

Bases: ThreadingHTTPServer

The HTTP server; :func:make_server builds it.

url property

The page's address, token included.

make_server(app, port=0, log=None)

Bind the server to 127.0.0.1; serve_forever starts it.

Parameters:

Name Type Description Default
app App

The shared state.

required
port int

Port to listen on; 0 takes a free one.

0
log Callable[[str], None] | None

Receives one line per request; silent by default.

None

Raises:

Type Description
OSError

When the port cannot be bound.

Source code in src/modelmap/serve.py
338
339
340
341
342
343
344
345
346
347
348
349
def make_server(app: App, port: int = 0, log: Callable[[str], None] | None = None) -> Server:
    """Bind the server to 127.0.0.1; ``serve_forever`` starts it.

    :param app: The shared state.
    :param port: Port to listen on; 0 takes a free one.
    :param log: Receives one line per request; silent by default.
    :raises OSError: When the port cannot be bound.
    """
    server = Server((HOST, port), Handler)
    server.app = app
    server.log = log or (lambda line: None)
    return server

plan_json(step, view)

A plan as the page shows it in the dialog.

Source code in src/modelmap/serve.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def plan_json(step: Plan, view: str) -> dict[str, Any]:
    """A plan as the page shows it in the dialog."""
    record = step.record
    return {
        "view": view,
        "name": record.name,
        "store": DISPLAY_NAMES.get(record.provider, record.provider),
        "size": format_size(record.size_bytes),
        "path": record.path,
        "action": step.action,
        "note": step.note,
        "command": shlex.join(step.argv) if step.action == "tool" else "",
        "paths": list(step.paths),
        "variants": list(step.variants),
        "undo": step.action == "trash",
        "digest": plan_digest(step),
    }