@composable-os/pack-programs 0.0.0-stage → 0.1.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +109 -0
  2. package/dist/authoring.d.ts +47 -0
  3. package/dist/authoring.js +493 -0
  4. package/dist/blocks/programs-bank/exercise-bank.d.ts +4 -0
  5. package/dist/blocks/programs-bank/exercise-bank.js +68 -0
  6. package/dist/blocks/programs-builder/program-builder.d.ts +26 -0
  7. package/dist/blocks/programs-builder/program-builder.js +295 -0
  8. package/dist/blocks/programs-class-today/class-today.d.ts +6 -0
  9. package/dist/blocks/programs-class-today/class-today.js +15 -0
  10. package/dist/blocks/programs-coach-client/coach-client.d.ts +5 -0
  11. package/dist/blocks/programs-coach-client/coach-client.js +10 -0
  12. package/dist/blocks/programs-native-class-today/class-today-screen.d.ts +6 -0
  13. package/dist/blocks/programs-native-class-today/class-today-screen.js +14 -0
  14. package/dist/blocks/programs-native-coach-client/coach-client-screen.d.ts +7 -0
  15. package/dist/blocks/programs-native-coach-client/coach-client-screen.js +9 -0
  16. package/dist/blocks/programs-native-progress/progress-screen.d.ts +5 -0
  17. package/dist/blocks/programs-native-progress/progress-screen.js +31 -0
  18. package/dist/blocks/programs-native-session/session-screen.d.ts +7 -0
  19. package/dist/blocks/programs-native-session/session-screen.js +130 -0
  20. package/dist/blocks/programs-native-today/today-screen.d.ts +7 -0
  21. package/dist/blocks/programs-native-today/today-screen.js +11 -0
  22. package/dist/blocks/programs-progress/progress.d.ts +10 -0
  23. package/dist/blocks/programs-progress/progress.js +40 -0
  24. package/dist/blocks/programs-session/session-view.d.ts +9 -0
  25. package/dist/blocks/programs-session/session-view.js +116 -0
  26. package/dist/blocks/programs-today/today.d.ts +7 -0
  27. package/dist/blocks/programs-today/today.js +16 -0
  28. package/dist/client/index.d.ts +1723 -0
  29. package/dist/client/index.js +779 -0
  30. package/dist/dashboards.d.ts +5 -0
  31. package/dist/dashboards.js +145 -0
  32. package/dist/index.d.ts +1181 -0
  33. package/dist/index.js +608 -0
  34. package/dist/layout.d.ts +88 -0
  35. package/dist/layout.js +268 -0
  36. package/dist/tools.d.ts +344 -0
  37. package/dist/tools.js +930 -0
  38. package/package.json +36 -4
  39. package/README.md +0 -3
package/dist/tools.js ADDED
@@ -0,0 +1,930 @@
1
+ // The Programs tools. They become operations x.programs.<tool>, run in the sandbox, and reach
2
+ // the host only through ctx.ops. None of them holds a rule: what a layout may hold, who may read
3
+ // a session or write a log, which moves a session may make and that a move is made once are all
4
+ // the host's (the document schema, the customer and signed-in scopes, `states` and `from`). A
5
+ // tool composes those, and works out what is asked of it (a session's dates, a set's target from
6
+ // its plan, bests over a person's sets).
7
+ //
8
+ // Called by a customer, a tool runs as that customer (ADR 0414): its calls are my.* and see only
9
+ // what the seam shows them. Called by staff, it uses record.* and names the person.
10
+ import { defineTool, OpsCallError, z } from "@composable-os/sdk";
11
+ import { draftLayout, pickExercises, readBrief, readProgramText, } from "./authoring.js";
12
+ import { prescriptions, } from "./layout.js";
13
+ const EXERCISE = "programs.exercise";
14
+ const PROGRAM = "programs.program";
15
+ const ASSIGNMENT = "programs.assignment";
16
+ const SESSION = "programs.session";
17
+ const LOG = "programs.log";
18
+ /** Sessions written in one call: record.createMany's cap (ADR 0448). */
19
+ const SESSIONS_PER_BATCH = 50;
20
+ /** The most sets a history or progress reads (pages of 200). */
21
+ const SETS_READ_MAX = 2000;
22
+ const id = z.string().min(1).max(64);
23
+ const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "A date: YYYY-MM-DD");
24
+ const text = (value) => value === null || value === undefined ? null : String(value);
25
+ const num = (value) => typeof value === "number" ? value : value == null ? null : Number(value);
26
+ const isCustomer = (ctx) => ctx.caller?.kind === "customer";
27
+ /** A page of records: the caller's own (and shared) for a customer, any for staff. */
28
+ function list(ctx, object, input) {
29
+ return ctx.ops.call(isCustomer(ctx) ? "my.list" : "record.list", { object, ...input });
30
+ }
31
+ function get(ctx, object, recordId) {
32
+ return ctx.ops.call(isCustomer(ctx) ? "my.get" : "record.get", {
33
+ object,
34
+ id: recordId,
35
+ });
36
+ }
37
+ /** Every page, up to `cap` records. */
38
+ async function all(ctx, object, filter, sort, cap) {
39
+ const items = [];
40
+ let cursor;
41
+ do {
42
+ const page = await list(ctx, object, {
43
+ ...(filter ? { filter } : {}),
44
+ sort,
45
+ limit: 200,
46
+ ...(cursor ? { cursor } : {}),
47
+ });
48
+ items.push(...page.items);
49
+ cursor = page.nextCursor ?? undefined;
50
+ } while (cursor && items.length < cap);
51
+ return { items: items.slice(0, cap), capped: Boolean(cursor) || items.length > cap };
52
+ }
53
+ /** Staff name the person a call is about; a customer is always themselves, and never names one. */
54
+ function personFilter(ctx, personId) {
55
+ if (isCustomer(ctx)) {
56
+ if (personId)
57
+ throw new OpsCallError("invalid_input", "A member never names a person: it is always themselves");
58
+ return null;
59
+ }
60
+ if (!personId)
61
+ throw new OpsCallError("invalid_input", "Name the person (personId)");
62
+ return { field: "person", op: "eq", value: personId };
63
+ }
64
+ function addDays(day, days) {
65
+ const at = new Date(`${day}T00:00:00Z`);
66
+ at.setUTCDate(at.getUTCDate() + days);
67
+ return at.toISOString().slice(0, 10);
68
+ }
69
+ const todayUtc = () => new Date().toISOString().slice(0, 10);
70
+ const and = (...filters) => {
71
+ const kept = filters.filter((f) => Boolean(f));
72
+ return kept.length === 0 ? undefined : kept.length === 1 ? kept[0] : { and: kept };
73
+ };
74
+ // --- Assign --------------------------------------------------------------------------------------
75
+ export const assign = defineTool({
76
+ description: "Give a published program to a person or to a class type from a start date: pins the " +
77
+ "program's current published version and makes one dated session per session of its " +
78
+ "layout (week w's session on day d is dated start + 7(w-1) + (d-1)). Editing the program " +
79
+ "later changes none of them; publish a new version and assign again. Refused when the " +
80
+ "program has never been published. Safe to call again with the same program, person or " +
81
+ "class type and start date: it finishes what an interrupted call began.",
82
+ input: z
83
+ .object({
84
+ programId: id,
85
+ personId: id.optional().describe("A person: a client program"),
86
+ classTypeId: id.optional().describe("A class type: a class program"),
87
+ startDate: date,
88
+ })
89
+ .refine((v) => Boolean(v.personId) !== Boolean(v.classTypeId), {
90
+ message: "Name a person or a class type, not both",
91
+ }),
92
+ output: z.object({
93
+ assignmentId: z.string(),
94
+ programVersion: z.number(),
95
+ sessions: z.number(),
96
+ startDate: z.string(),
97
+ endDate: z.string(),
98
+ }),
99
+ // Many sessions in one call.
100
+ risk: "bulk-write",
101
+ async handler(input, ctx) {
102
+ const program = await ctx.ops.call("record.get", {
103
+ object: PROGRAM,
104
+ id: input.programId,
105
+ });
106
+ let version;
107
+ try {
108
+ version = await ctx.ops.call("record.version", { object: PROGRAM, id: input.programId });
109
+ }
110
+ catch (error) {
111
+ if (error instanceof OpsCallError && error.code === "not_found") {
112
+ throw new OpsCallError("invalid_input", "This program has not been published: a person with the publish permission publishes it first", { programId: input.programId });
113
+ }
114
+ throw error;
115
+ }
116
+ const layout = version.values.layout;
117
+ const weeks = layout.weeks.length;
118
+ const endDate = addDays(input.startDate, weeks * 7 - 1);
119
+ const kind = input.personId ? "personal" : "class";
120
+ const programTitle = text(version.values.title) ?? program.title ?? "Program";
121
+ const forWhom = input.personId
122
+ ? text((await ctx.ops.call("person.get", {
123
+ id: input.personId,
124
+ })).displayName)
125
+ : text((await ctx.ops.call("record.get", {
126
+ object: "programs.classtype",
127
+ id: input.classTypeId,
128
+ })).title);
129
+ const who = input.personId
130
+ ? { field: "person", value: input.personId }
131
+ : { field: "classType", value: input.classTypeId };
132
+ // An earlier call that stopped part-way left its assignment making sessions: finish it.
133
+ const earlier = await ctx.ops.call("record.list", {
134
+ object: ASSIGNMENT,
135
+ filter: {
136
+ and: [
137
+ { field: "program", op: "eq", value: input.programId },
138
+ { field: who.field, op: "eq", value: who.value },
139
+ { field: "startDate", op: "eq", value: input.startDate },
140
+ { field: "programVersion", op: "eq", value: version.version },
141
+ { field: "state", op: "eq", value: "generating" },
142
+ ],
143
+ },
144
+ limit: 1,
145
+ });
146
+ const assignmentId = earlier.items[0]?.id ??
147
+ (await ctx.ops.call("record.create", {
148
+ object: ASSIGNMENT,
149
+ values: {
150
+ title: `${programTitle}${forWhom ? ` for ${forWhom}` : ""}`,
151
+ program: input.programId,
152
+ programVersion: version.version,
153
+ kind,
154
+ [who.field]: who.value,
155
+ startDate: input.startDate,
156
+ endDate,
157
+ ...(ctx.caller?.kind === "staff"
158
+ ? { assignedBy: ctx.caller.userId, assignedByName: ctx.caller.name }
159
+ : {}),
160
+ },
161
+ })).id;
162
+ const made = new Set((await all(ctx, SESSION, { field: "assignment", op: "eq", value: assignmentId }, { field: "date", direction: "asc" }, 10_000)).items.map((s) => text(s.values.key)));
163
+ const wanted = [];
164
+ layout.weeks.forEach((week, w) => {
165
+ week.sessions.forEach((session, position) => {
166
+ const key = `${assignmentId}:${w + 1}:${position}`;
167
+ if (made.has(key))
168
+ return;
169
+ wanted.push({
170
+ name: session.name,
171
+ assignment: assignmentId,
172
+ program: input.programId,
173
+ programVersion: version.version,
174
+ kind,
175
+ [who.field]: who.value,
176
+ date: addDays(input.startDate, w * 7 + session.day - 1),
177
+ week: w + 1,
178
+ day: session.day,
179
+ position,
180
+ key,
181
+ ...(session.focus ? { focus: session.focus } : {}),
182
+ plan: session,
183
+ programTitle,
184
+ ...(who.field === "classType" && forWhom ? { classTypeName: forWhom } : {}),
185
+ });
186
+ });
187
+ });
188
+ for (let start = 0; start < wanted.length; start += SESSIONS_PER_BATCH) {
189
+ await ctx.ops.call("record.createMany", {
190
+ object: SESSION,
191
+ records: wanted.slice(start, start + SESSIONS_PER_BATCH),
192
+ });
193
+ }
194
+ const sessions = made.size + wanted.length;
195
+ // The "done" state last, from the state it was in (ADR 0437): a second call cannot do it twice.
196
+ try {
197
+ await ctx.ops.call("record.update", {
198
+ object: ASSIGNMENT,
199
+ id: assignmentId,
200
+ from: "generating",
201
+ values: { state: "active", sessionCount: sessions },
202
+ });
203
+ }
204
+ catch (error) {
205
+ if (!(error instanceof OpsCallError) || error.code !== "conflict")
206
+ throw error;
207
+ }
208
+ return {
209
+ assignmentId,
210
+ programVersion: version.version,
211
+ sessions,
212
+ startDate: input.startDate,
213
+ endDate,
214
+ };
215
+ },
216
+ });
217
+ // --- Reading sessions ----------------------------------------------------------------------------
218
+ const lastSet = z.object({
219
+ date: z.string().nullable(),
220
+ reps: z.number().nullable(),
221
+ seconds: z.number().nullable(),
222
+ load: z.number().nullable(),
223
+ rpe: z.number().nullable(),
224
+ level: z.number().nullable(),
225
+ });
226
+ const exerciseOut = z.object({
227
+ id: z.string(),
228
+ name: z.string().nullable(),
229
+ video: z.string().nullable(),
230
+ cues: z.string().nullable(),
231
+ measure: z.string().nullable(),
232
+ last: z
233
+ .array(lastSet)
234
+ .describe("The sets of the last time this person did it, before this session"),
235
+ });
236
+ const loggedSet = z.object({
237
+ id: z.string(),
238
+ item: z.string().nullable(),
239
+ exercise: z.string().nullable(),
240
+ setNumber: z.number().nullable(),
241
+ level: z.number().nullable(),
242
+ target: z.object({
243
+ reps: z.number().nullable(),
244
+ seconds: z.number().nullable(),
245
+ load: z.number().nullable(),
246
+ }),
247
+ actual: z.object({
248
+ reps: z.number().nullable(),
249
+ seconds: z.number().nullable(),
250
+ load: z.number().nullable(),
251
+ }),
252
+ rpe: z.number().nullable(),
253
+ note: z.string().nullable(),
254
+ recordedAs: z.string().nullable(),
255
+ recordedByName: z.string().nullable(),
256
+ exerciseName: z.string().nullable().describe("The exercise's name, as it was when logged"),
257
+ });
258
+ const sessionOut = z.object({
259
+ id: z.string(),
260
+ name: z.string().nullable(),
261
+ date: z.string().nullable(),
262
+ week: z.number().nullable(),
263
+ day: z.number().nullable(),
264
+ kind: z.string().nullable(),
265
+ classType: z.string().nullable(),
266
+ assignment: z.string().nullable(),
267
+ programVersion: z.number().nullable(),
268
+ programTitle: z.string().nullable(),
269
+ classTypeName: z.string().nullable(),
270
+ focus: z.string().nullable(),
271
+ state: z.string().nullable(),
272
+ plan: z
273
+ .record(z.string(), z.unknown())
274
+ .nullable()
275
+ .describe("The session of the layout: blocks, items, levels and typed sets"),
276
+ });
277
+ function sessionOf(record) {
278
+ const v = record.values;
279
+ return {
280
+ id: record.id,
281
+ name: text(v.name),
282
+ date: text(v.date),
283
+ week: num(v.week),
284
+ day: num(v.day),
285
+ kind: text(v.kind),
286
+ classType: text(v.classType),
287
+ assignment: text(v.assignment),
288
+ programVersion: num(v.programVersion),
289
+ programTitle: text(v.programTitle),
290
+ classTypeName: text(v.classTypeName),
291
+ focus: text(v.focus),
292
+ state: text(v.state),
293
+ plan: v.plan ?? null,
294
+ };
295
+ }
296
+ function loggedOf(record) {
297
+ const v = record.values;
298
+ return {
299
+ id: record.id,
300
+ item: text(v.item),
301
+ exercise: text(v.exercise),
302
+ setNumber: num(v.setNumber),
303
+ level: num(v.level),
304
+ target: { reps: num(v.targetReps), seconds: num(v.targetSeconds), load: num(v.targetLoad) },
305
+ actual: { reps: num(v.actualReps), seconds: num(v.actualSeconds), load: num(v.actualLoad) },
306
+ rpe: num(v.rpe),
307
+ note: text(v.note),
308
+ recordedAs: text(v.recordedAs),
309
+ recordedByName: text(v.recordedByName),
310
+ exerciseName: text(v.exerciseName),
311
+ };
312
+ }
313
+ /**
314
+ * The exercises a session's plan names, from the bank, with the person's last time at each.
315
+ * `person` is whose sets: null for a member (the seam gives them their own), a filter for staff,
316
+ * or `false` when the call is about no one (a coach reading a class): no last times then.
317
+ */
318
+ async function exercisesFor(ctx, session, person) {
319
+ const plan = session.plan;
320
+ if (!plan)
321
+ return [];
322
+ const ids = [
323
+ ...new Set([
324
+ ...(plan.warmup?.exercises ?? []).map((p) => p.exercise),
325
+ ...prescriptions(plan).map((p) => p.prescription.exercise),
326
+ ]),
327
+ ];
328
+ if (!ids.length)
329
+ return [];
330
+ const bank = await list(ctx, EXERCISE, {
331
+ filter: { field: "id", op: "in", value: ids },
332
+ limit: 200,
333
+ });
334
+ // The person's sets of these exercises before this session, newest first: the last time.
335
+ const earlier = person === false
336
+ ? { items: [] }
337
+ : await all(ctx, LOG, and({ field: "exercise", op: "in", value: ids }, { field: "session", op: "neq", value: session.id }, session.date ? { field: "date", op: "lte", value: session.date } : null, person), { field: "date", direction: "desc" }, 400);
338
+ return ids.map((exerciseId) => {
339
+ const found = bank.items.find((e) => e.id === exerciseId);
340
+ const mine = earlier.items.filter((l) => l.values.exercise === exerciseId);
341
+ const lastSession = mine[0]?.values.session;
342
+ return {
343
+ id: exerciseId,
344
+ name: text(found?.values.name),
345
+ video: text(found?.values.video),
346
+ cues: text(found?.values.cues),
347
+ measure: text(found?.values.measure),
348
+ last: mine
349
+ .filter((l) => l.values.session === lastSession)
350
+ .sort((a, b) => (num(a.values.setNumber) ?? 0) - (num(b.values.setNumber) ?? 0))
351
+ .map((l) => ({
352
+ date: text(l.values.date),
353
+ reps: num(l.values.actualReps),
354
+ seconds: num(l.values.actualSeconds),
355
+ load: num(l.values.actualLoad),
356
+ rpe: num(l.values.rpe),
357
+ level: num(l.values.level),
358
+ })),
359
+ };
360
+ });
361
+ }
362
+ const personInput = id.optional().describe("Staff: the person. A member is always themselves.");
363
+ export const today = defineTool({
364
+ description: "A person's own sessions on a date (default today, UTC: pass the person's local date), " +
365
+ "each with its plan (blocks, items, levels and typed targets), the bank exercises it uses " +
366
+ "and the numbers of the last time they did each. A member sees their own; staff name the " +
367
+ "person. A class type's sessions are programs.classToday. Read-only.",
368
+ input: z.object({ date: date.optional(), personId: personInput }),
369
+ output: z.object({
370
+ date: z.string(),
371
+ sessions: z.array(sessionOut.extend({ exercises: z.array(exerciseOut) })),
372
+ }),
373
+ risk: "read",
374
+ audiences: ["staff", "customer"],
375
+ async handler(input, ctx) {
376
+ const day = input.date ?? todayUtc();
377
+ const person = personFilter(ctx, input.personId);
378
+ const page = await list(ctx, SESSION, {
379
+ filter: and({ field: "date", op: "eq", value: day }, { field: "kind", op: "eq", value: "personal" }, person),
380
+ sort: { field: "week", direction: "asc" },
381
+ limit: 50,
382
+ });
383
+ const sessions = [];
384
+ for (const record of page.items) {
385
+ const session = sessionOf(record);
386
+ sessions.push({ ...session, exercises: await exercisesFor(ctx, session, person) });
387
+ }
388
+ return { date: day, sessions };
389
+ },
390
+ });
391
+ export const sessionGet = defineTool({
392
+ description: "One session: its plan, the bank exercises it uses with the person's last numbers at each, " +
393
+ "and the sets logged on it so far. A member reads their own sessions and their class " +
394
+ "types' (where `personId` is never given); staff read any, and name the person for a " +
395
+ "class session's logs. Read-only.",
396
+ input: z.object({ sessionId: id, personId: personInput }),
397
+ output: z.object({
398
+ session: sessionOut,
399
+ exercises: z.array(exerciseOut),
400
+ logged: z.array(loggedSet),
401
+ }),
402
+ risk: "read",
403
+ audiences: ["staff", "customer"],
404
+ async handler(input, ctx) {
405
+ const record = await get(ctx, SESSION, input.sessionId);
406
+ const session = sessionOf(record);
407
+ const owner = sessionPerson(ctx, record, input.personId);
408
+ // A coach reading a class session for no one in particular: every logged set, no last times.
409
+ const person = owner
410
+ ? { field: "person", op: "eq", value: owner }
411
+ : isCustomer(ctx)
412
+ ? null
413
+ : false;
414
+ const logged = await all(ctx, LOG, and({ field: "session", op: "eq", value: input.sessionId }, person || null), { field: "setNumber", direction: "asc" }, 400);
415
+ return {
416
+ session,
417
+ exercises: await exercisesFor(ctx, session, person),
418
+ logged: logged.items.map(loggedOf),
419
+ };
420
+ },
421
+ });
422
+ /**
423
+ * Whose numbers a session is read or logged for: for a member, themselves (the seam already
424
+ * holds them to it, so null); for staff, the session's person, or the person they name on a class
425
+ * session. A personal session is its person's, so naming another is a mistake in the call.
426
+ */
427
+ function sessionPerson(ctx, record, personId) {
428
+ if (isCustomer(ctx)) {
429
+ if (personId) {
430
+ throw new OpsCallError("invalid_input", "A member never names a person: it is always themselves");
431
+ }
432
+ return null;
433
+ }
434
+ if (record.values.kind === "class")
435
+ return personId ?? null;
436
+ const own = text(record.values.person);
437
+ if (personId && personId !== own) {
438
+ throw new OpsCallError("invalid_input", "This session is another person's: leave personId out, or name its person");
439
+ }
440
+ return own;
441
+ }
442
+ export const classToday = defineTool({
443
+ description: "A class type's sessions on a date (default today, UTC), with their plans: every level of " +
444
+ "every item, typed targets, and the bank exercises. What a coach runs a class from and a " +
445
+ "member reads before it. Notes for coaches only are left out for members. Read-only.",
446
+ input: z.object({ classTypeId: id, date: date.optional() }),
447
+ output: z.object({
448
+ date: z.string(),
449
+ sessions: z.array(sessionOut.extend({ exercises: z.array(exerciseOut) })),
450
+ }),
451
+ risk: "read",
452
+ audiences: ["staff", "customer"],
453
+ async handler(input, ctx) {
454
+ const day = input.date ?? todayUtc();
455
+ const page = await list(ctx, SESSION, {
456
+ filter: {
457
+ and: [
458
+ { field: "date", op: "eq", value: day },
459
+ { field: "kind", op: "eq", value: "class" },
460
+ { field: "classType", op: "eq", value: input.classTypeId },
461
+ ],
462
+ },
463
+ sort: { field: "week", direction: "asc" },
464
+ limit: 20,
465
+ });
466
+ const sessions = [];
467
+ for (const record of page.items) {
468
+ const session = sessionOf(record);
469
+ // A member's own last numbers on a class's exercises are theirs; a coach's call is about no one.
470
+ sessions.push({
471
+ ...session,
472
+ exercises: await exercisesFor(ctx, session, isCustomer(ctx) ? null : false),
473
+ });
474
+ }
475
+ return { date: day, sessions };
476
+ },
477
+ });
478
+ // --- Logging -------------------------------------------------------------------------------------
479
+ /** The prescription and its set's target that `item` (and `level`) names in a session's plan. */
480
+ function targetIn(plan, item, exercise, level, setNumber) {
481
+ const found = prescriptions(plan).filter((p) => p.item === item);
482
+ if (!found.length) {
483
+ throw new OpsCallError("invalid_input", `This session has no item ${item}`, { item });
484
+ }
485
+ const levels = [...new Set(found.map((p) => p.level))];
486
+ if (levels.some((l) => l !== null) && level === undefined) {
487
+ throw new OpsCallError("invalid_input", `Item ${item} has levels: say which was taken`, {
488
+ item,
489
+ levels,
490
+ });
491
+ }
492
+ const atLevel = found.filter((p) => level === undefined || p.level === level);
493
+ if (!atLevel.length) {
494
+ throw new OpsCallError("invalid_input", `Item ${item} has no level ${level}`, { item, levels });
495
+ }
496
+ const match = exercise ? atLevel.filter((p) => p.prescription.exercise === exercise) : atLevel;
497
+ if (!match.length || (!exercise && match.length > 1)) {
498
+ throw new OpsCallError("invalid_input", exercise
499
+ ? `Item ${item}${level ? ` at level ${level}` : ""} does not have that exercise`
500
+ : `Item ${item} has more than one exercise: say which`, { item, exercises: atLevel.map((p) => p.prescription.exercise) });
501
+ }
502
+ const chosen = match[0];
503
+ return {
504
+ prescription: chosen.prescription,
505
+ target: chosen.prescription.sets[setNumber - 1] ?? null,
506
+ level: chosen.level,
507
+ };
508
+ }
509
+ const actual = z.object({
510
+ reps: z.number().int().min(0).max(999).optional(),
511
+ seconds: z.number().int().min(0).max(7200).optional(),
512
+ load: z.number().min(0).max(1000).optional().describe("Kilograms"),
513
+ });
514
+ const rpe = z
515
+ .number()
516
+ .min(1)
517
+ .max(10)
518
+ .refine((n) => Number.isInteger(n * 2), "In halves: 7 or 7.5")
519
+ .optional()
520
+ .describe("How hard it felt, 1 to 10 in halves");
521
+ export const logAdd = defineTool({
522
+ description: "Log one set done on a session: the item (A1), the exercise when the item has more than " +
523
+ "one, the level taken when it has levels, which set (1, 2, …), what was done (reps, " +
524
+ "seconds, load) and how hard it felt (RPE). The target is taken from the session's plan, " +
525
+ "and who recorded it is the caller. A member logs on their own sessions and their class " +
526
+ "types'; a coach logs for a client (on a class session, naming them). Nobody logs on a " +
527
+ "session that is not theirs. Returns the set.",
528
+ input: z.object({
529
+ sessionId: id,
530
+ item: z.string().min(1).max(6),
531
+ exerciseId: id.optional(),
532
+ level: z.number().int().min(1).max(5).optional(),
533
+ setNumber: z.number().int().min(1).max(30),
534
+ actual,
535
+ rpe,
536
+ note: z.string().max(500).optional(),
537
+ personId: personInput,
538
+ }),
539
+ output: loggedSet,
540
+ risk: "write",
541
+ audiences: ["staff", "customer"],
542
+ customerFields: {
543
+ [LOG]: [
544
+ "label",
545
+ "exerciseName",
546
+ "session",
547
+ "assignment",
548
+ "exercise",
549
+ "item",
550
+ "setNumber",
551
+ "level",
552
+ "date",
553
+ "targetReps",
554
+ "targetSeconds",
555
+ "targetLoad",
556
+ "recordedAs",
557
+ ],
558
+ },
559
+ async handler(input, ctx) {
560
+ // A member reads only sessions that are theirs or their class types': another's is not found.
561
+ const record = await get(ctx, SESSION, input.sessionId);
562
+ const session = sessionOf(record);
563
+ const person = sessionPerson(ctx, record, input.personId);
564
+ if (!isCustomer(ctx) && !person) {
565
+ throw new OpsCallError("invalid_input", "A class session: name the person (personId)");
566
+ }
567
+ if (!session.plan)
568
+ throw new OpsCallError("invalid_input", "This session has no plan");
569
+ const { prescription, target, level } = targetIn(session.plan, input.item, input.exerciseId, input.level, input.setNumber);
570
+ const values = {
571
+ label: `${input.item} set ${input.setNumber}`,
572
+ session: input.sessionId,
573
+ assignment: session.assignment,
574
+ exercise: prescription.exercise,
575
+ exerciseName: text((await get(ctx, EXERCISE, prescription.exercise)).values.name),
576
+ item: input.item,
577
+ setNumber: input.setNumber,
578
+ level,
579
+ date: session.date,
580
+ targetReps: target?.kind === "reps" ? target.reps : null,
581
+ targetSeconds: target && target.kind !== "reps" ? target.seconds : null,
582
+ targetLoad: target?.load ?? null,
583
+ actualReps: input.actual.reps ?? null,
584
+ actualSeconds: input.actual.seconds ?? null,
585
+ actualLoad: input.actual.load ?? null,
586
+ rpe: input.rpe ?? null,
587
+ note: input.note ?? null,
588
+ recordedAs: isCustomer(ctx) ? "self" : "staff",
589
+ };
590
+ if (isCustomer(ctx)) {
591
+ // The host makes it the caller's, and refuses a session they cannot see (ADR 0447).
592
+ return loggedOf(await ctx.ops.call("my.create", { object: LOG, values }));
593
+ }
594
+ const caller = ctx.caller?.kind === "staff" ? ctx.caller : null;
595
+ return loggedOf(await ctx.ops.call("record.create", {
596
+ object: LOG,
597
+ values: {
598
+ ...values,
599
+ person,
600
+ ...(caller ? { recordedBy: caller.userId, recordedByName: caller.name } : {}),
601
+ },
602
+ }));
603
+ },
604
+ });
605
+ export const logUpdate = defineTool({
606
+ description: "Change a logged set's numbers, effort or note. A member changes their own sets only; " +
607
+ "staff any. The target, the exercise and who recorded it stay as they were. Returns the set.",
608
+ input: z.object({
609
+ logId: id,
610
+ actual: actual.optional(),
611
+ rpe,
612
+ note: z.string().max(500).nullable().optional(),
613
+ }),
614
+ output: loggedSet,
615
+ risk: "write",
616
+ audiences: ["staff", "customer"],
617
+ async handler(input, ctx) {
618
+ const values = {
619
+ ...(input.actual?.reps !== undefined ? { actualReps: input.actual.reps } : {}),
620
+ ...(input.actual?.seconds !== undefined ? { actualSeconds: input.actual.seconds } : {}),
621
+ ...(input.actual?.load !== undefined ? { actualLoad: input.actual.load } : {}),
622
+ ...(input.rpe !== undefined ? { rpe: input.rpe } : {}),
623
+ ...(input.note !== undefined ? { note: input.note } : {}),
624
+ };
625
+ if (!Object.keys(values).length) {
626
+ return loggedOf(await get(ctx, LOG, input.logId));
627
+ }
628
+ return loggedOf(await ctx.ops.call(isCustomer(ctx) ? "my.update" : "record.update", {
629
+ object: LOG,
630
+ id: input.logId,
631
+ values,
632
+ }));
633
+ },
634
+ });
635
+ export const sessionComplete = defineTool({
636
+ description: "Mark one of a person's sessions done or skipped (or back to planned). A member marks their " +
637
+ "own; staff any personal session. A class type's sessions are not marked by members. Made " +
638
+ "from the session's current state, so two marks at once count once. Returns the session.",
639
+ input: z.object({
640
+ sessionId: id,
641
+ state: z.enum(["done", "skipped", "planned"]).default("done"),
642
+ }),
643
+ output: z.object({ changed: z.boolean(), session: sessionOut }),
644
+ risk: "write",
645
+ audiences: ["staff", "customer"],
646
+ customerFields: { [SESSION]: ["state", "completedAt"] },
647
+ async handler(input, ctx) {
648
+ const current = sessionOf(await get(ctx, SESSION, input.sessionId));
649
+ if (current.state === input.state)
650
+ return { changed: false, session: current };
651
+ const from = current.state ?? "planned";
652
+ const marked = input.state === "planned" ? { completedAt: null } : { completedAt: new Date().toISOString() };
653
+ const caller = ctx.caller?.kind === "staff" ? ctx.caller : null;
654
+ try {
655
+ const after = await ctx.ops.call(isCustomer(ctx) ? "my.update" : "record.update", {
656
+ object: SESSION,
657
+ id: input.sessionId,
658
+ from,
659
+ values: {
660
+ state: input.state,
661
+ ...marked,
662
+ ...(caller
663
+ ? input.state === "planned"
664
+ ? { completedBy: null, completedByName: null }
665
+ : { completedBy: caller.userId, completedByName: caller.name }
666
+ : {}),
667
+ },
668
+ });
669
+ return { changed: true, session: sessionOf(after) };
670
+ }
671
+ catch (error) {
672
+ if (!(error instanceof OpsCallError) || error.code !== "conflict")
673
+ throw error;
674
+ // Marked by someone else meanwhile: report the session as it is now.
675
+ return { changed: false, session: sessionOf(await get(ctx, SESSION, input.sessionId)) };
676
+ }
677
+ },
678
+ });
679
+ // --- History and progress ------------------------------------------------------------------------
680
+ const best = z.object({
681
+ load: z.number().nullable().describe("Heaviest load in one set"),
682
+ reps: z.number().nullable().describe("Most reps in one set"),
683
+ seconds: z.number().nullable().describe("Longest time in one set"),
684
+ });
685
+ /** Bests over sets: the heaviest, the most reps, the longest. */
686
+ function bestOf(sets) {
687
+ const max = (field) => {
688
+ const values = sets.map((s) => num(s.values[field])).filter((n) => n !== null);
689
+ return values.length ? Math.max(...values) : null;
690
+ };
691
+ return { load: max("actualLoad"), reps: max("actualReps"), seconds: max("actualSeconds") };
692
+ }
693
+ export const history = defineTool({
694
+ description: "Every set a person logged of one exercise, oldest first (date, set, level, target and " +
695
+ "what was done, effort), and their bests at it (heaviest load, most reps, longest time). " +
696
+ "A member reads their own; staff name the person. At most 2,000 sets; `capped` says when " +
697
+ "there were more. Read-only.",
698
+ input: z.object({
699
+ exerciseId: id,
700
+ personId: personInput,
701
+ from: date.optional(),
702
+ until: date.optional(),
703
+ }),
704
+ output: z.object({
705
+ exercise: z.object({ id: z.string(), name: z.string().nullable() }),
706
+ sets: z.array(loggedSet.extend({ date: z.string().nullable() })),
707
+ best,
708
+ capped: z.boolean(),
709
+ }),
710
+ risk: "read",
711
+ audiences: ["staff", "customer"],
712
+ async handler(input, ctx) {
713
+ const person = personFilter(ctx, input.personId);
714
+ const exercise = await get(ctx, EXERCISE, input.exerciseId);
715
+ const sets = await all(ctx, LOG, and({ field: "exercise", op: "eq", value: input.exerciseId }, person, input.from ? { field: "date", op: "gte", value: input.from } : null, input.until ? { field: "date", op: "lte", value: input.until } : null), { field: "date", direction: "asc" }, SETS_READ_MAX);
716
+ return {
717
+ exercise: { id: exercise.id, name: text(exercise.values.name) },
718
+ sets: sets.items.map((s) => ({ ...loggedOf(s), date: text(s.values.date) })),
719
+ best: bestOf(sets.items),
720
+ capped: sets.capped,
721
+ };
722
+ },
723
+ });
724
+ export const progress = defineTool({
725
+ description: "A person's training at a glance: for each exercise they logged, how many sets, the first " +
726
+ "and last date, and their bests; and for each of their assignments, sessions planned, done " +
727
+ "and skipped. Optionally only one assignment. A member reads their own; staff name the " +
728
+ "person. Worked out over at most 2,000 sets (`capped`). Read-only.",
729
+ input: z.object({ personId: personInput, assignmentId: id.optional() }),
730
+ output: z.object({
731
+ exercises: z.array(z.object({
732
+ id: z.string(),
733
+ name: z.string().nullable(),
734
+ sets: z.number(),
735
+ first: z.string().nullable(),
736
+ last: z.string().nullable(),
737
+ best,
738
+ })),
739
+ assignments: z.array(z.object({
740
+ id: z.string(),
741
+ title: z.string().nullable(),
742
+ sessions: z.number(),
743
+ done: z.number(),
744
+ skipped: z.number(),
745
+ planned: z.number(),
746
+ })),
747
+ capped: z.boolean(),
748
+ }),
749
+ risk: "read",
750
+ audiences: ["staff", "customer"],
751
+ async handler(input, ctx) {
752
+ const person = personFilter(ctx, input.personId);
753
+ const only = input.assignmentId
754
+ ? { field: "assignment", op: "eq", value: input.assignmentId }
755
+ : null;
756
+ const sets = await all(ctx, LOG, and(person, only), { field: "date", direction: "asc" }, SETS_READ_MAX);
757
+ const byExercise = new Map();
758
+ for (const set of sets.items) {
759
+ const exercise = text(set.values.exercise);
760
+ if (exercise)
761
+ byExercise.set(exercise, [...(byExercise.get(exercise) ?? []), set]);
762
+ }
763
+ const ids = [...byExercise.keys()];
764
+ const names = new Map();
765
+ for (let start = 0; start < ids.length; start += 200) {
766
+ const page = await list(ctx, EXERCISE, {
767
+ filter: { field: "id", op: "in", value: ids.slice(start, start + 200) },
768
+ limit: 200,
769
+ });
770
+ for (const e of page.items)
771
+ names.set(e.id, text(e.values.name));
772
+ }
773
+ const assignments = await all(ctx, ASSIGNMENT, and(person, { field: "kind", op: "eq", value: "personal" }, input.assignmentId ? { field: "id", op: "eq", value: input.assignmentId } : null), { field: "startDate", direction: "asc" }, 100);
774
+ const summaries = [];
775
+ for (const assignment of assignments.items) {
776
+ const sessions = await all(ctx, SESSION, { field: "assignment", op: "eq", value: assignment.id }, { field: "date", direction: "asc" }, 1000);
777
+ const count = (state) => sessions.items.filter((s) => s.values.state === state).length;
778
+ summaries.push({
779
+ id: assignment.id,
780
+ title: text(assignment.values.title),
781
+ sessions: sessions.items.length,
782
+ done: count("done"),
783
+ skipped: count("skipped"),
784
+ planned: count("planned"),
785
+ });
786
+ }
787
+ return {
788
+ exercises: ids.map((exerciseId) => {
789
+ const mine = byExercise.get(exerciseId) ?? [];
790
+ return {
791
+ id: exerciseId,
792
+ name: names.get(exerciseId) ?? null,
793
+ sets: mine.length,
794
+ first: text(mine[0]?.values.date),
795
+ last: text(mine.at(-1)?.values.date),
796
+ best: bestOf(mine),
797
+ };
798
+ }),
799
+ assignments: summaries,
800
+ capped: sets.capped,
801
+ };
802
+ },
803
+ });
804
+ // --- Drafting and importing (step 6) ---------------------------------------------------------------
805
+ /** The bank, as the authoring functions read it. */
806
+ async function bankOf(ctx) {
807
+ const rows = await all(ctx, EXERCISE, undefined, { field: "name", direction: "asc" }, 2000);
808
+ return rows.items.map((e) => ({
809
+ id: e.id,
810
+ name: text(e.values.name) ?? "",
811
+ measure: text(e.values.measure),
812
+ theme: text(e.values.theme),
813
+ level: text(e.values.level),
814
+ }));
815
+ }
816
+ const workingCopy = z.object({
817
+ programId: z.string(),
818
+ title: z.string(),
819
+ weeks: z.number(),
820
+ sessions: z.number(),
821
+ published: z.literal(false).describe("Always false: a person publishes it"),
822
+ });
823
+ export const draft = defineTool({
824
+ description: 'Draft a program from a brief ("12 weeks of handstand strength, 3 sessions a week") as a ' +
825
+ "working copy for a coach to edit: weeks of sessions of blocks of exercises taken only from " +
826
+ "the bank, with default sets. The assistant reads the brief with the extract model role when " +
827
+ "the deployment has AI, and the numbers and words in it otherwise. It never publishes: a " +
828
+ "person with the publish permission does, after editing. Returns the new program.",
829
+ input: z.object({
830
+ brief: z.string().trim().min(3).max(2000),
831
+ title: z.string().trim().min(1).max(200).optional(),
832
+ kind: z.enum(["class", "client", "course"]).default("client"),
833
+ }),
834
+ output: workingCopy.extend({
835
+ exercises: z.array(z.object({ id: z.string(), name: z.string() })),
836
+ }),
837
+ risk: "write",
838
+ async handler(input, ctx) {
839
+ const bank = await bankOf(ctx);
840
+ if (!bank.length) {
841
+ throw new OpsCallError("invalid_input", "The exercise bank is empty: add exercises first");
842
+ }
843
+ const floor = readBrief(input.brief);
844
+ let plan = floor;
845
+ try {
846
+ // A model role, never a model id: the deployment decides which model reads it.
847
+ const read = await ctx.ai.extract(input.brief, {
848
+ weeks: "How many weeks the program runs, a whole number",
849
+ sessionsPerWeek: "How many sessions a week, a whole number from 1 to 7",
850
+ focus: "The themes, body areas or moves it is about, as a comma-separated list",
851
+ });
852
+ const weeks = Number(read.weeks);
853
+ const perWeek = Number(read.sessionsPerWeek);
854
+ const focus = typeof read.focus === "string" ? read.focus.toLowerCase().split(/[,;]/) : [];
855
+ plan = {
856
+ weeks: Number.isInteger(weeks) && weeks >= 1 && weeks <= 52 ? weeks : floor.weeks,
857
+ sessionsPerWeek: Number.isInteger(perWeek) && perWeek >= 1 && perWeek <= 7
858
+ ? perWeek
859
+ : floor.sessionsPerWeek,
860
+ focus: [...new Set([...focus.map((f) => f.trim()).filter(Boolean), ...floor.focus])],
861
+ };
862
+ }
863
+ catch {
864
+ // No AI on this deployment, or it failed: the brief's own numbers and words.
865
+ }
866
+ const chosen = pickExercises(bank, plan.focus).slice(0, 12);
867
+ const layout = draftLayout(plan, chosen);
868
+ const title = input.title ?? `Draft: ${input.brief.slice(0, 60)}`;
869
+ const created = await ctx.ops.call("record.create", {
870
+ object: PROGRAM,
871
+ values: {
872
+ title,
873
+ kind: input.kind,
874
+ guidance: `Drafted from the brief: ${input.brief}`.slice(0, 5000),
875
+ layout,
876
+ },
877
+ });
878
+ return {
879
+ programId: created.id,
880
+ title,
881
+ weeks: layout.weeks.length,
882
+ sessions: layout.weeks.reduce((n, w) => n + w.sessions.length, 0),
883
+ published: false,
884
+ exercises: chosen.map((e) => ({ id: e.id, name: e.name })),
885
+ };
886
+ },
887
+ });
888
+ export const importText = defineTool({
889
+ description: "Turn pasted program shorthand, or a document's text, into a working copy with structured " +
890
+ "targets: Title:, Guidance:, Week:, Session: (a weekday names its day), Focus:, Warm-up: " +
891
+ "with - lines, Block A: with its rounds, items A1: with an exercise (for everyone) or with " +
892
+ 'level lines 1: to 5: ("+" done together, "|" alternatives), * notes for coaches and TV: ' +
893
+ "notes shown to members. Exercises are matched to the bank by name. Every line it could not " +
894
+ "read is listed with why, for the coach to fix; nothing is guessed. Never publishes. Returns " +
895
+ "the new program and the unread lines.",
896
+ input: z.object({
897
+ text: z.string().min(1).max(200_000),
898
+ title: z.string().trim().min(1).max(200).optional(),
899
+ kind: z.enum(["class", "client", "course"]).default("class"),
900
+ }),
901
+ output: workingCopy.extend({
902
+ items: z.number(),
903
+ unread: z.array(z.object({ line: z.number(), text: z.string(), reason: z.string() })),
904
+ }),
905
+ risk: "write",
906
+ async handler(input, ctx) {
907
+ const bank = await bankOf(ctx);
908
+ const read = readProgramText(input.text, bank);
909
+ const title = input.title ?? read.title ?? "Imported program";
910
+ const created = await ctx.ops.call("record.create", {
911
+ object: PROGRAM,
912
+ values: {
913
+ title,
914
+ kind: input.kind,
915
+ ...(read.guidance ? { guidance: read.guidance } : {}),
916
+ layout: read.layout,
917
+ },
918
+ });
919
+ const sessions = read.layout.weeks.flatMap((w) => w.sessions);
920
+ return {
921
+ programId: created.id,
922
+ title,
923
+ weeks: read.layout.weeks.length,
924
+ sessions: sessions.length,
925
+ items: sessions.reduce((n, s) => n + s.blocks.reduce((m, b) => m + b.items.length, 0), 0),
926
+ published: false,
927
+ unread: read.unread,
928
+ };
929
+ },
930
+ });