@mgcrea/mcp-apple-maps 1.37.1 → 1.41.0

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.
@@ -1,10 +1,9 @@
1
- import { AppleAutomationError, AppleAutomationError as AppleMapsError, BaseConfigSchema, CORE_DATA_EPOCH_OFFSET, IndexUnavailableError, SchemaDriftError, SchemaDriftError as SchemaDriftError$1, buildBaseDiagnostics, columnsOf, compact, confirmArg, describeStore, detectEpoch, escapeLike, fail, fingerprintSchema, inspectFile, interferenceNote, limitArg, ok, openAxChannel, openReadOnly, parseBool, parseConfig, parseIntOpt, promptArg, readPackageIdentity, registerSurfaceResources, registerWorkflowPrompt, resolveLimit, trimmed, watchInterference, withLazyTools, wrap, wrapResult } from "@mgcrea/mcp-apple-core";
1
+ import { AppleAutomationError, AppleAutomationError as AppleMapsError, BaseConfigSchema, CORE_DATA_EPOCH_OFFSET, IndexUnavailableError, SchemaDriftError, SchemaDriftError as SchemaDriftError$1, StoreLaneError, buildBaseDiagnostics, columnsOf, compact, confirmArg, describeStore, detectEpoch, escapeLike, fail, fingerprintSchema, inspectFile, limitArg, ok, openReadOnly, openStoreLane, parseBool, parseConfig, parseIntOpt, promptArg, readPackageIdentity, registerSurfaceResources, registerWorkflowPrompt, resolveLimit, trimmed, withLazyTools, wrap, wrapResult } from "@mgcrea/mcp-apple-core";
2
2
  import { readdirSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
- import { execFile, execFileSync } from "node:child_process";
6
- import { randomUUID } from "node:crypto";
7
5
  import { DatabaseSync } from "node:sqlite";
6
+ import { execFile } from "node:child_process";
8
7
  import { promisify } from "node:util";
9
8
  import { z } from "zod";
10
9
  import { McpServer } from "@modelcontextprotocol/server";
@@ -16,8 +15,8 @@ const pkg = readPackageIdentity(new URL("../package.json", import.meta.url), {
16
15
  const BUILD_INFO = {
17
16
  name: pkg.name,
18
17
  version: pkg.version,
19
- gitCommit: "5bbbddc",
20
- gitCommitDate: "2026-11-07T14:03:33+01:00"
18
+ gitCommit: "3d3130b",
19
+ gitCommitDate: "2026-11-17T12:53:14+01:00"
21
20
  };
22
21
  //#endregion
23
22
  //#region src/client/dates.ts
@@ -107,6 +106,14 @@ var MapsStoreUnavailableError = class extends AppleAutomationError {
107
106
  super(`${reason} Maps has no second lane — it ships no scripting dictionary, so there is no Apple Events fallback and nothing at all can be read without the grant.`, {});
108
107
  }
109
108
  };
109
+ /**
110
+ * A write could not be prepared: no place record to copy, or one Maps
111
+ * resolved too far from the coordinate given. Raised before the store lane is
112
+ * asked to save anything, so nothing was written.
113
+ */
114
+ var MapsWriteError = class extends AppleAutomationError {
115
+ name = "MapsWriteError";
116
+ };
110
117
  /** A ref no longer resolves — the place was removed, or the store was re-synced. */
111
118
  var PlaceNotFoundError = class extends AppleAutomationError {
112
119
  name = "PlaceNotFoundError";
@@ -230,302 +237,359 @@ const locateStore = (opts = {}) => {
230
237
  };
231
238
  };
232
239
  //#endregion
233
- //#region src/client/ax.ts
234
- /**
235
- * Maps' place card, driven through Cupertino's native Accessibility driver.
236
- *
237
- * ## Why this exists beside the SQL lane rather than replacing it
238
- *
239
- * `client/write.ts` writes favourites by copying a record Maps minted and
240
- * INSERTing it. That lane is correct and stays: pressing the card's `AddButton`
241
- * does not create a favourite. `docs/desktop.md` measured it — the press lands
242
- * an **unfiled saved place** and `ZFAVORITEITEM` was 26 rows before and 26
243
- * after. The two lanes address different objects.
244
- *
245
- * What this reaches is the set the SQL lane does not offer at all:
246
- *
247
- * * **The Places library** — `add_to_places` / `delete_from_places`.
248
- * * **Guide membership** — `docs/maps.md` lists it as unbuilt: "Adding a place
249
- * to a collection needs one `Z_6PLACES` join row".
250
- *
251
- * ## The safety argument, which is the real reason to prefer it here
252
- *
253
- * The store is mirrored by `NSPersistentCloudKitContainer` and mirroring does
254
- * not wait to be told, so a malformed row is not a local mistake — it reaches
255
- * every device on the account. `write.ts` carries the rule that keeps SQL safe:
256
- * never fabricate a place record, only copy one Maps wrote. **A write made
257
- * through the interface cannot be malformed at all**, because Maps performs it.
258
- * Where both lanes could do a job, this one has the smaller blast radius.
259
- *
260
- * ## The cost, which is the same one the SQL lane pays
261
- *
262
- * Reaching the card means opening `maps://?q=<name>&ll=<lat>,<lon>`, so the
263
- * place is left in **Recents** whether or not anything is kept. That is the
264
- * mechanism rather than an oversight, and every tool built on this says so.
265
- */
266
- const MAPS_BUNDLE = "com.apple.Maps";
267
- /** Identifiers Maps sets on the card. Unlocalised, unlike every name here. */
268
- const CARD = {
269
- add: "AddButton",
270
- more: "MoreButton",
271
- card: "PlaceCardViewController",
272
- addToGuides: "add_to_guides",
273
- deleteFromPlaces: "delete_from_places",
274
- addToPlaces: "add_to_places",
275
- picker: "GuidesPickerView",
276
- guideRow: "UserGuidesPickerRowCell",
277
- done: "CardButtonTypeDone",
278
- close: "CardButtonTypeClose"
279
- };
280
- const defaultOpenUrl$1 = (url) => {
281
- execFileSync("/usr/bin/open", ["-g", url], {
282
- timeout: 1e4,
283
- stdio: "ignore"
284
- });
285
- };
240
+ //#region src/client/lane.ts
241
+ const isRecord = (v) => typeof v === "object" && v !== null;
242
+ const isStringOrNull = (v) => v === null || typeof v === "string";
243
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
244
+ /** Only the keys given: an absent `name` or `near` is left off the wire, not sent as null. */
245
+ const placeParams = (p) => ({
246
+ source: p.source,
247
+ sourceId: p.sourceId,
248
+ query: p.query,
249
+ ...p.name !== void 0 ? { name: p.name } : {},
250
+ ...p.near ? { near: {
251
+ latitude: p.near.latitude,
252
+ longitude: p.near.longitude
253
+ } } : {}
254
+ });
286
255
  /**
287
- * `"Favorites, 3 places"` -> `{ name: "Favorites", places: 3 }`.
288
- *
289
- * The count is a bonus and the name is the point, so a row whose shape is not
290
- * recognised keeps its whole label as the name rather than being dropped. A
291
- * guide that cannot be matched is worse than one with an odd name.
256
+ * Maps' writes, saved by Cupertino.app through Core Data with Maps' own model,
257
+ * so they are recorded in persistent history like a change made in the app.
258
+ *
259
+ * The app does the work and validates every argument; this side only names the
260
+ * method and checks the answer has the shape the tools report. A reply of
261
+ * another shape is a `StoreLaneError` with reason `protocol`, the reason core
262
+ * uses for a reply it cannot read. The same lane as Voice Memos'
263
+ * (`packages/voice-memos/src/client/lane.ts`), on surface `maps`.
292
264
  */
293
- const parseGuideRow = (label) => {
294
- const match = /^(.*),\s*(\d+)\s+places?$/.exec(label);
295
- if (!match?.[1]) return {
296
- name: label,
297
- places: null
298
- };
299
- return {
300
- name: match[1],
301
- places: Number(match[2])
302
- };
303
- };
304
- const DEFAULT_WAITS = {
305
- card: 1e4,
306
- sheet: 4e3
307
- };
308
- var MapsAxLane = class MapsAxLane {
309
- #channel;
310
- #openUrl;
311
- #waits;
312
- constructor(channel, openUrl, waits) {
313
- this.#channel = channel;
314
- this.#openUrl = openUrl;
315
- this.#waits = waits;
316
- }
317
- /** Null when this server is not hosted by Cupertino — see `core/src/ax.ts`. */
318
- static open(env = process.env, openUrl = defaultOpenUrl$1, waits = {}) {
319
- const channel = openAxChannel(MAPS_SURFACE, env);
320
- return channel ? new MapsAxLane(channel, openUrl, {
321
- ...DEFAULT_WAITS,
322
- ...waits
323
- }) : null;
265
+ var MapsLane = class MapsLane {
266
+ #lane;
267
+ constructor(lane) {
268
+ this.#lane = lane;
269
+ }
270
+ /**
271
+ * Null when this server is not hosted by Cupertino: see `core/src/store-lane.ts`.
272
+ *
273
+ * Opening connects nothing. Cupertino spawns the server with the lane env just
274
+ * to list its tools, and that listing must never wait on the app.
275
+ */
276
+ static open(env = process.env) {
277
+ const lane = openStoreLane(MAPS_SURFACE, env);
278
+ return lane ? new MapsLane(lane) : null;
324
279
  }
325
280
  close() {
326
- this.#channel.close();
281
+ this.#lane.close();
327
282
  }
328
- /** Start watching for someone using the Mac during a sequence. */
329
- watch() {
330
- return watchInterference(this.#channel);
283
+ /** A favourite with its own copy of the source's place record. */
284
+ addFavorite(p) {
285
+ return this.#write("maps.addFavorite", placeParams(p));
331
286
  }
332
- #call(tool, args = {}) {
333
- return this.#channel.call({
334
- tool: `apple_desktop_${tool}`,
335
- args
336
- });
287
+ removeFavorite(id) {
288
+ return this.#write("maps.removeFavorite", { id });
337
289
  }
338
- async #tree() {
339
- return (await this.#call("ui_tree", {
340
- bundleId: MAPS_BUNDLE,
341
- detail: "all",
342
- maxDepth: 20,
343
- maxNodes: 4e3,
344
- budgetSeconds: 20
345
- })).elements ?? [];
290
+ /** A saved place in no Guide, with its own copy of the source's place record. */
291
+ savePlace(p) {
292
+ return this.#write("maps.savePlace", placeParams(p));
346
293
  }
347
- /**
348
- * Wait for an element rather than for a duration.
349
- *
350
- * `docs/desktop.md` calls this the trap that cost it the most: a card's chrome
351
- * appears before its content, so no fixed settle time is correct. Cheap here —
352
- * a whole Maps walk is ~0.17 s.
353
- */
354
- async #poll(match, timeoutMs = this.#waits.card) {
355
- const deadline = Date.now() + timeoutMs;
356
- let lastError = null;
357
- for (;;) {
358
- try {
359
- const found = (await this.#tree()).find(match);
360
- if (found) return found;
361
- lastError = null;
362
- } catch (error) {
363
- lastError = error;
364
- }
365
- if (Date.now() >= deadline) {
366
- if (lastError) throw lastError;
367
- return null;
368
- }
369
- await new Promise((resolve) => setTimeout(resolve, 300));
370
- }
294
+ removeSavedPlace(id) {
295
+ return this.#write("maps.removeSavedPlace", { id });
371
296
  }
372
297
  /**
373
- * Open a place and wait for its card.
374
- *
375
- * The combined `q=` and `ll=` form, because a coordinate positions the map and
376
- * a NAME selects a place — `write.ts` records the same thing for the same
377
- * reason.
298
+ * File a saved place in a Guide: one already saved, by `placeId`, or one to
299
+ * save first from a source, which the app saves and files in one save.
378
300
  */
379
- async openCard(place) {
380
- this.#openUrl(`maps://?q=${encodeURIComponent(place.name)}&ll=${place.latitude},${place.longitude}`);
381
- return await this.#poll((e) => e.id === CARD.add) !== null;
301
+ fileInGuide(p) {
302
+ const params = "placeId" in p ? {
303
+ guide: p.guide,
304
+ placeId: p.placeId
305
+ } : {
306
+ guide: p.guide,
307
+ ...placeParams(p)
308
+ };
309
+ return this.#write("maps.fileInGuide", params, { filed: true });
310
+ }
311
+ async status() {
312
+ const r = await this.#lane.call("maps.status", {});
313
+ if (!isRecord(r) || typeof r.compatible !== "boolean" || !isStringOrNull(r.modelVersion) || typeof r.syncMeasured !== "boolean" || !isStringOrNull(r.refusal)) throw this.#unreadable("maps.status");
314
+ return {
315
+ compatible: r.compatible,
316
+ modelVersion: r.modelVersion,
317
+ syncMeasured: r.syncMeasured,
318
+ refusal: r.refusal
319
+ };
382
320
  }
383
321
  /**
384
- * Is this place saved?
385
- *
386
- * Read off `AddButton`'s NAME, which is the state bit. `docs/desktop.md`
387
- * corrected itself on this: `FavoriteButton` reports identical attributes
388
- * either way, and the sibling carries `"Add"` versus `"Added"`.
389
- *
390
- * Localised, and that is a real limit rather than an oversight — there is no
391
- * unlocalised state anywhere on this card.
322
+ * One write, its answer checked. `filed` is required where the method files:
323
+ * the tool reports it, and a missing one must not read as "not filed".
392
324
  */
393
- async isSaved() {
394
- const add = await this.#poll((e) => e.id === CARD.add, this.#waits.sheet);
395
- if (!add?.name) return null;
396
- return add.name !== "Add";
325
+ async #write(method, params, want = {}) {
326
+ const r = await this.#lane.call(method, params);
327
+ if (!isRecord(r) || typeof r.id !== "string" || !UUID.test(r.id) || !Array.isArray(r.changed) || !r.changed.every((c) => typeof c === "string") || typeof r.created !== "boolean" || (want.filed ? typeof r.filed !== "boolean" : r.filed !== void 0 && typeof r.filed !== "boolean") || !isStringOrNull(r.modelVersion) || typeof r.syncMeasured !== "boolean") throw this.#unreadable(method);
328
+ return {
329
+ id: r.id.toLowerCase(),
330
+ changed: r.changed,
331
+ created: r.created,
332
+ ...typeof r.filed === "boolean" ? { filed: r.filed } : {},
333
+ modelVersion: r.modelVersion,
334
+ syncMeasured: r.syncMeasured
335
+ };
336
+ }
337
+ #unreadable(method) {
338
+ return new StoreLaneError(MAPS_SURFACE, "protocol", `the reply to ${method} is not the shape this server reads`);
339
+ }
340
+ };
341
+ //#endregion
342
+ //#region src/client/open-url.ts
343
+ const defaultOpenUrl = async (url) => {
344
+ await promisify(execFile)("/usr/bin/open", ["-g", url], { timeout: 1e4 });
345
+ };
346
+ //#endregion
347
+ //#region src/client/place-source.ts
348
+ const STORAGE_POLL_MS = 250;
349
+ /** A pause that yields the event loop, unlike `Atomics.wait`, which does not. */
350
+ const sleep = (ms) => new Promise((resolve) => {
351
+ setTimeout(resolve, ms);
352
+ });
353
+ /**
354
+ * Progress, on stderr: stdout carries the MCP protocol. Seeding can take tens
355
+ * of seconds, and a long call that says nothing reads as a hang.
356
+ */
357
+ const progress = (message) => {
358
+ process.stderr.write(`[apple-maps-mcp] ${message}\n`);
359
+ };
360
+ /**
361
+ * Same doorway: 1e-5 degrees is ~1.1 m of latitude. Close enough that two rows
362
+ * are one place, far enough apart that neighbouring shops are not merged.
363
+ */
364
+ const NEAR = 1e-5;
365
+ /**
366
+ * How far a resolved place may sit from the caller's coordinate: ~250 m. The
367
+ * caller's number and Apple's routinely differ by a building's width, and a
368
+ * search resolves to the entrance rather than the pin.
369
+ */
370
+ const SEED_TOLERANCE = .0025;
371
+ const near = (aLat, aLon, bLat, bLon) => Math.abs(aLat - bLat) <= SEED_TOLERANCE && Math.abs(aLon - bLon) <= SEED_TOLERANCE;
372
+ const toRad = (deg) => deg * Math.PI / 180;
373
+ /** Metres between two coordinates, for the error message only. */
374
+ const haversineMetres = (aLat, aLon, bLat, bLon) => {
375
+ const dLat = toRad(bLat - aLat);
376
+ const dLon = toRad(bLon - aLon);
377
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(aLat)) * Math.cos(toRad(bLat)) * Math.sin(dLon / 2) ** 2;
378
+ return 12742e3 * Math.asin(Math.sqrt(h));
379
+ };
380
+ /** `HEX(ZIDENTIFIER)` to the dashed lowercase form refs and the lane use. */
381
+ const uuidOfHex = (hex) => {
382
+ if (typeof hex !== "string") return null;
383
+ const h = hex.toLowerCase();
384
+ if (!/^[0-9a-f]{32}$/.test(h)) return null;
385
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
386
+ };
387
+ /**
388
+ * A row's entity, by name.
389
+ *
390
+ * `ZCOLLECTIONITEM` holds both `CollectionPlaceItem` and `CollectionTransitItem`
391
+ * rows, and `ZHISTORYITEM` more than places, so the table alone does not say a
392
+ * row is a saved place or a recent place. A missing entity yields NULL, and a
393
+ * comparison with NULL matches nothing, which is the right answer for a store
394
+ * that has no such entity.
395
+ */
396
+ const entityIs = (alias, name) => `${alias}."Z_ENT" = (SELECT "Z_ENT" FROM "Z_PRIMARYKEY" WHERE "Z_NAME" = '${name}')`;
397
+ /**
398
+ * An identifier the lane can be given: present and the 16 bytes of a uuid. A
399
+ * row without one cannot be named to the lane, which fetches by uuid only.
400
+ */
401
+ const named = (alias) => `LENGTH(${alias}."ZIDENTIFIER") = 16`;
402
+ const TABLE_OF = {
403
+ favorite: "ZFAVORITEITEM",
404
+ "collection-item": "ZCOLLECTIONITEM",
405
+ history: "ZHISTORYITEM"
406
+ };
407
+ const num$1 = (v) => v === null || v === void 0 ? null : Number(v);
408
+ const str$1 = (v) => typeof v === "string" ? v : null;
409
+ var PlaceSourceFinder = class {
410
+ #path;
411
+ #openUrl;
412
+ #seedTimeoutMs;
413
+ constructor(opts) {
414
+ this.#path = opts.storePath;
415
+ this.#openUrl = opts.openUrl ?? defaultOpenUrl;
416
+ this.#seedTimeoutMs = opts.seedTimeoutMs ?? 3e4;
397
417
  }
398
418
  /**
399
- * Open the card's overflow menu and return its items.
400
- *
401
- * POLLED, not settled. The first version asked for the items in the same
402
- * breath as the press and got an empty list every time — the menu takes on the
403
- * order of half a second to appear — and then reported "the overflow menu did
404
- * not open", which is a sentence about Maps rather than about the race. That
405
- * is this repo's own rule broken in the file that quotes it: **poll for the
406
- * control, never wait a fixed time for it.**
419
+ * A short-lived read-only handle per use. Under WAL a connection that has
420
+ * begun reading holds a snapshot and may not see another process's commits,
421
+ * so a handle is never kept between calls.
407
422
  */
408
- async #openMenu() {
409
- const more = await this.#poll((e) => e.id === CARD.more);
410
- if (!more) return [];
411
- await this.#call("press", { handle: more.handle });
412
- const deadline = Date.now() + this.#waits.sheet;
413
- for (;;) {
414
- const items = await this.#call("find_elements", {
415
- bundleId: MAPS_BUNDLE,
416
- role: "AXMenuItem"
417
- });
418
- if (items.elements?.length) return items.elements;
419
- if (Date.now() >= deadline) return [];
420
- await new Promise((resolve) => setTimeout(resolve, 250));
423
+ #read(fn) {
424
+ const db = new DatabaseSync(this.#path, { readOnly: true });
425
+ try {
426
+ return fn(db);
427
+ } finally {
428
+ db.close();
421
429
  }
422
430
  }
423
431
  /**
424
- * Close whatever menu is open, with an Escape aimed at Maps.
425
- *
426
- * Named, because the card was opened with `open -g` and Maps is behind
427
- * whatever the person is using. A bare Escape went to THAT app, and the
428
- * driving notice honestly named it. With the bundle id the desktop server
429
- * brings Maps forward first, or posts nothing.
432
+ * An existing item in `table` for this place, matched as the SQL route
433
+ * matched favourites: a TIGHT coordinate (~1 m) when both numbers came from Maps, or
434
+ * the NAME plus a LOOSE coordinate (~250 m) for a caller's own coordinate.
435
+ * The name is what makes the loose radius safe: it only merges rows the
436
+ * caller already calls the same thing.
430
437
  */
431
- async #dismiss() {
432
- await this.#call("key", {
433
- key: "escape",
434
- modifiers: [],
435
- bundleId: MAPS_BUNDLE
438
+ #existing(table, where, q) {
439
+ return this.#read((db) => {
440
+ const select = `SELECT HEX(t."ZIDENTIFIER") AS hex FROM "${table}" t
441
+ WHERE ${where} AND ${named("t")}
442
+ AND t."ZLATITUDE" BETWEEN ? AND ? AND t."ZLONGITUDE" BETWEEN ? AND ?`;
443
+ const { latitude: lat, longitude: lon } = q;
444
+ const row = db.prepare(`${select} LIMIT 1`).get(lat - NEAR, lat + NEAR, lon - NEAR, lon + NEAR) ?? (q.name === void 0 ? void 0 : db.prepare(`${select} AND t."ZMAPITEMNAME" = ? LIMIT 1`).get(lat - SEED_TOLERANCE, lat + SEED_TOLERANCE, lon - SEED_TOLERANCE, lon + SEED_TOLERANCE, q.name));
445
+ return row ? this.#describeIn(db, table, row.hex) : null;
436
446
  });
437
447
  }
448
+ /** The row with this `HEX(ZIDENTIFIER)` in `table`, described, or null. */
449
+ #describeIn(db, table, hex) {
450
+ const id = uuidOfHex(hex);
451
+ if (!id) return null;
452
+ const row = db.prepare(`SELECT COALESCE(t."ZCUSTOMNAME", t."ZMAPITEMNAME") AS name,
453
+ COALESCE(t."ZLATITUDE", m."ZLATITUDE") AS lat,
454
+ COALESCE(t."ZLONGITUDE", m."ZLONGITUDE") AS lon
455
+ FROM "${table}" t LEFT JOIN "ZMIXINMAPITEM" m ON m."Z_PK" = t."ZMAPITEM"
456
+ WHERE HEX(t."ZIDENTIFIER") = ? LIMIT 1`).get(hex.toUpperCase());
457
+ if (!row) return null;
458
+ return {
459
+ id,
460
+ name: str$1(row.name),
461
+ latitude: num$1(row.lat),
462
+ longitude: num$1(row.lon)
463
+ };
464
+ }
438
465
  /**
439
- * Save the open place into the Places library.
440
- *
441
- * Two presses, not one: `AddButton` raises a **"Name This Location"** sheet
442
- * and nothing is written until its `Save` is pressed. The sheet REPLACES the
443
- * window list — a full walk during it returns the sheet and nothing else — so
444
- * the card's elements are unreachable until it closes, and `Save` carries no
445
- * `AXIdentifier`, which is why it is addressed by name.
466
+ * Read back a favourite or saved place by the identifier the lane answered
467
+ * with, so a tool reports the item as it stands rather than what was asked
468
+ * for. Null when no such row is in the store (yet), or `id` is not a uuid.
446
469
  */
447
- async savePlace() {
448
- const add = await this.#poll((e) => e.id === CARD.add);
449
- if (!add) return false;
450
- await this.#call("press", { handle: add.handle });
451
- const save = await this.#poll((e) => e.role === "AXButton" && e.name === "Save", this.#waits.sheet);
452
- if (!save) return false;
453
- await this.#call("press", { handle: save.handle });
454
- return true;
470
+ describe(kind, id) {
471
+ const hex = id.replaceAll("-", "").toUpperCase();
472
+ if (!/^[0-9A-F]{32}$/.test(hex)) return null;
473
+ return this.#read((db) => this.#describeIn(db, TABLE_OF[kind], hex));
474
+ }
475
+ /** An existing favourite for this place. Idempotence for `add_favorite`. */
476
+ existingFavorite(q) {
477
+ return this.#existing("ZFAVORITEITEM", "1 = 1", q);
478
+ }
479
+ /** An existing saved place (a `CollectionPlaceItem`) for this place. */
480
+ existingSavedPlace(q) {
481
+ return this.#existing("ZCOLLECTIONITEM", entityIs("t", "CollectionPlaceItem"), q);
455
482
  }
456
483
  /**
457
- * Remove the open place from the Places library.
458
- *
459
- * The menu item is `delete_from_places`, and it is only present when the place
460
- * IS saved — the same slot carries `add_to_places` when it is not. So its
461
- * absence is a state reading rather than a failure, and this reports which.
484
+ * A record already in the store within ~1 m, with an owner the lane can be
485
+ * given. Favourites first, then saved places, then recents: the record is the
486
+ * same object whichever row points at it, so the order only makes the answer
487
+ * deterministic.
462
488
  */
463
- async removePlace() {
464
- const items = await this.#openMenu();
465
- if (!items.length) return "no-menu";
466
- const remove = items.find((e) => e.id === CARD.deleteFromPlaces);
467
- if (!remove) {
468
- await this.#dismiss();
469
- return items.some((e) => e.id === CARD.addToPlaces) ? "not-saved" : "no-menu";
470
- }
471
- await this.#call("press", { handle: remove.handle });
472
- return "removed";
489
+ #donorNear(db, lat, lon) {
490
+ return db.prepare(`WITH near AS (
491
+ SELECT m."Z_PK" AS pk, m."ZLATITUDE" AS lat, m."ZLONGITUDE" AS lon
492
+ FROM "ZMIXINMAPITEM" m
493
+ WHERE m."ZMAPITEMSTORAGE" IS NOT NULL
494
+ AND m."ZLATITUDE" BETWEEN ? AND ? AND m."ZLONGITUDE" BETWEEN ? AND ?
495
+ )
496
+ SELECT kind, hex, lat, lon FROM (
497
+ SELECT 0 AS rank, 'favorite' AS kind, HEX(f."ZIDENTIFIER") AS hex, n.lat, n.lon
498
+ FROM near n JOIN "ZFAVORITEITEM" f ON f."ZMAPITEM" = n.pk
499
+ WHERE ${named("f")}
500
+ UNION ALL
501
+ SELECT 1, 'savedPlace', HEX(ci."ZIDENTIFIER"), n.lat, n.lon
502
+ FROM near n JOIN "ZCOLLECTIONITEM" ci ON ci."ZMAPITEM" = n.pk
503
+ WHERE ${named("ci")} AND ${entityIs("ci", "CollectionPlaceItem")}
504
+ UNION ALL
505
+ SELECT 2, 'recent', HEX(h."ZIDENTIFIER"), n.lat, n.lon
506
+ FROM near n JOIN "ZHISTORYITEM" h ON h."ZMAPITEM" = n.pk
507
+ WHERE ${named("h")} AND ${entityIs("h", "HistoryPlaceItem")}
508
+ )
509
+ ORDER BY rank LIMIT 1`).get(lat - NEAR, lat + NEAR, lon - NEAR, lon + NEAR) ?? null;
473
510
  }
474
511
  /**
475
- * Every guide Maps knows about, read off its own picker.
476
- *
477
- * This is the authoritative list, and it is not the same as the store's:
478
- * `docs/desktop.md` found the picker showing a "Favorites" guide that
479
- * `apple_maps_list_collections` does not return. Read here as a side effect of
480
- * being on the way to a write, rather than as a tool of its own — reaching it
481
- * needs a place card, which needs a `maps://` open, which leaves a Recents
482
- * entry. That is too much side effect for something calling itself a read.
483
- *
484
- * Leaves the picker OPEN, because the caller is normally about to press a row.
512
+ * The recent places carrying a record above a watermark, newest first, two
513
+ * at most: two is enough to tell the seed's own from a second place opened
514
+ * in Maps meanwhile.
485
515
  */
486
- async openGuidePicker() {
487
- const items = await this.#openMenu();
488
- const guides = items.find((e) => e.id === CARD.addToGuides);
489
- if (!guides) {
490
- if (items.length) await this.#dismiss();
491
- return null;
492
- }
493
- await this.#call("press", { handle: guides.handle });
494
- if (!await this.#poll((e) => e.id === CARD.picker, this.#waits.sheet)) return null;
495
- return (await this.#tree()).filter((e) => e.id === CARD.guideRow && e.name).map((e) => parseGuideRow(e.name));
496
- }
497
- /** Press one guide row, then Done. Returns false if no row matched. */
498
- async chooseGuide(name) {
499
- const wanted = name.toLowerCase();
500
- const row = (await this.#tree()).find((e) => e.id === CARD.guideRow && parseGuideRow(e.name ?? "").name.toLowerCase() === wanted);
501
- if (!row) return false;
502
- await this.#call("press", { handle: row.handle });
503
- const done = await this.#poll((e) => e.id === CARD.done, this.#waits.sheet);
504
- if (!done) return false;
505
- await this.#call("press", { handle: done.handle });
506
- return true;
516
+ #seededDonors(db, sinceHistoryPk) {
517
+ return db.prepare(`SELECT 'recent' AS kind, HEX(h."ZIDENTIFIER") AS hex,
518
+ m."ZLATITUDE" AS lat, m."ZLONGITUDE" AS lon
519
+ FROM "ZHISTORYITEM" h
520
+ JOIN "ZMIXINMAPITEM" m ON m."Z_PK" = h."ZMAPITEM"
521
+ WHERE h."Z_PK" > ? AND m."ZMAPITEMSTORAGE" IS NOT NULL
522
+ AND ${named("h")} AND ${entityIs("h", "HistoryPlaceItem")}
523
+ ORDER BY h."Z_PK" DESC LIMIT 2`).all(sinceHistoryPk);
524
+ }
525
+ #maxHistory(db) {
526
+ const row = db.prepare(`SELECT MAX(Z_PK) AS m FROM ZHISTORYITEM`).get();
527
+ return Number(row?.m ?? 0);
528
+ }
529
+ #toSource(row, seeded) {
530
+ const id = uuidOfHex(row.hex);
531
+ if (!id) throw new MapsWriteError("A place record's owner has no usable identifier.");
532
+ return {
533
+ kind: row.kind,
534
+ id,
535
+ latitude: Number(row.lat),
536
+ longitude: Number(row.lon),
537
+ seeded
538
+ };
507
539
  }
508
540
  /**
509
- * Re-open the card and read the state bit, which is the only way to verify.
541
+ * A place record for `query`: one already in the store near the coordinate,
542
+ * else one Maps mints on being asked. Refuses a resolution more than ~250 m
543
+ * from the coordinate given, and a seed that produces nothing in time.
510
544
  *
511
- * **A write closes the card.** Saving through the naming sheet dismisses the
512
- * whole place card and returns Maps to its main view, so reading `AddButton`
513
- * straight after a press finds nothing and reports "the card does not say it
514
- * is saved" — which is a sentence about the write having failed, when what
515
- * actually happened is that the thing being read went away.
516
- *
517
- * So verification re-opens the place first. That costs another `maps://`,
518
- * which is free in the sense that matters: the Recents entry this leaves was
519
- * already left by opening the card in the first place.
545
+ * Async because the seed can take thirty seconds, and a blocking wait would
546
+ * leave this single-threaded stdio server unable to answer anything.
520
547
  */
521
- async verifySaved(place) {
522
- if (!await this.openCard(place)) return null;
523
- return this.isSaved();
548
+ async find(q) {
549
+ const hasCoords = q.latitude !== void 0 && q.longitude !== void 0;
550
+ const lat = q.latitude ?? 0;
551
+ const lon = q.longitude ?? 0;
552
+ progress(`finding a place record for ${JSON.stringify(q.query)}: reading the store`);
553
+ const { donor, watermark } = this.#read((db) => ({
554
+ donor: hasCoords ? this.#donorNear(db, lat, lon) : null,
555
+ watermark: this.#maxHistory(db)
556
+ }));
557
+ if (donor) return this.#toSource(donor, false);
558
+ const url = `maps://?q=${encodeURIComponent(q.query)}`;
559
+ progress(`asking Maps to resolve ${JSON.stringify(q.query)}…`);
560
+ await this.#openUrl(url);
561
+ progress(`opened, waiting up to ${Math.round(this.#seedTimeoutMs / 1e3)}s for a record`);
562
+ const deadline = Date.now() + this.#seedTimeoutMs;
563
+ let landed = [];
564
+ let polls = 0;
565
+ while (Date.now() < deadline && landed.length === 0) {
566
+ landed = this.#read((db) => this.#seededDonors(db, watermark));
567
+ if (landed.length === 0) await sleep(STORAGE_POLL_MS);
568
+ polls += 1;
569
+ if (polls % 8 === 0) progress(`still waiting (${polls * (STORAGE_POLL_MS / 1e3)}s)…`);
570
+ }
571
+ if (landed.length > 1) throw new MapsWriteError(`While Maps resolved ${JSON.stringify(q.query)}, another place was opened in Maps too, so which record is this one's cannot be told. Nothing was saved — try again.`, {
572
+ query: q.query,
573
+ reason: "invalid"
574
+ });
575
+ const seeded = landed[0] ?? null;
576
+ if (!seeded) throw new MapsWriteError(`Maps did not produce a place record for "${q.query}" within ${Math.round(this.#seedTimeoutMs / 1e3)}s. Maps must be RUNNING for this to work — it is the only thing that can create a place record. It may also have resolved the query to a search rather than a place, since searches get no record. Try a more specific name, or pass latitude and longitude.`, { query: q.query });
577
+ if (hasCoords && !near(Number(seeded.lat), Number(seeded.lon), lat, lon)) throw new MapsWriteError(`Maps resolved ${JSON.stringify(q.query)} to a place about ${Math.round(haversineMetres(Number(seeded.lat), Number(seeded.lon), lat, lon))}m from the coordinate given, so it is probably not the place meant. Nothing was saved — try a more specific name.`, { query: q.query });
578
+ progress(`got a place record after ${polls} polls`);
579
+ return this.#toSource(seeded, true);
524
580
  }
525
- /** Abandon the picker without filing anything. */
526
- async cancelGuidePicker() {
527
- const close = await this.#poll((e) => e.id === CARD.close, this.#waits.sheet);
528
- if (close) await this.#call("press", { handle: close.handle });
581
+ /**
582
+ * The `ZIDENTIFIER` of the row a read tool's ref names, or null when the row
583
+ * is not there or has no identifier — a row-id-only ref the lane, which
584
+ * fetches by uuid, cannot be given.
585
+ */
586
+ identifierOf(kind, key) {
587
+ const table = TABLE_OF[kind];
588
+ const [where, param] = "uuid" in key ? [`HEX("ZIDENTIFIER") = ?`, key.uuid.replaceAll("-", "").toUpperCase()] : [`"Z_PK" = ?`, key.rowId];
589
+ return this.#read((db) => {
590
+ const row = db.prepare(`SELECT HEX("ZIDENTIFIER") AS hex FROM "${table}" WHERE ${where} LIMIT 1`).get(param);
591
+ return uuidOfHex(row?.hex);
592
+ });
529
593
  }
530
594
  };
531
595
  //#endregion
@@ -1281,396 +1345,6 @@ const openStore = (opts) => {
1281
1345
  });
1282
1346
  };
1283
1347
  //#endregion
1284
- //#region src/client/write.ts
1285
- /**
1286
- * Writing to Maps' store.
1287
- *
1288
- * ## Why this is SQL and not the app's own API
1289
- *
1290
- * Maps ships no scripting dictionary and registers no App Intents on macOS, so
1291
- * there is no lane where the app performs the write on our behalf. Every other
1292
- * surface in this repo writes through an Apple Event; this one cannot, and the
1293
- * alternatives were measured rather than assumed — see `docs/maps.md`.
1294
- *
1295
- * ## The one thing that cannot be synthesised, and how it is obtained anyway
1296
- *
1297
- * A place is only real to Maps if it has a `ZMAPITEMSTORAGE` — a GEO protobuf of
1298
- * one to four kilobytes that this repo has never decoded and cannot generate.
1299
- *
1300
- * It does not have to. **Opening a place makes Maps write one.**
1301
- * `maps://?q=<name>&ll=<lat>,<lon>` goes through LaunchServices — not Apple
1302
- * Events, not Accessibility — and Maps resolves the place and records it in
1303
- * Recents with a full record attached. That record is then copied into the new
1304
- * favourite. The blob is always minted by Maps, which is the only thing that can
1305
- * mint one correctly.
1306
- *
1307
- * MEASURED consequences of that design, all of them in `docs/maps.md`:
1308
- *
1309
- * * The insert needs THREE tables — the favourite, its map item, and the two
1310
- * `Z_PRIMARYKEY` counters. Not the eight the app touches.
1311
- * * No persistent history and no `NSCK*` metadata is written. Core Data
1312
- * reconciles unregistered objects on the app's next save and mirrors them to
1313
- * iCloud by itself; a favourite written this way reached another device.
1314
- * * It works with Maps RUNNING, and survives a subsequent save by the app.
1315
- * There is no need to quit anything.
1316
- *
1317
- * ## The cost the caller must be told about
1318
- *
1319
- * Seeding leaves the place in the user's **Recents**, whether or not the
1320
- * favourite is kept. That is unavoidable — it is the mechanism — so every tool
1321
- * built on this says so in its description rather than springing it on somebody.
1322
- *
1323
- * ## Why writes are dangerous here in a way the other surfaces are not
1324
- *
1325
- * The store is mirrored by `NSPersistentCloudKitContainer`, and mirroring does
1326
- * not wait to be told. A malformed row is not a local mistake: it reaches every
1327
- * device on the account as soon as Maps next runs. There is no such thing as a
1328
- * local-only insert here — that was believed for a while and measured false.
1329
- * Hence: never fabricate a place record, only ever copy one Maps wrote.
1330
- */
1331
- const STORAGE_POLL_MS = 250;
1332
- /** A pause that yields the event loop, unlike `Atomics.wait`, which does not. */
1333
- const sleep = (ms) => new Promise((resolve) => {
1334
- setTimeout(resolve, ms);
1335
- });
1336
- /**
1337
- * Progress, on stderr.
1338
- *
1339
- * Adding a favourite can take tens of seconds — Maps has to resolve a place over
1340
- * the network before there is anything to copy — and the first version said
1341
- * NOTHING for the whole of it. That is indistinguishable from a hang, and was
1342
- * reported as one three times while three different theories were tried. A long
1343
- * operation that reports nothing cannot be diagnosed, only guessed at.
1344
- *
1345
- * stderr because this is an MCP stdio server: stdout carries the protocol, and
1346
- * the server already writes its banner here.
1347
- */
1348
- const progress = (message) => {
1349
- process.stderr.write(`[apple-maps-mcp] ${message}\n`);
1350
- };
1351
- var MapsWriteError = class extends AppleAutomationError {
1352
- name = "MapsWriteError";
1353
- };
1354
- const defaultOpenUrl = async (url) => {
1355
- await promisify(execFile)("/usr/bin/open", ["-g", url], { timeout: 1e4 });
1356
- };
1357
- const uuidBytes = () => Uint8Array.from(Buffer.from(randomUUID().replaceAll("-", ""), "hex"));
1358
- const uuidOf = (bytes) => {
1359
- const h = Buffer.from(bytes).toString("hex");
1360
- return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
1361
- };
1362
- /**
1363
- * Coordinates are floats and never compare exactly across sources, so identity
1364
- * is "within about a metre" rather than equality. 1e-5 degrees is ~1.1 m of
1365
- * latitude — close enough that two rows are the same doorway, far enough apart
1366
- * that neighbouring shops are not merged.
1367
- */
1368
- const NEAR = 1e-5;
1369
- /** Same doorway, within about a metre. */
1370
- const near = (aLat, aLon, bLat, bLon) => Math.abs(aLat - bLat) <= SEED_TOLERANCE && Math.abs(aLon - bLon) <= SEED_TOLERANCE;
1371
- /**
1372
- * How far a seeded place may sit from the coordinate the caller gave.
1373
- *
1374
- * Far looser than `NEAR`: the caller's coordinate and Apple's for the same place
1375
- * routinely differ by a building's width, and a search resolves to the entrance
1376
- * rather than the pin. ~250 m accepts that and still rejects a different town.
1377
- */
1378
- const SEED_TOLERANCE = .0025;
1379
- const toRad = (deg) => deg * Math.PI / 180;
1380
- /** Metres between two coordinates, for the error message only. */
1381
- const haversineMetres = (aLat, aLon, bLat, bLon) => {
1382
- const dLat = toRad(bLat - aLat);
1383
- const dLon = toRad(bLon - aLon);
1384
- const h = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(aLat)) * Math.cos(toRad(bLat)) * Math.sin(dLon / 2) ** 2;
1385
- return 12742e3 * Math.asin(Math.sqrt(h));
1386
- };
1387
- var MapsWriter = class {
1388
- #path;
1389
- #openUrl;
1390
- #seedTimeoutMs;
1391
- constructor(opts) {
1392
- this.#path = opts.storePath;
1393
- this.#openUrl = opts.openUrl ?? defaultOpenUrl;
1394
- this.#seedTimeoutMs = opts.seedTimeoutMs ?? 3e4;
1395
- }
1396
- /**
1397
- * A read-write handle.
1398
- *
1399
- * `busy_timeout` is not optional: Maps and `mapssyncd` hold this store open,
1400
- * and without it a write during ordinary use is refused outright rather than
1401
- * waiting for the lock the way any other SQLite client would.
1402
- */
1403
- #open() {
1404
- const db = new DatabaseSync(this.#path);
1405
- db.exec("PRAGMA busy_timeout = 5000");
1406
- return db;
1407
- }
1408
- #entity(db, name) {
1409
- const row = db.prepare(`SELECT Z_ENT AS e FROM Z_PRIMARYKEY WHERE Z_NAME = ?`).get(name);
1410
- if (!row) throw new MapsWriteError(`This store has no "${name}" entity, so it cannot be written.`);
1411
- return Number(row.e);
1412
- }
1413
- /**
1414
- * The next primary key: one past whichever is HIGHER, the counter or the
1415
- * highest row actually present.
1416
- *
1417
- * `Z_PRIMARYKEY.Z_MAX` is the counter Core Data maintains, and trusting it
1418
- * alone is what a first version did. It is not always current — Maps can be
1419
- * mid-write, a crash can leave it behind, and a foreign writer that forgot to
1420
- * bump it (a mistake this very file guards against making) leaves it stale
1421
- * forever. Taking `MAX(Z_PK)` as well costs one indexed lookup and makes a
1422
- * collision impossible rather than unlikely.
1423
- *
1424
- * Found by a test whose stand-in for Maps inserted a row without bumping the
1425
- * counter. The stand-in was unfaithful; the bug it exposed was not.
1426
- */
1427
- #nextPk(db, name, table) {
1428
- const counter = db.prepare(`SELECT Z_MAX AS m FROM Z_PRIMARYKEY WHERE Z_NAME = ?`).get(name);
1429
- const highest = db.prepare(`SELECT MAX(Z_PK) AS m FROM "${table}"`).get();
1430
- return Math.max(Number(counter?.m ?? 0), Number(highest?.m ?? 0)) + 1;
1431
- }
1432
- /**
1433
- * An existing favourite for this place.
1434
- *
1435
- * Two ways to match, because a coordinate alone is not enough in either
1436
- * direction. TIGHT coordinate (~1 m) catches the canonical case, where both
1437
- * numbers came from Maps. NAME plus a LOOSE coordinate (~250 m) catches the
1438
- * case that matters to a caller: it passed its own coordinate, which differs
1439
- * from Apple's by a building's width — measured at 6.9e-5 for Sagrada Família.
1440
- *
1441
- * Without the second, every repeated call re-seeded before discovering the
1442
- * duplicate, leaving a Recents entry each time for a favourite it then did not
1443
- * create. Loosening the coordinate ALONE was the wrong fix: two different shops
1444
- * 200 m apart would merge. Requiring the name as well makes the loose radius
1445
- * safe, because it only ever merges rows the caller already calls the same
1446
- * thing.
1447
- */
1448
- #existingFavorite(db, lat, lon, name) {
1449
- const tight = db.prepare(`SELECT Z_PK AS pk, HEX(ZIDENTIFIER) AS hex, ZMAPITEMNAME AS name,
1450
- ZLATITUDE AS lat, ZLONGITUDE AS lon
1451
- FROM ZFAVORITEITEM
1452
- WHERE ZLATITUDE BETWEEN ? AND ? AND ZLONGITUDE BETWEEN ? AND ?
1453
- LIMIT 1`).get(lat - NEAR, lat + NEAR, lon - NEAR, lon + NEAR);
1454
- if (tight || !name) return tight;
1455
- return db.prepare(`SELECT Z_PK AS pk, HEX(ZIDENTIFIER) AS hex, ZMAPITEMNAME AS name,
1456
- ZLATITUDE AS lat, ZLONGITUDE AS lon
1457
- FROM ZFAVORITEITEM
1458
- WHERE ZMAPITEMNAME = ?
1459
- AND ZLATITUDE BETWEEN ? AND ? AND ZLONGITUDE BETWEEN ? AND ?
1460
- LIMIT 1`).get(name, lat - SEED_TOLERANCE, lat + SEED_TOLERANCE, lon - SEED_TOLERANCE, lon + SEED_TOLERANCE);
1461
- }
1462
- /**
1463
- * A place record already in the store for this coordinate.
1464
- *
1465
- * Checked before seeding, so asking for somewhere the user has already looked
1466
- * at costs no Recents entry and no network round trip. Recents, collection
1467
- * items and other favourites are all valid sources — the record is the same
1468
- * object whichever row points at it.
1469
- */
1470
- #donorNear(db, lat, lon) {
1471
- return db.prepare(`SELECT m."Z_PK" AS mapPk, m."ZLATITUDE" AS lat, m."ZLONGITUDE" AS lon,
1472
- m."ZMAPITEMSTORAGE" AS storage,
1473
- COALESCE(f."ZMAPITEMNAME", ci."ZMAPITEMNAME") AS name,
1474
- COALESCE(f."ZMAPITEMADDRESS", ci."ZMAPITEMADDRESS") AS address,
1475
- COALESCE(f."ZMAPITEMCATEGORY", ci."ZMAPITEMCATEGORY") AS category,
1476
- CAST(COALESCE(f."ZMUID", ci."ZMUID") AS TEXT) AS muid
1477
- FROM "ZMIXINMAPITEM" m
1478
- LEFT JOIN "ZFAVORITEITEM" f ON f."ZMAPITEM" = m."Z_PK"
1479
- LEFT JOIN "ZCOLLECTIONITEM" ci ON ci."ZMAPITEM" = m."Z_PK"
1480
- WHERE m."ZMAPITEMSTORAGE" IS NOT NULL
1481
- AND m."ZLATITUDE" BETWEEN ? AND ? AND m."ZLONGITUDE" BETWEEN ? AND ?
1482
- LIMIT 1`).get(lat - NEAR, lat + NEAR, lon - NEAR, lon + NEAR) ?? null;
1483
- }
1484
- /** The newest recent carrying a place record, above a watermark. */
1485
- #seededDonor(db, sinceHistoryPk) {
1486
- return db.prepare(`SELECT m."Z_PK" AS mapPk, m."ZLATITUDE" AS lat, m."ZLONGITUDE" AS lon,
1487
- m."ZMAPITEMSTORAGE" AS storage,
1488
- h."ZCUSTOMNAME" AS name, NULL AS address, NULL AS category,
1489
- CAST(h."ZMUID" AS TEXT) AS muid
1490
- FROM "ZHISTORYITEM" h
1491
- JOIN "ZMIXINMAPITEM" m ON m."Z_PK" = h."ZMAPITEM"
1492
- WHERE h."Z_PK" > ? AND m."ZMAPITEMSTORAGE" IS NOT NULL
1493
- ORDER BY h."Z_PK" DESC LIMIT 1`).get(sinceHistoryPk) ?? null;
1494
- }
1495
- #maxHistory(db) {
1496
- const row = db.prepare(`SELECT MAX(Z_PK) AS m FROM ZHISTORYITEM`).get();
1497
- return Number(row?.m ?? 0);
1498
- }
1499
- /**
1500
- * Add a favourite, in three phases with a connection open for as little of it
1501
- * as possible.
1502
- *
1503
- * THE PHASES ARE THE POINT. A first version opened one read-write handle at the
1504
- * top and held it across the whole seed — including the wait for Maps to
1505
- * resolve a place, which can run to tens of seconds. That hung: Maps is being
1506
- * asked to WRITE the very record being waited for, into a store this process is
1507
- * holding open for writing. Whatever the precise interaction, the shape was a
1508
- * departure from the sequence that had been proven by hand, and the proven
1509
- * sequence never holds a write handle while waiting on the app.
1510
- *
1511
- * 1. READ — look for an existing favourite and an existing place record.
1512
- * 2. SEED — ask Maps to mint a record, holding NO connection at all, and
1513
- * poll with a short-lived read-only handle each time.
1514
- * 3. WRITE — open read-write, insert, close.
1515
- */
1516
- /**
1517
- * Async because the seed can take THIRTY SECONDS.
1518
- *
1519
- * When the place is not already in the store this asks Maps to mint it
1520
- * through the URL scheme and then polls for the row to appear. That poll used
1521
- * `Atomics.wait`, which blocks the thread — and this server is single
1522
- * threaded, so for the whole seed it answered nothing at all: not a ping, not
1523
- * a cancellation, not another tool call. A sleep that yields costs the same
1524
- * wall clock and leaves the server able to speak.
1525
- */
1526
- async addFavorite(input) {
1527
- const hasCoords = input.latitude !== void 0 && input.longitude !== void 0;
1528
- const lat = input.latitude ?? 0;
1529
- const lon = input.longitude ?? 0;
1530
- progress(`add_favorite ${JSON.stringify(input.query)}: reading the store`);
1531
- const ro = new DatabaseSync(this.#path, { readOnly: true });
1532
- let existing = null;
1533
- let donor = null;
1534
- let watermark = 0;
1535
- try {
1536
- if (hasCoords) {
1537
- existing = this.#existingFavorite(ro, lat, lon, input.name ?? input.query) ?? null;
1538
- donor = this.#donorNear(ro, lat, lon);
1539
- }
1540
- watermark = this.#maxHistory(ro);
1541
- } finally {
1542
- ro.close();
1543
- }
1544
- if (existing) return {
1545
- rowId: Number(existing.pk),
1546
- uuid: uuidOf(Buffer.from(existing.hex, "hex")),
1547
- name: existing.name,
1548
- latitude: Number(existing.lat),
1549
- longitude: Number(existing.lon),
1550
- created: false,
1551
- seeded: false
1552
- };
1553
- let seeded = false;
1554
- if (!donor) {
1555
- const url = `maps://?q=${encodeURIComponent(input.query)}`;
1556
- progress(`asking Maps to resolve ${JSON.stringify(input.query)}…`);
1557
- await this.#openUrl(url);
1558
- seeded = true;
1559
- progress(`opened, waiting up to ${Math.round(this.#seedTimeoutMs / 1e3)}s for a record`);
1560
- const deadline = Date.now() + this.#seedTimeoutMs;
1561
- let polls = 0;
1562
- while (Date.now() < deadline && !donor) {
1563
- const probe = new DatabaseSync(this.#path, { readOnly: true });
1564
- try {
1565
- donor = this.#seededDonor(probe, watermark);
1566
- } finally {
1567
- probe.close();
1568
- }
1569
- if (!donor) await sleep(STORAGE_POLL_MS);
1570
- polls += 1;
1571
- if (polls % 8 === 0) progress(`still waiting (${polls * (STORAGE_POLL_MS / 1e3)}s)…`);
1572
- }
1573
- if (donor && hasCoords && !near(donor.lat, donor.lon, lat, lon)) throw new MapsWriteError(`Maps resolved ${JSON.stringify(input.query)} to a place about ${Math.round(haversineMetres(donor.lat, donor.lon, lat, lon))}m from the coordinate given, so it is probably not the place meant. Nothing was saved — try a more specific name.`, { query: input.query });
1574
- if (donor) progress(`got a place record (${donor.storage?.length ?? 0} bytes) after ${polls} polls`);
1575
- if (!donor) throw new MapsWriteError(`Maps did not produce a place record for "${input.query}" within ${Math.round(this.#seedTimeoutMs / 1e3)}s. Maps must be RUNNING for this to work — it is the only thing that can create a place record. It may also have resolved the query to a search rather than a place, since searches get no record. Try a more specific name, or pass latitude and longitude.`, { query: input.query });
1576
- }
1577
- const canonical = new DatabaseSync(this.#path, { readOnly: true });
1578
- let duplicate = null;
1579
- try {
1580
- duplicate = this.#existingFavorite(canonical, donor.lat, donor.lon) ?? null;
1581
- } finally {
1582
- canonical.close();
1583
- }
1584
- if (duplicate) {
1585
- progress("already a favourite; nothing written");
1586
- return {
1587
- rowId: Number(duplicate.pk),
1588
- uuid: uuidOf(Buffer.from(duplicate.hex, "hex")),
1589
- name: duplicate.name,
1590
- latitude: Number(duplicate.lat),
1591
- longitude: Number(duplicate.lon),
1592
- created: false,
1593
- seeded
1594
- };
1595
- }
1596
- progress("writing the favourite");
1597
- const db = this.#open();
1598
- try {
1599
- const now = Date.now() / 1e3 - CORE_DATA_EPOCH_OFFSET;
1600
- const id = uuidBytes();
1601
- const label = input.name ?? donor.name ?? input.query;
1602
- let favPk = 0;
1603
- db.exec("BEGIN IMMEDIATE");
1604
- try {
1605
- const favEnt = this.#entity(db, "FavoriteItem");
1606
- const mixEnt = this.#entity(db, "MixinMapItem");
1607
- favPk = this.#nextPk(db, "FavoriteItem", "ZFAVORITEITEM");
1608
- const mixPk = this.#nextPk(db, "MixinMapItem", "ZMIXINMAPITEM");
1609
- const position = Number(db.prepare(`SELECT COUNT(*) AS c FROM ZFAVORITEITEM`).get().c);
1610
- db.prepare(`INSERT INTO "ZFAVORITEITEM"
1611
- (Z_PK, Z_ENT, Z_OPT, ZHIDDEN, ZPOSITIONINDEX, ZSOURCE, ZTYPE, ZVERSION,
1612
- ZMAPITEM, ZMUID, ZCREATETIME, ZMODIFICATIONTIME, ZMAPITEMLASTREFRESHED,
1613
- ZLATITUDE, ZLONGITUDE, ZMAPITEMNAME, ZMAPITEMADDRESS, ZMAPITEMCATEGORY,
1614
- ZIDENTIFIER)
1615
- VALUES (?, ?, 1, 0, ?, 0, 1, 2, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(favPk, favEnt, position, mixPk, donor.muid === null ? null : BigInt(donor.muid), now, now, now, donor.lat, donor.lon, label, donor.address, donor.category, id);
1616
- db.prepare(`INSERT INTO "ZMIXINMAPITEM"
1617
- (Z_PK, Z_ENT, Z_OPT, ZFAVORITEITEM, ZCREATETIME, ZMODIFICATIONTIME,
1618
- ZLATITUDE, ZLONGITUDE, ZMAPITEMSTORAGE)
1619
- VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?)`).run(mixPk, mixEnt, favPk, now, now, donor.lat, donor.lon, donor.storage);
1620
- db.prepare(`UPDATE Z_PRIMARYKEY SET Z_MAX = ? WHERE Z_NAME = 'FavoriteItem'`).run(favPk);
1621
- db.prepare(`UPDATE Z_PRIMARYKEY SET Z_MAX = ? WHERE Z_NAME = 'MixinMapItem'`).run(mixPk);
1622
- db.exec("COMMIT");
1623
- } catch (err) {
1624
- try {
1625
- db.exec("ROLLBACK");
1626
- } catch {}
1627
- throw err;
1628
- }
1629
- return {
1630
- rowId: favPk,
1631
- uuid: uuidOf(id),
1632
- name: label,
1633
- latitude: Number(donor.lat),
1634
- longitude: Number(donor.lon),
1635
- created: true,
1636
- seeded
1637
- };
1638
- } finally {
1639
- db.close();
1640
- }
1641
- }
1642
- /**
1643
- * Remove a favourite and the place record it owns.
1644
- *
1645
- * `Z_MAX` is deliberately NOT rolled back. Core Data never reuses a primary
1646
- * key, and decrementing the counter would hand the next insert one that is
1647
- * already spoken for by a row still referenced elsewhere.
1648
- */
1649
- removeFavorite(key) {
1650
- const db = this.#open();
1651
- try {
1652
- const where = "uuid" in key ? `HEX(ZIDENTIFIER) = ?` : `Z_PK = ?`;
1653
- const param = "uuid" in key ? key.uuid.replaceAll("-", "").toUpperCase() : key.rowId;
1654
- const row = db.prepare(`SELECT Z_PK AS pk, ZMAPITEM AS mapPk FROM ZFAVORITEITEM WHERE ${where} LIMIT 1`).get(param);
1655
- if (!row) return false;
1656
- db.exec("BEGIN IMMEDIATE");
1657
- try {
1658
- if (row.mapPk !== null) db.prepare(`DELETE FROM ZMIXINMAPITEM WHERE Z_PK = ?`).run(row.mapPk);
1659
- db.prepare(`DELETE FROM ZFAVORITEITEM WHERE Z_PK = ?`).run(row.pk);
1660
- db.exec("COMMIT");
1661
- } catch (err) {
1662
- try {
1663
- db.exec("ROLLBACK");
1664
- } catch {}
1665
- throw err;
1666
- }
1667
- return true;
1668
- } finally {
1669
- db.close();
1670
- }
1671
- }
1672
- };
1673
- //#endregion
1674
1348
  //#region src/client/maps.ts
1675
1349
  /**
1676
1350
  * What diagnostics says about one entity: how many rows, which column won for
@@ -1685,13 +1359,16 @@ const summariseEntity = (e) => ({
1685
1359
  var AppleMapsClient = class {
1686
1360
  #config;
1687
1361
  /**
1688
- * The interface lane, when this server is hosted by Cupertino.
1362
+ * The store lane, when this server is hosted by Cupertino: the five writes,
1363
+ * saved by the app with Maps' own model, and Maps' only write route.
1689
1364
  *
1690
1365
  * Null when it is not, which is the supported case rather than a fault: the
1691
- * npm package has to work with no app on the machine. `tools/index.ts` skips
1692
- * registering the tools that need it.
1366
+ * npm package has to work with no app on the machine, and then it only
1367
+ * reads. `tools/index.ts` registers no write tool. Opening it connects
1368
+ * nothing.
1693
1369
  */
1694
- #ax;
1370
+ #lane;
1371
+ #openUrl;
1695
1372
  #logger;
1696
1373
  #home;
1697
1374
  #located = null;
@@ -1699,15 +1376,16 @@ var AppleMapsClient = class {
1699
1376
  #storeError = null;
1700
1377
  constructor(opts) {
1701
1378
  this.#config = opts.config;
1702
- this.#ax = opts.ax !== void 0 ? opts.ax : MapsAxLane.open();
1379
+ this.#lane = opts.lane !== void 0 ? opts.lane : MapsLane.open();
1380
+ this.#openUrl = opts.openUrl;
1703
1381
  this.#logger = opts.logger;
1704
1382
  this.#home = opts.home;
1705
1383
  }
1706
1384
  get config() {
1707
1385
  return this.#config;
1708
1386
  }
1709
- get axLane() {
1710
- return this.#ax;
1387
+ get lane() {
1388
+ return this.#lane;
1711
1389
  }
1712
1390
  located() {
1713
1391
  this.#located ??= locateStore({
@@ -1717,17 +1395,15 @@ var AppleMapsClient = class {
1717
1395
  return this.#located;
1718
1396
  }
1719
1397
  /**
1720
- * A writer bound to the located store, or an error explaining why not.
1721
- *
1722
- * Writes go through their own read-write connection rather than the shared
1723
- * read-only one: `store()` opens with `query_only` and an `immutable` fallback
1724
- * precisely so a read can never mutate by accident, and widening it would
1725
- * throw that guarantee away for every read on the surface.
1398
+ * A read-only finder of place records for the store lane, bound to the
1399
+ * located store, or an error explaining why not. It writes nothing: the lane
1400
+ * does the writing, through Maps' own model. Its own connections, rather than
1401
+ * the shared one `store()` opens, because it must not hold one across a seed.
1726
1402
  */
1727
- writer(openUrl) {
1403
+ placeSource(openUrl = this.#openUrl) {
1728
1404
  const located = this.located();
1729
1405
  if (!located.readable || !located.storePath) throw new MapsStoreUnavailableError(located.reason ?? "Maps' store could not be opened.");
1730
- return new MapsWriter({
1406
+ return new PlaceSourceFinder({
1731
1407
  storePath: located.storePath,
1732
1408
  seedTimeoutMs: this.#config.seedTimeoutMs,
1733
1409
  ...openUrl ? { openUrl } : {}
@@ -1882,6 +1558,7 @@ var AppleMapsClient = class {
1882
1558
  close() {
1883
1559
  this.#store?.close();
1884
1560
  this.#store = null;
1561
+ this.#lane?.close();
1885
1562
  }
1886
1563
  };
1887
1564
  //#endregion
@@ -1890,13 +1567,14 @@ var AppleMapsClient = class {
1890
1567
  * Configuration is environment-only — this server holds no secret at all. Its
1891
1568
  * access is the macOS permission the user granted, which is the whole point.
1892
1569
  *
1893
- * `allowWrites` gates two mutating tools, and gates them harder than elsewhere.
1894
- * Maps has no scripting dictionary and no registered App Intents, so a write is
1895
- * SQL straight into a Core Data store that `NSPersistentCloudKitContainer`
1896
- * mirrors — which means it reaches every device on the account, not just this
1897
- * Mac. That was measured, along with the rule that keeps it safe: never
1898
- * fabricate a place record, only ever copy one Maps wrote itself. See
1899
- * `docs/maps.md` and `client/write.ts`.
1570
+ * `allowWrites` gates the mutating tools, and only matters when Cupertino
1571
+ * hosts this server. Maps has no scripting dictionary and no registered App
1572
+ * Intents, so its one write route is Cupertino's store lane, which saves with
1573
+ * Maps' own Core Data model; on macOS 27.2 those saves were measured on
1574
+ * 2026-11-11 to reach an iPhone through iCloud. Run from npm there is no lane,
1575
+ * and no write tool is registered whatever this says. The lane keeps one rule:
1576
+ * never fabricate a place record, only ever copy one Maps wrote itself. See
1577
+ * `docs/maps.md`.
1900
1578
  */
1901
1579
  const ConfigSchema = BaseConfigSchema.extend({
1902
1580
  /** Explicit store path. Bypasses discovery — for tests and forensic copies. */
@@ -1964,6 +1642,49 @@ genuinely saved nothing of that kind. Check
1964
1642
  | Find a saved place by name or address | \`apple_maps_search_places\` |
1965
1643
  | One place, in full | \`apple_maps_get_place\` |
1966
1644
 
1645
+ ## Writing, when Cupertino hosts this server
1646
+
1647
+ With writes on and Cupertino hosting this server, five tools save through Maps'
1648
+ own data model inside Cupertino, as a change made in the app is. They are the
1649
+ only way this server writes: run from npm it only reads, and none of them is
1650
+ listed. If the user asks for a change then, say it needs Cupertino.
1651
+
1652
+ | Change | Tool |
1653
+ | --- | --- |
1654
+ | Pin a place (the Pinned list) | \`apple_maps_add_favorite\` |
1655
+ | Unpin it | \`apple_maps_remove_favorite\` |
1656
+ | Save a place to the library, in no Guide | \`apple_maps_save_place\` |
1657
+ | Remove a saved place | \`apple_maps_remove_saved_place\` |
1658
+ | File a place in an existing Guide | \`apple_maps_add_place_to_guide\` |
1659
+
1660
+ **Unpinning is not removing.** As in Maps, \`apple_maps_remove_favorite\` keeps
1661
+ the place in the user's library as a saved place. To take a place out of Maps
1662
+ entirely, unpin it and then remove the saved place with
1663
+ \`apple_maps_remove_saved_place\`, by a ref from \`apple_maps_list_unfiled_places\`
1664
+ or \`apple_maps_list_collection_places\`.
1665
+
1666
+ **Removes take a ref** from a listing, never a coordinate.
1667
+ \`apple_maps_add_place_to_guide\` takes a ref to a saved place, or a \`query\` to
1668
+ save a new place and file it in one call.
1669
+
1670
+ **A new place lands in Recents.** Only Maps can make a place record, so unless the
1671
+ place is already in the store near the coordinate given, Maps resolves it by
1672
+ name, and it then also appears in the user's Recents. Give a coordinate when
1673
+ you have one. The answer says so in \`recentsNote\`; tell the user.
1674
+
1675
+ **On the measured model, a save reaches iCloud without the app:** when the
1676
+ result's \`syncMeasured\` is true, Maps' background service uploads it even
1677
+ with Maps closed. Say the change is saved on this Mac and on its way to
1678
+ other devices, not that it is already on the iPhone. When the result's
1679
+ \`syncMeasured\` is false, the save still happened but sync is not yet measured on
1680
+ this macOS: pass on its \`sync\` sentence, which asks to check the place on another
1681
+ device.
1682
+
1683
+ A refusal's reason is in \`details.reason\`. A place Maps resolved more than about
1684
+ 250 m from the coordinate given is refused as \`invalid\`: confirm the place with
1685
+ the user rather than retrying without a coordinate. \`incompatible\` and
1686
+ \`writesOff\` will not pass on a retry.
1687
+
1967
1688
  ## Four things not to say
1968
1689
 
1969
1690
  **\`linked: false\` is not a broken row.** Some favourites have no place
@@ -2042,10 +1763,385 @@ Full Disk Access grant takes all of it at once.`
2042
1763
  //#region src/tools/util.ts
2043
1764
  const placeRefArg = z.string().min(1).describe("An opaque place ref from a listing (looks like \"p1:f:12\"). Do not construct one by hand. Refs address a row in the local store, so they are only valid for this session — an iCloud re-sync can renumber them.");
2044
1765
  const collectionRefArg = z.string().min(1).describe("An opaque collection ref from apple_maps_list_collections (looks like \"pc1:3\").");
2045
- const queryArg = z.string().min(1).describe("Text to look for in a place's name, the label you gave it, or its address. Wildcards are escaped, so searching for \"100%\" finds that literal string.");
1766
+ const queryArg$1 = z.string().min(1).describe("Text to look for in a place's name, the label you gave it, or its address. Wildcards are escaped, so searching for \"100%\" finds that literal string.");
1767
+ //#endregion
1768
+ //#region src/tools/store-writes.ts
1769
+ /** The five tools this file registers, in registration order. */
1770
+ const STORE_WRITE_TOOLS = [
1771
+ "apple_maps_add_favorite",
1772
+ "apple_maps_remove_favorite",
1773
+ "apple_maps_save_place",
1774
+ "apple_maps_remove_saved_place",
1775
+ "apple_maps_add_place_to_guide"
1776
+ ];
1777
+ /**
1778
+ * What a write promises about iCloud, in one sentence, on Voice Memos' pattern
1779
+ * (`packages/voice-memos/src/tools/store-writes.ts`).
1780
+ *
1781
+ * Sync is promised only on a model version whose upload was measured: Maps'
1782
+ * model on macOS 27.2 (checksum `CaxhFk…`, listed in the Swift writer's
1783
+ * `measuredVersions`), every write seen on a Mac and an iPhone on
1784
+ * 2026-11-11, one with Maps quit and mapssyncd exporting alone (`docs/maps.md`,
1785
+ * "Measured 2026-11-11"). Elsewhere the save still happened, but nobody has
1786
+ * watched it reach another device, so the result says so. The two removes say
1787
+ * it of a removal.
1788
+ */
1789
+ const syncSentence = (w, kind = "save") => {
1790
+ if (w.changed.length === 0) return "Nothing to change.";
1791
+ const [done, how] = kind === "remove" ? ["Removed", "removes"] : ["Saved", "saves"];
1792
+ if (w.syncMeasured) return `${done} the way Maps ${how} it. It reaches your other devices through iCloud, even with Maps closed.`;
1793
+ return `${done}, but sync is not yet measured on this macOS (model ${w.modelVersion ?? "unknown"}): check the place on another device.`;
1794
+ };
1795
+ /** The lane's own fields, plus the sentence. */
1796
+ const laneFields = (w, kind = "save") => ({
1797
+ changed: w.changed,
1798
+ modelVersion: w.modelVersion,
1799
+ syncMeasured: w.syncMeasured,
1800
+ sync: syncSentence(w, kind)
1801
+ });
1802
+ /**
1803
+ * The answer when an item already stood there and the lane was never asked: no
1804
+ * model version to report, because nothing was saved.
1805
+ */
1806
+ const unchanged = {
1807
+ changed: [],
1808
+ sync: "Nothing to change."
1809
+ };
1810
+ const RECENTS_NOTE = "Maps was asked to resolve this place, so it now also appears in the user's Recents. That is how the place record is obtained and cannot be avoided.";
1811
+ /** What follows, in every lane tool's description, what the tool does. */
1812
+ const LANE_TAIL = "the result's `sync` says whether that is measured to reach the user's other Apple devices on this macOS. Only available when Cupertino hosts this server.";
1813
+ /** The three tools that add something say this. */
1814
+ const SAVED_LIKE = `Saved through Maps' own data model inside Cupertino, as a change made in the app is; ${LANE_TAIL}`;
1815
+ /** The two removes say this: what they take away goes the way the app takes it away. */
1816
+ const REMOVED_LIKE = `Removed through Maps' own data model inside Cupertino, as a removal made in the app is; ${LANE_TAIL}`;
1817
+ /** The three tools that may need a place record Maps has not minted yet. */
1818
+ const SEEDS = "SIDE EFFECT: unless the place is already in the store, Maps is asked to resolve it by name and the place also appears in the user's Recents; there is no way to have the record without that.";
1819
+ /**
1820
+ * Where an unpinned place went. Maps does not delete a pin it unpins: it moves
1821
+ * the place into the library as a saved place (watched 2026-11-11,
1822
+ * `docs/maps.md`), and the lane does the same. `changed` lists `savedPlace`
1823
+ * when the lane made one. Only `favorite` has two causes the answer does not
1824
+ * tell apart: a saved place already stood at that spot, or the pin carried no
1825
+ * place record or coordinate to move. The sentence is true of both.
1826
+ */
1827
+ const libraryNote = (changed) => {
1828
+ if (!changed.includes("favorite")) return void 0;
1829
+ const from = "by its ref from apple_maps_list_unfiled_places or apple_maps_list_collection_places.";
1830
+ return changed.includes("savedPlace") ? `Unpinned, and kept in your library as a saved place, as Maps does. apple_maps_remove_saved_place removes it entirely, ${from}` : `Unpinned. No new saved place was made: one already stood at this spot, or the pin carried no place record to keep. apple_maps_remove_saved_place removes a saved place entirely, ${from}`;
1831
+ };
1832
+ const WRITE = {
1833
+ readOnlyHint: false,
1834
+ destructiveHint: false,
1835
+ idempotentHint: true
1836
+ };
1837
+ const REMOVE = {
1838
+ ...WRITE,
1839
+ destructiveHint: true
1840
+ };
1841
+ const queryArg = z.string().min(1).describe("The place's name, as you would type it into Maps' search field. A bare coordinate does not identify a place to Maps.");
1842
+ const latitudeArg = z.number().min(-90).max(90).optional().describe("Latitude, when known: makes the match exact and can skip asking Maps.");
1843
+ const longitudeArg = z.number().min(-180).max(180).optional().describe("Longitude, when known.");
1844
+ const nameArg = z.string().min(1).optional().describe("A label of your own, saved as the place's custom name, which the listings show before the place's own. Left out, the place keeps the name Maps gives it.");
1845
+ /** A refusal decided here, before the lane is called, in the lane's own vocabulary. */
1846
+ const refuse = (reason, message) => fail(message, { reason });
1847
+ /**
1848
+ * Both halves of a coordinate, or neither. Half of one is a caller's mistake,
1849
+ * refused rather than dropped: dropping it would seed by name alone and could
1850
+ * save a namesake on the other side of the world.
1851
+ */
1852
+ const coordsOf = (latitude, longitude) => {
1853
+ if (latitude !== void 0 && longitude !== void 0) return { near: {
1854
+ latitude,
1855
+ longitude
1856
+ } };
1857
+ if (latitude === void 0 && longitude === void 0) return { near: void 0 };
1858
+ return { refusal: refuse("invalid", "Give both latitude and longitude, or neither.") };
1859
+ };
1860
+ /** Where `find` got the record, as the lane names it. */
1861
+ const fromSource = (s) => ({
1862
+ source: s.kind,
1863
+ sourceId: s.id
1864
+ });
1865
+ /**
1866
+ * A lane write that copies a source's record, with the lane's `notFound` for
1867
+ * that source said plainly. Between `find` and the save Maps can replace the
1868
+ * recent it filed (it does as it refreshes them), and the lane then finds no
1869
+ * item with that identifier. Nothing was saved, and a second call finds the
1870
+ * record Maps holds now.
1871
+ */
1872
+ const copying = async (write) => {
1873
+ try {
1874
+ return { w: await write };
1875
+ } catch (err) {
1876
+ if (err instanceof StoreLaneError && err.reason === "notFound") return { refusal: refuse("notFound", "The place record Maps had filed for this place was replaced before it could be copied: Maps replaces its Recents as it refreshes them. Nothing was saved; repeat the call.") };
1877
+ throw err;
1878
+ }
1879
+ };
1880
+ /**
1881
+ * A place in an answer: its ref, and the item's own name and coordinate as the
1882
+ * store holds them. Fields the read-back did not find are left out, never
1883
+ * filled with what the caller asked for.
1884
+ *
1885
+ * The read-back comes after the lane committed the save, which is already on
1886
+ * its way to the user's other devices, so a read that fails answers the ref
1887
+ * alone, as one that finds nothing does, rather than an error for a write that
1888
+ * happened.
1889
+ */
1890
+ const described = (client, kind, id, stored) => {
1891
+ let row;
1892
+ try {
1893
+ row = stored === void 0 ? client.placeSource().describe(kind, id) : stored;
1894
+ } catch {
1895
+ row = null;
1896
+ }
1897
+ return compact({
1898
+ ref: encodePlaceRef(kind, { uuid: id }),
1899
+ name: row?.name ?? void 0,
1900
+ latitude: row?.latitude ?? void 0,
1901
+ longitude: row?.longitude ?? void 0
1902
+ });
1903
+ };
1904
+ /**
1905
+ * A ref from a listing to the identifier the lane fetches by, or a refusal.
1906
+ *
1907
+ * A ref that does not decode is refused `invalid`, like every other refusal
1908
+ * decided here. Null from `identifierOf` is a row with no `ZIDENTIFIER` (a
1909
+ * row-id ref), or no row at all: either way the lane, which fetches by uuid
1910
+ * only, cannot be given it, so the lane is not called.
1911
+ */
1912
+ const identifierFor = (client, ref, want, verb) => {
1913
+ let decoded;
1914
+ try {
1915
+ decoded = decodePlaceRef(ref);
1916
+ } catch (err) {
1917
+ if (err instanceof InvalidMapsRefError) return { refusal: refuse("invalid", err.message) };
1918
+ throw err;
1919
+ }
1920
+ const { kind, key } = decoded;
1921
+ const what = want === "favorite" ? "favourite" : "saved place";
1922
+ if (kind !== want) return { refusal: refuse("invalid", `That ref points at a ${kind === "history" ? "recent" : kind === "favorite" ? "favourite" : "saved place"}, not a ${what}. Pass a ref from ${want === "favorite" ? "apple_maps_list_favorites" : "apple_maps_list_unfiled_places or apple_maps_list_collection_places"}.`) };
1923
+ const id = client.placeSource().identifierOf(kind, key);
1924
+ if (id === null) return { refusal: refuse("notFound", "uuid" in key ? `No ${what} matched that ref. It may already have been removed; re-run the listing.` : `This ${what} has no stable id, so it cannot be ${verb} through Cupertino (or it is no longer in the store).`) };
1925
+ return { id };
1926
+ };
1927
+ /**
1928
+ * The store lane's Maps tools, and Maps' only writes. Registered only when
1929
+ * writes are on and Cupertino hosts this server (`tools/index.ts`): run from
1930
+ * npm, this server registers no write tool at all.
1931
+ *
1932
+ * This side keeps what only it can do: de-duplicate on the caller's coordinate
1933
+ * and name before anything else, find a place record Maps minted (seeding when
1934
+ * there is none), and turn a listing's ref into the identifier the lane fetches
1935
+ * by. The app validates every argument again and answers with a `reason` on
1936
+ * refusal (`invalid`, `notFound`, `incompatible`, `writesOff`, `failed`, or one
1937
+ * of the connection's own), which the tool error carries in `details.reason`.
1938
+ * Refusals decided here use the same vocabulary.
1939
+ *
1940
+ * A place in an answer is the item as the store holds it, read back after the
1941
+ * lane answers: the de-duplication can match a favourite saved under another
1942
+ * name, or ~250 m from the caller's coordinate, and the caller's guess must
1943
+ * not be reported as the place.
1944
+ *
1945
+ * The list does not depend on whether the lane is compatible: MCP clients cache
1946
+ * it, so an incompatible lane refuses per call instead.
1947
+ */
1948
+ const registerStoreWriteTools = (server, client, lane) => {
1949
+ server.registerTool("apple_maps_add_favorite", {
1950
+ description: `Save a place to Maps' favourites (the Pinned list). Give the place NAME as \`query\`, and latitude/longitude when known. ${SEEDS} ${SAVED_LIKE} Idempotent: asking twice for the same place returns the existing favourite rather than creating a second. Needs Full Disk Access.`,
1951
+ inputSchema: z.object({
1952
+ query: queryArg,
1953
+ latitude: latitudeArg,
1954
+ longitude: longitudeArg,
1955
+ name: nameArg
1956
+ }),
1957
+ annotations: WRITE
1958
+ }, async ({ query, latitude, longitude, name }) => wrapResult(async () => {
1959
+ const label = name ?? query;
1960
+ const coords = coordsOf(latitude, longitude);
1961
+ if ("refusal" in coords) return coords.refusal;
1962
+ const { near } = coords;
1963
+ const finder = client.placeSource();
1964
+ const existing = near ? finder.existingFavorite({
1965
+ ...near,
1966
+ name: label
1967
+ }) : null;
1968
+ if (existing) return ok({
1969
+ favorite: described(client, "favorite", existing.id, existing),
1970
+ created: false,
1971
+ alreadyExisted: "A favourite for this place already existed and was returned unchanged.",
1972
+ ...unchanged
1973
+ });
1974
+ const s = await finder.find(near ? {
1975
+ query,
1976
+ ...near
1977
+ } : { query });
1978
+ const copied = await copying(lane.addFavorite({
1979
+ ...fromSource(s),
1980
+ query,
1981
+ name,
1982
+ near
1983
+ }));
1984
+ if ("refusal" in copied) return copied.refusal;
1985
+ const { w } = copied;
1986
+ return ok(compact({
1987
+ favorite: described(client, "favorite", w.id),
1988
+ created: w.created,
1989
+ alreadyExisted: w.created ? void 0 : "A favourite for this place already existed and was returned unchanged.",
1990
+ ...laneFields(w),
1991
+ recentsNote: s.seeded ? RECENTS_NOTE : void 0
1992
+ }));
1993
+ }));
1994
+ server.registerTool("apple_maps_remove_favorite", {
1995
+ description: `Unpin a place from Maps' favourites (the Pinned list), by a ref from apple_maps_list_favorites. As in Maps, unpinning keeps the place in the user's library as a saved place, in no Guide; no new one is made when one already stands at that spot, or the pin carries no place record. apple_maps_remove_saved_place removes it entirely. Only pins: the Home, Work and School slots are refused. It does not touch Guides or Recents. ${REMOVED_LIKE} Needs Full Disk Access, and an explicit confirm: the unpin is not undoable from here.`,
1996
+ inputSchema: z.object({
1997
+ ref: placeRefArg,
1998
+ confirm: confirmArg
1999
+ }),
2000
+ annotations: REMOVE
2001
+ }, async ({ ref }) => wrapResult(async () => {
2002
+ const target = identifierFor(client, ref, "favorite", "removed");
2003
+ if ("refusal" in target) return target.refusal;
2004
+ const w = await lane.removeFavorite(target.id);
2005
+ return ok(compact({
2006
+ removed: w.changed.length > 0,
2007
+ id: w.id,
2008
+ library: libraryNote(w.changed),
2009
+ ...laneFields(w, "remove")
2010
+ }));
2011
+ }));
2012
+ server.registerTool("apple_maps_save_place", {
2013
+ description: `Save a place into Maps' Places library, in no Guide. This is NOT a favourite: the Pinned list is a different set, written by apple_maps_add_favorite. Give the place NAME as \`query\`, and latitude/longitude when known. ${SEEDS} ${SAVED_LIKE} Idempotent: a place already saved is returned unchanged. Needs Full Disk Access.`,
2014
+ inputSchema: z.object({
2015
+ query: queryArg,
2016
+ latitude: latitudeArg,
2017
+ longitude: longitudeArg,
2018
+ name: nameArg
2019
+ }),
2020
+ annotations: WRITE
2021
+ }, async ({ query, latitude, longitude, name }) => wrapResult(async () => {
2022
+ const label = name ?? query;
2023
+ const coords = coordsOf(latitude, longitude);
2024
+ if ("refusal" in coords) return coords.refusal;
2025
+ const { near } = coords;
2026
+ const finder = client.placeSource();
2027
+ const existing = near ? finder.existingSavedPlace({
2028
+ ...near,
2029
+ name: label
2030
+ }) : null;
2031
+ if (existing) return ok({
2032
+ place: described(client, "collection-item", existing.id, existing),
2033
+ saved: true,
2034
+ alreadySaved: true,
2035
+ created: false,
2036
+ ...unchanged
2037
+ });
2038
+ const s = await finder.find(near ? {
2039
+ query,
2040
+ ...near
2041
+ } : { query });
2042
+ const copied = await copying(lane.savePlace({
2043
+ ...fromSource(s),
2044
+ query,
2045
+ name,
2046
+ near
2047
+ }));
2048
+ if ("refusal" in copied) return copied.refusal;
2049
+ const { w } = copied;
2050
+ return ok(compact({
2051
+ place: described(client, "collection-item", w.id),
2052
+ saved: true,
2053
+ alreadySaved: !w.created,
2054
+ created: w.created,
2055
+ ...laneFields(w),
2056
+ recentsNote: s.seeded ? RECENTS_NOTE : void 0
2057
+ }));
2058
+ }));
2059
+ server.registerTool("apple_maps_remove_saved_place", {
2060
+ description: `Remove a place from Maps' Places library, by a ref from apple_maps_list_unfiled_places or apple_maps_list_collection_places. That takes it out of every Guide it is filed in. This does NOT touch favourites: use apple_maps_remove_favorite for those. ${REMOVED_LIKE} Needs Full Disk Access, and an explicit confirm: the removal is not undoable from here.`,
2061
+ inputSchema: z.object({
2062
+ ref: placeRefArg,
2063
+ confirm: confirmArg
2064
+ }),
2065
+ annotations: REMOVE
2066
+ }, async ({ ref }) => wrapResult(async () => {
2067
+ const target = identifierFor(client, ref, "collection-item", "removed");
2068
+ if ("refusal" in target) return target.refusal;
2069
+ const w = await lane.removeSavedPlace(target.id);
2070
+ return ok({
2071
+ removed: w.changed.length > 0,
2072
+ id: w.id,
2073
+ ...laneFields(w, "remove")
2074
+ });
2075
+ }));
2076
+ server.registerTool("apple_maps_add_place_to_guide", {
2077
+ description: `File a place into one of Maps' Guides. Give either \`ref\`, a saved place from apple_maps_list_unfiled_places or apple_maps_list_collection_places, or \`query\` (with latitude/longitude when known) for a place to save and file in one save; not both. The Guide must already exist, and a name that matches none, or several, is refused naming the candidates. \`filed\` comes from reading the Guide back after the save, never from having asked. ${SEEDS} ${SAVED_LIKE} Needs Full Disk Access.`,
2078
+ inputSchema: z.object({
2079
+ guide: z.string().min(1).describe("The Guide's name, as Maps shows it."),
2080
+ ref: placeRefArg.optional().describe("A saved place's ref, from apple_maps_list_unfiled_places or apple_maps_list_collection_places. Give this or `query`, not both."),
2081
+ query: queryArg.optional().describe("The place's name, for a place to save first, as apple_maps_save_place takes it. Give this or `ref`, not both."),
2082
+ latitude: latitudeArg.describe("Latitude, with `query`, when known."),
2083
+ longitude: longitudeArg.describe("Longitude, with `query`, when known.")
2084
+ }),
2085
+ annotations: WRITE
2086
+ }, async ({ guide, ref, query, latitude, longitude }) => wrapResult(async () => {
2087
+ if (ref === void 0 === (query === void 0) || ref !== void 0 && (latitude !== void 0 || longitude !== void 0)) return refuse("invalid", "Give either `ref` (a saved place) or `query` with an optional latitude and longitude (a place to save first): exactly one of the two.");
2088
+ const filedAnswer = (w, seeded) => ok(compact({
2089
+ filed: w.filed,
2090
+ created: w.created,
2091
+ guide,
2092
+ place: described(client, "collection-item", w.id),
2093
+ ...laneFields(w),
2094
+ recentsNote: seeded ? RECENTS_NOTE : void 0
2095
+ }));
2096
+ if (ref !== void 0) {
2097
+ const target = identifierFor(client, ref, "collection-item", "filed");
2098
+ if ("refusal" in target) return target.refusal;
2099
+ return filedAnswer(await lane.fileInGuide({
2100
+ guide,
2101
+ placeId: target.id
2102
+ }), false);
2103
+ }
2104
+ const q = query;
2105
+ const coords = coordsOf(latitude, longitude);
2106
+ if ("refusal" in coords) return coords.refusal;
2107
+ const { near } = coords;
2108
+ const finder = client.placeSource();
2109
+ const existing = near ? finder.existingSavedPlace(near) : null;
2110
+ if (existing) return filedAnswer(await lane.fileInGuide({
2111
+ guide,
2112
+ placeId: existing.id
2113
+ }), false);
2114
+ const s = await finder.find(near ? {
2115
+ query: q,
2116
+ ...near
2117
+ } : { query: q });
2118
+ const copied = await copying(lane.fileInGuide({
2119
+ guide,
2120
+ ...fromSource(s),
2121
+ query: q,
2122
+ near
2123
+ }));
2124
+ if ("refusal" in copied) return copied.refusal;
2125
+ return filedAnswer(copied.w, s.seeded);
2126
+ }));
2127
+ };
2046
2128
  //#endregion
2047
2129
  //#region src/tools/diagnostics.ts
2048
2130
  /**
2131
+ * The store lane's own answer, asked only when Cupertino hosts this server. A
2132
+ * lane that cannot answer is reported as `{ error }`, never as a failed
2133
+ * diagnostics call: this report is where a person looks when the lane is the
2134
+ * thing that broke. As Voice Memos' diagnostics does.
2135
+ */
2136
+ const writeLaneStatus = async (client) => {
2137
+ if (!client.lane) return null;
2138
+ try {
2139
+ return await client.lane.status();
2140
+ } catch (err) {
2141
+ return { error: err instanceof Error ? err.message : String(err) };
2142
+ }
2143
+ };
2144
+ /**
2049
2145
  * Build the report.
2050
2146
  *
2051
2147
  * Split out of the tool registration so the `cupertino://maps/diagnostics`
@@ -2056,6 +2152,12 @@ const queryArg = z.string().min(1).describe("Text to look for in a place's name,
2056
2152
  const buildDiagnostics = async (client) => {
2057
2153
  const status = client.status();
2058
2154
  const located = status.located;
2155
+ const hosted = client.lane !== null;
2156
+ const writeLane = await writeLaneStatus(client);
2157
+ const allowWrites = client.config.allowWrites;
2158
+ /** The route `tools/index.ts` registered, so this report cannot disagree with it. */
2159
+ const route = !allowWrites ? "off" : hosted ? "store lane" : "not hosted";
2160
+ const tools = allowWrites && hosted ? [...STORE_WRITE_TOOLS] : [];
2059
2161
  const base = buildBaseDiagnostics({
2060
2162
  build: BUILD_INFO,
2061
2163
  config: client.config,
@@ -2076,12 +2178,17 @@ const buildDiagnostics = async (client) => {
2076
2178
  },
2077
2179
  appleEvents: "none — Maps is not scriptable",
2078
2180
  writes: {
2079
- enabled: client.config.allowWrites,
2080
- lane: "SQL, directly into the Core Data store. Maps ships no scripting dictionary and registers no App Intents on macOS, so there is no lane where the app performs the write on our behalf — this is the only surface here that writes its own store.",
2081
- seeding: "A place is only real to Maps if it carries a ZMAPITEMSTORAGE blob, which this repo cannot generate. Opening maps://?q=<name>&ll=<lat>,<lon> through LaunchServices makes Maps mint one, and that record is copied. The place is therefore left in Recents whether or not the favourite is kept, and resolving it can take tens of seconds.",
2082
- blastRadius: "The store is mirrored by NSPersistentCloudKitContainer, and mirroring does not wait to be told. A malformed row is not a local mistake: it reaches every device on the account as soon as Maps next runs. Hence the rule in client/write.ts — never fabricate a place record, only ever copy one Maps wrote.",
2083
- tools: client.config.allowWrites ? ["apple_maps_add_favorite", "apple_maps_remove_favorite"] : []
2084
- }
2181
+ enabled: allowWrites,
2182
+ route,
2183
+ ...hosted ? {
2184
+ lane: "Cupertino's store lane, Maps' only write route: the app saves each write through Core Data with Maps' own model, so it is recorded in persistent history like a change made in Maps. This server only reads the store, to de-duplicate, find a place record to copy, and turn a ref into the identifier the lane fetches by.",
2185
+ seeding: "A place is only real to Maps if it carries a ZMAPITEMSTORAGE record, which nothing here can generate. When no record is already in the store near the coordinate, this server opens maps://?q=<query> (the name alone, no coordinate) through LaunchServices and waits, read-only, for the recent Maps files with a record; the lane then copies that record. The place is therefore left in Recents, and resolving it can take tens of seconds.",
2186
+ blastRadius: "The store is mirrored by NSPersistentCloudKitContainer, and a lane write goes with it: on the model whose syncMeasured is true, every one of the five was seen on a Mac and an iPhone on 2026-11-11, one with Maps quit. Each one is saved by Cupertino through Maps' own model and only ever copies a place record Maps minted; a model that does not match the store is refused as incompatible rather than opened."
2187
+ } : { lane: "none: run from npm, this server writes nothing to Maps, whatever APPLE_MAPS_ALLOW_WRITES says. Maps' writes exist only when Cupertino hosts this server, through its store lane. The route this package wrote through itself was retired on 2026-11-11: its inserts were watched never to reach iCloud (docs/maps.md)." },
2188
+ tools
2189
+ },
2190
+ writeLane,
2191
+ ...hosted ? {} : { writeLaneNote: "not hosted by Cupertino: the store lane, and the writes that go through it, need the app" }
2085
2192
  },
2086
2193
  store: {
2087
2194
  path: located.storePath,
@@ -2119,141 +2226,6 @@ const registerDiagnosticsTools = (server, client) => {
2119
2226
  }, async () => wrap(() => buildDiagnostics(client)));
2120
2227
  };
2121
2228
  //#endregion
2122
- //#region src/tools/ax-writes.ts
2123
- /**
2124
- * The tools that go through Maps' own interface rather than its store.
2125
- *
2126
- * ## Why these are not in `writes.ts`
2127
- *
2128
- * Different lane, different objects, different failure modes. `writes.ts` writes
2129
- * SQL into the Core Data store and reaches **favourites**; these press controls
2130
- * on a place card and reach the **Places library** and **guide membership** —
2131
- * two sets the SQL lane does not offer at all. `docs/maps.md` lists guide
2132
- * membership as unbuilt for exactly that reason.
2133
- *
2134
- * ## Registered only when the app is hosting this server
2135
- *
2136
- * The Accessibility grant belongs to Cupertino.app, not to node, so a package
2137
- * installed from npm and run by hand has no lane here and these tools are not
2138
- * registered at all — the same rule the write gate follows, so a host is never
2139
- * told about a tool that cannot work for it.
2140
- *
2141
- * ## What every description has to say
2142
- *
2143
- * **It opens Maps and leaves the place in Recents.** Reaching a card means
2144
- * opening `maps://`, which is how the SQL lane seeds a record too. There is no
2145
- * way to have the card without the Recents entry.
2146
- *
2147
- * **It moves the user's screen.** Unlike a SQL write, this brings a window
2148
- * forward and presses things in it. That is worth stating plainly.
2149
- */
2150
- const noCard = (query, disturbed) => fail(`Maps did not show a place card for "${query}" within 10s. Nothing was changed. The coordinates may not resolve to a place Maps recognises, or Maps may not have finished loading it.` + disturbed);
2151
- const registerAxWriteTools = (server, lane) => {
2152
- const place = {
2153
- query: z.string().min(1).describe("The place's name, as you would type it into Maps' search field."),
2154
- latitude: z.number().min(-90).max(90).describe("Latitude of the place."),
2155
- longitude: z.number().min(-180).max(180).describe("Longitude of the place.")
2156
- };
2157
- const openCard = async (args) => lane.openCard({
2158
- name: args.query,
2159
- latitude: args.latitude,
2160
- longitude: args.longitude
2161
- });
2162
- server.registerTool("apple_maps_save_place", {
2163
- description: "Save a place into Maps' Places library, by pressing Add on its card. This is NOT a favourite: the Pinned list is a different set, written by apple_maps_add_favorite. Maps performs the write itself, so it cannot produce a malformed record. SIDE EFFECTS: opens Maps, brings its window forward, and leaves the place in the user's Recents. Syncs to the user's other Apple devices. Needs Accessibility for Cupertino.",
2164
- inputSchema: z.object(place),
2165
- annotations: {
2166
- readOnlyHint: false,
2167
- destructiveHint: false,
2168
- idempotentHint: true
2169
- }
2170
- }, async (args) => wrapResult(async () => {
2171
- const watch = lane.watch();
2172
- const disturbed = async () => interferenceNote(await watch.check());
2173
- if (!await openCard(args)) return noCard(args.query, await disturbed());
2174
- if (await lane.isSaved() === true) return ok({
2175
- saved: true,
2176
- alreadySaved: true,
2177
- query: args.query
2178
- });
2179
- if (!await lane.savePlace()) return fail(`The card for "${args.query}" opened but the naming sheet did not, so nothing was saved. The card may still be on screen.` + await disturbed());
2180
- return await lane.verifySaved({
2181
- name: args.query,
2182
- latitude: args.latitude,
2183
- longitude: args.longitude
2184
- }) === true ? ok({
2185
- saved: true,
2186
- alreadySaved: false,
2187
- query: args.query
2188
- }) : fail(`"${args.query}" was pressed through the save sheet but its card does not report it as saved, so this MUST NOT be reported as done. Check Maps.` + await disturbed());
2189
- }));
2190
- server.registerTool("apple_maps_remove_saved_place", {
2191
- description: "Remove a place from Maps' Places library, through the card's overflow menu. This does NOT touch favourites — use apple_maps_remove_favorite for those. SIDE EFFECTS: opens Maps, brings its window forward, and leaves the place in the user's Recents. Syncs to the user's other Apple devices. Needs Accessibility for Cupertino, and an explicit confirm: the removal is not undoable from here.",
2192
- inputSchema: z.object({
2193
- ...place,
2194
- confirm: confirmArg
2195
- }),
2196
- annotations: {
2197
- readOnlyHint: false,
2198
- destructiveHint: true,
2199
- idempotentHint: true
2200
- }
2201
- }, async (args) => wrapResult(async () => {
2202
- const watch = lane.watch();
2203
- const disturbed = async () => interferenceNote(await watch.check());
2204
- if (!await openCard(args)) return noCard(args.query, await disturbed());
2205
- const outcome = await lane.removePlace();
2206
- if (outcome === "not-saved") return ok({
2207
- removed: false,
2208
- wasSaved: false,
2209
- query: args.query
2210
- });
2211
- if (outcome === "no-menu") return fail(`The card for "${args.query}" opened but its overflow menu did not, so nothing was removed.` + await disturbed());
2212
- return await lane.verifySaved({
2213
- name: args.query,
2214
- latitude: args.latitude,
2215
- longitude: args.longitude
2216
- }) === false ? ok({
2217
- removed: true,
2218
- wasSaved: true,
2219
- query: args.query
2220
- }) : fail(`"${args.query}" was pressed through Delete from Places but its card still reports it as saved, so this MUST NOT be reported as done. Check Maps.` + await disturbed());
2221
- }));
2222
- server.registerTool("apple_maps_add_place_to_guide", {
2223
- description: "File a place into one of Maps' Guides, through the card's Add to Guides picker. This is the write apple_maps_list_collections has no counterpart for. IT CANNOT CONFIRM ITSELF: Maps does not expose whether the place ended up in the guide, so the result says filed: \"unverified\" and it must not be reported as done. The guide must already exist; when the name does not match, the refusal lists every guide Maps offers, which is the authoritative list and can differ from what apple_maps_list_collections returns. SIDE EFFECTS: opens Maps, brings its window forward, and leaves the place in the user's Recents. Syncs to the user's other Apple devices. Needs Accessibility for Cupertino.",
2224
- inputSchema: z.object({
2225
- ...place,
2226
- guide: z.string().min(1).describe("Name of the guide to file it into, as Maps shows it.")
2227
- }),
2228
- annotations: {
2229
- readOnlyHint: false,
2230
- destructiveHint: false,
2231
- idempotentHint: true
2232
- }
2233
- }, async (args) => wrapResult(async () => {
2234
- const watch = lane.watch();
2235
- const disturbed = async () => interferenceNote(await watch.check());
2236
- if (!await openCard(args)) return noCard(args.query, await disturbed());
2237
- const guides = await lane.openGuidePicker();
2238
- if (guides === null) return fail(`The card for "${args.query}" opened but its Add to Guides picker did not, so nothing was filed.` + await disturbed());
2239
- if (!await lane.chooseGuide(args.guide)) {
2240
- await lane.cancelGuidePicker();
2241
- return fail(`Maps offers no guide called "${args.guide}", so nothing was filed. It offers: ${guides.map((g) => g.name).join(", ")}.`, { guides: compactGuides(guides) });
2242
- }
2243
- return ok({
2244
- filed: "unverified",
2245
- query: args.query,
2246
- guide: args.guide,
2247
- guides: compactGuides(guides),
2248
- note: "The guide row and then Done were pressed. Maps does not expose whether the place ended up in the guide — the picker's counts do not refresh in the accessibility tree — so this MUST NOT be reported to the user as filed. Check Maps."
2249
- });
2250
- }));
2251
- };
2252
- const compactGuides = (guides) => guides.map((g) => g.places === null ? { name: g.name } : {
2253
- name: g.name,
2254
- places: g.places
2255
- });
2256
- //#endregion
2257
2229
  //#region src/tools/places.ts
2258
2230
  /**
2259
2231
  * The place tools.
@@ -2386,7 +2358,7 @@ const registerPlaceTools = (server, client) => {
2386
2358
  server.registerTool("apple_maps_search_places", {
2387
2359
  description: "Search every saved place — favourites, collection entries and recents — by name, by the label the user gave it, or by address. Returns each match with the kind of entry it came from. Needs Full Disk Access. This searches what is SAVED on this Mac; it does not search Apple's map of the world.",
2388
2360
  inputSchema: z.object({
2389
- query: queryArg,
2361
+ query: queryArg$1,
2390
2362
  limit: limitArg
2391
2363
  }),
2392
2364
  annotations: {
@@ -2420,84 +2392,6 @@ const registerPlaceTools = (server, client) => {
2420
2392
  }));
2421
2393
  };
2422
2394
  //#endregion
2423
- //#region src/tools/writes.ts
2424
- /**
2425
- * The mutating tools.
2426
- *
2427
- * Registered only when `APPLE_MAPS_ALLOW_WRITES` is true, so a host that has not
2428
- * opted in is never told they exist — the same gate every other surface uses.
2429
- *
2430
- * ## Two things these descriptions must say, because they are surprising
2431
- *
2432
- * **Adding a favourite leaves an entry in Recents.** A place is only real to
2433
- * Maps once it has a GEO record, and the only thing that can produce one is Maps
2434
- * itself: the place is opened through the `maps://` URL scheme, Maps resolves it
2435
- * and files it in Recents, and that record is copied into the favourite. There
2436
- * is no way to have the first without the second, so the caller is told rather
2437
- * than surprised. When the place is already known to the store, no seeding
2438
- * happens and no Recents entry appears.
2439
- *
2440
- * **It reaches the user's other devices.** The store is mirrored by
2441
- * `NSPersistentCloudKitContainer`, which reconciles on the app's next save
2442
- * whether or not it was told anything. A favourite added here arrived on an
2443
- * iPhone. That makes this the one write in the bundle whose blast radius is
2444
- * larger than the machine it runs on, and the descriptions say so.
2445
- */
2446
- const registerWriteTools = (server, client) => {
2447
- server.registerTool("apple_maps_add_favorite", {
2448
- description: "Save a place to Maps' favourites (the Pinned list). Give the place NAME as `query` — a bare coordinate does not identify a place to Maps — and latitude/longitude when known, which makes the match exact and skips the lookup. SIDE EFFECT: unless the place is already in the store, Maps is asked to resolve it and the place also appears in the user's Recents; there is no way to add a favourite without that. The favourite syncs to the user's other Apple devices through iCloud. Idempotent: asking twice for the same place returns the existing favourite rather than creating a second. Needs Full Disk Access.",
2449
- inputSchema: z.object({
2450
- query: z.string().min(1).describe("The place's name, as you would type it into Maps' search field."),
2451
- latitude: z.number().min(-90).max(90).optional().describe("Latitude, when known."),
2452
- longitude: z.number().min(-180).max(180).optional().describe("Longitude, when known."),
2453
- name: z.string().min(1).optional().describe("Label to save it under. Defaults to `query`.")
2454
- }),
2455
- annotations: {
2456
- readOnlyHint: false,
2457
- idempotentHint: true
2458
- }
2459
- }, async ({ query, latitude, longitude, name }) => wrapResult(async () => {
2460
- const result = await client.writer().addFavorite({
2461
- query,
2462
- latitude,
2463
- longitude,
2464
- name
2465
- });
2466
- return ok(compact({
2467
- favorite: {
2468
- ref: `p1:f:${result.uuid.replaceAll("-", "")}`,
2469
- name: result.name,
2470
- latitude: result.latitude,
2471
- longitude: result.longitude
2472
- },
2473
- created: result.created,
2474
- alreadyExisted: result.created ? void 0 : "A favourite for this place already existed and was returned unchanged.",
2475
- recentsNote: result.seeded ? "Maps was asked to resolve this place, so it now also appears in the user's Recents. That is how the place record is obtained and cannot be avoided." : void 0,
2476
- syncNote: "This favourite will reach the user's other Apple devices through iCloud once Maps next runs."
2477
- }));
2478
- }));
2479
- server.registerTool("apple_maps_remove_favorite", {
2480
- description: "Remove a place from Maps' favourites, by a ref from apple_maps_list_favorites. This deletes the favourite on the user's other Apple devices too, through iCloud. It does not affect Guides, Recents, or anything else that references the same place. Needs Full Disk Access, and an explicit confirm: the deletion is not undoable from here.",
2481
- inputSchema: z.object({
2482
- ref: placeRefArg,
2483
- confirm: confirmArg
2484
- }),
2485
- annotations: {
2486
- readOnlyHint: false,
2487
- idempotentHint: true,
2488
- destructiveHint: true
2489
- }
2490
- }, async ({ ref }) => wrapResult(async () => {
2491
- const { kind, key } = decodePlaceRef(ref);
2492
- if (kind !== "favorite") return fail(`That ref points at a ${kind === "history" ? "recent" : "collection entry"}, not a favourite. Only favourites can be removed; pass a ref from apple_maps_list_favorites.`);
2493
- if (!client.writer().removeFavorite(key)) return fail("No favourite matched that ref. It may already have been removed, or the listing it came from may predate a change. Re-run apple_maps_list_favorites.");
2494
- return ok({
2495
- removed: true,
2496
- syncNote: "The removal will reach the user's other Apple devices through iCloud once Maps next runs."
2497
- });
2498
- }));
2499
- };
2500
- //#endregion
2501
2395
  //#region src/tools/index.ts
2502
2396
  /**
2503
2397
  * Register the Apple Maps tools.
@@ -2512,9 +2406,8 @@ const registerTools = (server, client, ctx) => {
2512
2406
  registerDiagnosticsTools(server, client);
2513
2407
  registerPlaceTools(server, client);
2514
2408
  if (!ctx.allowWrites) return;
2515
- registerWriteTools(server, client);
2516
- const ax = client.axLane;
2517
- if (ax) registerAxWriteTools(server, ax);
2409
+ const lane = client.lane;
2410
+ if (lane) registerStoreWriteTools(server, client, lane);
2518
2411
  };
2519
2412
  //#endregion
2520
2413
  //#region src/server.ts
@@ -2563,4 +2456,4 @@ const createServer = (opts) => {
2563
2456
  //#endregion
2564
2457
  export { fromStoreTime as A, MAPS_SURFACE as C, UndatableStoreError as D, SchemaDriftError$1 as E, resolveEpoch as M, BUILD_INFO as N, APPLE_SECONDS as O, MAPS_BUNDLE_ID as S, PlaceNotFoundError as T, defaultDirectory as _, loadConfig as a, AppleMapsError as b, introspect as c, InvalidMapsRefError as d, PLACE_REF_VERSION as f, encodePlaceRef as g, encodeCollectionRef as h, registerTools as i, renderInstant as j, CORE_DATA_EPOCH_OFFSET as k, openStore as l, decodePlaceRef as m, SERVER_VERSION as n, AppleMapsClient as o, decodeCollectionRef as p, createServer as r, MapsStore as s, SERVER_NAME as t, COLLECTION_REF_VERSION as u, defaultStorePath as v, MapsStoreUnavailableError as w, IndexUnavailableError as x, locateStore as y };
2565
2458
 
2566
- //# sourceMappingURL=server-C5JyIvr1.js.map
2459
+ //# sourceMappingURL=server-QidAKfSq.js.map