@composable-os/pack-equipment 0.0.0-stage → 0.1.0-beta.16

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.
package/dist/tools.js ADDED
@@ -0,0 +1,767 @@
1
+ // Equipment's staff tools (stage 59, step 3; ADR 0862). They become operations x.equipment.<tool>,
2
+ // run in the sandbox, and reach the host only through ctx.ops. None of them holds a rule: the
3
+ // tag's uniqueness, which moves an item and a fault may make, who may make them and what each move
4
+ // needs are the host's (index.ts). A tool asks, and reports what the host answered.
5
+ //
6
+ // Who may call which:
7
+ // - equipment:report (every staff member; granted to a coach or a cleaner, ADR 0600): the
8
+ // register, one item, report a fault (with or without taking the item out), take an item
9
+ // out of service;
10
+ // - equipment:manage (restricted, ADR 0625: admins and those granted it): put an item back in
11
+ // service (a person's own act, never an AI's: decision 4), retire it, triage faults, and
12
+ // correct a fault's report or why an item is out (fields only the tools write).
13
+ // Taking out, retiring, triage and corrections are a person's acts: the assistant, an MCP client
14
+ // or an automation may ask, and the call waits for a person (personApproves, ADR 0552). So is
15
+ // `reportFault`, which takes the item out in the same call (decision 3); `reportFaultOnly`
16
+ // changes nothing but the new fault, and the assistant may make it as an ordinary write.
17
+ import { defineTool, OpsCallError, z } from "@composable-os/sdk";
18
+ export const ITEM = "equipment.item";
19
+ export const FAULT = "equipment.fault";
20
+ export const REPORT = "equipment:report";
21
+ export const MANAGE = "equipment:manage";
22
+ const text = (value) => value === null || value === undefined || value === "" ? null : String(value);
23
+ const num = (value) => value === null || value === undefined || value === "" ? null : Number(value);
24
+ const ids = z.string().min(1).max(64);
25
+ const isConflict = (error) => error instanceof OpsCallError
26
+ ? error.code === "conflict"
27
+ : error?.code === "conflict";
28
+ const ITEM_STATES = ["in_service", "out_of_service", "retired"];
29
+ const FAULT_STATES = ["reported", "acknowledged", "fixed", "not_a_fault", "duplicate"];
30
+ const SEVERITIES = ["safety_risk", "not_working", "worn"];
31
+ /** A date (YYYY-MM-DD) on or after the day of `at`: under warranty on that day. */
32
+ const coversDay = (until, at) => until !== null && typeof at === "string" && at.length >= 10 && until >= at.slice(0, 10);
33
+ const staffOf = (ctx) => (ctx.caller?.kind === "staff" ? ctx.caller : null);
34
+ // --- The register --------------------------------------------------------------------------------
35
+ const registerRow = z.object({
36
+ id: z.string(),
37
+ name: z.string().nullable(),
38
+ tag: z.string().nullable(),
39
+ category: z.string().nullable(),
40
+ place: z.string().nullable(),
41
+ state: z.enum(ITEM_STATES).nullable(),
42
+ outSince: z.string().nullable(),
43
+ outReason: z.string().nullable(),
44
+ keeper: z.string().nullable().describe("The keeper's account id; empty means the managers"),
45
+ issuedTo: z.string().nullable(),
46
+ supplier: z.string().nullable(),
47
+ warrantyUntil: z.string().nullable(),
48
+ openFaults: z.number().describe("Faults reported or acknowledged, not yet closed"),
49
+ safetyRisks: z.number().describe("Of the open faults, those reported as a safety risk"),
50
+ });
51
+ /** The most items one call lists. */
52
+ export const REGISTER_LIMIT = 200;
53
+ export const register = defineTool({
54
+ description: "The equipment register: items with their tag, category, place, state (in service, out of " +
55
+ "service with why and since when, retired), keeper, supplier, warranty end and how many " +
56
+ "faults are open. Out-of-service items and those with open safety risks come first. Retired " +
57
+ "items are left out unless state is retired. Narrow it with state, category, place or q (a " +
58
+ "name, tag, make, model or serial). Read-only.",
59
+ input: z.object({
60
+ state: z.enum(ITEM_STATES).optional(),
61
+ category: z.string().max(80).optional(),
62
+ place: z.string().max(200).optional().describe("Only items whose place contains this"),
63
+ q: z.string().trim().min(1).max(100).optional(),
64
+ }),
65
+ output: z.object({ items: z.array(registerRow), truncated: z.boolean() }),
66
+ risk: "read",
67
+ permission: REPORT,
68
+ async handler(input, ctx) {
69
+ const where = [];
70
+ const params = [];
71
+ if (input.state) {
72
+ where.push("i.state = ?");
73
+ params.push(input.state);
74
+ }
75
+ else {
76
+ where.push("i.state <> 'retired'");
77
+ }
78
+ if (input.category) {
79
+ where.push("i.category = ?");
80
+ params.push(input.category);
81
+ }
82
+ if (input.place) {
83
+ where.push("instr(lower(i.place), lower(?)) > 0");
84
+ params.push(input.place);
85
+ }
86
+ if (input.q) {
87
+ where.push("(instr(lower(i.name), lower(?)) > 0 OR lower(i.tag) = lower(?) OR " +
88
+ "instr(lower(coalesce(i.make, '') || ' ' || coalesce(i.model, '') || ' ' || " +
89
+ "coalesce(i.serial, '')), lower(?)) > 0)");
90
+ params.push(input.q, input.q, input.q);
91
+ }
92
+ // One statement whatever the size of the register: the items, their supplier's name and the
93
+ // open faults counted per item in one grouped join (AC 17).
94
+ const result = await ctx.ops.call("query.sql", {
95
+ sql: "SELECT i.id AS id, i.name AS name, i.tag AS tag, i.category AS category, " +
96
+ "i.place AS place, i.state AS state, i.out_since AS out_since, " +
97
+ "i.out_reason AS out_reason, i.keeper AS keeper, i.issued_to AS issued_to, " +
98
+ "o.name AS supplier, i.warranty_until AS warranty_until, " +
99
+ "coalesce(f.open_faults, 0) AS open_faults, coalesce(f.safety_risks, 0) AS safety_risks " +
100
+ "FROM rec_x_equipment_item i " +
101
+ "LEFT JOIN rec_organisation o ON o.id = i.supplier " +
102
+ "LEFT JOIN (SELECT item, count(*) AS open_faults, " +
103
+ "sum(CASE WHEN severity = 'safety_risk' THEN 1 ELSE 0 END) AS safety_risks " +
104
+ "FROM rec_x_equipment_fault WHERE state IN ('reported', 'acknowledged') GROUP BY item) f " +
105
+ "ON f.item = i.id " +
106
+ `WHERE ${where.join(" AND ")} ` +
107
+ "ORDER BY (i.state = 'out_of_service') DESC, coalesce(f.safety_risks, 0) DESC, " +
108
+ "coalesce(f.open_faults, 0) DESC, i.name ASC, i.id ASC",
109
+ params,
110
+ // The host stops at this many rows and says when there were more.
111
+ maxRows: REGISTER_LIMIT,
112
+ });
113
+ return {
114
+ truncated: result.truncated === true,
115
+ items: result.rows.slice(0, REGISTER_LIMIT).map((row) => ({
116
+ id: String(row.id),
117
+ name: text(row.name),
118
+ tag: text(row.tag),
119
+ category: text(row.category),
120
+ place: text(row.place),
121
+ state: text(row.state) ?? null,
122
+ outSince: text(row.out_since),
123
+ outReason: text(row.out_reason),
124
+ keeper: text(row.keeper),
125
+ issuedTo: text(row.issued_to),
126
+ supplier: text(row.supplier),
127
+ warrantyUntil: text(row.warranty_until),
128
+ openFaults: Number(row.open_faults ?? 0),
129
+ safetyRisks: Number(row.safety_risks ?? 0),
130
+ })),
131
+ };
132
+ },
133
+ });
134
+ // --- One item ------------------------------------------------------------------------------------
135
+ const faultRow = z.object({
136
+ id: z.string(),
137
+ title: z.string().nullable(),
138
+ description: z.string().nullable(),
139
+ severity: z.enum(SEVERITIES).nullable(),
140
+ state: z.enum(FAULT_STATES).nullable(),
141
+ reportedBy: z.string().nullable(),
142
+ reportedByName: z.string().nullable(),
143
+ closedWhy: z.string().nullable(),
144
+ reportedAt: z.string().nullable(),
145
+ underWarranty: z
146
+ .boolean()
147
+ .describe("The item's warranty had not ended on the day it was reported"),
148
+ });
149
+ const itemOutput = z.object({
150
+ id: z.string(),
151
+ name: z.string().nullable(),
152
+ tag: z.string().nullable(),
153
+ category: z.string().nullable(),
154
+ place: z.string().nullable(),
155
+ make: z.string().nullable(),
156
+ model: z.string().nullable(),
157
+ serial: z.string().nullable(),
158
+ state: z.enum(ITEM_STATES).nullable(),
159
+ outSince: z.string().nullable(),
160
+ outReason: z.string().nullable(),
161
+ keeper: z.string().nullable(),
162
+ issuedTo: z.string().nullable(),
163
+ supplierId: z.string().nullable(),
164
+ supplier: z.string().nullable(),
165
+ boughtOn: z.string().nullable(),
166
+ warrantyUntil: z.string().nullable(),
167
+ warrantyNotes: z.string().nullable(),
168
+ renewalDue: z.string().nullable(),
169
+ listForMembers: z.string().nullable(),
170
+ notes: z.string().nullable(),
171
+ costs: z.object({
172
+ purchase: z.number().nullable().describe("What it cost to buy, in the base currency"),
173
+ }),
174
+ faults: z.array(faultRow).describe("Newest first, at most 50"),
175
+ moreFaults: z.boolean(),
176
+ });
177
+ /** The most faults one item's answer lists. */
178
+ export const ITEM_FAULTS_LIMIT = 50;
179
+ async function readItem(ctx, id) {
180
+ return ctx.ops.call("record.get", { object: ITEM, id });
181
+ }
182
+ export const item = defineTool({
183
+ description: "One item of the register: its details, state (and why and since when it is out of " +
184
+ "service), keeper, who has it, supplier, purchase cost, warranty and renewal dates, and its " +
185
+ "faults newest first, each saying whether the item was under warranty when it was reported. " +
186
+ "Costs are for every staff member. Read-only.",
187
+ input: z.object({ itemId: ids }),
188
+ output: itemOutput,
189
+ risk: "read",
190
+ permission: REPORT,
191
+ async handler(input, ctx) {
192
+ const record = await readItem(ctx, input.itemId);
193
+ const v = record.values;
194
+ const supplierId = text(v.supplier);
195
+ const [supplier, faults] = await Promise.all([
196
+ supplierId
197
+ ? ctx.ops
198
+ .call("query.sql", {
199
+ sql: "SELECT name FROM rec_organisation WHERE id = ?",
200
+ params: [supplierId],
201
+ })
202
+ .then((r) => text(r.rows[0]?.name))
203
+ : Promise.resolve(null),
204
+ ctx.ops.call("record.list", {
205
+ object: FAULT,
206
+ filter: { field: "item", op: "eq", value: record.id },
207
+ sort: { field: "createdAt", direction: "desc" },
208
+ limit: ITEM_FAULTS_LIMIT + 1,
209
+ }),
210
+ ]);
211
+ const warrantyUntil = text(v.warrantyUntil);
212
+ return {
213
+ id: record.id,
214
+ name: text(v.name),
215
+ tag: text(v.tag),
216
+ category: text(v.category),
217
+ place: text(v.place),
218
+ make: text(v.make),
219
+ model: text(v.model),
220
+ serial: text(v.serial),
221
+ state: text(v.state) ?? null,
222
+ outSince: text(v.outSince),
223
+ outReason: text(v.outReason),
224
+ keeper: text(v.keeper),
225
+ issuedTo: text(v.issuedTo),
226
+ supplierId,
227
+ supplier,
228
+ boughtOn: text(v.boughtOn),
229
+ warrantyUntil,
230
+ warrantyNotes: text(v.warrantyNotes),
231
+ renewalDue: text(v.renewalDue),
232
+ listForMembers: text(v.listForMembers),
233
+ notes: text(v.notes),
234
+ costs: { purchase: num(v.cost) },
235
+ moreFaults: faults.items.length > ITEM_FAULTS_LIMIT,
236
+ faults: faults.items.slice(0, ITEM_FAULTS_LIMIT).map((f) => ({
237
+ id: f.id,
238
+ title: f.title,
239
+ description: text(f.values.description),
240
+ severity: text(f.values.severity) ?? null,
241
+ state: text(f.values.state) ?? null,
242
+ reportedBy: text(f.values.reportedBy),
243
+ reportedByName: text(f.values.reportedByName),
244
+ closedWhy: text(f.values.closedWhy),
245
+ reportedAt: f.createdAt ?? null,
246
+ underWarranty: coversDay(warrantyUntil, f.createdAt),
247
+ })),
248
+ };
249
+ },
250
+ });
251
+ // --- Out of service ------------------------------------------------------------------------------
252
+ /**
253
+ * Takes the item out of service, from in service only (ADR 0437): of two people taking it out at
254
+ * once, one write moves it. False when it was not in service; the caller says what it is.
255
+ */
256
+ async function moveOut(ctx, itemId, reason) {
257
+ try {
258
+ await ctx.ops.call("record.update", {
259
+ object: ITEM,
260
+ id: itemId,
261
+ from: "in_service",
262
+ values: {
263
+ state: "out_of_service",
264
+ outReason: reason,
265
+ outSince: new Date().toISOString(),
266
+ },
267
+ });
268
+ return true;
269
+ }
270
+ catch (error) {
271
+ if (isConflict(error))
272
+ return false;
273
+ throw error;
274
+ }
275
+ }
276
+ const reason = z.string().trim().min(3).max(500);
277
+ const STATE_WORDS = {
278
+ in_service: "in service",
279
+ out_of_service: "out of service",
280
+ retired: "retired",
281
+ };
282
+ /**
283
+ * Takes the item out of service and says what happened, never throwing: for a report whose fault
284
+ * is already recorded, which must say truthfully that the take-out failed.
285
+ */
286
+ async function tryMoveOut(ctx, itemId, why) {
287
+ try {
288
+ return (await moveOut(ctx, itemId, why)) ? { moved: true } : { moved: false, error: null };
289
+ }
290
+ catch (error) {
291
+ return { moved: false, error: error instanceof Error ? error.message : String(error) };
292
+ }
293
+ }
294
+ /** A short, stable digest of a text (FNV-1a, 32 bits): enough to tell one report from another. */
295
+ function digest(value) {
296
+ let hash = 0x811c9dc5;
297
+ for (let i = 0; i < value.length; i++) {
298
+ hash ^= value.charCodeAt(i);
299
+ hash = Math.imul(hash, 0x01000193) >>> 0;
300
+ }
301
+ return hash.toString(36);
302
+ }
303
+ const reportInput = {
304
+ itemId: ids,
305
+ description: z.string().trim().min(3).max(4000),
306
+ severity: z.enum(SEVERITIES),
307
+ requestId: z
308
+ .string()
309
+ .trim()
310
+ .min(1)
311
+ .max(64)
312
+ .optional()
313
+ .describe("The caller's own id for this report, the same on every retry: a retry finds the report " +
314
+ "it made rather than making a second. Left out, a report by the same person on the same " +
315
+ "item with the same words and severity, still open, is the same report."),
316
+ };
317
+ const reportOutput = z.object({
318
+ faultId: z.string(),
319
+ itemId: z.string(),
320
+ alreadyReported: z
321
+ .boolean()
322
+ .describe("This report was made before (a retry, or the same report again): no second fault"),
323
+ takenOut: z.boolean().describe("This call took the item out of service"),
324
+ takeOutFailed: z
325
+ .string()
326
+ .nullable()
327
+ .describe("Why the take-out asked for did not happen, when it did not; the fault is recorded"),
328
+ itemState: z.enum(ITEM_STATES).nullable(),
329
+ underWarranty: z.boolean(),
330
+ message: z.string(),
331
+ });
332
+ /**
333
+ * Records a fault once: found by its report key (the caller's request id, or the reporter, item,
334
+ * severity and words) among the open faults before it is made, and by the database's uniqueness
335
+ * on the key when two calls make it at once. The host refuses a fault on a retired item.
336
+ */
337
+ async function recordFault(ctx, input) {
338
+ const staff = staffOf(ctx);
339
+ const who = staff?.userId ?? "-";
340
+ // The item is part of every key: a request id used again on another item is another report.
341
+ const reportKey = input.requestId
342
+ ? `r:${who}:${input.itemId}:${input.requestId}`
343
+ : `k:${who}:${input.itemId}:${input.severity}:${digest(input.description.toLowerCase())}`;
344
+ /**
345
+ * A fault found by the key is this report only when it says the same: the same item, words and
346
+ * severity. Anything else is another report under a reused request id: refused, never answered
347
+ * as "already reported" (the report it carries would be lost).
348
+ */
349
+ const same = (found) => {
350
+ const v = found.values;
351
+ const words = (x) => String(x ?? "")
352
+ .trim()
353
+ .toLowerCase();
354
+ if (v.item !== input.itemId ||
355
+ v.severity !== input.severity ||
356
+ words(v.description) !== words(input.description)) {
357
+ throw new OpsCallError("conflict", "This request id was used for another report. Send this report with a new request id, or with none.", { reason: "request_id_reused", faultId: found.id });
358
+ }
359
+ return found;
360
+ };
361
+ const find = async () => (await ctx.ops.call("record.list", {
362
+ object: FAULT,
363
+ filter: {
364
+ and: [
365
+ { field: "reportKey", op: "eq", value: reportKey },
366
+ { field: "state", op: "in", value: ["reported", "acknowledged"] },
367
+ ],
368
+ },
369
+ limit: 1,
370
+ })).items[0];
371
+ const earlier = await find();
372
+ if (earlier)
373
+ return { fault: same(earlier), again: true };
374
+ try {
375
+ const fault = await ctx.ops.call("record.create", {
376
+ object: FAULT,
377
+ values: {
378
+ item: input.itemId,
379
+ description: input.description,
380
+ severity: input.severity,
381
+ reportKey,
382
+ reportedBy: staff?.userId ?? null,
383
+ reportedByName: staff?.name || null,
384
+ },
385
+ });
386
+ return { fault, again: false };
387
+ }
388
+ catch (error) {
389
+ // The same report made at the same moment by another call: that one is this one.
390
+ const raced = isConflict(error) ? await find() : undefined;
391
+ if (raced)
392
+ return { fault: same(raced), again: true };
393
+ throw error;
394
+ }
395
+ }
396
+ async function reportHandler(input, ctx) {
397
+ // The report first: a call stopped part way leaves the fault recorded, never an item taken
398
+ // out with nothing saying why; a retry finds it and goes on to the take-out.
399
+ const { fault, again } = await recordFault(ctx, input);
400
+ const out = input.takeOut
401
+ ? await tryMoveOut(ctx, input.itemId, input.takeOut.reason)
402
+ : { moved: false, error: null };
403
+ const after = await readItem(ctx, input.itemId).catch(() => null);
404
+ const state = text(after?.values.state) ?? null;
405
+ const underWarranty = coversDay(text(after?.values.warrantyUntil), fault.createdAt ?? new Date().toISOString());
406
+ const failed = input.takeOut && !out.moved
407
+ ? out.error
408
+ ? `it could not be taken out of service (${out.error}); take it out with takeOut`
409
+ : `it was not taken out of service: it is ${STATE_WORDS[state ?? ""] ?? "not in service"}`
410
+ : null;
411
+ const said = input.takeOut
412
+ ? out.moved
413
+ ? " It is out of service."
414
+ : ` The fault is recorded, but ${failed}.`
415
+ : "";
416
+ return {
417
+ faultId: fault.id,
418
+ itemId: input.itemId,
419
+ alreadyReported: again,
420
+ takenOut: out.moved,
421
+ takeOutFailed: input.takeOut && !out.moved ? failed : null,
422
+ itemState: state,
423
+ underWarranty,
424
+ message: `${again ? "Already reported." : "Fault reported."}${said}${underWarranty ? " The item is under warranty." : ""}`,
425
+ };
426
+ }
427
+ export const reportFault = defineTool({
428
+ description: "Report a fault on an item and take it out of service in the same call: what is wrong " +
429
+ "(never an injury: that goes on the incident form), how bad (safety_risk, not_working, worn) " +
430
+ "and, in takeOut, why it must not be used. For a staff member who sees something unsafe " +
431
+ "(decision 3). To report without taking it out, use reportFaultOnly. The report is recorded " +
432
+ "as the caller's, once: a retry with the same requestId (or the same report while it is " +
433
+ "open) finds it. The answer says whether it was taken out, and why not if not. A fault on a " +
434
+ "retired item is refused. A person's act: the assistant, an MCP client or an automation " +
435
+ "may ask, and it waits for a person to approve it.",
436
+ input: z.object({
437
+ ...reportInput,
438
+ takeOut: z
439
+ .object({ reason })
440
+ .optional()
441
+ .describe("Take the item out of service, with why it must not be used"),
442
+ }),
443
+ output: reportOutput,
444
+ risk: "write",
445
+ permission: REPORT,
446
+ personApproves: true,
447
+ handler: reportHandler,
448
+ });
449
+ export const reportFaultOnly = defineTool({
450
+ description: "Report a fault on an item without taking it out of service: what is wrong (never an " +
451
+ "injury: that goes on the incident form) and how bad (safety_risk, not_working, worn). The " +
452
+ "report is recorded as the caller's, once: a retry with the same requestId (or the same " +
453
+ "report while it is open) finds it. Nothing else changes: the item stays as it is, and a " +
454
+ "manager triages the fault. To take the item out too, use reportFault or takeOut. A fault " +
455
+ "on a retired item is refused.",
456
+ input: z.object(reportInput),
457
+ output: reportOutput,
458
+ risk: "write",
459
+ permission: REPORT,
460
+ handler: (input, ctx) => reportHandler(input, ctx),
461
+ });
462
+ export const takeOut = defineTool({
463
+ description: "Take an item out of service, with why it must not be used: any staff member may (decision " +
464
+ "4). Only from in service; an item already out of service or retired is refused with its " +
465
+ "state. Only a manager puts it back (putBack). A person's act: the assistant, an MCP client " +
466
+ "or an automation may ask, and it waits for a person to approve it.",
467
+ input: z.object({ itemId: ids, reason }),
468
+ output: z.object({
469
+ itemId: z.string(),
470
+ state: z.literal("out_of_service"),
471
+ outSince: z.string(),
472
+ }),
473
+ risk: "write",
474
+ permission: REPORT,
475
+ personApproves: true,
476
+ recordAction: {
477
+ object: ITEM,
478
+ label: "Take out of service",
479
+ idInput: "itemId",
480
+ ask: {
481
+ input: "reason",
482
+ label: "Why must it not be used?",
483
+ options: [
484
+ { value: "Broken: do not use", label: "Broken" },
485
+ { value: "Unsafe: do not use", label: "Unsafe" },
486
+ { value: "Being serviced or repaired", label: "Being serviced or repaired" },
487
+ { value: "Being cleaned", label: "Being cleaned" },
488
+ ],
489
+ },
490
+ hideWhen: { field: "state", values: ["out_of_service", "retired"] },
491
+ },
492
+ async handler(input, ctx) {
493
+ if (!(await moveOut(ctx, input.itemId, input.reason))) {
494
+ const now = await readItem(ctx, input.itemId);
495
+ const state = text(now.values.state) ?? "";
496
+ // A refusal is an error, never an answer: an approved request that cannot apply shows it.
497
+ throw new OpsCallError("conflict", `The item is ${STATE_WORDS[state] ?? state}, not in service`, {
498
+ reason: "not_in_service",
499
+ state,
500
+ });
501
+ }
502
+ const after = await readItem(ctx, input.itemId);
503
+ return {
504
+ itemId: input.itemId,
505
+ state: "out_of_service",
506
+ outSince: text(after.values.outSince) ?? "",
507
+ };
508
+ },
509
+ });
510
+ export const putBack = defineTool({
511
+ description: "Put an item that is out of service back in service, once it is safe to use: a manager's " +
512
+ "own act (equipment:manage), never the assistant's or an automation's (decision 4). Its " +
513
+ "reason and time out of service are cleared; the state history keeps them.",
514
+ input: z.object({ itemId: ids }),
515
+ output: z.object({ itemId: z.string(), state: z.literal("in_service") }),
516
+ risk: "write",
517
+ permission: MANAGE,
518
+ humanOnly: true,
519
+ recordAction: {
520
+ object: ITEM,
521
+ label: "Put back in service",
522
+ idInput: "itemId",
523
+ confirm: "Is it safe to use again?",
524
+ hideWhen: { field: "state", values: ["in_service", "retired"] },
525
+ },
526
+ async handler(input, ctx) {
527
+ try {
528
+ await ctx.ops.call("record.update", {
529
+ object: ITEM,
530
+ id: input.itemId,
531
+ from: "out_of_service",
532
+ values: { state: "in_service", outReason: null, outSince: null },
533
+ });
534
+ }
535
+ catch (error) {
536
+ if (!isConflict(error))
537
+ throw error;
538
+ const now = await readItem(ctx, input.itemId);
539
+ const state = text(now.values.state) ?? "";
540
+ throw new OpsCallError("conflict", `The item is ${STATE_WORDS[state] ?? state}, not out of service`, {
541
+ reason: "not_out_of_service",
542
+ state,
543
+ });
544
+ }
545
+ return { itemId: input.itemId, state: "in_service" };
546
+ },
547
+ });
548
+ export const retire = defineTool({
549
+ description: "Retire an item for good (worn out, replaced, sold, lost), with why: it leaves the register's " +
550
+ "usual list, is no longer listed for members, and cannot come back. Its faults and history " +
551
+ "stay. A manager's (equipment:manage); the assistant, an MCP client or an automation may " +
552
+ "ask, and it waits for a person to approve it.",
553
+ input: z.object({ itemId: ids, reason }),
554
+ output: z.object({ itemId: z.string(), state: z.literal("retired") }),
555
+ risk: "destructive",
556
+ permission: MANAGE,
557
+ personApproves: true,
558
+ recordAction: {
559
+ object: ITEM,
560
+ label: "Retire",
561
+ idInput: "itemId",
562
+ ask: {
563
+ input: "reason",
564
+ label: "Why is it retired?",
565
+ options: [
566
+ { value: "Worn out", label: "Worn out" },
567
+ { value: "Replaced", label: "Replaced" },
568
+ { value: "Sold or given away", label: "Sold or given away" },
569
+ { value: "Lost or stolen", label: "Lost or stolen" },
570
+ ],
571
+ },
572
+ hideWhen: { field: "state", values: ["retired"] },
573
+ },
574
+ async handler(input, ctx) {
575
+ const now = await readItem(ctx, input.itemId);
576
+ const state = text(now.values.state) ?? "";
577
+ if (state === "retired") {
578
+ // Said as the other tools say it; the host would refuse the move either way.
579
+ throw new OpsCallError("conflict", "The item is already retired", {
580
+ reason: "already_retired",
581
+ state,
582
+ });
583
+ }
584
+ const before = text(now.values.notes);
585
+ const line = `Retired ${new Date().toISOString().slice(0, 10)}: ${input.reason}`;
586
+ try {
587
+ // From the state just read (ADR 0437): a move made meanwhile is refused, never overwritten.
588
+ await ctx.ops.call("record.update", {
589
+ object: ITEM,
590
+ id: input.itemId,
591
+ from: state,
592
+ values: {
593
+ state: "retired",
594
+ listForMembers: "not_listed",
595
+ notes: before ? `${before}\n\n${line}` : line,
596
+ // Not out of service any more: retired.
597
+ outReason: null,
598
+ outSince: null,
599
+ },
600
+ });
601
+ }
602
+ catch (error) {
603
+ if (!isConflict(error))
604
+ throw error;
605
+ throw new OpsCallError("conflict", "The item changed while it was being retired", {
606
+ reason: "moved_meanwhile",
607
+ });
608
+ }
609
+ return { itemId: input.itemId, state: "retired" };
610
+ },
611
+ });
612
+ // --- Faults --------------------------------------------------------------------------------------
613
+ const TRIAGE_TO = {
614
+ acknowledge: "acknowledged",
615
+ fixed: "fixed",
616
+ not_a_fault: "not_a_fault",
617
+ duplicate: "duplicate",
618
+ };
619
+ export const triage = defineTool({
620
+ description: "Triage a fault: acknowledge it (seen, being dealt with), or close it as fixed, not a fault " +
621
+ "or a duplicate, with why (what fixed it, or which report it repeats). A manager's " +
622
+ "(equipment:manage); the assistant, an MCP client or an automation may ask, and it waits " +
623
+ "for a person to approve it. A closed fault stays closed. It does not put the item back in " +
624
+ "service: that is putBack.",
625
+ input: z.object({
626
+ faultId: ids,
627
+ action: z.enum(["acknowledge", "fixed", "not_a_fault", "duplicate"]),
628
+ why: z
629
+ .string()
630
+ .trim()
631
+ .min(3)
632
+ .max(1000)
633
+ .optional()
634
+ .describe("Why it is closed. Needed to close one; optional to acknowledge"),
635
+ }),
636
+ output: z.object({ faultId: z.string(), state: z.enum(FAULT_STATES) }),
637
+ risk: "write",
638
+ permission: MANAGE,
639
+ personApproves: true,
640
+ async handler(input, ctx) {
641
+ const fault = await ctx.ops.call("record.get", {
642
+ object: FAULT,
643
+ id: input.faultId,
644
+ });
645
+ const from = text(fault.values.state) ?? "";
646
+ const to = TRIAGE_TO[input.action];
647
+ // Which moves a fault may make, and that a close says why, are the host's (index.ts): a
648
+ // closed fault, or a close without why, is refused by it and the refusal passed on.
649
+ try {
650
+ await ctx.ops.call("record.update", {
651
+ object: FAULT,
652
+ id: input.faultId,
653
+ from,
654
+ values: { state: to, ...(input.why ? { closedWhy: input.why } : {}) },
655
+ });
656
+ }
657
+ catch (error) {
658
+ if (!isConflict(error))
659
+ throw error;
660
+ throw new OpsCallError("conflict", "The fault changed while it was being triaged", {
661
+ reason: "moved_meanwhile",
662
+ });
663
+ }
664
+ return { faultId: input.faultId, state: to };
665
+ },
666
+ });
667
+ // --- Corrections ---------------------------------------------------------------------------------
668
+ export const correctFault = defineTool({
669
+ description: "Correct a fault's report: how bad it is (safety_risk, not_working, worn) and what is wrong. " +
670
+ "Once reported these are fixed for everyone else, so a safety risk is never quietly lowered; " +
671
+ "a manager (equipment:manage) corrects them here. The assistant, an MCP client or an " +
672
+ "automation may ask, and it waits for a person to approve it.",
673
+ input: z
674
+ .object({
675
+ faultId: ids,
676
+ severity: z.enum(SEVERITIES).optional(),
677
+ description: z.string().trim().min(3).max(4000).optional(),
678
+ })
679
+ .refine((v) => v.severity !== undefined || v.description !== undefined, {
680
+ message: "Give the severity, the description or both",
681
+ }),
682
+ output: z.object({
683
+ faultId: z.string(),
684
+ severity: z.enum(SEVERITIES).nullable(),
685
+ description: z.string().nullable(),
686
+ }),
687
+ risk: "write",
688
+ permission: MANAGE,
689
+ personApproves: true,
690
+ async handler(input, ctx) {
691
+ const fault = await ctx.ops.call("record.get", {
692
+ object: FAULT,
693
+ id: input.faultId,
694
+ });
695
+ const state = text(fault.values.state) ?? "";
696
+ if (state !== "reported" && state !== "acknowledged") {
697
+ // A closed fault is the item's history, kept as it was closed.
698
+ throw new OpsCallError("conflict", "The fault is closed: its report is kept as it was", {
699
+ reason: "closed",
700
+ state,
701
+ });
702
+ }
703
+ const after = await ctx.ops.call("record.update", {
704
+ object: FAULT,
705
+ id: input.faultId,
706
+ // Only while it is still open as read (ADR 0865): a close landing first wins.
707
+ while: state,
708
+ values: {
709
+ ...(input.severity ? { severity: input.severity } : {}),
710
+ ...(input.description ? { description: input.description } : {}),
711
+ },
712
+ });
713
+ return {
714
+ faultId: input.faultId,
715
+ severity: text(after.values.severity) ?? null,
716
+ description: text(after.values.description),
717
+ };
718
+ },
719
+ });
720
+ export const correctOutReason = defineTool({
721
+ description: "Correct why an item that is out of service must not be used. Only the tools that take it " +
722
+ "out write the reason, so nobody can change it to 'fine now' while it is out; a manager " +
723
+ "(equipment:manage) corrects it here. To put the item back, use putBack. The assistant, an " +
724
+ "MCP client or an automation may ask, and it waits for a person to approve it.",
725
+ input: z.object({ itemId: ids, reason }),
726
+ output: z.object({ itemId: z.string(), outReason: z.string().nullable() }),
727
+ risk: "write",
728
+ permission: MANAGE,
729
+ personApproves: true,
730
+ async handler(input, ctx) {
731
+ const now = await readItem(ctx, input.itemId);
732
+ const state = text(now.values.state) ?? "";
733
+ if (state !== "out_of_service") {
734
+ throw new OpsCallError("conflict", `The item is ${STATE_WORDS[state] ?? state}, not out of service`, { reason: "not_out_of_service", state });
735
+ }
736
+ const after = await ctx.ops.call("record.update", {
737
+ object: ITEM,
738
+ id: input.itemId,
739
+ // Only while it is still out of service (ADR 0865): a put-back landing first wins.
740
+ while: "out_of_service",
741
+ values: { outReason: input.reason },
742
+ });
743
+ return { itemId: input.itemId, outReason: text(after.values.outReason) };
744
+ },
745
+ });
746
+ export const correctTag = defineTool({
747
+ description: "Change an item's tag (the code on its sticker), when a sticker is replaced or was entered " +
748
+ "wrong. Once an item is added its tag is changed only here, by a manager (equipment:manage), " +
749
+ "and only while the item is in service: the sticker of a machine out of service stays with " +
750
+ "it. The tag is unique in the register, whatever its case or spaces. The assistant, an MCP " +
751
+ "client or an automation may ask, and it waits for a person to approve it.",
752
+ input: z.object({ itemId: ids, tag: z.string().trim().min(1).max(100) }),
753
+ output: z.object({ itemId: z.string(), tag: z.string().nullable() }),
754
+ risk: "write",
755
+ permission: MANAGE,
756
+ personApproves: true,
757
+ async handler(input, ctx) {
758
+ const after = await ctx.ops.call("record.update", {
759
+ object: ITEM,
760
+ id: input.itemId,
761
+ // Only while it is in service (ADR 0865): a take-out landing first wins.
762
+ while: "in_service",
763
+ values: { tag: input.tag },
764
+ });
765
+ return { itemId: input.itemId, tag: text(after.values.tag) };
766
+ },
767
+ });