Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e80cbaf388 | ||
|
|
0bff3c9794 |
No files matched your search
+1
-1
@@ -136,7 +136,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
|
||||
});
|
||||
|
||||
await registerAuthRoutes(app, { db, config, sessions });
|
||||
await registerMeRoutes(app, { db, sessions });
|
||||
await registerMeRoutes(app, { db, sessions, broadcaster });
|
||||
await registerCalendarRoutes(app, { sessions, calendar: new CalendarService({ db, secrets, ...(fetchImpl && { fetchImpl }) }) });
|
||||
await registerOrgRoutes(app, { db, sessions });
|
||||
await registerEventRoutes(app, { db, sessions, sports, broadcaster });
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { MODULES } from "@photoreport/contracts";
|
||||
import { DeskCommand, MODULES } from "@photoreport/contracts";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { currentUserId, requireAuth } from "../auth/guard.js";
|
||||
import type { SessionService } from "../auth/sessions.js";
|
||||
import type { Db } from "../db.js";
|
||||
import { notFound } from "../lib/errors.js";
|
||||
import { silentBroadcaster, type Broadcaster } from "../realtime.js";
|
||||
|
||||
const PreferencesBody = z.object({
|
||||
editorModules: z
|
||||
@@ -13,8 +14,9 @@ const PreferencesBody = z.object({
|
||||
.transform((mods) => [...new Set(mods)]),
|
||||
});
|
||||
|
||||
export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService }) {
|
||||
export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; broadcaster?: Broadcaster }) {
|
||||
const { db } = deps;
|
||||
const broadcaster = deps.broadcaster ?? silentBroadcaster;
|
||||
const authenticate = requireAuth(deps.sessions);
|
||||
|
||||
app.get("/v1/me", { preHandler: authenticate }, async (req) => {
|
||||
@@ -52,4 +54,11 @@ export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; ses
|
||||
});
|
||||
return { editorModules: prefs.editorModules };
|
||||
});
|
||||
|
||||
/** The assistant asks the open PhotoReport of this person to change module, photo or tool. */
|
||||
app.post("/v1/me/desk", { preHandler: authenticate }, async (req) => {
|
||||
const command = DeskCommand.parse(req.body);
|
||||
broadcaster.desk(currentUserId(req), command);
|
||||
return { ok: true as const };
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { LIBRARY_CHANNEL, type LibraryMessage, roomForOrg, roomForUser } from "@photoreport/contracts";
|
||||
import { LIBRARY_CHANNEL, type DeskCommand, type LibraryMessage, roomForOrg, roomForUser } from "@photoreport/contracts";
|
||||
import type { Server as HttpServer } from "node:http";
|
||||
import pg from "pg";
|
||||
import { Server } from "socket.io";
|
||||
@@ -8,17 +8,23 @@ import type { Db } from "./db.js";
|
||||
/** Anything that can push library messages to the people of an organization. */
|
||||
export interface Broadcaster {
|
||||
library(organizationId: string, message: LibraryMessage): void;
|
||||
/** The open PhotoReport of this user: change module, photo or tool. */
|
||||
desk(userId: string, command: DeskCommand): void;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export const silentBroadcaster: Broadcaster = { library: () => {}, close: async () => {} };
|
||||
export const silentBroadcaster: Broadcaster = { library: () => {}, desk: () => {}, close: async () => {} };
|
||||
|
||||
/** Records messages; used by tests. */
|
||||
export class MemoryBroadcaster implements Broadcaster {
|
||||
readonly sent: { organizationId: string; message: LibraryMessage }[] = [];
|
||||
readonly deskSent: { userId: string; command: DeskCommand }[] = [];
|
||||
library(organizationId: string, message: LibraryMessage): void {
|
||||
this.sent.push({ organizationId, message });
|
||||
}
|
||||
desk(userId: string, command: DeskCommand): void {
|
||||
this.deskSent.push({ userId, command });
|
||||
}
|
||||
async close(): Promise<void> {}
|
||||
}
|
||||
|
||||
@@ -27,6 +33,8 @@ export class MemoryBroadcaster implements Broadcaster {
|
||||
* delivers to its own sockets, the ingest worker only publishes. No Redis, no sticky sessions.
|
||||
*/
|
||||
const PG_CHANNEL = "photoreport_realtime";
|
||||
/** Window instructions, delivered to one person's sockets (not the whole organization). */
|
||||
const DESK_CHANNEL = "photoreport_desk";
|
||||
/** NOTIFY payloads are limited to 8000 bytes; batch updates are split so each message fits. */
|
||||
const IDS_PER_MESSAGE = 100;
|
||||
|
||||
@@ -113,8 +121,14 @@ export function attachRealtime(
|
||||
if (closed) return;
|
||||
const client = new pg.Client({ connectionString: deps.databaseUrl });
|
||||
client.on("notification", (n) => {
|
||||
if (n.channel !== PG_CHANNEL || !n.payload) return;
|
||||
if (!n.payload) return;
|
||||
try {
|
||||
if (n.channel === DESK_CHANNEL) {
|
||||
const { userId, command } = JSON.parse(n.payload) as { userId: string; command: DeskCommand };
|
||||
io.to(roomForUser(userId)).emit("desk", command);
|
||||
return;
|
||||
}
|
||||
if (n.channel !== PG_CHANNEL) return;
|
||||
const { organizationId, message } = JSON.parse(n.payload) as Envelope;
|
||||
io.to(roomForOrg(organizationId)).emit(LIBRARY_CHANNEL, message);
|
||||
} catch (err) {
|
||||
@@ -132,6 +146,7 @@ export function attachRealtime(
|
||||
return;
|
||||
}
|
||||
await client.query(`LISTEN ${PG_CHANNEL}`);
|
||||
await client.query(`LISTEN ${DESK_CHANNEL}`);
|
||||
listener = client;
|
||||
};
|
||||
const ready = listen().catch((err) => {
|
||||
@@ -139,8 +154,18 @@ export function attachRealtime(
|
||||
if (!closed) retry = setTimeout(() => void listen().catch(onError), 1000);
|
||||
});
|
||||
|
||||
const desk = (userId: string, command: DeskCommand) => {
|
||||
if (closed) return;
|
||||
const q = pool.query("SELECT pg_notify($1, $2)", [DESK_CHANNEL, JSON.stringify({ userId, command })]).catch((err) => {
|
||||
if (closed && isPoolEndedError(err)) return;
|
||||
onError(err);
|
||||
});
|
||||
trackPending(pending)(q);
|
||||
};
|
||||
|
||||
return {
|
||||
library: publisher(pool, onError, () => closed, trackPending(pending)),
|
||||
desk,
|
||||
close: async () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
@@ -159,8 +184,17 @@ export function createRemoteBroadcaster(databaseUrl: string, onError: (err: unkn
|
||||
const pool = new pg.Pool({ connectionString: databaseUrl, max: 1 });
|
||||
let closed = false;
|
||||
const pending = new Set<Promise<unknown>>();
|
||||
const desk = (userId: string, command: DeskCommand) => {
|
||||
if (closed) return;
|
||||
const q = pool.query("SELECT pg_notify($1, $2)", [DESK_CHANNEL, JSON.stringify({ userId, command })]).catch((err) => {
|
||||
if (closed && isPoolEndedError(err)) return;
|
||||
onError(err);
|
||||
});
|
||||
trackPending(pending)(q);
|
||||
};
|
||||
return {
|
||||
library: publisher(pool, onError, () => closed, trackPending(pending)),
|
||||
desk,
|
||||
close: async () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { deskPath, type DeskCommand } from "@photoreport/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deskState } from "./desk.js";
|
||||
|
||||
const show = (patch: Partial<DeskCommand>): DeskCommand => ({ module: "library", ...patch });
|
||||
|
||||
describe("deskPath", () => {
|
||||
it("opens the library at the front page", () => {
|
||||
expect(deskPath(show({ module: "library" }))).toBe("/");
|
||||
});
|
||||
|
||||
it("opens one photo in develop", () => {
|
||||
expect(deskPath(show({ module: "develop", photoId: "11111111-1111-4111-8111-111111111111" }))).toBe("/develop/11111111-1111-4111-8111-111111111111");
|
||||
});
|
||||
|
||||
it("opens a shop tab", () => {
|
||||
expect(deskPath(show({ module: "shop", section: "orders" }))).toBe("/shop?tab=orders");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deskState", () => {
|
||||
it("asks develop to start on the crop", () => {
|
||||
expect(deskState(show({ module: "develop", tool: "crop" }))).toEqual({ crop: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { deskPath, type DeskCommand } from "@photoreport/contracts";
|
||||
|
||||
export { deskPath };
|
||||
export type { DeskCommand };
|
||||
|
||||
/** Where a develop tool is asked for. Crop and white balance already open from this state. */
|
||||
export function deskState(command: DeskCommand): { crop?: boolean; picking?: boolean; spotting?: boolean } | null {
|
||||
if (command.tool === "crop") return { crop: true };
|
||||
if (command.tool === "wb") return { picking: true };
|
||||
if (command.tool === "spot") return { spotting: true };
|
||||
return null;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { LIBRARY_CHANNEL, type LibraryMessage } from "@photoreport/contracts";
|
||||
import { LIBRARY_CHANNEL, type DeskCommand, type LibraryMessage } from "@photoreport/contracts";
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { io } from "socket.io-client";
|
||||
@@ -40,6 +40,9 @@ export function useLibraryLive(api: ApiClient, onMessage: (message: LibraryMessa
|
||||
socket.on("disconnect", () => setState("offline"));
|
||||
socket.on("connect_error", () => setState("offline"));
|
||||
socket.on(LIBRARY_CHANNEL, (message: LibraryMessage) => handler.current(message));
|
||||
socket.on("desk", (command: DeskCommand) => {
|
||||
window.dispatchEvent(new CustomEvent("photoreport-desk", { detail: command }));
|
||||
});
|
||||
return () => {
|
||||
socket.close();
|
||||
};
|
||||
|
||||
@@ -684,16 +684,18 @@ export function DevelopPage() {
|
||||
// R in the library: the photo opens here with the crop tool on, once it is loaded (opening a photo turns it off).
|
||||
const location = useLocation();
|
||||
// W: with the white balance eyedropper.
|
||||
const asked = location.state as { crop?: boolean; picking?: boolean } | null;
|
||||
const asked = location.state as { crop?: boolean; picking?: boolean; spotting?: boolean } | null;
|
||||
const cropAsked = asked?.crop === true;
|
||||
const pickAsked = asked?.picking === true;
|
||||
const spotAsked = asked?.spotting === true;
|
||||
const loadedId = session?.loaded ? session.photoId : null;
|
||||
useEffect(() => {
|
||||
if ((!cropAsked && !pickAsked) || !loadedId || loadedId !== current?.id) return;
|
||||
if ((!cropAsked && !pickAsked && !spotAsked) || !loadedId || loadedId !== current?.id) return;
|
||||
if (canEdit && cropAsked) setCropping(true);
|
||||
if (canEdit && pickAsked) setPicking(true);
|
||||
if (canEdit && spotAsked) setSpotting(true);
|
||||
navigate(".", { replace: true, state: null });
|
||||
}, [cropAsked, pickAsked, loadedId, current?.id, canEdit, navigate]);
|
||||
}, [cropAsked, pickAsked, spotAsked, loadedId, current?.id, canEdit, navigate]);
|
||||
|
||||
// Entering crop on a photo that was never cropped: it starts with the default aspect (the last one chosen).
|
||||
const defaulted = useRef(new Set<string>());
|
||||
|
||||
@@ -191,6 +191,15 @@ export function LibraryPage() {
|
||||
[api, orgId, state.scope],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onOpen = (ev: Event) => {
|
||||
const id = (ev as CustomEvent<string>).detail;
|
||||
if (typeof id === "string" && id) void open(id).catch(() => setError(t.unexpectedError));
|
||||
};
|
||||
window.addEventListener("photoreport-open-event", onOpen);
|
||||
return () => window.removeEventListener("photoreport-open-event", onOpen);
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
let alive = true;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { hasRole } from "@photoreport/sdk";
|
||||
import { NavLink, Outlet } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import { NavLink, Outlet, useNavigate } from "react-router";
|
||||
import { deskPath, deskState, type DeskCommand } from "../desk.js";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { Bell } from "../components/Bell.js";
|
||||
import { Logo } from "../components/ui.js";
|
||||
@@ -140,6 +142,7 @@ export function Shell() {
|
||||
</div>
|
||||
</details>
|
||||
</header>
|
||||
<DeskHost />
|
||||
<UpdateNotice />
|
||||
<UiReadyNotice />
|
||||
<LocalDeliveries />
|
||||
@@ -156,6 +159,22 @@ export function Shell() {
|
||||
);
|
||||
}
|
||||
|
||||
/** Follows the assistant: the open window changes module, photo or tool. */
|
||||
function DeskHost() {
|
||||
const navigate = useNavigate();
|
||||
useEffect(() => {
|
||||
const onDesk = (ev: Event) => {
|
||||
const command = (ev as CustomEvent<DeskCommand>).detail;
|
||||
if (!command || typeof command.module !== "string") return;
|
||||
navigate(deskPath(command), { state: deskState(command) });
|
||||
if (command.eventId) window.dispatchEvent(new CustomEvent("photoreport-open-event", { detail: command.eventId }));
|
||||
};
|
||||
window.addEventListener("photoreport-desk", onDesk);
|
||||
return () => window.removeEventListener("photoreport-desk", onDesk);
|
||||
}, [navigate]);
|
||||
return null;
|
||||
}
|
||||
|
||||
function initials(name: string): string {
|
||||
return name
|
||||
.split(/\s+/)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "@photoreport/mcp",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"photoreport-mcp": "dist/index.js"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run",
|
||||
"start": "node dist/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/server": "^2.3.1",
|
||||
"@photoreport/contracts": "workspace:*",
|
||||
"@photoreport/sdk": "workspace:*",
|
||||
"zod": "^4.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { getControl } from "@photoreport/contracts";
|
||||
|
||||
/** Checks each develop value against the engine's control list before it is sent. */
|
||||
export function developValues(input: Record<string, number>): Record<string, number> {
|
||||
const out: Record<string, number> = {};
|
||||
for (const [id, value] of Object.entries(input)) {
|
||||
const control = getControl(id);
|
||||
if (!control) throw new Error(`Unknown control "${id}". Call photoreport_develop_controls for the ids and ranges.`);
|
||||
if (!Number.isFinite(value) || value < control.min || value > control.max) {
|
||||
throw new Error(`${id} is ${value}. It must be between ${control.min} and ${control.max} (default ${control.default}).`);
|
||||
}
|
||||
out[id] = value;
|
||||
}
|
||||
if (Object.keys(out).length === 0) throw new Error("No controls to change.");
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* PhotoReport assistant. Speaks MCP over stdio and calls the PhotoReport API
|
||||
* as the signed-in photographer. Stdout is the protocol; logs go to stderr.
|
||||
*/
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
||||
import { registerAccount } from "./tools/account.js";
|
||||
import { registerDelivery } from "./tools/delivery.js";
|
||||
import { registerDevelop } from "./tools/develop.js";
|
||||
import { registerLibrary } from "./tools/library.js";
|
||||
import { registerScreen } from "./tools/screen.js";
|
||||
import { registerTeach } from "./tools/teach.js";
|
||||
|
||||
export function createServer(): McpServer {
|
||||
const server = new McpServer({ name: "photoreport", version: "0.1.0" });
|
||||
registerAccount(server);
|
||||
registerScreen(server);
|
||||
registerLibrary(server);
|
||||
registerDevelop(server);
|
||||
registerDelivery(server);
|
||||
registerTeach(server);
|
||||
return server;
|
||||
}
|
||||
|
||||
const isMain = process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href;
|
||||
if (isMain) {
|
||||
serveStdio(createServer);
|
||||
console.error("photoreport-mcp on stdio");
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import { failText } from "./session.js";
|
||||
|
||||
type ToolContent = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string };
|
||||
type ToolResult = { content: ToolContent[]; isError?: boolean };
|
||||
|
||||
/** Tool results the model reads. Lists are already capped by the caller. */
|
||||
export function text(body: string): ToolResult {
|
||||
return { content: [{ type: "text", text: body }] };
|
||||
}
|
||||
|
||||
export function textAndImages(body: string, images: { data: string; mimeType: string }[]): ToolResult {
|
||||
return {
|
||||
content: [
|
||||
{ type: "text", text: body },
|
||||
...images.map((image) => ({ type: "image" as const, data: image.data, mimeType: image.mimeType })),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export async function guard(work: () => Promise<ToolResult>): Promise<ToolResult> {
|
||||
try {
|
||||
return await work();
|
||||
} catch (err) {
|
||||
return { isError: true, content: [{ type: "text", text: failText(err) }] };
|
||||
}
|
||||
}
|
||||
|
||||
export type Server = McpServer;
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { developValues } from "./edits.js";
|
||||
import { reviewPhotos } from "./review.js";
|
||||
|
||||
function photo(patch: Partial<PhotoSummary>): PhotoSummary {
|
||||
return {
|
||||
id: "p",
|
||||
eventId: "e",
|
||||
originalName: "a.jpg",
|
||||
name: "a.jpg",
|
||||
sha256: "abc",
|
||||
originalStored: true,
|
||||
status: "READY",
|
||||
width: 1000,
|
||||
height: 800,
|
||||
capturedAt: null,
|
||||
cameraModel: null,
|
||||
lens: null,
|
||||
focalLength: null,
|
||||
aperture: null,
|
||||
exposureTime: null,
|
||||
iso: null,
|
||||
rating: 0,
|
||||
flag: "NONE",
|
||||
colorLabel: "NONE",
|
||||
players: [],
|
||||
uploader: null,
|
||||
developSeq: 0,
|
||||
urls: { thumb: "", preview: "", source: "" },
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
describe("reviewPhotos", () => {
|
||||
it("counts the frames a photographer still has to look at", () => {
|
||||
const report = reviewPhotos([
|
||||
photo({ id: "1", name: "pick.jpg", flag: "PICK" }),
|
||||
photo({ id: "2", name: "bad.jpg", status: "FAILED", error: "truncated" }),
|
||||
photo({ id: "3", name: "sent.jpg", flag: "PICK", developSeq: 4, delivery: "DONE", players: ["Ana"] }),
|
||||
]);
|
||||
expect(report.picks).toBe(2);
|
||||
expect(report.uneditedPicks).toBe(1);
|
||||
expect(report.failed).toBe(1);
|
||||
expect(report.unsentPicks).toBe(1);
|
||||
expect(report.lookAt.map((note) => note.name)).toEqual(["pick.jpg", "bad.jpg"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("developValues", () => {
|
||||
it("refuses a control the engine does not have", () => {
|
||||
expect(() => developValues({ "light.nope": 1 })).toThrow(/Unknown control/);
|
||||
});
|
||||
|
||||
it("refuses a value outside the range", () => {
|
||||
expect(() => developValues({ "light.exposure": 99 })).toThrow(/between/);
|
||||
});
|
||||
|
||||
it("keeps a value inside the range", () => {
|
||||
expect(developValues({ "light.exposure": 0.2 })).toEqual({ "light.exposure": 0.2 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
|
||||
export interface ReviewNote {
|
||||
id: string;
|
||||
name: string;
|
||||
reasons: string[];
|
||||
}
|
||||
|
||||
export interface ReviewReport {
|
||||
total: number;
|
||||
ready: number;
|
||||
failed: number;
|
||||
processing: number;
|
||||
picks: number;
|
||||
rejects: number;
|
||||
unrated: number;
|
||||
uneditedPicks: number;
|
||||
withoutPlayers: number;
|
||||
deliveryFailed: number;
|
||||
unsentPicks: number;
|
||||
lookAt: ReviewNote[];
|
||||
}
|
||||
|
||||
/**
|
||||
* What a photographer (or the assistant) should look at. Sharpness is not on the photo row: a face tool
|
||||
* answers that. This uses the catalogue: flags, ratings, edits, players and delivery.
|
||||
*/
|
||||
export function reviewPhotos(photos: PhotoSummary[], limit = 20): ReviewReport {
|
||||
const lookAt: ReviewNote[] = [];
|
||||
let ready = 0;
|
||||
let failed = 0;
|
||||
let processing = 0;
|
||||
let picks = 0;
|
||||
let rejects = 0;
|
||||
let unrated = 0;
|
||||
let uneditedPicks = 0;
|
||||
let withoutPlayers = 0;
|
||||
let deliveryFailed = 0;
|
||||
let unsentPicks = 0;
|
||||
|
||||
for (const photo of photos) {
|
||||
if (photo.status === "READY") ready += 1;
|
||||
else if (photo.status === "FAILED") failed += 1;
|
||||
else processing += 1;
|
||||
if (photo.flag === "PICK") picks += 1;
|
||||
if (photo.flag === "REJECT") rejects += 1;
|
||||
if (photo.rating === 0 && photo.flag === "NONE") unrated += 1;
|
||||
if (photo.flag === "PICK" && photo.developSeq === 0) uneditedPicks += 1;
|
||||
if (photo.players.length === 0 && photo.flag !== "REJECT") withoutPlayers += 1;
|
||||
if (photo.delivery === "FAILED") deliveryFailed += 1;
|
||||
if (photo.flag === "PICK" && photo.delivery !== "DONE" && photo.delivery !== "QUEUED") unsentPicks += 1;
|
||||
|
||||
const reasons: string[] = [];
|
||||
if (photo.status === "FAILED") reasons.push(photo.error ? `failed to read (${photo.error})` : "failed to read");
|
||||
if (photo.delivery === "FAILED") reasons.push("delivery failed");
|
||||
if (photo.flag === "PICK" && photo.developSeq === 0) reasons.push("pick with no edit yet");
|
||||
if (photo.flag === "NONE" && photo.rating === 0 && photo.status === "READY") reasons.push("not culled");
|
||||
if (reasons.length && lookAt.length < limit) lookAt.push({ id: photo.id, name: photo.name, reasons });
|
||||
}
|
||||
|
||||
return {
|
||||
total: photos.length,
|
||||
ready,
|
||||
failed,
|
||||
processing,
|
||||
picks,
|
||||
rejects,
|
||||
unrated,
|
||||
uneditedPicks,
|
||||
withoutPlayers,
|
||||
deliveryFailed,
|
||||
unsentPicks,
|
||||
lookAt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { ApiClient, ApiError, type RefreshTokenStore } from "@photoreport/sdk";
|
||||
|
||||
/** Where the assistant's refresh token lives. Never printed. */
|
||||
export const sessionFile = process.env.PHOTOREPORT_SESSION_FILE ?? join(homedir(), ".config", "photoreport", "mcp-session.json");
|
||||
|
||||
interface Saved {
|
||||
refreshToken?: string;
|
||||
deviceCode?: string;
|
||||
userCode?: string;
|
||||
}
|
||||
|
||||
async function readSaved(): Promise<Saved> {
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(sessionFile, "utf8")) as unknown;
|
||||
if (!parsed || typeof parsed !== "object") return {};
|
||||
return parsed as Saved;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
async function writeSaved(next: Saved): Promise<void> {
|
||||
await mkdir(dirname(sessionFile), { recursive: true });
|
||||
await writeFile(sessionFile, JSON.stringify(next), { mode: 0o600 });
|
||||
await chmod(sessionFile, 0o600);
|
||||
}
|
||||
|
||||
const store: RefreshTokenStore = {
|
||||
async get() {
|
||||
const saved = await readSaved();
|
||||
return saved.refreshToken ?? process.env.PHOTOREPORT_REFRESH_TOKEN ?? null;
|
||||
},
|
||||
async set(token: string) {
|
||||
const saved = await readSaved();
|
||||
saved.refreshToken = token;
|
||||
delete saved.deviceCode;
|
||||
delete saved.userCode;
|
||||
await writeSaved(saved);
|
||||
},
|
||||
async clear() {
|
||||
const saved = await readSaved();
|
||||
delete saved.refreshToken;
|
||||
await writeSaved(saved);
|
||||
},
|
||||
};
|
||||
|
||||
export const api = new ApiClient({
|
||||
baseUrl: (process.env.PHOTOREPORT_API_URL ?? "https://api.next.photoreport.pt").replace(/\/$/, ""),
|
||||
refreshStore: store,
|
||||
});
|
||||
|
||||
const SIGN_IN = "Not signed in. Call photoreport_connect, approve the code in PhotoReport (the bell, or the link), then photoreport_connect_finish.";
|
||||
|
||||
/** Restores the saved session, or signs in with PHOTOREPORT_EMAIL and PHOTOREPORT_PASSWORD when both are set. */
|
||||
export async function ensureSession(): Promise<void> {
|
||||
if (api.isAuthenticated) return;
|
||||
const email = process.env.PHOTOREPORT_EMAIL;
|
||||
const password = process.env.PHOTOREPORT_PASSWORD;
|
||||
if (email && password) {
|
||||
await api.login(email, password, "PhotoReport assistant");
|
||||
return;
|
||||
}
|
||||
if (!(await api.resume())) throw new Error(SIGN_IN);
|
||||
}
|
||||
|
||||
let cachedOrg: string | null = process.env.PHOTOREPORT_ORG_ID ?? null;
|
||||
|
||||
/** The organization to work in: the argument, PHOTOREPORT_ORG_ID, or the account's first one. */
|
||||
export async function orgId(given?: string): Promise<string> {
|
||||
if (given) return given;
|
||||
if (cachedOrg) return cachedOrg;
|
||||
await ensureSession();
|
||||
const me = await api.me();
|
||||
const id = me.memberships[0]?.organization.id;
|
||||
if (!id) throw new Error("This account belongs to no organization.");
|
||||
cachedOrg = id;
|
||||
return id;
|
||||
}
|
||||
|
||||
export async function beginConnect(): Promise<{ userCode: string; url: string; expiresIn: number }> {
|
||||
const grant = await api.startDeviceLogin("PhotoReport assistant");
|
||||
const saved = await readSaved();
|
||||
saved.deviceCode = grant.deviceCode;
|
||||
saved.userCode = grant.userCode;
|
||||
await writeSaved(saved);
|
||||
return { userCode: grant.userCode, url: grant.verificationUriComplete, expiresIn: grant.expiresIn };
|
||||
}
|
||||
|
||||
export async function finishConnect(): Promise<"approved" | "pending" | "expired" | "denied"> {
|
||||
const saved = await readSaved();
|
||||
if (!saved.deviceCode) throw new Error("No sign-in in progress. Call photoreport_connect first.");
|
||||
const result = await api.pollDeviceLogin(saved.deviceCode);
|
||||
if (result.status === "approved") return "approved";
|
||||
if (result.status === "pending" || result.status === "slow_down") return "pending";
|
||||
if (result.status === "denied") return "denied";
|
||||
return "expired";
|
||||
}
|
||||
|
||||
export async function disconnect(): Promise<void> {
|
||||
await ensureSession();
|
||||
await api.logout();
|
||||
cachedOrg = process.env.PHOTOREPORT_ORG_ID ?? null;
|
||||
}
|
||||
|
||||
/** What the model should read when a call fails. */
|
||||
export function failText(err: unknown): string {
|
||||
if (err instanceof ApiError) {
|
||||
if (err.status === 401) return `${SIGN_IN} (${err.code})`;
|
||||
if (err.status === 403) return `Not allowed (${err.code}). This account's role cannot do that.`;
|
||||
if (err.status === 404) return `Not found (${err.code}). Check the id from a list tool.`;
|
||||
return `The API refused the call (${err.status} ${err.code}).`;
|
||||
}
|
||||
if (err instanceof Error) return err.message;
|
||||
return "The call failed.";
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import * as z from "zod/v4";
|
||||
import { api, beginConnect, disconnect, ensureSession, finishConnect, orgId } from "../session.js";
|
||||
import { guard, text, type Server } from "../result.js";
|
||||
|
||||
export function registerAccount(server: Server): void {
|
||||
server.registerTool(
|
||||
"photoreport_connect",
|
||||
{
|
||||
title: "Sign in to PhotoReport",
|
||||
description: "Starts a sign-in. Returns a short code and a link. The photographer approves it in the PhotoReport app, then call photoreport_connect_finish. The refresh token stays on this computer and is never returned.",
|
||||
annotations: { readOnlyHint: false, openWorldHint: true, idempotentHint: true },
|
||||
},
|
||||
async () =>
|
||||
guard(async () => {
|
||||
const grant = await beginConnect();
|
||||
return text(`Approve this code in PhotoReport: ${grant.userCode}\n${grant.url}\nIt expires in ${grant.expiresIn} seconds. Then call photoreport_connect_finish.`);
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_connect_finish",
|
||||
{
|
||||
title: "Finish PhotoReport sign-in",
|
||||
description: "Checks whether the photographer approved photoreport_connect. Call again in a few seconds while the status is pending.",
|
||||
annotations: { readOnlyHint: false, openWorldHint: true },
|
||||
},
|
||||
async () =>
|
||||
guard(async () => {
|
||||
const status = await finishConnect();
|
||||
if (status === "approved") return text("Signed in. Call photoreport_whoami to see the account and organization.");
|
||||
if (status === "pending") return text("Still waiting. Ask the photographer to approve the code, then call this again.");
|
||||
if (status === "denied") return text("The photographer refused. Call photoreport_connect to start again.");
|
||||
return text("The code expired. Call photoreport_connect to start again.");
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_disconnect",
|
||||
{
|
||||
title: "Sign out of PhotoReport",
|
||||
description: "Forgets the assistant's PhotoReport session on this computer.",
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
async () =>
|
||||
guard(async () => {
|
||||
await disconnect();
|
||||
return text("Signed out.");
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_whoami",
|
||||
{
|
||||
title: "Who is signed in",
|
||||
description: "The signed-in photographer and their organizations. Use the organization id in later calls when they belong to more than one. Example: who am I working as?",
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async () =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const me = await api.me();
|
||||
const lines = [`${me.user.name} <${me.user.email}>`];
|
||||
for (const membership of me.memberships) {
|
||||
lines.push(`- ${membership.organization.name} (${membership.organization.id}) role ${membership.role}`);
|
||||
}
|
||||
if (me.memberships.length === 0) lines.push("No organization.");
|
||||
return text(lines.join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_list_events",
|
||||
{
|
||||
title: "List events",
|
||||
description: "Events in the organization, newest ingest window first as the API returns them. Use this to find the match the photographer is shooting before listing photos or sending. Pass archived to include closed events.",
|
||||
inputSchema: z.object({
|
||||
organizationId: z.string().optional().describe("Organization id. Defaults to PHOTOREPORT_ORG_ID or the account's first organization."),
|
||||
archived: z.boolean().default(false).describe("Include archived events."),
|
||||
}),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ organizationId, archived }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(organizationId);
|
||||
const { events } = await api.listEvents(id, archived ? { includeArchived: true } : {});
|
||||
if (events.length === 0) return text("No events.");
|
||||
const lines = events.slice(0, 40).map((event) => {
|
||||
const match = event.away ? `${event.home} x ${event.away}` : event.home;
|
||||
return `- ${match} (${event.id}) ${event.startsAt} · ${event.photoCount} photos${event.archivedAt ? " · archived" : ""}`;
|
||||
});
|
||||
if (events.length > 40) lines.push(`… ${events.length - 40} more. Narrow by asking for one event id.`);
|
||||
return text(lines.join("\n"));
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import type { PhotoQuery } from "@photoreport/sdk";
|
||||
import * as z from "zod/v4";
|
||||
import { api, ensureSession, orgId } from "../session.js";
|
||||
import { guard, text, type Server } from "../result.js";
|
||||
|
||||
export function registerDelivery(server: Server): void {
|
||||
server.registerTool(
|
||||
"photoreport_list_destinations",
|
||||
{
|
||||
title: "List send destinations",
|
||||
description: "Where photos can be sent (FTP, SFTP, Nextcloud, a local folder, and the rest). Use the name or id with photoreport_send_photos. Example: where can I send this match?",
|
||||
inputSchema: z.object({ organizationId: z.string().optional() }),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ organizationId }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(organizationId);
|
||||
const { targets } = await api.listDeliveryTargets(id);
|
||||
if (targets.length === 0) return text("No destinations. Create one in Entregar.");
|
||||
return text(targets.map((target) => `- ${target.name} (${target.id}) · ${target.kind}`).join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_send_photos",
|
||||
{
|
||||
title: "Send photos",
|
||||
description: "Sends photos to one destination. Pass photoIds, or an eventId plus picksOnly to send that event's picks (up to limit, ready photos, rejects are left out by the server). originals sends the camera file instead of the destination's resize. again sends photos that destination already has. Example: send the picks of this event to Cofina, at most 40.",
|
||||
inputSchema: z.object({
|
||||
organizationId: z.string().optional(),
|
||||
destination: z.string().describe("Destination id or name."),
|
||||
photoIds: z.array(z.string()).max(500).optional(),
|
||||
eventId: z.string().optional().describe("Used when photoIds is omitted."),
|
||||
picksOnly: z.boolean().default(true),
|
||||
limit: z.number().int().min(1).max(300).default(40),
|
||||
originals: z.boolean().default(false),
|
||||
again: z.boolean().default(false),
|
||||
}),
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(input.organizationId);
|
||||
const { targets } = await api.listDeliveryTargets(id);
|
||||
const target = targets.find((item) => item.id === input.destination || item.name.toLowerCase() === input.destination.toLowerCase());
|
||||
if (!target) throw new Error(`No destination named "${input.destination}". Call photoreport_list_destinations.`);
|
||||
let ids = input.photoIds ?? [];
|
||||
if (ids.length === 0) {
|
||||
if (!input.eventId) throw new Error("Pass photoIds or an eventId.");
|
||||
const query: PhotoQuery = { event: input.eventId, limit: input.limit };
|
||||
if (input.picksOnly) query.flag = "PICK";
|
||||
const page = await api.listPhotos(id, query);
|
||||
ids = page.photos.filter((photo) => photo.status === "READY" && photo.flag !== "REJECT").map((photo) => photo.id);
|
||||
}
|
||||
if (ids.length === 0) return text("Nothing to send. No ready photos matched.");
|
||||
const result = await api.deliver(id, target.id, ids, input.again, input.originals);
|
||||
const skipped = result.skipped.map((item) => `${item.photoId} ${item.reason}`).join(", ");
|
||||
return text(`Queued ${result.queued.length} to ${target.name}.${result.skipped.length ? ` Skipped ${result.skipped.length}: ${skipped}.` : ""} Call photoreport_delivery_status to watch them.`);
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_send_best",
|
||||
{
|
||||
title: "Send the best of a match",
|
||||
description: "Sends the best N moments of an event, spread over the match, to one destination. dryRun only lists the choice and sends nothing. Example: send the best 30 of this match to Cofina.",
|
||||
inputSchema: z.object({
|
||||
organizationId: z.string().optional(),
|
||||
destination: z.string(),
|
||||
eventId: z.string(),
|
||||
count: z.number().int().min(1).max(300).default(30),
|
||||
dryRun: z.boolean().default(false),
|
||||
again: z.boolean().default(false),
|
||||
originals: z.boolean().default(false),
|
||||
}),
|
||||
annotations: { readOnlyHint: false, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(input.organizationId);
|
||||
const { targets } = await api.listDeliveryTargets(id);
|
||||
const target = targets.find((item) => item.id === input.destination || item.name.toLowerCase() === input.destination.toLowerCase());
|
||||
if (!target) throw new Error(`No destination named "${input.destination}". Call photoreport_list_destinations.`);
|
||||
const result = await api.deliverBest(id, { targetId: target.id, eventId: input.eventId, count: input.count, dryRun: input.dryRun, again: input.again, originals: input.originals });
|
||||
if (input.dryRun) return text(`Would send ${result.chosen.length} photos. Nothing was queued.`);
|
||||
return text(`Queued ${result.queued.length} of ${result.chosen.length} chosen for ${target.name}. Skipped ${result.skipped.length}.`);
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_delivery_status",
|
||||
{
|
||||
title: "Delivery status",
|
||||
description: "Recent deliveries and how many are queued, running, done or failed. Pass a destination id to narrow it.",
|
||||
inputSchema: z.object({
|
||||
organizationId: z.string().optional(),
|
||||
destinationId: z.string().optional(),
|
||||
}),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(input.organizationId);
|
||||
const query: { targetId?: string } = {};
|
||||
if (input.destinationId) query.targetId = input.destinationId;
|
||||
const page = await api.listDeliveries(id, query);
|
||||
const counts = Object.entries(page.counts).map(([status, count]) => `${status} ${count}`).join(" · ");
|
||||
const lines = [counts || "No deliveries.", ...page.items.slice(0, 20).map((item) => `- ${item.status} ${item.remotePath ?? item.photoId} (${item.id})${item.lastError ? ` · ${item.lastError}` : ""}`)];
|
||||
return text(lines.join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_retry_delivery",
|
||||
{
|
||||
title: "Retry a delivery",
|
||||
description: "Retries one failed delivery. The id comes from photoreport_delivery_status.",
|
||||
inputSchema: z.object({
|
||||
organizationId: z.string().optional(),
|
||||
deliveryId: z.string(),
|
||||
}),
|
||||
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ organizationId, deliveryId }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(organizationId);
|
||||
const item = await api.retryDelivery(id, deliveryId);
|
||||
return text(`Delivery ${item.id} is ${item.status}.`);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { CONTROLS, type Module } from "@photoreport/contracts";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import * as z from "zod/v4";
|
||||
import { api, ensureSession } from "../session.js";
|
||||
import { developValues } from "../edits.js";
|
||||
import { guard, text, type Server } from "../result.js";
|
||||
|
||||
const CLIENT = "photoreport-mcp";
|
||||
|
||||
export function registerDevelop(server: Server): void {
|
||||
server.registerTool(
|
||||
"photoreport_develop_controls",
|
||||
{
|
||||
title: "Develop controls",
|
||||
description: "The edit controls the engine accepts, with min, max and default. Call this before photoreport_edit_photo when the control id is not already known. Common ones: light.exposure, light.contrast, light.highlights, light.shadows, light.whites, light.blacks, color.temperature, color.tint, detail.sharpenAmount.",
|
||||
inputSchema: z.object({
|
||||
module: z.string().optional().describe("One module: basic controls live under light and color ids. Pass crop, detail, optics, vignette, or leave empty for the basic light and colour ids."),
|
||||
}),
|
||||
annotations: { readOnlyHint: true, openWorldHint: false },
|
||||
},
|
||||
async ({ module }) =>
|
||||
guard(async () => {
|
||||
const wanted = module ? CONTROLS.filter((control) => control.module === (module as Module) || control.id.startsWith(`${module}.`)) : CONTROLS.filter((control) => control.id.startsWith("light.") || control.id.startsWith("color.") || control.id.startsWith("detail."));
|
||||
const lines = wanted.slice(0, 80).map((control) => `- ${control.id} (${control.label}) ${control.min}…${control.max}, default ${control.default}`);
|
||||
if (wanted.length > 80) lines.push(`… ${wanted.length - 80} more. Pass a module name.`);
|
||||
if (lines.length === 0) return text("No controls for that module. Modules include crop, basic, detail, optics, vignette, colorGrading.");
|
||||
return text(lines.join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_develop_state",
|
||||
{
|
||||
title: "Develop state",
|
||||
description: "The current edit of one photo: snapshot sequence and the commands applied after it. Use photoreport_edit_photo to change it.",
|
||||
inputSchema: z.object({ photoId: z.string() }),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ photoId }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const state = await api.developState(photoId);
|
||||
const lines = [`Sequence ${state.developSeq}, snapshot ${state.snapshotSeq}, ${state.ops.length} later edits.`];
|
||||
for (const op of state.ops.slice(-12)) lines.push(`- ${op.seq} ${op.command.command}`);
|
||||
return text(lines.join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_edit_photo",
|
||||
{
|
||||
title: "Edit a photo",
|
||||
description: "Applies develop commands to one photo. Values must be inside the control ranges (photoreport_develop_controls). Crop rect is 0..1 of the frame. reset clears the edit first. The same command is safe to retry: each call has its own id and the server stores it once. Example: raise exposure by setting light.exposure to 0.4 on photo <id>.",
|
||||
inputSchema: z.object({
|
||||
photoId: z.string(),
|
||||
values: z.record(z.string(), z.number()).optional().describe("Control id to value, for example { \"light.exposure\": 0.3, \"light.contrast\": 10 }."),
|
||||
reset: z.boolean().default(false).describe("Clear the edit before applying values."),
|
||||
crop: z
|
||||
.object({
|
||||
x0: z.number().min(0).max(1),
|
||||
y0: z.number().min(0).max(1),
|
||||
x1: z.number().min(0).max(1),
|
||||
y1: z.number().min(0).max(1),
|
||||
angle: z.number().min(-45).max(45).default(0),
|
||||
aspectW: z.number().int().positive().nullable().default(null),
|
||||
aspectH: z.number().int().positive().nullable().default(null),
|
||||
})
|
||||
.optional(),
|
||||
}),
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const ops: { opId: string; command: { command: "develop.reset" } | { command: "develop.set"; params: { values: Record<string, number> } } | { command: "crop.set"; params: { rect: { x0: number; y0: number; x1: number; y1: number }; angle: number; aspect: [number, number] | null } } }[] = [];
|
||||
if (input.reset) ops.push({ opId: randomUUID(), command: { command: "develop.reset" } });
|
||||
if (input.values) ops.push({ opId: randomUUID(), command: { command: "develop.set", params: { values: developValues(input.values) } } });
|
||||
if (input.crop) {
|
||||
if (input.crop.x0 >= input.crop.x1 || input.crop.y0 >= input.crop.y1) throw new Error("The crop must have a positive size (x0 < x1 and y0 < y1).");
|
||||
const aspect = input.crop.aspectW && input.crop.aspectH ? ([input.crop.aspectW, input.crop.aspectH] as [number, number]) : null;
|
||||
ops.push({
|
||||
opId: randomUUID(),
|
||||
command: { command: "crop.set", params: { rect: { x0: input.crop.x0, y0: input.crop.y0, x1: input.crop.x1, y1: input.crop.y1 }, angle: input.crop.angle, aspect } },
|
||||
});
|
||||
}
|
||||
if (ops.length === 0) throw new Error("Nothing to change. Pass values, crop, or reset.");
|
||||
const result = await api.postEdits(input.photoId, { clientId: CLIENT, ops });
|
||||
return text(`Edited. Sequence is now ${result.developSeq}. The preview updates when the render worker finishes.`);
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_set_autopilot",
|
||||
{
|
||||
title: "Set autopilot",
|
||||
description: "Turns the event autopilot on or off and sets how it edits arriving photos (crop, level, tone, white balance, look). New camera photos are edited on the desktop and the server with these rules. It does not re-edit photos already in the event.",
|
||||
inputSchema: z.object({
|
||||
eventId: z.string(),
|
||||
enabled: z.boolean(),
|
||||
crop: z.boolean().default(true),
|
||||
level: z.boolean().default(true),
|
||||
tone: z.boolean().default(true),
|
||||
whiteBalance: z.boolean().default(true),
|
||||
toneStrength: z.number().min(0).max(1).default(0.75),
|
||||
look: z.enum(["agency", "natural", "none"]).default("none"),
|
||||
framing: z.enum(["tight", "full"]).default("tight"),
|
||||
}),
|
||||
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const event = await api.updateEvent(input.eventId, {
|
||||
autopilot: {
|
||||
enabled: input.enabled,
|
||||
crop: input.crop,
|
||||
level: input.level,
|
||||
tone: input.tone,
|
||||
whiteBalance: input.whiteBalance,
|
||||
toneStrength: input.toneStrength,
|
||||
look: input.look,
|
||||
framing: input.framing,
|
||||
},
|
||||
});
|
||||
return text(`Autopilot on ${event.title}: ${input.enabled ? "on" : "off"}.`);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import type { PhotoQuery } from "@photoreport/sdk";
|
||||
import * as z from "zod/v4";
|
||||
import { api, ensureSession, orgId } from "../session.js";
|
||||
import { reviewPhotos } from "../review.js";
|
||||
import { guard, text, type Server } from "../result.js";
|
||||
|
||||
const Flag = z.enum(["PICK", "REJECT", "NONE"]);
|
||||
const Color = z.enum(["NONE", "RED", "YELLOW", "GREEN", "BLUE", "PURPLE"]);
|
||||
|
||||
function line(photo: PhotoSummary): string {
|
||||
const exposure = [photo.focalLength ? `${photo.focalLength}mm` : "", photo.aperture ? `f/${photo.aperture}` : "", photo.iso ? `ISO ${photo.iso}` : ""].filter(Boolean).join(" ");
|
||||
const mark = photo.flag === "NONE" ? "" : ` ${photo.flag}`;
|
||||
const stars = photo.rating > 0 ? ` ${photo.rating}★` : "";
|
||||
const players = photo.players.length ? ` · ${photo.players.join(", ")}` : "";
|
||||
return `- ${photo.name} (${photo.id})${mark}${stars}${photo.colorLabel !== "NONE" ? ` ${photo.colorLabel}` : ""} · ${photo.status}${photo.delivery ? `/${photo.delivery}` : ""}${photo.developSeq ? " · edited" : ""}${players}${exposure ? ` · ${exposure}` : ""}`;
|
||||
}
|
||||
|
||||
async function loadEvent(organization: string, eventId: string): Promise<PhotoSummary[]> {
|
||||
const photos: PhotoSummary[] = [];
|
||||
let offset = 0;
|
||||
for (;;) {
|
||||
const page = await api.listPhotos(organization, { event: eventId, offset, limit: 500 });
|
||||
photos.push(...page.photos);
|
||||
offset += page.photos.length;
|
||||
if (page.photos.length === 0 || offset >= page.total || photos.length >= 1000) break;
|
||||
}
|
||||
return photos;
|
||||
}
|
||||
|
||||
export function registerLibrary(server: Server): void {
|
||||
server.registerTool(
|
||||
"photoreport_list_photos",
|
||||
{
|
||||
title: "List photos",
|
||||
description: "Photos of one event or the inbox. Filter by flag, minimum stars, or photos with no players. Returns names and ids for photoreport_photo, photoreport_set_photos and photoreport_send_photos. Example: the picks of event <id>.",
|
||||
inputSchema: z.object({
|
||||
organizationId: z.string().optional(),
|
||||
eventId: z.string().describe("Event id, or inbox for photos no event claimed."),
|
||||
flag: z.enum(["PICK", "REJECT", "NONE", "UNREJECTED"]).optional(),
|
||||
minRating: z.number().int().min(0).max(5).optional(),
|
||||
withoutPlayers: z.boolean().default(false),
|
||||
status: z.enum(["PROCESSING", "READY", "FAILED"]).optional(),
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(80).default(40),
|
||||
}),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(input.organizationId);
|
||||
const query: PhotoQuery = { event: input.eventId, offset: input.offset, limit: input.limit };
|
||||
if (input.flag) query.flag = input.flag;
|
||||
if (input.minRating !== undefined) query.minRating = input.minRating;
|
||||
if (input.withoutPlayers) query.withoutPlayers = true;
|
||||
if (input.status) query.status = input.status;
|
||||
const page = await api.listPhotos(id, query);
|
||||
const lines = [`${page.photos.length} of ${page.total}, offset ${page.offset}`];
|
||||
lines.push(...page.photos.map(line));
|
||||
if (page.offset + page.photos.length < page.total) lines.push(`More: offset ${page.offset + page.photos.length}.`);
|
||||
return text(lines.join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_search",
|
||||
{
|
||||
title: "Search the library",
|
||||
description: "Search across events by name, team, file name or a person id. Use photoreport_list_photos when the event is already known.",
|
||||
inputSchema: z.object({
|
||||
organizationId: z.string().optional(),
|
||||
query: z.string().optional().describe("Text: name, team, competition, file name."),
|
||||
personId: z.string().optional(),
|
||||
limit: z.number().int().min(1).max(40).default(20),
|
||||
}),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(input.organizationId);
|
||||
const query: { q?: string; personId?: string; limit: number } = { limit: input.limit };
|
||||
if (input.query) query.q = input.query;
|
||||
if (input.personId) query.personId = input.personId;
|
||||
const found = await api.search(id, query);
|
||||
const lines = [`${found.total} photos`];
|
||||
lines.push(...found.photos.map(line));
|
||||
if (found.suggested.length) {
|
||||
lines.push("Suggested (face, not confirmed):");
|
||||
lines.push(...found.suggested.map(line));
|
||||
}
|
||||
return text(lines.join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_review_event",
|
||||
{
|
||||
title: "Review an event",
|
||||
description: "Looks through an event (up to 1000 photos) and says what still needs the photographer: unread files, failed deliveries, picks with no edit, frames not culled, photos with no player. It does not judge sharpness from pixels. For one frame, call photoreport_photo. For shirt numbers, call photoreport_jersey_queue. Example: are the photos of this match in good shape?",
|
||||
inputSchema: z.object({
|
||||
organizationId: z.string().optional(),
|
||||
eventId: z.string(),
|
||||
}),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ organizationId, eventId }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(organizationId);
|
||||
const photos = await loadEvent(id, eventId);
|
||||
const report = reviewPhotos(photos);
|
||||
const lines = [
|
||||
`${report.total} photos · ${report.ready} ready · ${report.processing} processing · ${report.failed} failed`,
|
||||
`${report.picks} picks · ${report.rejects} rejects · ${report.unrated} not culled`,
|
||||
`${report.uneditedPicks} picks with no edit · ${report.withoutPlayers} without a player · ${report.deliveryFailed} deliveries failed · ${report.unsentPicks} picks not sent`,
|
||||
];
|
||||
if (report.lookAt.length === 0) lines.push("Nothing in the catalogue asks for a look. Sharpness and shirt numbers are separate tools.");
|
||||
else {
|
||||
lines.push("Look at:");
|
||||
for (const note of report.lookAt) lines.push(`- ${note.name} (${note.id}): ${note.reasons.join("; ")}`);
|
||||
}
|
||||
return text(lines.join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_photo",
|
||||
{
|
||||
title: "One photo",
|
||||
description: "One photo: exposure, marks, players, faces found on it, and whether it has been edited. Preview URL is included so a client that can open images can look. Use photoreport_edit_photo to change the develop settings.",
|
||||
inputSchema: z.object({ photoId: z.string() }),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ photoId }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const [faces, develop, iptc] = await Promise.all([
|
||||
api.photoFaces(photoId),
|
||||
api.developState(photoId),
|
||||
api.photoIptc(photoId).catch(() => null),
|
||||
]);
|
||||
const lines = [`Faces: ${faces.status}, ${faces.faces.length}`];
|
||||
for (const face of faces.faces) {
|
||||
const who = face.person?.name ?? (face.suggestion ? `${face.suggestion.name} (suggested)` : "unnamed");
|
||||
const visible = face.inPreview ? "in the crop" : "cropped out";
|
||||
lines.push(`- ${who} · ${visible} · box ${face.x0.toFixed(2)},${face.y0.toFixed(2)}–${face.x1.toFixed(2)},${face.y1.toFixed(2)}`);
|
||||
}
|
||||
lines.push(`Develop sequence ${develop.developSeq}. ${develop.ops.length} edits after the snapshot.`);
|
||||
if (iptc && iptc.issues.length) {
|
||||
lines.push("IPTC:");
|
||||
for (const issue of iptc.issues) lines.push(`- ${issue.field}: ${issue.detail}`);
|
||||
}
|
||||
return text(lines.join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_set_photos",
|
||||
{
|
||||
title: "Mark photos",
|
||||
description: "Sets the flag, stars, colour or players on one or many photos, or moves them to another event. This is the cull, not the develop edit (use photoreport_edit_photo for exposure and crop). Example: flag these ids as picks.",
|
||||
inputSchema: z.object({
|
||||
organizationId: z.string().optional(),
|
||||
photoIds: z.array(z.string()).min(1).max(500),
|
||||
flag: Flag.optional(),
|
||||
rating: z.number().int().min(0).max(5).optional(),
|
||||
color: Color.optional(),
|
||||
players: z.array(z.string()).max(30).optional().describe("Replaces the player list."),
|
||||
eventId: z.string().nullable().optional().describe("Move the photos to this event. Null sends them to the inbox."),
|
||||
}),
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(input.organizationId);
|
||||
const patch: {
|
||||
flag?: "PICK" | "REJECT" | "NONE";
|
||||
rating?: number;
|
||||
colorLabel?: "NONE" | "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
|
||||
players?: string[];
|
||||
eventId?: string | null;
|
||||
} = {};
|
||||
if (input.flag) patch.flag = input.flag;
|
||||
if (input.rating !== undefined) patch.rating = input.rating;
|
||||
if (input.color) patch.colorLabel = input.color;
|
||||
if (input.players) patch.players = input.players;
|
||||
if (input.eventId !== undefined) patch.eventId = input.eventId;
|
||||
const result = await api.updatePhotos(id, input.photoIds, patch);
|
||||
return text(`Updated ${result.updated} photos.`);
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_squads",
|
||||
{
|
||||
title: "Event squads",
|
||||
description: "The two teams of a match and whether each athlete has an enrolled face. Use this before naming faces or checking who is missing from the photos.",
|
||||
inputSchema: z.object({ eventId: z.string() }),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ eventId }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const squads = await api.eventSquads(eventId);
|
||||
const lines: string[] = [];
|
||||
for (const side of squads.sides) {
|
||||
lines.push(`${side.team.name}`);
|
||||
for (const player of side.players) {
|
||||
const face = player.hasFace ? "face enrolled" : player.faceUrl ? "squad photo only" : "no face";
|
||||
lines.push(`- ${player.number ?? "?"} ${player.name} (${face})`);
|
||||
}
|
||||
}
|
||||
if (lines.length === 0) return text("No squad on this event. photoreport_sync_squads pulls the official list when the match is linked.");
|
||||
return text(lines.join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_sync_squads",
|
||||
{
|
||||
title: "Sync squads",
|
||||
description: "Pulls the official squad for an event that is linked to a match. Does nothing useful when the event has no fixture.",
|
||||
inputSchema: z.object({ eventId: z.string() }),
|
||||
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ eventId }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const result = await api.syncEventSquads(eventId);
|
||||
return text(`Squad sync: ${result.created} created, ${result.updated} updated, ${result.headshots} headshots.`);
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_list_galleries",
|
||||
{
|
||||
title: "List galleries",
|
||||
description: "Galleries of the organization. Use the id with photoreport_add_to_gallery.",
|
||||
inputSchema: z.object({ organizationId: z.string().optional() }),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ organizationId }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(organizationId);
|
||||
const { galleries } = await api.listGalleries(id);
|
||||
if (galleries.length === 0) return text("No galleries.");
|
||||
return text(galleries.slice(0, 40).map((gallery) => `- ${gallery.title} (${gallery.id}) · ${gallery.photoCount} photos${gallery.publishedAt ? " · published" : ""}`).join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_add_to_gallery",
|
||||
{
|
||||
title: "Add photos to a gallery",
|
||||
description: "Adds photos to a gallery. Does not publish it. Example: put these picks in the match gallery.",
|
||||
inputSchema: z.object({
|
||||
galleryId: z.string(),
|
||||
photoIds: z.array(z.string()).min(1).max(500),
|
||||
}),
|
||||
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ galleryId, photoIds }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
await api.changeGalleryPhotos(galleryId, { add: photoIds });
|
||||
return text(`Added ${photoIds.length} photos to the gallery.`);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import type { DeskCommand } from "@photoreport/contracts";
|
||||
import * as z from "zod/v4";
|
||||
import { api, ensureSession } from "../session.js";
|
||||
import { guard, text, type Server } from "../result.js";
|
||||
|
||||
const exec = promisify(execFile);
|
||||
|
||||
/** Brings the installed PhotoReport window forward. The command still goes to whichever copy is signed in. */
|
||||
async function raiseApp(): Promise<string> {
|
||||
try {
|
||||
if (process.platform === "darwin") {
|
||||
await exec("open", ["-a", "PhotoReport"]);
|
||||
return "PhotoReport is in front.";
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
await exec("cmd", ["/c", "start", "", "PhotoReport"]);
|
||||
return "PhotoReport was asked to open.";
|
||||
}
|
||||
} catch {
|
||||
return "PhotoReport is not installed under that name. Open it yourself. The signed-in window still follows.";
|
||||
}
|
||||
return "Open PhotoReport. The signed-in window still follows.";
|
||||
}
|
||||
|
||||
const Modules = ["library", "develop", "metadata", "delivery", "shop", "print", "archive", "faces", "numbers", "help", "preferences", "members"] as const;
|
||||
|
||||
export function registerScreen(server: Server): void {
|
||||
server.registerTool(
|
||||
"photoreport_show",
|
||||
{
|
||||
title: "Open a PhotoReport window",
|
||||
description:
|
||||
"Opens the PhotoReport application on this computer and moves the signed-in window. Use it to change tabs and to open a photo. module is library, develop, metadata, delivery, shop, print, archive, faces, numbers, help, preferences or members. photoId opens that photo in Revelar. eventId opens that event in the library. tool crop, spot or wb opens that tool on the photo. section is a shop tab (orders, products) or a metadata section (iptc, codes, people, faces). Example: open this photo and start the crop. The photographer sees the window move. Do this before saying a photo was shown.",
|
||||
inputSchema: z.object({
|
||||
module: z.enum(Modules),
|
||||
photoId: z.string().optional(),
|
||||
eventId: z.string().optional(),
|
||||
tool: z.enum(["crop", "spot", "wb"]).optional(),
|
||||
section: z.string().max(40).optional(),
|
||||
}),
|
||||
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const raised = await raiseApp();
|
||||
const command: DeskCommand = { module: input.module };
|
||||
if (input.photoId) command.photoId = input.photoId;
|
||||
if (input.eventId) command.eventId = input.eventId;
|
||||
if (input.tool) command.tool = input.tool;
|
||||
if (input.section) command.section = input.section;
|
||||
await api.desk(command);
|
||||
const where = [input.module, input.photoId, input.eventId, input.tool, input.section].filter(Boolean).join(" · ");
|
||||
return text(`${raised} Showing ${where}. If the window was signed out, sign in and call this again.`);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { JerseySample } from "@photoreport/sdk";
|
||||
import * as z from "zod/v4";
|
||||
import { api, ensureSession, orgId } from "../session.js";
|
||||
import { guard, text, textAndImages, type Server } from "../result.js";
|
||||
|
||||
async function cropImage(sample: JerseySample): Promise<{ data: string; mimeType: string } | null> {
|
||||
try {
|
||||
const response = await fetch(api.absolute(sample.crop), { signal: AbortSignal.timeout(15_000) });
|
||||
if (!response.ok) return null;
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
if (bytes.length === 0 || bytes.length > 1_500_000) return null;
|
||||
const mime = response.headers.get("content-type")?.split(";")[0] ?? "image/jpeg";
|
||||
return { data: bytes.toString("base64"), mimeType: mime };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function registerTeach(server: Server): void {
|
||||
server.registerTool(
|
||||
"photoreport_jersey_queue",
|
||||
{
|
||||
title: "Shirt numbers to check",
|
||||
description: "Crops of shirt numbers waiting to be taught, with the model's guess. The first few crops are attached as images so you can see whether the number is readable. Say the digits when they are clear, or illegible when the crop does not show a number, then call photoreport_jersey_review. Do not guess a number you cannot see. Example: show me numbers to teach.",
|
||||
inputSchema: z.object({
|
||||
organizationId: z.string().optional(),
|
||||
status: z.enum(["PENDING", "CONFIRMED", "ILLEGIBLE", "SKIPPED"]).default("PENDING"),
|
||||
limit: z.number().int().min(1).max(12).default(4),
|
||||
}),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const id = await orgId(input.organizationId);
|
||||
const page = await api.jerseySamples(id, input.status, input.limit);
|
||||
const counts = Object.entries(page.stats.counts).map(([status, count]) => `${status} ${count}`).join(" · ");
|
||||
const lines = [`Collected ${page.collected}. ${counts || "No counts."}`];
|
||||
const images: { data: string; mimeType: string }[] = [];
|
||||
for (const sample of page.samples) {
|
||||
lines.push(`- ${sample.id} · ${sample.region} · guess ${sample.suggested ?? "none"} · player ${sample.person ?? "unknown"}`);
|
||||
const image = await cropImage(sample);
|
||||
if (image) images.push(image);
|
||||
}
|
||||
if (page.samples.length === 0) lines.push("Nothing in this queue.");
|
||||
else lines.push("The images follow in the same order. Confirm with photoreport_jersey_review.");
|
||||
return textAndImages(lines.join("\n"), images);
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_jersey_review",
|
||||
{
|
||||
title: "Teach a shirt number",
|
||||
description: "Records what the crop shows. CONFIRMED needs the digits you can see (label). ILLEGIBLE means the number is not readable. SKIPPED leaves it out of the dataset. The sample id comes from photoreport_jersey_queue.",
|
||||
inputSchema: z.object({
|
||||
sampleId: z.string(),
|
||||
status: z.enum(["CONFIRMED", "ILLEGIBLE", "SKIPPED"]),
|
||||
label: z.string().max(4).optional().describe("The digits you can see. Required when status is CONFIRMED."),
|
||||
}),
|
||||
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
if (input.status === "CONFIRMED" && !input.label) throw new Error("A confirmed number needs the digits in label.");
|
||||
const sample = await api.reviewJerseySample(input.sampleId, input.status, input.label ?? null);
|
||||
return text(`Sample ${sample.id} is ${sample.status}${sample.label ? ` (${sample.label})` : ""}.`);
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_face_groups",
|
||||
{
|
||||
title: "Faces in an event",
|
||||
description: "People the faces worker grouped in one event, with the suggestion and how many photos. Unnamed groups are the ones to teach with photoreport_confirm_face.",
|
||||
inputSchema: z.object({ eventId: z.string() }),
|
||||
annotations: { readOnlyHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ eventId }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const page = await api.faceGroups(eventId);
|
||||
const lines = [`${page.groups.length} groups · ${page.pending} photos still running · ${page.unclear} unclear${page.available === false ? " · faces are off for this organization" : ""}`];
|
||||
for (const group of page.groups.slice(0, 40)) {
|
||||
const who = group.person?.name ?? (group.suggestion ? `${group.suggestion.name} suggested ${Math.round(group.suggestion.score * 100)}%` : "unnamed");
|
||||
const number = group.number ? ` · shirt ${group.number.value}` : "";
|
||||
lines.push(`- ${who} (${group.id}) · ${group.size} photos${number}${group.ignored ? " · ignored" : ""}`);
|
||||
}
|
||||
return text(lines.join("\n"));
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_confirm_face",
|
||||
{
|
||||
title: "Name a face group",
|
||||
description: "Names every photo in a face group as one person. Pass personId from the squad, or a name (and club, number) to create the person. The group id comes from photoreport_face_groups.",
|
||||
inputSchema: z.object({
|
||||
groupId: z.string(),
|
||||
personId: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
club: z.string().optional(),
|
||||
number: z.string().max(4).optional(),
|
||||
}),
|
||||
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
async (input) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
if (!input.personId && !input.name) throw new Error("Pass personId or a name.");
|
||||
const who = input.personId
|
||||
? { personId: input.personId }
|
||||
: { name: input.name as string, ...(input.club ? { club: input.club } : {}), ...(input.number ? { number: input.number } : {}) };
|
||||
const result = await api.confirmFaceGroup(input.groupId, who);
|
||||
return text(`Named as ${result.person.name}.`);
|
||||
}),
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"photoreport_analyse_faces",
|
||||
{
|
||||
title: "Analyse faces",
|
||||
description: "Queues face detection for an event. The organization must have biometrics on. This does not name anyone; use photoreport_face_groups afterwards.",
|
||||
inputSchema: z.object({ eventId: z.string() }),
|
||||
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
async ({ eventId }) =>
|
||||
guard(async () => {
|
||||
await ensureSession();
|
||||
const result = await api.analyseEventFaces(eventId);
|
||||
return text(`Queued ${result.queued} photos for faces.`);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"lib": ["ES2023"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** Modules the assistant can open. `library` is the front page. */
|
||||
export const DESK_MODULES = ["library", "develop", "metadata", "delivery", "shop", "print", "archive", "faces", "numbers", "help", "preferences", "members"] as const;
|
||||
|
||||
/**
|
||||
* One instruction for the PhotoReport window that is open and signed in as this person.
|
||||
* The API delivers it on the realtime socket. It does not change photos by itself.
|
||||
*/
|
||||
export const DeskCommand = z.object({
|
||||
module: z.enum(DESK_MODULES),
|
||||
photoId: z.uuid().optional(),
|
||||
eventId: z.uuid().optional(),
|
||||
/** Develop only: open that tool on the photo. */
|
||||
tool: z.enum(["crop", "spot", "wb"]).optional(),
|
||||
/** Shop tab or metadata section, when that module has one. */
|
||||
section: z.string().max(40).optional(),
|
||||
});
|
||||
export type DeskCommand = z.infer<typeof DeskCommand>;
|
||||
|
||||
/** Where the window should go. Library is `/`, not `/library`. */
|
||||
export function deskPath(command: DeskCommand): string {
|
||||
if (command.module === "library") return "/";
|
||||
if (command.module === "develop") return command.photoId ? `/develop/${command.photoId}` : "/develop";
|
||||
if (command.module === "shop" && command.section) return `/shop?tab=${encodeURIComponent(command.section)}`;
|
||||
if (command.module === "metadata" && command.section) return `/metadata?s=${encodeURIComponent(command.section)}`;
|
||||
return `/${command.module}`;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from "./commands.js";
|
||||
export * from "./desk.js";
|
||||
export * from "./controls.js";
|
||||
export * from "./library.js";
|
||||
export * from "./shop.js";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
|
||||
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DeskCommand, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
|
||||
import type { AgendaEntry, ArchiveStorage, CardScan, FaceIdentify, FaceRoster, CloudFolderSummary, CloudSource, CloudTreeFolder, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, RealEstateFrame, RealEstateGrouping, Role, ZerozeroGame } from "./types.js";
|
||||
|
||||
/**
|
||||
@@ -241,6 +241,11 @@ export class ApiClient {
|
||||
return this.request<Me>("GET", "/v1/me");
|
||||
}
|
||||
|
||||
/** Asks the open PhotoReport of this person to show a module, a photo or a tool. */
|
||||
desk(command: DeskCommand) {
|
||||
return this.request<{ ok: true }>("POST", "/v1/me/desk", command);
|
||||
}
|
||||
|
||||
updateEditorModules(editorModules: Module[]) {
|
||||
return this.request<{ editorModules: Module[] }>("PUT", "/v1/me/preferences", { editorModules });
|
||||
}
|
||||
|
||||
@@ -237,6 +237,7 @@ export interface PhotoQuery {
|
||||
flag?: "PICK" | "REJECT" | "NONE" | "UNREJECTED";
|
||||
minRating?: number;
|
||||
withoutPlayers?: boolean;
|
||||
status?: "PROCESSING" | "READY" | "FAILED";
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
Generated
+32
@@ -212,6 +212,21 @@ importers:
|
||||
specifier: ^2.12.2
|
||||
version: 2.12.2
|
||||
|
||||
apps/mcp:
|
||||
dependencies:
|
||||
'@modelcontextprotocol/server':
|
||||
specifier: ^2.3.1
|
||||
version: 2.4.0
|
||||
'@photoreport/contracts':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/contracts
|
||||
'@photoreport/sdk':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/sdk
|
||||
zod:
|
||||
specifier: ^4.2.0
|
||||
version: 4.6.5
|
||||
|
||||
apps/print-agent:
|
||||
dependencies:
|
||||
'@photoreport/contracts':
|
||||
@@ -817,6 +832,14 @@ packages:
|
||||
resolution: {integrity: sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
'@modelcontextprotocol/[email protected]':
|
||||
resolution: {integrity: sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==}
|
||||
engines: {node: '>=20'}
|
||||
|
||||
'@modelcontextprotocol/[email protected]':
|
||||
resolution: {integrity: sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==}
|
||||
engines: {node: '>=20'}
|
||||
|
||||
'@napi-rs/[email protected]':
|
||||
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
|
||||
engines: {node: ^22.20 || ^24.12 || >=25}
|
||||
@@ -3628,6 +3651,15 @@ snapshots:
|
||||
|
||||
'@lukeed/[email protected]': {}
|
||||
|
||||
'@modelcontextprotocol/[email protected]':
|
||||
dependencies:
|
||||
zod: 4.6.5
|
||||
|
||||
'@modelcontextprotocol/[email protected]':
|
||||
dependencies:
|
||||
'@modelcontextprotocol/core': 2.4.0
|
||||
zod: 4.6.5
|
||||
|
||||
'@napi-rs/[email protected]':
|
||||
optional: true
|
||||
|
||||
|
||||
Reference in new issue
Block a user