@wayai/cli 0.3.333 → 0.3.335

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/index.js CHANGED
@@ -447,11 +447,11 @@ function captureException2(error, context) {
447
447
  Sentry.captureException(error);
448
448
  });
449
449
  }
450
- function addApiBreadcrumb(method, path50) {
450
+ function addApiBreadcrumb(method, path51) {
451
451
  if (!initialized) return;
452
452
  Sentry.addBreadcrumb({
453
453
  category: "http",
454
- message: `${method} ${path50}`,
454
+ message: `${method} ${path51}`,
455
455
  level: "info"
456
456
  });
457
457
  }
@@ -459,8 +459,8 @@ function setSentryUser(accessToken) {
459
459
  if (!initialized) return;
460
460
  try {
461
461
  if (accessToken.startsWith("way_")) {
462
- const hash = __require("crypto").createHash("sha256").update(accessToken).digest("hex").slice(0, 16);
463
- Sentry.setUser({ id: `token:${hash}` });
462
+ const hash2 = __require("crypto").createHash("sha256").update(accessToken).digest("hex").slice(0, 16);
463
+ Sentry.setUser({ id: `token:${hash2}` });
464
464
  return;
465
465
  }
466
466
  const payloadBase64 = accessToken.split(".")[1];
@@ -867,8 +867,8 @@ var init_ZodError = __esm({
867
867
  "not_finite"
868
868
  ]);
869
869
  quotelessJson = (obj) => {
870
- const json = JSON.stringify(obj, null, 2);
871
- return json.replace(/"([^"]+)":/g, "$1:");
870
+ const json2 = JSON.stringify(obj, null, 2);
871
+ return json2.replace(/"([^"]+)":/g, "$1:");
872
872
  };
873
873
  ZodError = class _ZodError extends Error {
874
874
  get errors() {
@@ -1121,8 +1121,8 @@ var init_parseUtil = __esm({
1121
1121
  init_errors2();
1122
1122
  init_en();
1123
1123
  makeIssue = (params) => {
1124
- const { data, path: path50, errorMaps, issueData } = params;
1125
- const fullPath = [...path50, ...issueData.path || []];
1124
+ const { data, path: path51, errorMaps, issueData } = params;
1125
+ const fullPath = [...path51, ...issueData.path || []];
1126
1126
  const fullIssue = {
1127
1127
  ...issueData,
1128
1128
  path: fullPath
@@ -1433,11 +1433,11 @@ var init_types = __esm({
1433
1433
  init_parseUtil();
1434
1434
  init_util();
1435
1435
  ParseInputLazyPath = class {
1436
- constructor(parent, value, path50, key) {
1436
+ constructor(parent, value, path51, key) {
1437
1437
  this._cachedPath = [];
1438
1438
  this.parent = parent;
1439
1439
  this.data = value;
1440
- this._path = path50;
1440
+ this._path = path51;
1441
1441
  this._key = key;
1442
1442
  }
1443
1443
  get path() {
@@ -5172,6 +5172,9 @@ function toIso(epochMs) {
5172
5172
  function fromIso(iso) {
5173
5173
  return new Date(iso).getTime();
5174
5174
  }
5175
+ function nowIso() {
5176
+ return (/* @__PURE__ */ new Date()).toISOString();
5177
+ }
5175
5178
  function isIsoTimestamp(value) {
5176
5179
  return typeof value === "string" && ISO_UTC_RE.test(value);
5177
5180
  }
@@ -5189,8 +5192,8 @@ function optionalTrimmedText(max) {
5189
5192
  }
5190
5193
  function jsonLengthOrNull(value) {
5191
5194
  try {
5192
- const json = JSON.stringify(value);
5193
- return typeof json === "string" ? json.length : null;
5195
+ const json2 = JSON.stringify(value);
5196
+ return typeof json2 === "string" ? json2.length : null;
5194
5197
  } catch {
5195
5198
  return null;
5196
5199
  }
@@ -6327,6 +6330,71 @@ var init_chunk_63UWXV4T = __esm({
6327
6330
  }
6328
6331
  });
6329
6332
 
6333
+ // ../../packages/core/dist/chunk-S4HVRNEQ.js
6334
+ var PERMISSIONS;
6335
+ var init_chunk_S4HVRNEQ = __esm({
6336
+ "../../packages/core/dist/chunk-S4HVRNEQ.js"() {
6337
+ "use strict";
6338
+ PERMISSIONS = [
6339
+ "hub:read",
6340
+ "hub:write",
6341
+ "hub:admin",
6342
+ "conversation:read",
6343
+ "conversation:write",
6344
+ "analytics:read",
6345
+ "billing:read",
6346
+ "billing:write",
6347
+ "org:read",
6348
+ "org:write",
6349
+ "org:admin",
6350
+ "contacts:write",
6351
+ "platform:admin",
6352
+ "*"
6353
+ ];
6354
+ }
6355
+ });
6356
+
6357
+ // ../../packages/core/dist/chunk-WTIGECE5.js
6358
+ var MAX_NAME_LENGTH, MAX_HUBS_PER_GRANT, MAX_HUB_TAGS_PER_GRANT, MAX_GRANTS, permissionEnum, grantScopeSchema, grantSchema, createTokenBody, tokenOrgIdParam;
6359
+ var init_chunk_WTIGECE5 = __esm({
6360
+ "../../packages/core/dist/chunk-WTIGECE5.js"() {
6361
+ "use strict";
6362
+ init_chunk_S4HVRNEQ();
6363
+ init_chunk_HZ6CADSY();
6364
+ init_zod();
6365
+ MAX_NAME_LENGTH = 100;
6366
+ MAX_HUBS_PER_GRANT = 50;
6367
+ MAX_HUB_TAGS_PER_GRANT = 20;
6368
+ MAX_GRANTS = 20;
6369
+ permissionEnum = external_exports.enum(PERMISSIONS).refine(
6370
+ (p) => p !== "platform:admin",
6371
+ { message: "platform:admin cannot be delegated via token creation" }
6372
+ );
6373
+ grantScopeSchema = external_exports.object({
6374
+ // Required: every token grant must declare its org tenancy. The handler
6375
+ // also strict-checks this as defense-in-depth, but failing at the Zod
6376
+ // boundary keeps the generated client type honest (org_id: string).
6377
+ org_id: external_exports.string().min(1),
6378
+ hubs: external_exports.array(external_exports.string().min(1)).min(1, "Each grant must have scope.hubs as a non-empty array").max(MAX_HUBS_PER_GRANT),
6379
+ hub_tags: external_exports.array(external_exports.string().min(1)).min(1, "scope.hub_tags must be a non-empty array if provided").max(MAX_HUB_TAGS_PER_GRANT).optional(),
6380
+ environments: external_exports.array(external_exports.enum(["production", "preview"])).min(1, "scope.environments must be a non-empty array if provided").optional()
6381
+ }).strict();
6382
+ grantSchema = external_exports.object({
6383
+ scope: grantScopeSchema,
6384
+ permissions: external_exports.array(permissionEnum).min(1, "Each grant must have permissions as a non-empty array")
6385
+ }).strict();
6386
+ createTokenBody = external_exports.object({
6387
+ name: external_exports.string().trim().min(1, "name is required").max(MAX_NAME_LENGTH, `name must be ${MAX_NAME_LENGTH} characters or fewer`),
6388
+ grants: external_exports.array(grantSchema).min(1, "grants must be a non-empty array").max(MAX_GRANTS),
6389
+ expires_at: external_exports.string().datetime({ message: "expires_at must be a valid ISO 8601 date" }).refine(
6390
+ (s) => new Date(s).getTime() > Date.now(),
6391
+ { message: "expires_at must be in the future" }
6392
+ ).optional()
6393
+ });
6394
+ tokenOrgIdParam = external_exports.object({ orgId: uuidSchema });
6395
+ }
6396
+ });
6397
+
6330
6398
  // ../../packages/core/dist/chunk-WDAXZDJO.js
6331
6399
  var TOOLSET_ANSWER_PERSON_PARTIES, toolsetAnswerPersonSchema, toolsetAnswerPersonsSchema;
6332
6400
  var init_chunk_WDAXZDJO = __esm({
@@ -6414,6 +6482,33 @@ var init_chunk_ZC6YGHNX = __esm({
6414
6482
  }
6415
6483
  });
6416
6484
 
6485
+ // ../../packages/core/dist/chunk-5DGHIY7L.js
6486
+ var rekorBaseChangeMessageSchema;
6487
+ var init_chunk_5DGHIY7L = __esm({
6488
+ "../../packages/core/dist/chunk-5DGHIY7L.js"() {
6489
+ "use strict";
6490
+ init_zod();
6491
+ rekorBaseChangeMessageSchema = external_exports.object({
6492
+ /** The WayAI org UUID — one id namespace. */
6493
+ org_id: external_exports.string().uuid(),
6494
+ /**
6495
+ * Not a UUID: a preview base id is `{prod_base_id}--{slug}`. Immutable per base — a
6496
+ * preview clone is its OWN base_id — so `(base_id, scope)` keys never collide across
6497
+ * environments. Empty is never a real base id, so it is non-conforming rather than a
6498
+ * frame keyed on nothing.
6499
+ */
6500
+ base_id: external_exports.string().min(1),
6501
+ /**
6502
+ * Rides along so the client scopes its refetch without a lookup; the inspector scopes
6503
+ * by side.
6504
+ */
6505
+ environment: external_exports.enum(["production", "preview"]),
6506
+ /** Which pane refetches. `base` covers create/delete/promote/config changes. */
6507
+ scope: external_exports.enum(["records", "record_types", "files", "base"])
6508
+ });
6509
+ }
6510
+ });
6511
+
6417
6512
  // ../../packages/core/dist/chunk-5FO3GNKP.js
6418
6513
  var DATA_PROXY_MOUNT, DATA_PROXY_PREFIX, BASE_DESTRUCTION_MOUNT, BASE_DESTRUCTION_PREFIX, BASE_DESTRUCTION_CONFIRM_PATH, COMMUNITY_EMAIL_UNSUBSCRIBE_PATH, CONTACT_BOOK_EMAIL_UNSUBSCRIBE_PATH, AUTOMATION_WEBHOOK_MOUNT, MANAGED_AGENTS_WEBHOOK_MOUNT, TELEGRAM_VAULT_WEBHOOK_PATH;
6419
6514
  var init_chunk_5FO3GNKP = __esm({
@@ -6433,8 +6528,8 @@ var init_chunk_5FO3GNKP = __esm({
6433
6528
  });
6434
6529
 
6435
6530
  // ../../packages/core/dist/chunk-7AYJHO5P.js
6436
- function matchPath(pattern, path50) {
6437
- const pathSegments2 = path50.replace(/\/$/, "").split("/");
6531
+ function matchPath(pattern, path51) {
6532
+ const pathSegments2 = path51.replace(/\/$/, "").split("/");
6438
6533
  const isPrefix = pattern.endsWith("/*");
6439
6534
  const patternSegments = (isPrefix ? pattern.slice(0, -2) : pattern).split("/");
6440
6535
  if (isPrefix ? pathSegments2.length < patternSegments.length : pathSegments2.length !== patternSegments.length) {
@@ -6442,19 +6537,19 @@ function matchPath(pattern, path50) {
6442
6537
  }
6443
6538
  return patternSegments.every((segment, i) => segment === "*" ? pathSegments2[i] !== "" : segment === pathSegments2[i]);
6444
6539
  }
6445
- function getEndpointConfig(path50) {
6540
+ function getEndpointConfig(path51) {
6446
6541
  for (const excluded of EXCLUDED_PATHS) {
6447
- if (matchPath(excluded, path50)) {
6542
+ if (matchPath(excluded, path51)) {
6448
6543
  return null;
6449
6544
  }
6450
6545
  }
6451
- const normalizedPath = path50.replace(/\/$/, "");
6546
+ const normalizedPath = path51.replace(/\/$/, "");
6452
6547
  if (!normalizedPath.endsWith("/*") && Object.prototype.hasOwnProperty.call(ENDPOINT_CONFIGS, normalizedPath)) {
6453
6548
  return ENDPOINT_CONFIGS[normalizedPath];
6454
6549
  }
6455
6550
  const sortedPatterns = Object.keys(ENDPOINT_CONFIGS).sort((a, b) => b.length - a.length);
6456
6551
  for (const pattern of sortedPatterns) {
6457
- if (matchPath(pattern, path50)) {
6552
+ if (matchPath(pattern, path51)) {
6458
6553
  return ENDPOINT_CONFIGS[pattern];
6459
6554
  }
6460
6555
  }
@@ -7356,71 +7451,6 @@ var init_chunk_TVUDMGWV = __esm({
7356
7451
  }
7357
7452
  });
7358
7453
 
7359
- // ../../packages/core/dist/chunk-S4HVRNEQ.js
7360
- var PERMISSIONS;
7361
- var init_chunk_S4HVRNEQ = __esm({
7362
- "../../packages/core/dist/chunk-S4HVRNEQ.js"() {
7363
- "use strict";
7364
- PERMISSIONS = [
7365
- "hub:read",
7366
- "hub:write",
7367
- "hub:admin",
7368
- "conversation:read",
7369
- "conversation:write",
7370
- "analytics:read",
7371
- "billing:read",
7372
- "billing:write",
7373
- "org:read",
7374
- "org:write",
7375
- "org:admin",
7376
- "contacts:write",
7377
- "platform:admin",
7378
- "*"
7379
- ];
7380
- }
7381
- });
7382
-
7383
- // ../../packages/core/dist/chunk-WTIGECE5.js
7384
- var MAX_NAME_LENGTH, MAX_HUBS_PER_GRANT, MAX_HUB_TAGS_PER_GRANT, MAX_GRANTS, permissionEnum, grantScopeSchema, grantSchema, createTokenBody, tokenOrgIdParam;
7385
- var init_chunk_WTIGECE5 = __esm({
7386
- "../../packages/core/dist/chunk-WTIGECE5.js"() {
7387
- "use strict";
7388
- init_chunk_S4HVRNEQ();
7389
- init_chunk_HZ6CADSY();
7390
- init_zod();
7391
- MAX_NAME_LENGTH = 100;
7392
- MAX_HUBS_PER_GRANT = 50;
7393
- MAX_HUB_TAGS_PER_GRANT = 20;
7394
- MAX_GRANTS = 20;
7395
- permissionEnum = external_exports.enum(PERMISSIONS).refine(
7396
- (p) => p !== "platform:admin",
7397
- { message: "platform:admin cannot be delegated via token creation" }
7398
- );
7399
- grantScopeSchema = external_exports.object({
7400
- // Required: every token grant must declare its org tenancy. The handler
7401
- // also strict-checks this as defense-in-depth, but failing at the Zod
7402
- // boundary keeps the generated client type honest (org_id: string).
7403
- org_id: external_exports.string().min(1),
7404
- hubs: external_exports.array(external_exports.string().min(1)).min(1, "Each grant must have scope.hubs as a non-empty array").max(MAX_HUBS_PER_GRANT),
7405
- hub_tags: external_exports.array(external_exports.string().min(1)).min(1, "scope.hub_tags must be a non-empty array if provided").max(MAX_HUB_TAGS_PER_GRANT).optional(),
7406
- environments: external_exports.array(external_exports.enum(["production", "preview"])).min(1, "scope.environments must be a non-empty array if provided").optional()
7407
- }).strict();
7408
- grantSchema = external_exports.object({
7409
- scope: grantScopeSchema,
7410
- permissions: external_exports.array(permissionEnum).min(1, "Each grant must have permissions as a non-empty array")
7411
- }).strict();
7412
- createTokenBody = external_exports.object({
7413
- name: external_exports.string().trim().min(1, "name is required").max(MAX_NAME_LENGTH, `name must be ${MAX_NAME_LENGTH} characters or fewer`),
7414
- grants: external_exports.array(grantSchema).min(1, "grants must be a non-empty array").max(MAX_GRANTS),
7415
- expires_at: external_exports.string().datetime({ message: "expires_at must be a valid ISO 8601 date" }).refine(
7416
- (s) => new Date(s).getTime() > Date.now(),
7417
- { message: "expires_at must be in the future" }
7418
- ).optional()
7419
- });
7420
- tokenOrgIdParam = external_exports.object({ orgId: uuidSchema });
7421
- }
7422
- });
7423
-
7424
7454
  // ../../packages/core/dist/chunk-ZVXO3XL6.js
7425
7455
  var PEOPLE_CONTACT_PAGE_MAX, PEOPLE_CONTACT_PAGE_DEFAULT, PEOPLE_CONTACT_EMAIL_MAX_LENGTH, peopleUserIdSchema, peopleInviteEmailSchema, peopleContactInviteBody, peopleContactInviteIdParam, peopleContactUserIdParam, peopleContactBlockBody, peopleContactPageQuery, peopleOutgoingInviteSchema, peopleContactPersonSchema, peopleContactSchema, peopleIncomingInviteSchema, peopleBlockedUserSchema;
7426
7456
  var init_chunk_ZVXO3XL6 = __esm({
@@ -7750,30 +7780,32 @@ var init_chunk_MGBAXT5Y = __esm({
7750
7780
  }
7751
7781
  });
7752
7782
 
7753
- // ../../packages/core/dist/chunk-5DGHIY7L.js
7754
- var rekorBaseChangeMessageSchema;
7755
- var init_chunk_5DGHIY7L = __esm({
7756
- "../../packages/core/dist/chunk-5DGHIY7L.js"() {
7783
+ // ../../packages/core/dist/chunk-YUZFHVB2.js
7784
+ var invitePreviewQuery, inviteRolePreviewResponse, inviteContactPreviewResponse, invitePreviewResponse, inviteUnsubscribeBody;
7785
+ var init_chunk_YUZFHVB2 = __esm({
7786
+ "../../packages/core/dist/chunk-YUZFHVB2.js"() {
7757
7787
  "use strict";
7758
7788
  init_zod();
7759
- rekorBaseChangeMessageSchema = external_exports.object({
7760
- /** The WayAI org UUID — one id namespace. */
7761
- org_id: external_exports.string().uuid(),
7762
- /**
7763
- * Not a UUID: a preview base id is `{prod_base_id}--{slug}`. Immutable per base — a
7764
- * preview clone is its OWN base_id — so `(base_id, scope)` keys never collide across
7765
- * environments. Empty is never a real base id, so it is non-conforming rather than a
7766
- * frame keyed on nothing.
7767
- */
7768
- base_id: external_exports.string().min(1),
7769
- /**
7770
- * Rides along so the client scopes its refetch without a lookup; the inspector scopes
7771
- * by side.
7772
- */
7773
- environment: external_exports.enum(["production", "preview"]),
7774
- /** Which pane refetches. `base` covers create/delete/promote/config changes. */
7775
- scope: external_exports.enum(["records", "record_types", "files", "base"])
7789
+ invitePreviewQuery = external_exports.object({
7790
+ token: external_exports.string().min(1).max(2048)
7791
+ });
7792
+ inviteRolePreviewResponse = external_exports.object({
7793
+ inviter_name: external_exports.string(),
7794
+ entity_id: external_exports.string().uuid(),
7795
+ entity_name: external_exports.string(),
7796
+ entity_type: external_exports.enum(["org", "hub"]),
7797
+ role: external_exports.enum(["org_admin", "admin", "team_user", "user"]),
7798
+ expires_at: external_exports.string().datetime()
7776
7799
  });
7800
+ inviteContactPreviewResponse = external_exports.object({
7801
+ inviter_name: external_exports.string().nullable(),
7802
+ entity_id: external_exports.string().uuid(),
7803
+ entity_type: external_exports.literal("contact"),
7804
+ role: external_exports.literal("contact"),
7805
+ expires_at: external_exports.string().datetime()
7806
+ });
7807
+ invitePreviewResponse = external_exports.union([inviteRolePreviewResponse, inviteContactPreviewResponse]);
7808
+ inviteUnsubscribeBody = external_exports.object({ token: external_exports.string().min(1).max(256) }).strict();
7777
7809
  }
7778
7810
  });
7779
7811
 
@@ -8057,16 +8089,16 @@ function parseCommunityLessonVideoUrl(url) {
8057
8089
  const parts = /^https?:\/\/([^/?#]+)([^?#]*)(?:\?([^#]*))?(?:#.*)?$/i.exec(url.trim());
8058
8090
  if (!parts) return null;
8059
8091
  const host = parts[1].toLowerCase();
8060
- const path50 = parts[2] ?? "";
8092
+ const path51 = parts[2] ?? "";
8061
8093
  const query = parts[3] ?? "";
8062
8094
  let id;
8063
8095
  if (host === YOUTU_BE) {
8064
- id = /^\/([A-Za-z0-9_-]{11})\/?$/.exec(path50)?.[1];
8096
+ id = /^\/([A-Za-z0-9_-]{11})\/?$/.exec(path51)?.[1];
8065
8097
  } else if (YOUTUBE_HOSTS.has(host)) {
8066
- if (path50 === "/watch" || path50 === "/watch/") {
8098
+ if (path51 === "/watch" || path51 === "/watch/") {
8067
8099
  id = query.split("&").find((param) => param.startsWith("v="))?.slice(2);
8068
8100
  } else {
8069
- id = YOUTUBE_ID_PATH.exec(path50)?.[1];
8101
+ id = YOUTUBE_ID_PATH.exec(path51)?.[1];
8070
8102
  }
8071
8103
  }
8072
8104
  return id !== void 0 && YOUTUBE_ID.test(id) ? { provider: "youtube", id } : null;
@@ -8264,12 +8296,12 @@ function typeMatches(typeField, allowed) {
8264
8296
  if (Array.isArray(typeField)) return typeField.every((t) => typeof t === "string" && allowed.has(t));
8265
8297
  return false;
8266
8298
  }
8267
- function validateSchema(schema, path50, errors, opts = {}) {
8299
+ function validateSchema(schema, path51, errors, opts = {}) {
8268
8300
  if (typeof schema === "boolean") return;
8269
8301
  const depth = opts.depth ?? 0;
8270
8302
  if (depth > MAX_SCHEMA_DEPTH) {
8271
8303
  errors.push({
8272
- path: path50 || "<root>",
8304
+ path: path51 || "<root>",
8273
8305
  message: `schema nesting exceeds ${MAX_SCHEMA_DEPTH} levels`,
8274
8306
  suggestion: "Flatten the schema; LLM providers reject deeply nested tool input_schemas."
8275
8307
  });
@@ -8277,7 +8309,7 @@ function validateSchema(schema, path50, errors, opts = {}) {
8277
8309
  }
8278
8310
  if (!isRecord(schema)) {
8279
8311
  errors.push({
8280
- path: path50,
8312
+ path: path51,
8281
8313
  message: `expected object, got ${schema === null ? "null" : typeof schema}`
8282
8314
  });
8283
8315
  return;
@@ -8285,14 +8317,14 @@ function validateSchema(schema, path50, errors, opts = {}) {
8285
8317
  if (opts.isRoot) {
8286
8318
  if ("type" in schema && schema.type !== "object") {
8287
8319
  errors.push({
8288
- path: path50 ? `${path50}.type` : "type",
8320
+ path: path51 ? `${path51}.type` : "type",
8289
8321
  message: `root type must be 'object', got ${JSON.stringify(schema.type)}`,
8290
8322
  suggestion: "Tool parameters at the root must be an object: `{ type: 'object', properties: { ... } }`."
8291
8323
  });
8292
8324
  }
8293
8325
  } else if ("type" in schema && !typeMatches(schema.type, ALLOWED_TYPES)) {
8294
8326
  errors.push({
8295
- path: `${path50}.type`,
8327
+ path: `${path51}.type`,
8296
8328
  message: `type must be one of ${[...ALLOWED_TYPES].join("/")} or an array of those, got ${JSON.stringify(schema.type)}`
8297
8329
  });
8298
8330
  }
@@ -8302,25 +8334,25 @@ function validateSchema(schema, path50, errors, opts = {}) {
8302
8334
  const isPlaceholder = PLACEHOLDER_TOKENS.includes(e);
8303
8335
  const isOutcomePlaceholder = e === "[KANBAN_OUTCOME_VALUES]";
8304
8336
  errors.push({
8305
- path: `${path50}.enum`,
8337
+ path: `${path51}.enum`,
8306
8338
  message: `enum must be a non-empty array of primitives, got string ${JSON.stringify(e)}`,
8307
8339
  suggestion: isOutcomePlaceholder ? "Declare `outcomes` on the hub's terminal kanban status so the platform can render the placeholder into a valid array; with none configured the platform drops the parameter instead." : isPlaceholder ? "Set `operation: 'update_kanban_status'` on the tool and ensure at least one hub.kanban_status has `allowsAgentUpdate: true` so the platform can render the placeholder into a valid array." : 'Wrap the value in an array: `enum: ["value"]`.'
8308
8340
  });
8309
8341
  } else if (!Array.isArray(e)) {
8310
8342
  errors.push({
8311
- path: `${path50}.enum`,
8343
+ path: `${path51}.enum`,
8312
8344
  message: `enum must be a non-empty array of primitives, got ${typeof e}`
8313
8345
  });
8314
8346
  } else if (e.length === 0) {
8315
8347
  errors.push({
8316
- path: `${path50}.enum`,
8348
+ path: `${path51}.enum`,
8317
8349
  message: "enum must not be empty"
8318
8350
  });
8319
8351
  } else {
8320
8352
  for (let i = 0; i < e.length; i++) {
8321
8353
  if (!isPrimitive(e[i])) {
8322
8354
  errors.push({
8323
- path: `${path50}.enum[${i}]`,
8355
+ path: `${path51}.enum[${i}]`,
8324
8356
  message: `enum entry must be a primitive (string/number/boolean/null), got ${typeof e[i]}`
8325
8357
  });
8326
8358
  }
@@ -8330,7 +8362,7 @@ function validateSchema(schema, path50, errors, opts = {}) {
8330
8362
  for (const key of ["exclusiveMinimum", "exclusiveMaximum"]) {
8331
8363
  if (key in schema && typeof schema[key] === "boolean") {
8332
8364
  errors.push({
8333
- path: `${path50}.${key}`,
8365
+ path: `${path51}.${key}`,
8334
8366
  message: `${key} as boolean is draft-04 syntax; draft 2020-12 requires a numeric value`,
8335
8367
  suggestion: `Replace with the numeric bound, e.g. \`${key}: 0\`.`
8336
8368
  });
@@ -8339,45 +8371,45 @@ function validateSchema(schema, path50, errors, opts = {}) {
8339
8371
  if ("properties" in schema) {
8340
8372
  if (!isRecord(schema.properties)) {
8341
8373
  errors.push({
8342
- path: `${path50}.properties`,
8374
+ path: `${path51}.properties`,
8343
8375
  message: `properties must be an object, got ${Array.isArray(schema.properties) ? "array" : typeof schema.properties}`
8344
8376
  });
8345
8377
  } else {
8346
8378
  for (const [propName, propSchema] of Object.entries(schema.properties)) {
8347
- validateSchema(propSchema, `${path50}.properties.${propName}`, errors, { depth: depth + 1 });
8379
+ validateSchema(propSchema, `${path51}.properties.${propName}`, errors, { depth: depth + 1 });
8348
8380
  }
8349
8381
  }
8350
8382
  }
8351
8383
  if (schemaTypeIncludes(schema, "array") && "items" in schema) {
8352
8384
  if (Array.isArray(schema.items)) {
8353
- schema.items.forEach((sub, i) => validateSchema(sub, `${path50}.items[${i}]`, errors, { depth: depth + 1 }));
8385
+ schema.items.forEach((sub, i) => validateSchema(sub, `${path51}.items[${i}]`, errors, { depth: depth + 1 }));
8354
8386
  } else {
8355
- validateSchema(schema.items, `${path50}.items`, errors, { depth: depth + 1 });
8387
+ validateSchema(schema.items, `${path51}.items`, errors, { depth: depth + 1 });
8356
8388
  }
8357
8389
  }
8358
8390
  for (const key of SUBSCHEMA_OBJECT_KEYWORDS) {
8359
8391
  if (key in schema && isRecord(schema[key])) {
8360
- validateSchema(schema[key], `${path50}.${key}`, errors, { depth: depth + 1 });
8392
+ validateSchema(schema[key], `${path51}.${key}`, errors, { depth: depth + 1 });
8361
8393
  }
8362
8394
  }
8363
8395
  for (const key of SUBSCHEMA_LIST_KEYWORDS) {
8364
8396
  const list2 = schema[key];
8365
8397
  if (Array.isArray(list2)) {
8366
- list2.forEach((sub, i) => validateSchema(sub, `${path50}.${key}[${i}]`, errors, { depth: depth + 1 }));
8398
+ list2.forEach((sub, i) => validateSchema(sub, `${path51}.${key}[${i}]`, errors, { depth: depth + 1 }));
8367
8399
  }
8368
8400
  }
8369
8401
  for (const key of SUBSCHEMA_MAP_KEYWORDS) {
8370
8402
  const map = schema[key];
8371
8403
  if (isRecord(map)) {
8372
8404
  for (const [name, sub] of Object.entries(map)) {
8373
- validateSchema(sub, `${path50}.${key}.${name}`, errors, { depth: depth + 1 });
8405
+ validateSchema(sub, `${path51}.${key}.${name}`, errors, { depth: depth + 1 });
8374
8406
  }
8375
8407
  }
8376
8408
  }
8377
8409
  const reportedPaths = new Set(errors.map((e) => e.path));
8378
8410
  for (const [k, v] of Object.entries(schema)) {
8379
8411
  if (typeof v !== "string") continue;
8380
- const fieldPath = `${path50}.${k}`;
8412
+ const fieldPath = `${path51}.${k}`;
8381
8413
  if (reportedPaths.has(fieldPath)) continue;
8382
8414
  for (const token of PLACEHOLDER_TOKENS) {
8383
8415
  if (v === token) {
@@ -9053,32 +9085,19 @@ var init_chunk_2ZZZHXZR = __esm({
9053
9085
  }
9054
9086
  });
9055
9087
 
9056
- // ../../packages/core/dist/chunk-YUZFHVB2.js
9057
- var invitePreviewQuery, inviteRolePreviewResponse, inviteContactPreviewResponse, invitePreviewResponse, inviteUnsubscribeBody;
9058
- var init_chunk_YUZFHVB2 = __esm({
9059
- "../../packages/core/dist/chunk-YUZFHVB2.js"() {
9088
+ // ../../packages/core/dist/chunk-KSTYTQ7I.js
9089
+ var copilotSuggestBody, copilotSuggestResponse;
9090
+ var init_chunk_KSTYTQ7I = __esm({
9091
+ "../../packages/core/dist/chunk-KSTYTQ7I.js"() {
9060
9092
  "use strict";
9061
9093
  init_zod();
9062
- invitePreviewQuery = external_exports.object({
9063
- token: external_exports.string().min(1).max(2048)
9064
- });
9065
- inviteRolePreviewResponse = external_exports.object({
9066
- inviter_name: external_exports.string(),
9067
- entity_id: external_exports.string().uuid(),
9068
- entity_name: external_exports.string(),
9069
- entity_type: external_exports.enum(["org", "hub"]),
9070
- role: external_exports.enum(["org_admin", "admin", "team_user", "user"]),
9071
- expires_at: external_exports.string().datetime()
9094
+ copilotSuggestBody = external_exports.object({
9095
+ hub_id: external_exports.string().uuid()
9072
9096
  });
9073
- inviteContactPreviewResponse = external_exports.object({
9074
- inviter_name: external_exports.string().nullable(),
9075
- entity_id: external_exports.string().uuid(),
9076
- entity_type: external_exports.literal("contact"),
9077
- role: external_exports.literal("contact"),
9078
- expires_at: external_exports.string().datetime()
9097
+ copilotSuggestResponse = external_exports.object({
9098
+ status: external_exports.enum(["processing", "skipped"]),
9099
+ reason: external_exports.string().optional()
9079
9100
  });
9080
- invitePreviewResponse = external_exports.union([inviteRolePreviewResponse, inviteContactPreviewResponse]);
9081
- inviteUnsubscribeBody = external_exports.object({ token: external_exports.string().min(1).max(256) }).strict();
9082
9101
  }
9083
9102
  });
9084
9103
 
@@ -12188,9 +12207,9 @@ function monitorRuleActions(monitorConfig) {
12188
12207
  if (!monitorConfig || typeof monitorConfig !== "object") return [];
12189
12208
  const config = monitorConfig;
12190
12209
  const found = [];
12191
- const visit = (action, path50) => {
12210
+ const visit = (action, path51) => {
12192
12211
  if (!action || typeof action !== "object" || Array.isArray(action)) return;
12193
- found.push({ action, path: path50 });
12212
+ found.push({ action, path: path51 });
12194
12213
  };
12195
12214
  if (Array.isArray(config.rules)) {
12196
12215
  config.rules.forEach((rule, index) => {
@@ -12222,25 +12241,25 @@ function collectMonitorRuleIssues(monitorConfig) {
12222
12241
  const trigger = resolveMonitorTrigger(monitorConfig);
12223
12242
  const kinds = monitorRuleActionKinds(trigger);
12224
12243
  const issues = [...callUtteranceRuleIssues(monitorConfig), ...automationGateIssues(monitorConfig)];
12225
- for (const { action, path: path50 } of monitorRuleActions(monitorConfig)) {
12226
- if (trigger === "call_utterance" && path50[0] === "fallback") continue;
12244
+ for (const { action, path: path51 } of monitorRuleActions(monitorConfig)) {
12245
+ if (trigger === "call_utterance" && path51[0] === "fallback") continue;
12227
12246
  const kind = action.kind;
12228
12247
  if (typeof kind === "string" && !kinds.includes(kind)) {
12229
- issues.push({ path: [...path50, "kind"], message: monitorActionKindMessage(kind, trigger) });
12248
+ issues.push({ path: [...path51, "kind"], message: monitorActionKindMessage(kind, trigger) });
12230
12249
  }
12231
12250
  const toolName = action.tool_name;
12232
12251
  if (kind === "call_tool" && typeof toolName === "string" && isRefusedNativeToolName(toolName, trigger)) {
12233
- issues.push({ path: [...path50, "tool_name"], message: monitorRuleToolNotAllowedMessage(toolName, trigger) });
12252
+ issues.push({ path: [...path51, "tool_name"], message: monitorRuleToolNotAllowedMessage(toolName, trigger) });
12234
12253
  continue;
12235
12254
  }
12236
12255
  if (kind === "call_tool" && toolName === INSERT_NOTE_TOOL_NAME) {
12237
- issues.push(...insertNoteArgumentIssues(action, path50));
12256
+ issues.push(...insertNoteArgumentIssues(action, path51));
12238
12257
  }
12239
12258
  if (kind === "call_tool" && toolName === RUN_MONITOR_TOOL_NAME) {
12240
12259
  const callee = readRunMonitorCallee(action);
12241
12260
  if (!callee.ok) {
12242
12261
  issues.push({
12243
- path: [...path50, "args", "monitor_name"],
12262
+ path: [...path51, "args", "monitor_name"],
12244
12263
  message: runMonitorCalleeMessage(callee.reason)
12245
12264
  });
12246
12265
  }
@@ -12300,11 +12319,11 @@ function insertNoteTemplateMessage(reason3) {
12300
12319
  return `insert_note's template is longer than the ${MONITOR_NOTE_TEMPLATE_MAX}-character limit.`;
12301
12320
  }
12302
12321
  }
12303
- function insertNoteArgumentIssues(action, path50) {
12322
+ function insertNoteArgumentIssues(action, path51) {
12304
12323
  const result = readInsertNoteTemplate(action);
12305
12324
  if (result.ok) return [];
12306
12325
  return [{
12307
- path: [...path50, "args", "template"],
12326
+ path: [...path51, "args", "template"],
12308
12327
  message: insertNoteTemplateMessage(result.reason)
12309
12328
  }];
12310
12329
  }
@@ -12836,19 +12855,39 @@ var init_chunk_QEEQN2NE = __esm({
12836
12855
  }
12837
12856
  });
12838
12857
 
12839
- // ../../packages/core/dist/chunk-KSTYTQ7I.js
12840
- var copilotSuggestBody, copilotSuggestResponse;
12841
- var init_chunk_KSTYTQ7I = __esm({
12842
- "../../packages/core/dist/chunk-KSTYTQ7I.js"() {
12858
+ // ../../packages/core/dist/chunk-5Y2NNQHX.js
12859
+ var CASE_SUBMISSION_ISSUED_KINDS, CASE_SUBMISSION_RENDER_STUCK_MS, CASE_SUBMISSION_MARK_ID_PATTERN, CASE_CORRECTION_REASON_MAX_LENGTH, submitCaseBody, correctCaseSubmissionBody, caseDeliveryQuery;
12860
+ var init_chunk_5Y2NNQHX = __esm({
12861
+ "../../packages/core/dist/chunk-5Y2NNQHX.js"() {
12843
12862
  "use strict";
12863
+ init_chunk_HZ6CADSY();
12844
12864
  init_zod();
12845
- copilotSuggestBody = external_exports.object({
12846
- hub_id: external_exports.string().uuid()
12847
- });
12848
- copilotSuggestResponse = external_exports.object({
12849
- status: external_exports.enum(["processing", "skipped"]),
12850
- reason: external_exports.string().optional()
12851
- });
12865
+ CASE_SUBMISSION_ISSUED_KINDS = ["pdf", "docx", "csv"];
12866
+ CASE_SUBMISSION_RENDER_STUCK_MS = 3 * 60 * 60 * 1e3;
12867
+ CASE_SUBMISSION_MARK_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/[A-Z]{2,6}-[0-9]{4}-[0-9]{4,}\/[0-9]{2}-[a-z0-9-]+\/[a-z0-9]+(?:_[a-z0-9]+)*-v[1-9][0-9]*$/;
12868
+ CASE_CORRECTION_REASON_MAX_LENGTH = 2e3;
12869
+ submitCaseBody = external_exports.object({
12870
+ phase_id: uuidSchema,
12871
+ output_id: uuidSchema.optional()
12872
+ }).strict();
12873
+ correctCaseSubmissionBody = external_exports.object({
12874
+ reason: external_exports.string().trim().min(1).max(CASE_CORRECTION_REASON_MAX_LENGTH)
12875
+ }).strict();
12876
+ caseDeliveryQuery = external_exports.object({
12877
+ output_id: uuidSchema.optional(),
12878
+ submission_id: uuidSchema.optional()
12879
+ }).strict();
12880
+ }
12881
+ });
12882
+
12883
+ // ../../packages/core/dist/chunk-NNC2ZECG.js
12884
+ var caseVerifyQuery;
12885
+ var init_chunk_NNC2ZECG = __esm({
12886
+ "../../packages/core/dist/chunk-NNC2ZECG.js"() {
12887
+ "use strict";
12888
+ init_chunk_5Y2NNQHX();
12889
+ init_zod();
12890
+ caseVerifyQuery = external_exports.object({ id: external_exports.string().regex(CASE_SUBMISSION_MARK_ID_PATTERN) }).strict();
12852
12891
  }
12853
12892
  });
12854
12893
 
@@ -13278,8 +13317,8 @@ function evalInitialStateError(input) {
13278
13317
  const parsed = evalInitialStateEntry.safeParse(entries[i]);
13279
13318
  if (!parsed.success) {
13280
13319
  const issue = parsed.error.issues[0];
13281
- const path50 = issue?.path.join(".") || "?";
13282
- return `initial_state[${i}].${path50} is invalid: ${issue?.message ?? "malformed"}`;
13320
+ const path51 = issue?.path.join(".") || "?";
13321
+ return `initial_state[${i}].${path51} is invalid: ${issue?.message ?? "malformed"}`;
13283
13322
  }
13284
13323
  if (seenSlugs.has(parsed.data.slug)) {
13285
13324
  return `initial_state[${i}].slug "${parsed.data.slug}" is declared more than once`;
@@ -13805,12 +13844,12 @@ function validateFollowupLinks(followups, label3, ctx) {
13805
13844
  const linkTargets = /* @__PURE__ */ new Set();
13806
13845
  followups.forEach((followup, i) => {
13807
13846
  const ref = followup?.after_followup_id;
13808
- const path50 = ["followups", i, "after_followup_id"];
13847
+ const path51 = ["followups", i, "after_followup_id"];
13809
13848
  if (followup?.type !== "inactivity_after_before_event") {
13810
13849
  if (ref !== void 0) {
13811
13850
  ctx.addIssue({
13812
13851
  code: external_exports.ZodIssueCode.custom,
13813
- path: path50,
13852
+ path: path51,
13814
13853
  message: `kanban status ${label3}: after_followup_id is only valid on inactivity_after_before_event followups (this one is ${followup?.type})`
13815
13854
  });
13816
13855
  }
@@ -13819,7 +13858,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13819
13858
  if (ref === void 0) {
13820
13859
  ctx.addIssue({
13821
13860
  code: external_exports.ZodIssueCode.custom,
13822
- path: path50,
13861
+ path: path51,
13823
13862
  message: `kanban status ${label3}: inactivity_after_before_event requires after_followup_id naming the id of a before_event followup in the same status`
13824
13863
  });
13825
13864
  return;
@@ -13829,7 +13868,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13829
13868
  if (matches.length > 1) {
13830
13869
  ctx.addIssue({
13831
13870
  code: external_exports.ZodIssueCode.custom,
13832
- path: path50,
13871
+ path: path51,
13833
13872
  message: `kanban status ${label3}: after_followup_id "${ref}" matches ${matches.length} followups \u2014 a link must name exactly one`
13834
13873
  });
13835
13874
  return;
@@ -13841,7 +13880,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13841
13880
  );
13842
13881
  ctx.addIssue({
13843
13882
  code: external_exports.ZodIssueCode.custom,
13844
- path: path50,
13883
+ path: path51,
13845
13884
  message: hasIdlessBeforeEvent ? `kanban status ${label3}: after_followup_id "${ref}" matches no followup \u2014 a link target must declare an explicit id, and this status has before_event followups without one` : `kanban status ${label3}: after_followup_id "${ref}" matches no followup in this status`
13846
13885
  });
13847
13886
  return;
@@ -13849,7 +13888,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13849
13888
  if (target.type !== "before_event") {
13850
13889
  ctx.addIssue({
13851
13890
  code: external_exports.ZodIssueCode.custom,
13852
- path: path50,
13891
+ path: path51,
13853
13892
  message: `kanban status ${label3}: after_followup_id "${ref}" points at a ${target.type} followup \u2014 only before_event followups can anchor a chain`
13854
13893
  });
13855
13894
  }
@@ -14642,13 +14681,13 @@ function refineHubAsCodePersons(config, ctx) {
14642
14681
  function refineHubAsCodeEvalAttachments(config, ctx) {
14643
14682
  const cfg = config;
14644
14683
  const referencedHashes = /* @__PURE__ */ new Set();
14645
- const addTurnIssue = (path50, turn, name) => {
14684
+ const addTurnIssue = (path51, turn, name) => {
14646
14685
  const error = evalTurnAttachmentsError(turn);
14647
14686
  if (error) {
14648
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path50, message: `${name}: ${error}` });
14687
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path51, message: `${name}: ${error}` });
14649
14688
  return;
14650
14689
  }
14651
- for (const hash of collectTurnAttachmentHashes(turn)) referencedHashes.add(hash);
14690
+ for (const hash2 of collectTurnAttachmentHashes(turn)) referencedHashes.add(hash2);
14652
14691
  };
14653
14692
  if (Array.isArray(cfg.evals)) {
14654
14693
  cfg.evals.forEach((entry, e) => {
@@ -14703,12 +14742,12 @@ function refineHubAsCodeEvalAttachments(config, ctx) {
14703
14742
  });
14704
14743
  }
14705
14744
  }
14706
- for (const hash of referencedHashes) {
14707
- if (!carriedHashes.has(hash)) {
14745
+ for (const hash2 of referencedHashes) {
14746
+ if (!carriedHashes.has(hash2)) {
14708
14747
  ctx.addIssue({
14709
14748
  code: external_exports.ZodIssueCode.custom,
14710
14749
  path: ["eval_attachment_files"],
14711
- message: `attachment ${hash.slice(0, 12)}\u2026 is referenced by a turn but its bytes are missing from eval_attachment_files`
14750
+ message: `attachment ${hash2.slice(0, 12)}\u2026 is referenced by a turn but its bytes are missing from eval_attachment_files`
14712
14751
  });
14713
14752
  }
14714
14753
  }
@@ -14746,17 +14785,17 @@ function refineHubAsCodeCallOpenings(config, ctx) {
14746
14785
  const agent = entry;
14747
14786
  const openings = agent?.call_openings;
14748
14787
  if (openings === void 0 || openings === null) return;
14749
- const path50 = ["agents", a, "call_openings"];
14788
+ const path51 = ["agents", a, "call_openings"];
14750
14789
  const name = `agent "${typeof agent?.name === "string" ? agent.name : "<unnamed>"}"`;
14751
14790
  if (typeof openings !== "object" || Array.isArray(openings)) {
14752
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path50, message: `${name}: call_openings must map a language to an opening` });
14791
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path51, message: `${name}: call_openings must map a language to an opening` });
14753
14792
  return;
14754
14793
  }
14755
14794
  if (agent?.role !== "pilot_voice" && Object.keys(openings).length > 0) {
14756
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path50, message: `${name}: only a pilot_voice agent has call_openings` });
14795
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path51, message: `${name}: only a pilot_voice agent has call_openings` });
14757
14796
  }
14758
14797
  for (const [language, raw] of Object.entries(openings)) {
14759
- const at = [...path50, language];
14798
+ const at = [...path51, language];
14760
14799
  if (!callOpeningLanguage.safeParse(language).success) {
14761
14800
  ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: at, message: `${name}: call_openings language must be one of ${CALL_OPENING_LANGUAGES.join(", ")}` });
14762
14801
  continue;
@@ -14892,11 +14931,11 @@ function refineHubAsCodeDelegation(config, ctx) {
14892
14931
  }
14893
14932
  }
14894
14933
  if (del.context_boundary === void 0) return;
14895
- const path50 = ["agents", agentIndex, "tools", "delegation", delIndex, "context_boundary"];
14934
+ const path51 = ["agents", agentIndex, "tools", "delegation", delIndex, "context_boundary"];
14896
14935
  if (del.type !== "hub") {
14897
14936
  ctx.addIssue({
14898
14937
  code: external_exports.ZodIssueCode.custom,
14899
- path: path50,
14938
+ path: path51,
14900
14939
  message: `context_boundary applies only to \`type: hub\` delegations (got type "${got(del.type)}")`
14901
14940
  });
14902
14941
  return;
@@ -14904,18 +14943,18 @@ function refineHubAsCodeDelegation(config, ctx) {
14904
14943
  if (!CONTEXT_BOUNDARIES.includes(del.context_boundary)) {
14905
14944
  ctx.addIssue({
14906
14945
  code: external_exports.ZodIssueCode.custom,
14907
- path: path50,
14946
+ path: path51,
14908
14947
  message: `context_boundary must be one of: ${CONTEXT_BOUNDARIES.join(", ")}`
14909
14948
  });
14910
14949
  }
14911
14950
  });
14912
14951
  });
14913
14952
  }
14914
- function refuseNonBooleanFlag(ctx, subject, entry, key, path50) {
14953
+ function refuseNonBooleanFlag(ctx, subject, entry, key, path51) {
14915
14954
  const value = entry[key];
14916
14955
  if (value === void 0 || typeof value === "boolean") return;
14917
14956
  const shown3 = value === null || typeof value !== "object" ? JSON.stringify(value).slice(0, 40) : Array.isArray(value) ? "a list" : "an object";
14918
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: [...path50, key], message: `${subject}: ${key} must be true or false, got ${shown3}` });
14957
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: [...path51, key], message: `${subject}: ${key} must be true or false, got ${shown3}` });
14919
14958
  }
14920
14959
  function refineHubAsCodeFlags(config, ctx) {
14921
14960
  const { agents, connections, evals, journeys, teams } = config;
@@ -15106,11 +15145,11 @@ function pathPastDepth(root, levels) {
15106
15145
  function refusedNesting(value, at, ctx) {
15107
15146
  const past = pathPastDepth(value, MAX_HUB_AS_CODE_DEPTH - at.length);
15108
15147
  if (!past) return false;
15109
- const path50 = [...at, ...past].slice(0, NAMED_DEPTH_SEGMENTS).map((key) => typeof key === "string" ? key.slice(0, NAMED_DEPTH_KEY_CHARS) : key);
15148
+ const path51 = [...at, ...past].slice(0, NAMED_DEPTH_SEGMENTS).map((key) => typeof key === "string" ? key.slice(0, NAMED_DEPTH_KEY_CHARS) : key);
15110
15149
  ctx.addIssue({
15111
15150
  code: external_exports.ZodIssueCode.custom,
15112
- path: path50,
15113
- message: `${fieldName(path50)}\u2026 nests deeper than ${MAX_HUB_AS_CODE_DEPTH} levels of arrays and objects`,
15151
+ path: path51,
15152
+ message: `${fieldName(path51)}\u2026 nests deeper than ${MAX_HUB_AS_CODE_DEPTH} levels of arrays and objects`,
15114
15153
  fatal: true
15115
15154
  });
15116
15155
  return true;
@@ -15127,15 +15166,15 @@ function refusedStringConfigNesting(config, ctx) {
15127
15166
  }
15128
15167
  function refusedUnreadableSection(config, ctx) {
15129
15168
  if (!isPlainObject(config)) return false;
15130
- const refused = (path50, must) => {
15131
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path50, message: `${fieldName(path50)} must ${must}`, fatal: true });
15169
+ const refused = (path51, must) => {
15170
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path51, message: `${fieldName(path51)} must ${must}`, fatal: true });
15132
15171
  return true;
15133
15172
  };
15134
- const badList = (value, path50, reads = {}) => {
15173
+ const badList = (value, path51, reads = {}) => {
15135
15174
  if (value === void 0 || value === null && reads.nullSection !== false) return false;
15136
- if (!Array.isArray(value)) return refused(path50, "be an array");
15175
+ if (!Array.isArray(value)) return refused(path51, "be an array");
15137
15176
  const nullAt = reads.nullEntries ? -1 : value.indexOf(null);
15138
- return nullAt !== -1 && refused([...path50, nullAt], "not be null");
15177
+ return nullAt !== -1 && refused([...path51, nullAt], "not be null");
15139
15178
  };
15140
15179
  const entries = (section) => Array.isArray(section) ? section : [];
15141
15180
  return ["connections", "teams", "evals", "journeys", "agents", "eval_attachment_files", "call_opening_files"].some((section) => badList(config[section], [section])) || isPlainObject(config.hub) && badList(config.hub.tags, ["hub", "tags"], { nullEntries: true }) || [["evals", "history"], ["journeys", "transcript"]].some(([section, turns]) => entries(config[section]).some((entry, index) => isPlainObject(entry) && badList(entry[turns], [section, index, turns], { nullEntries: true }))) || entries(config.agents).some((agent, index) => {
@@ -15311,7 +15350,7 @@ var init_chunk_EO5MKW7Q = __esm({
15311
15350
  MAX_HUB_AS_CODE_DEPTH = 128;
15312
15351
  NAMED_DEPTH_SEGMENTS = 12;
15313
15352
  NAMED_DEPTH_KEY_CHARS = 64;
15314
- fieldName = (path50) => path50.reduce(
15353
+ fieldName = (path51) => path51.reduce(
15315
15354
  (name, key) => typeof key === "number" ? `${name}[${key}]` : name ? `${name}.${key}` : key,
15316
15355
  ""
15317
15356
  );
@@ -15524,31 +15563,6 @@ var init_chunk_JDJ4EUOL = __esm({
15524
15563
  }
15525
15564
  });
15526
15565
 
15527
- // ../../packages/core/dist/chunk-5Y2NNQHX.js
15528
- var CASE_SUBMISSION_ISSUED_KINDS, CASE_SUBMISSION_RENDER_STUCK_MS, CASE_SUBMISSION_MARK_ID_PATTERN, CASE_CORRECTION_REASON_MAX_LENGTH, submitCaseBody, correctCaseSubmissionBody, caseDeliveryQuery;
15529
- var init_chunk_5Y2NNQHX = __esm({
15530
- "../../packages/core/dist/chunk-5Y2NNQHX.js"() {
15531
- "use strict";
15532
- init_chunk_HZ6CADSY();
15533
- init_zod();
15534
- CASE_SUBMISSION_ISSUED_KINDS = ["pdf", "docx", "csv"];
15535
- CASE_SUBMISSION_RENDER_STUCK_MS = 3 * 60 * 60 * 1e3;
15536
- CASE_SUBMISSION_MARK_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/[A-Z]{2,6}-[0-9]{4}-[0-9]{4,}\/[0-9]{2}-[a-z0-9-]+\/[a-z0-9]+(?:_[a-z0-9]+)*-v[1-9][0-9]*$/;
15537
- CASE_CORRECTION_REASON_MAX_LENGTH = 2e3;
15538
- submitCaseBody = external_exports.object({
15539
- phase_id: uuidSchema,
15540
- output_id: uuidSchema.optional()
15541
- }).strict();
15542
- correctCaseSubmissionBody = external_exports.object({
15543
- reason: external_exports.string().trim().min(1).max(CASE_CORRECTION_REASON_MAX_LENGTH)
15544
- }).strict();
15545
- caseDeliveryQuery = external_exports.object({
15546
- output_id: uuidSchema.optional(),
15547
- submission_id: uuidSchema.optional()
15548
- }).strict();
15549
- }
15550
- });
15551
-
15552
15566
  // ../../packages/core/dist/chunk-KWRHZBGU.js
15553
15567
  function fold(segment) {
15554
15568
  return segment.toUpperCase().toLowerCase().replace(/ς/g, "\u03C3").replace(/ß/g, "ss").normalize("NFC");
@@ -15795,8 +15809,8 @@ var init_chunk_VROZDNLV = __esm({
15795
15809
  CASE_UPLOADS_BUSY_REASON = "case_uploads_busy";
15796
15810
  isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob;
15797
15811
  caseUploadForm = external_exports.record(external_exports.string(), external_exports.unknown()).transform((form2, ctx) => {
15798
- const refuse2 = (message, path50) => {
15799
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path50] });
15812
+ const refuse2 = (message, path51) => {
15813
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path51] });
15800
15814
  return external_exports.NEVER;
15801
15815
  };
15802
15816
  const text5 = form2[CASE_UPLOAD_REVISION_FIELD];
@@ -16005,17 +16019,17 @@ function fixedTextProblem(text5) {
16005
16019
  }
16006
16020
  return null;
16007
16021
  }
16008
- function casePieceSidecar(path50) {
16009
- if (/\.yaml$/i.test(path50)) return null;
16010
- const sidecar = path50.replace(/\.[^./]+$/, ".yaml");
16011
- return sidecar === path50 ? null : sidecar;
16022
+ function casePieceSidecar(path51) {
16023
+ if (/\.yaml$/i.test(path51)) return null;
16024
+ const sidecar = path51.replace(/\.[^./]+$/, ".yaml");
16025
+ return sidecar === path51 ? null : sidecar;
16012
16026
  }
16013
16027
  function pathsOverlap(a, b) {
16014
16028
  return a === b || a.endsWith("/") && b.startsWith(a) || b.endsWith("/") && a.startsWith(b);
16015
16029
  }
16016
- function boundPathKey(path50, folders) {
16017
- const folder = path50.endsWith("/");
16018
- const checked = checkCaseFilePath({ path: folder ? `${path50}${CHAPTER_PROBE}` : path50, type: "file" }, folders);
16030
+ function boundPathKey(path51, folders) {
16031
+ const folder = path51.endsWith("/");
16032
+ const checked = checkCaseFilePath({ path: folder ? `${path51}${CHAPTER_PROBE}` : path51, type: "file" }, folders);
16019
16033
  if (!checked.ok || checked.received) return null;
16020
16034
  return folder ? checked.fold_key.slice(0, -CHAPTER_PROBE.length) : checked.fold_key;
16021
16035
  }
@@ -16068,11 +16082,11 @@ function caseTypeDefinitionProblem(definition) {
16068
16082
  if (output.format === "file" && output.output_items.length > 0) return problem("file_output_with_items", outputAt);
16069
16083
  if (output.format === "file" && output.case_items_allowed) return problem("file_output_with_case_items", outputAt);
16070
16084
  if (caseValuesRepeated(output.approving_team_ids)) return problem("approving_team_repeated", outputAt);
16071
- for (const path50 of output.file_paths) {
16072
- if (!path50.startsWith(`${phase.folder}/`)) return problem("file_path_outside_phase", outputAt);
16073
- const key = boundPathKey(path50, folders);
16085
+ for (const path51 of output.file_paths) {
16086
+ if (!path51.startsWith(`${phase.folder}/`)) return problem("file_path_outside_phase", outputAt);
16087
+ const key = boundPathKey(path51, folders);
16074
16088
  if (key === null) return problem("file_path_not_writable", outputAt);
16075
- if (output.format === "file" && path50.endsWith("/")) return problem("file_path_folder_for_file", outputAt);
16089
+ if (output.format === "file" && path51.endsWith("/")) return problem("file_path_folder_for_file", outputAt);
16076
16090
  if (paths.some((held) => pathsOverlap(held, key))) return problem("file_path_overlaps", outputAt);
16077
16091
  paths.push(key);
16078
16092
  }
@@ -16193,8 +16207,8 @@ var init_chunk_PFPADFUC = __esm({
16193
16207
  const { folder, code: targetCode } = resolveItemLink("", target);
16194
16208
  return (!target.includes("/") || CASE_PHASE_FOLDER_PATTERN.test(folder)) && CASE_CODE_PATTERN.test(targetCode);
16195
16209
  }, "An item is named by its code, or by its phase folder and code");
16196
- filePath = external_exports.string().min(1).max(CASE_FILE_PATH_MAX_LENGTH).refine((path50) => {
16197
- const segments = (path50.endsWith("/") ? path50.slice(0, -1) : path50).split("/");
16210
+ filePath = external_exports.string().min(1).max(CASE_FILE_PATH_MAX_LENGTH).refine((path51) => {
16211
+ const segments = (path51.endsWith("/") ? path51.slice(0, -1) : path51).split("/");
16198
16212
  return segments.length >= 2 && segments.length <= 8 && CASE_PHASE_FOLDER_PATTERN.test(segments[0]) && segments.slice(1).every((segment) => FILE_PATH_SEGMENT_PATTERN.test(segment));
16199
16213
  }, "A file path is the phase folder, then letters, digits, dots, dashes and underscores");
16200
16214
  caseTypePartyRoleSchema = external_exports.object({
@@ -16372,7 +16386,7 @@ ${party.role}`;
16372
16386
  if (new Set(body.instrument_ids).size !== body.instrument_ids.length) return { reason: "instrument_repeated", at: "instrument_ids" };
16373
16387
  return null;
16374
16388
  }
16375
- var CASE_RECORD_CODE_PATTERN, CASE_RECORD_CODE_MAX_LENGTH, CASE_RECORD_PARTIES_MAX, CASE_RECORD_INSTRUMENTS_MAX, CASE_RECORD_ROLE_MAX_LENGTH, CASE_RECORDS_PAGE_MAX, CASE_RECORDS_QUERY_MAX_LENGTH, caseRecordPartySchema, openCaseShape, openCaseBody, previewOpenCaseShape, caseRecordParam, CASE_RECORD_STATUSES, caseRecordsQuery, CASE_STATE_SUMMARIES_MAX, caseStatesQuery, CASE_CLOSURE_REASON_MAX_LENGTH, closeCaseBody, setCaseConfidentialityBody;
16389
+ var CASE_RECORD_CODE_PATTERN, CASE_RECORD_CODE_MAX_LENGTH, CASE_RECORD_PARTIES_MAX, CASE_RECORD_INSTRUMENTS_MAX, CASE_RECORD_ROLE_MAX_LENGTH, CASE_RECORDS_PAGE_MAX, CASE_RECORDS_QUERY_MAX_LENGTH, caseRecordPartySchema, openCaseShape, openCaseBody, previewOpenCaseShape, caseRecordParam, CASE_RECORD_STATUSES, caseRecordsQuery, CASE_STATE_SUMMARIES_MAX, caseStatesQuery, CASE_CLOSED_REASON, CASE_CLOSURE_REASON_MAX_LENGTH, closeCaseBody, setCaseConfidentialityBody;
16376
16390
  var init_chunk_733K4J4G = __esm({
16377
16391
  "../../packages/core/dist/chunk-733K4J4G.js"() {
16378
16392
  "use strict";
@@ -16427,6 +16441,7 @@ var init_chunk_733K4J4G = __esm({
16427
16441
  caseStatesQuery = external_exports.object({
16428
16442
  codes: external_exports.string().max(CASE_STATE_SUMMARIES_MAX * (CASE_RECORD_CODE_MAX_LENGTH + 1)).transform((codes) => codes.split(",")).pipe(external_exports.array(external_exports.string().max(CASE_RECORD_CODE_MAX_LENGTH).regex(CASE_RECORD_CODE_PATTERN)).min(1).max(CASE_STATE_SUMMARIES_MAX))
16429
16443
  });
16444
+ CASE_CLOSED_REASON = "case_closed";
16430
16445
  CASE_CLOSURE_REASON_MAX_LENGTH = 2e3;
16431
16446
  closeCaseBody = external_exports.object({
16432
16447
  outcome_code: external_exports.string().max(CASE_CODE_MAX_LENGTH).regex(CASE_CODE_PATTERN),
@@ -16569,14 +16584,22 @@ var init_chunk_M2IF4G6X = __esm({
16569
16584
  }
16570
16585
  });
16571
16586
 
16572
- // ../../packages/core/dist/chunk-NNC2ZECG.js
16573
- var caseVerifyQuery;
16574
- var init_chunk_NNC2ZECG = __esm({
16575
- "../../packages/core/dist/chunk-NNC2ZECG.js"() {
16587
+ // ../../packages/core/dist/chunk-UOPCLXCU.js
16588
+ var CASE_CHANGE_TOPICS, caseChangedFrameSchema;
16589
+ var init_chunk_UOPCLXCU = __esm({
16590
+ "../../packages/core/dist/chunk-UOPCLXCU.js"() {
16576
16591
  "use strict";
16577
- init_chunk_5Y2NNQHX();
16592
+ init_chunk_733K4J4G();
16593
+ init_chunk_HZ6CADSY();
16578
16594
  init_zod();
16579
- caseVerifyQuery = external_exports.object({ id: external_exports.string().regex(CASE_SUBMISSION_MARK_ID_PATTERN) }).strict();
16595
+ CASE_CHANGE_TOPICS = ["submission", "agenda", "access"];
16596
+ caseChangedFrameSchema = external_exports.object({
16597
+ org_id: uuidSchema,
16598
+ space_id: uuidSchema,
16599
+ /** The case, by its code; null for an `access` change, which names none. */
16600
+ code: caseRecordParam.shape.code.nullable(),
16601
+ topic: external_exports.enum(CASE_CHANGE_TOPICS)
16602
+ }).strict();
16580
16603
  }
16581
16604
  });
16582
16605
 
@@ -16621,7 +16644,7 @@ var init_chunk_U3X3BIQH = __esm({
16621
16644
  }
16622
16645
  });
16623
16646
 
16624
- // ../../packages/core/dist/chunk-3LMWOJQX.js
16647
+ // ../../packages/core/dist/chunk-EYOBPUDN.js
16625
16648
  function withProblem(shape, problemOf) {
16626
16649
  return shape.superRefine((value, ctx) => {
16627
16650
  const found = problemOf(value);
@@ -16658,8 +16681,8 @@ ${party.role}`);
16658
16681
  return new Set(keys).size === keys.length ? null : { reason: "instrument_party_repeated", at: "parties" };
16659
16682
  }
16660
16683
  var CASE_REGISTRY_TYPE_CODE_PATTERN, CASE_REGISTRY_TYPE_CODE_MAX_LENGTH, CASE_REGISTRY_NAME_MAX_LENGTH, CASE_REGISTRY_TYPE_SCHEMA_MAX_CHARS, CASE_PARTY_ABBREVIATION_PATTERN, CASE_PARTY_PERSON_KINDS, CASE_PARTY_DOCUMENT_KINDS, CASE_PARTY_DOCUMENT_MAX_LENGTH, CASE_PARTY_GROUP_MEMBERS_MAX, CASE_INSTRUMENT_NUMBER_MAX_LENGTH, CASE_INSTRUMENT_ROLE_MAX_LENGTH, CASE_INSTRUMENT_PARTIES_MAX, CASE_REGISTRY_PAGE_MAX, CASE_REGISTRY_QUERY_MAX_LENGTH, trimmedName, dateSchema, attributesValues, registryTypeFields, createCaseRegistryTypeShape, updateCaseRegistryTypeShape, createCaseRegistryTypeBody, updateCaseRegistryTypeBody, saveCasePartyShape, saveCasePartyBody, saveCasePartyGroupShape, saveCasePartyGroupBody, caseInstrumentPartyInput, saveCaseInstrumentShape, saveCaseInstrumentBody, registryPage, searchText, casePartiesQuery, casePartyGroupsQuery, caseInstrumentsQuery, caseRegistryTypeParam, casePartyParam, casePartyGroupParam, caseInstrumentParam;
16661
- var init_chunk_3LMWOJQX = __esm({
16662
- "../../packages/core/dist/chunk-3LMWOJQX.js"() {
16684
+ var init_chunk_EYOBPUDN = __esm({
16685
+ "../../packages/core/dist/chunk-EYOBPUDN.js"() {
16663
16686
  "use strict";
16664
16687
  init_chunk_3T3D7LTE();
16665
16688
  init_chunk_M2T55BV6();
@@ -16753,11 +16776,11 @@ var init_chunk_3LMWOJQX = __esm({
16753
16776
  }
16754
16777
  });
16755
16778
 
16756
- // ../../packages/core/dist/chunk-PMBOHJKA.js
16779
+ // ../../packages/core/dist/chunk-6CHDJVQ6.js
16757
16780
  function collectionUploadForm(field, shape) {
16758
16781
  return external_exports.record(external_exports.string(), external_exports.unknown()).transform((form2, ctx) => {
16759
- const refuse2 = (message, path50) => {
16760
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path50] });
16782
+ const refuse2 = (message, path51) => {
16783
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path51] });
16761
16784
  return external_exports.NEVER;
16762
16785
  };
16763
16786
  const text5 = form2[field];
@@ -16793,11 +16816,11 @@ function caseCollectionFileName(sent) {
16793
16816
  return name || "document";
16794
16817
  }
16795
16818
  var CASE_COLLECTION_FOLDERS, CASE_COLLECTION_PARTS, isCaseCollectionPart, CASE_COLLECTION_TITLE_MAX_LENGTH, CASE_COLLECTION_TYPE_MAX_LENGTH, CASE_COLLECTION_REASON_MAX_LENGTH, CASE_COLLECTION_FILE_NAME_MAX_LENGTH, caseCollectionDocumentParam, dateOnly, title, registerCaseCollectionDocumentShape, addCaseCollectionVersionShape, CASE_COLLECTION_UPLOAD_BODY_MAX_BYTES, CASE_COLLECTION_DOCUMENT_FIELD, CASE_COLLECTION_VERSION_FIELD, caseCollectionDocumentUploadForm, caseCollectionVersionUploadForm, CASE_COLLECTION_PAGE_MAX, CASE_COLLECTION_CURSOR_MAX_LENGTH, caseCollectionQuery, CASE_COLLECTION_VERSIONS_PAGE_MAX, caseCollectionVersionsQuery, caseCollectionContentQuery;
16796
- var init_chunk_PMBOHJKA = __esm({
16797
- "../../packages/core/dist/chunk-PMBOHJKA.js"() {
16819
+ var init_chunk_6CHDJVQ6 = __esm({
16820
+ "../../packages/core/dist/chunk-6CHDJVQ6.js"() {
16798
16821
  "use strict";
16799
16822
  init_chunk_U3X3BIQH();
16800
- init_chunk_3LMWOJQX();
16823
+ init_chunk_EYOBPUDN();
16801
16824
  init_chunk_VROZDNLV();
16802
16825
  init_chunk_3T3D7LTE();
16803
16826
  init_chunk_M2T55BV6();
@@ -16859,7 +16882,7 @@ var init_chunk_PMBOHJKA = __esm({
16859
16882
  }
16860
16883
  });
16861
16884
 
16862
- // ../../packages/core/dist/chunk-ZB7W3DKK.js
16885
+ // ../../packages/core/dist/chunk-WYCUCSD5.js
16863
16886
  function caseReceivedFormat(fileName) {
16864
16887
  const dot = fileName.lastIndexOf(".");
16865
16888
  if (dot < 0) return null;
@@ -16867,10 +16890,10 @@ function caseReceivedFormat(fileName) {
16867
16890
  return isCaseReceivedFormat(extension) ? extension : null;
16868
16891
  }
16869
16892
  var ZIP_SIGNATURE, CASE_RECEIVED_FORMATS, isCaseReceivedFormat, CASE_RECEIVED_PARTS, CASE_RECEIVED_TITLE_MAX_LENGTH, CASE_RECEIVED_TYPE_MAX_LENGTH, CASE_RECEIVED_TEXT_MAX_BYTES, CASE_RECEIVED_UPLOAD_BODY_MAX_BYTES, CASE_RECEIVED_DOCUMENT_FIELD, caseReceivedParam, registerCaseReceivedDocumentShape, caseReceivedUploadForm, caseReceivedFileName, ZIP_DIRECTORY_MAX_BYTES, CONTENT_TYPES_MAX_BYTES, CONTENT_TYPES_INFLATED_MAX_BYTES, CASE_RECEIVED_PAGE_MAX, caseReceivedQuery, caseReceivedContentQuery;
16870
- var init_chunk_ZB7W3DKK = __esm({
16871
- "../../packages/core/dist/chunk-ZB7W3DKK.js"() {
16893
+ var init_chunk_WYCUCSD5 = __esm({
16894
+ "../../packages/core/dist/chunk-WYCUCSD5.js"() {
16872
16895
  "use strict";
16873
- init_chunk_PMBOHJKA();
16896
+ init_chunk_6CHDJVQ6();
16874
16897
  init_chunk_U3X3BIQH();
16875
16898
  init_chunk_VROZDNLV();
16876
16899
  init_chunk_733K4J4G();
@@ -16908,8 +16931,8 @@ var init_chunk_ZB7W3DKK = __esm({
16908
16931
  confidential: external_exports.boolean().default(false)
16909
16932
  }).strict();
16910
16933
  caseReceivedUploadForm = external_exports.record(external_exports.string(), external_exports.unknown()).transform((form2, ctx) => {
16911
- const refuse2 = (message, path50) => {
16912
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path50] });
16934
+ const refuse2 = (message, path51) => {
16935
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path51] });
16913
16936
  return external_exports.NEVER;
16914
16937
  };
16915
16938
  const text5 = form2[CASE_RECEIVED_DOCUMENT_FIELD];
@@ -16948,237 +16971,6 @@ var init_chunk_ZB7W3DKK = __esm({
16948
16971
  }
16949
16972
  });
16950
16973
 
16951
- // ../../packages/core/dist/chunk-H6V7NEWR.js
16952
- function isCaseDueDate(value) {
16953
- const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
16954
- if (!match) return false;
16955
- const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
16956
- if (year < CASE_DUE_DATE_MIN_YEAR || year > CASE_DUE_DATE_MAX_YEAR) return false;
16957
- const date = new Date(Date.UTC(year, month - 1, day));
16958
- return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
16959
- }
16960
- function setCaseDeadlinesProblem(body) {
16961
- const seen = /* @__PURE__ */ new Set();
16962
- for (const [index, phase] of body.phases.entries()) {
16963
- if (seen.has(phase.phase_id)) return { reason: "phase_repeated", at: `phases.${index}.phase_id` };
16964
- seen.add(phase.phase_id);
16965
- }
16966
- return null;
16967
- }
16968
- var CASE_DUE_DATE_MIN_YEAR, CASE_DUE_DATE_MAX_YEAR, CASE_DEADLINES_PHASES_MAX, CASE_OVERDUE_CASES_MAX, caseDueDateSchema, setCaseDeadlinesShape, setCaseDeadlinesBody, setCaseTaskPlanBody, setCaseOwnerBody, caseOverdueQuery;
16969
- var init_chunk_H6V7NEWR = __esm({
16970
- "../../packages/core/dist/chunk-H6V7NEWR.js"() {
16971
- "use strict";
16972
- init_chunk_3T3D7LTE();
16973
- init_chunk_HZ6CADSY();
16974
- init_zod();
16975
- CASE_DUE_DATE_MIN_YEAR = 2e3;
16976
- CASE_DUE_DATE_MAX_YEAR = 2100;
16977
- CASE_DEADLINES_PHASES_MAX = 50;
16978
- CASE_OVERDUE_CASES_MAX = 50;
16979
- caseDueDateSchema = external_exports.string().refine(isCaseDueDate, "Not a calendar date (YYYY-MM-DD)");
16980
- setCaseDeadlinesShape = external_exports.object({
16981
- phases: external_exports.array(external_exports.object({ phase_id: uuidSchema, due_on: caseDueDateSchema.nullable() }).strict()).min(1).max(CASE_DEADLINES_PHASES_MAX)
16982
- }).strict();
16983
- setCaseDeadlinesBody = setCaseDeadlinesShape.superRefine((body, ctx) => {
16984
- const found = setCaseDeadlinesProblem(body);
16985
- if (found) {
16986
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: found.reason, path: found.at.split("."), params: { case_deadlines_reason: found.reason } });
16987
- }
16988
- });
16989
- setCaseTaskPlanBody = external_exports.object({
16990
- owner_person_id: uuidSchema.nullable(),
16991
- due_on: caseDueDateSchema.nullable()
16992
- }).strict();
16993
- setCaseOwnerBody = external_exports.object({ owner_person_id: uuidSchema.nullable() }).strict();
16994
- caseOverdueQuery = casePageQuery.extend({
16995
- limit: external_exports.coerce.number().int().min(1).max(CASE_OVERDUE_CASES_MAX).optional()
16996
- });
16997
- }
16998
- });
16999
-
17000
- // ../../packages/core/dist/chunk-ZVIMTUGZ.js
17001
- var CASE_GUEST_EMAIL_MAX, CASE_GUEST_INVITATIONS_PAGE_MAX, CASE_GUEST_INVITE_TOKEN_LENGTH, caseGuestEmailSchema, caseGuestInviteTokenSchema, inviteCaseGuestBody, caseGuestInvitationParam, caseGuestInvitationsQuery, joinCaseSpaceBody, caseJoinSearchParams;
17002
- var init_chunk_ZVIMTUGZ = __esm({
17003
- "../../packages/core/dist/chunk-ZVIMTUGZ.js"() {
17004
- "use strict";
17005
- init_chunk_3T3D7LTE();
17006
- init_chunk_HZ6CADSY();
17007
- init_zod();
17008
- CASE_GUEST_EMAIL_MAX = 320;
17009
- CASE_GUEST_INVITATIONS_PAGE_MAX = 100;
17010
- CASE_GUEST_INVITE_TOKEN_LENGTH = 43;
17011
- caseGuestEmailSchema = external_exports.string().trim().toLowerCase().max(CASE_GUEST_EMAIL_MAX).email();
17012
- caseGuestInviteTokenSchema = external_exports.string().regex(new RegExp(`^[A-Za-z0-9_-]{${CASE_GUEST_INVITE_TOKEN_LENGTH}}$`));
17013
- inviteCaseGuestBody = external_exports.object({ email: caseGuestEmailSchema }).strict();
17014
- caseGuestInvitationParam = caseSpaceParam.extend({ invitation_id: uuidSchema });
17015
- caseGuestInvitationsQuery = casePageQuery.extend({
17016
- limit: external_exports.coerce.number().int().min(1).max(CASE_GUEST_INVITATIONS_PAGE_MAX).optional()
17017
- });
17018
- joinCaseSpaceBody = external_exports.object({ invite: caseGuestInviteTokenSchema }).strict();
17019
- caseJoinSearchParams = external_exports.object({ org: uuidSchema, space: uuidSchema, invite: caseGuestInviteTokenSchema });
17020
- }
17021
- });
17022
-
17023
- // ../../packages/core/dist/chunk-BVQCYBU6.js
17024
- var CASE_RELATION_TYPE_CODE_PATTERN, CASE_RELATION_TYPE_CODE_MAX_LENGTH, CASE_RELATION_TYPE_NAME_MAX_LENGTH, CASE_RELATION_TYPES_PER_SPACE_MAX, CASE_RELATION_DESCRIPTION_MAX_LENGTH, CASE_RELATION_SIDES, CASE_EXTERNAL_SYSTEM_PATTERN, CASE_EXTERNAL_NUMBER_MAX_LENGTH, CASE_EXTERNAL_URL_MAX_LENGTH, trimmedName2, relationTypeFields, createCaseRelationTypeBody, updateCaseRelationTypeBody, relateCasesBody, addCaseExternalReferenceBody, caseRelationTypeParam, caseRelationParam, caseExternalReferenceParam, caseRelationTypesQuery;
17025
- var init_chunk_BVQCYBU6 = __esm({
17026
- "../../packages/core/dist/chunk-BVQCYBU6.js"() {
17027
- "use strict";
17028
- init_chunk_733K4J4G();
17029
- init_chunk_3T3D7LTE();
17030
- init_chunk_HZ6CADSY();
17031
- init_zod();
17032
- CASE_RELATION_TYPE_CODE_PATTERN = /^[a-z0-9]+(_[a-z0-9]+)*$/;
17033
- CASE_RELATION_TYPE_CODE_MAX_LENGTH = 64;
17034
- CASE_RELATION_TYPE_NAME_MAX_LENGTH = 200;
17035
- CASE_RELATION_TYPES_PER_SPACE_MAX = 100;
17036
- CASE_RELATION_DESCRIPTION_MAX_LENGTH = 500;
17037
- CASE_RELATION_SIDES = ["origin", "destination"];
17038
- CASE_EXTERNAL_SYSTEM_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]{0,30}$/;
17039
- CASE_EXTERNAL_NUMBER_MAX_LENGTH = 120;
17040
- CASE_EXTERNAL_URL_MAX_LENGTH = 2048;
17041
- trimmedName2 = external_exports.string().trim().min(1).max(CASE_RELATION_TYPE_NAME_MAX_LENGTH);
17042
- relationTypeFields = { name: trimmedName2, inverse_name: trimmedName2, active: external_exports.boolean().default(true) };
17043
- createCaseRelationTypeBody = external_exports.object({
17044
- code: external_exports.string().trim().max(CASE_RELATION_TYPE_CODE_MAX_LENGTH).regex(CASE_RELATION_TYPE_CODE_PATTERN),
17045
- ...relationTypeFields
17046
- }).strict();
17047
- updateCaseRelationTypeBody = external_exports.object({ ...relationTypeFields, expected_updated_at: timestampSchema.optional() }).strict();
17048
- relateCasesBody = external_exports.object({
17049
- relation_type_id: uuidSchema,
17050
- other_code: external_exports.string().max(CASE_RECORD_CODE_MAX_LENGTH).regex(CASE_RECORD_CODE_PATTERN),
17051
- /** This case's side: `origin` reads the type's name ("continues"), `destination` its inverse. */
17052
- side: external_exports.enum(CASE_RELATION_SIDES).default("origin"),
17053
- description: external_exports.string().trim().min(1).max(CASE_RELATION_DESCRIPTION_MAX_LENGTH).nullable().default(null)
17054
- }).strict();
17055
- addCaseExternalReferenceBody = external_exports.object({
17056
- system: external_exports.string().trim().regex(CASE_EXTERNAL_SYSTEM_PATTERN),
17057
- number: external_exports.string().trim().min(1).max(CASE_EXTERNAL_NUMBER_MAX_LENGTH),
17058
- url: external_exports.string().trim().max(CASE_EXTERNAL_URL_MAX_LENGTH).url().refine((url) => url.startsWith("https://"), "An https link").nullable().default(null)
17059
- }).strict();
17060
- caseRelationTypeParam = caseSpaceParam.extend({ relation_type_id: uuidSchema });
17061
- caseRelationParam = caseRecordParam.extend({ relation_id: uuidSchema });
17062
- caseExternalReferenceParam = caseRecordParam.extend({ reference_id: uuidSchema });
17063
- caseRelationTypesQuery = casePageQuery.extend({
17064
- limit: external_exports.coerce.number().int().min(1).max(CASE_RELATION_TYPES_PER_SPACE_MAX).optional()
17065
- });
17066
- }
17067
- });
17068
-
17069
- // ../../packages/core/dist/chunk-UOPCLXCU.js
17070
- var CASE_CHANGE_TOPICS, caseChangedFrameSchema;
17071
- var init_chunk_UOPCLXCU = __esm({
17072
- "../../packages/core/dist/chunk-UOPCLXCU.js"() {
17073
- "use strict";
17074
- init_chunk_733K4J4G();
17075
- init_chunk_HZ6CADSY();
17076
- init_zod();
17077
- CASE_CHANGE_TOPICS = ["submission", "agenda", "access"];
17078
- caseChangedFrameSchema = external_exports.object({
17079
- org_id: uuidSchema,
17080
- space_id: uuidSchema,
17081
- /** The case, by its code; null for an `access` change, which names none. */
17082
- code: caseRecordParam.shape.code.nullable(),
17083
- topic: external_exports.enum(CASE_CHANGE_TOPICS)
17084
- }).strict();
17085
- }
17086
- });
17087
-
17088
- // ../../packages/core/dist/chunk-Z3SV3XTC.js
17089
- var caseAccessQuery;
17090
- var init_chunk_Z3SV3XTC = __esm({
17091
- "../../packages/core/dist/chunk-Z3SV3XTC.js"() {
17092
- "use strict";
17093
- init_chunk_HZ6CADSY();
17094
- init_zod();
17095
- caseAccessQuery = external_exports.object({ with_team_id: uuidSchema.optional() }).strict();
17096
- }
17097
- });
17098
-
17099
- // ../../packages/core/dist/chunk-NHC27NIE.js
17100
- var CASE_ADJUSTMENT_REASON_MAX_LENGTH, CASE_ADJUSTMENT_DISPENSATION_KINDS, reason, activateCasePhaseBody, dispenseCaseBody, addCaseTaskBody, addCaseInputBody, caseOwnItemSchema, addCaseItemBody;
17101
- var init_chunk_NHC27NIE = __esm({
17102
- "../../packages/core/dist/chunk-NHC27NIE.js"() {
17103
- "use strict";
17104
- init_chunk_PFPADFUC();
17105
- init_chunk_HZ6CADSY();
17106
- init_zod();
17107
- CASE_ADJUSTMENT_REASON_MAX_LENGTH = 2e3;
17108
- CASE_ADJUSTMENT_DISPENSATION_KINDS = ["phase", "item", "output", "input"];
17109
- reason = external_exports.string().trim().min(1).max(CASE_ADJUSTMENT_REASON_MAX_LENGTH);
17110
- activateCasePhaseBody = external_exports.object({ phase_id: uuidSchema, reason }).strict();
17111
- dispenseCaseBody = external_exports.object({ kind: external_exports.enum(CASE_ADJUSTMENT_DISPENSATION_KINDS), target_id: uuidSchema, reason }).strict();
17112
- addCaseTaskBody = external_exports.object({
17113
- phase_id: uuidSchema,
17114
- name: external_exports.string().trim().min(1).max(CASE_TASK_NAME_MAX_LENGTH),
17115
- required: external_exports.boolean().default(false),
17116
- /** Tasks of the same phase it waits for. */
17117
- depends_on: external_exports.array(uuidSchema).max(CASE_TASK_DEPENDENCIES_MAX).default([])
17118
- }).strict();
17119
- addCaseInputBody = external_exports.object({
17120
- phase_id: uuidSchema,
17121
- input: casePhaseInputSchema.extend({ agenda_group: caseAgendaGroupCodeSchema.nullable().default(null) }),
17122
- reason
17123
- }).strict();
17124
- caseOwnItemSchema = caseOutputItemSchema.omit({ waivable: true, template_mode: true, fixed_text: true }).extend({ agenda_group: caseAgendaGroupCodeSchema.nullable().default(null) });
17125
- addCaseItemBody = external_exports.object({
17126
- phase_id: uuidSchema,
17127
- /** The phase's output it goes in. */
17128
- output_id: uuidSchema,
17129
- item: caseOwnItemSchema,
17130
- reason
17131
- }).strict();
17132
- }
17133
- });
17134
-
17135
- // ../../packages/core/dist/chunk-UMAPAGFH.js
17136
- var CASE_AGENDA_VALUE_MAX_LENGTH, CASE_AGENDA_JUSTIFICATION_MAX_LENGTH, CASE_AGENDA_EVIDENCE_MAX_LENGTH, CASE_AGENDA_COMMENT_MAX_LENGTH, CASE_AGENDA_VERDICTS, comment, caseAgendaGroupParam, caseAgendaDecisionParam, caseAgendaQuery, caseApprovedDecisionsQuery, proposeCaseAgendaValueBody, decideCaseAgendaBody, dispenseCaseAgendaBody, addCaseDecisionBody;
17137
- var init_chunk_UMAPAGFH = __esm({
17138
- "../../packages/core/dist/chunk-UMAPAGFH.js"() {
17139
- "use strict";
17140
- init_chunk_733K4J4G();
17141
- init_chunk_PFPADFUC();
17142
- init_chunk_3T3D7LTE();
17143
- init_chunk_M2T55BV6();
17144
- init_chunk_HZ6CADSY();
17145
- init_zod();
17146
- CASE_AGENDA_VALUE_MAX_LENGTH = 2e3;
17147
- CASE_AGENDA_JUSTIFICATION_MAX_LENGTH = 2e3;
17148
- CASE_AGENDA_EVIDENCE_MAX_LENGTH = 500;
17149
- CASE_AGENDA_COMMENT_MAX_LENGTH = 2e3;
17150
- CASE_AGENDA_VERDICTS = ["approve", "return"];
17151
- comment = external_exports.string().trim().min(1).max(CASE_AGENDA_COMMENT_MAX_LENGTH);
17152
- caseAgendaGroupParam = caseRecordParam.extend({ group_id: uuidSchema });
17153
- caseAgendaDecisionParam = caseRecordParam.extend({ decision_code: caseDecisionCodeSchema });
17154
- caseAgendaQuery = external_exports.object({
17155
- phase_id: uuidSchema,
17156
- cursor: external_exports.string().min(1).max(CASE_PAGE_CURSOR_MAX_LENGTH).optional()
17157
- });
17158
- caseApprovedDecisionsQuery = external_exports.object({
17159
- confidential: external_exports.enum(["true", "false"]).optional().transform((value) => value === "true")
17160
- });
17161
- proposeCaseAgendaValueBody = external_exports.object({
17162
- /** As written: a numeric type also takes a string of digits with a `.` or `,` decimal mark (Rito's). */
17163
- value: external_exports.union([external_exports.number(), external_exports.boolean(), external_exports.string().max(CASE_AGENDA_VALUE_MAX_LENGTH)]),
17164
- justification: external_exports.string().trim().min(1).max(CASE_AGENDA_JUSTIFICATION_MAX_LENGTH),
17165
- evidence: external_exports.string().trim().max(CASE_AGENDA_EVIDENCE_MAX_LENGTH).nullable().default(null).transform((text5) => text5 || null),
17166
- /** Required on an approved group: why it is revised. */
17167
- reason: comment.nullable().default(null)
17168
- }).strict();
17169
- decideCaseAgendaBody = external_exports.object({
17170
- decision: external_exports.enum(CASE_AGENDA_VERDICTS),
17171
- /** The sending its decider read (`CaseAgendaGroupView.sending_id`). */
17172
- sending_id: uuidSchema,
17173
- comment: comment.nullable().default(null)
17174
- }).strict().superRefine((body, ctx) => {
17175
- if (body.decision === "return" && body.comment === null) ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "A return needs its comment", path: ["comment"] });
17176
- });
17177
- dispenseCaseAgendaBody = external_exports.object({ reason: comment }).strict();
17178
- addCaseDecisionBody = external_exports.object({ decision: caseAgendaDecisionSchema, reason: comment }).strict();
17179
- }
17180
- });
17181
-
17182
16974
  // ../../packages/core/dist/chunk-7TQYAKCB.js
17183
16975
  function addCaseNoteProblem(note) {
17184
16976
  return note.origin !== null && note.kind !== "contribution" ? { reason: "origin_not_contribution", at: "origin" } : null;
@@ -17259,7 +17051,7 @@ var init_chunk_S7UAXLHJ = __esm({
17259
17051
  });
17260
17052
 
17261
17053
  // ../../packages/core/dist/chunk-S4NDHW3Q.js
17262
- var CASE_VERSION_DECISION_REASON_MAX_LENGTH, CASE_VERSION_DECISIONS, caseVersionDecisionReason, reason2, lineNumber2, recordCaseReferenceBody, CASE_PASSAGE_REVERSED_REASON, citeCasePassageBody, decideCaseVersionBody;
17054
+ var CASE_VERSION_DECISION_REASON_MAX_LENGTH, CASE_VERSION_DECISIONS, caseVersionDecisionReason, reason, lineNumber2, recordCaseReferenceBody, CASE_PASSAGE_REVERSED_REASON, citeCasePassageBody, decideCaseVersionBody;
17263
17055
  var init_chunk_S4NDHW3Q = __esm({
17264
17056
  "../../packages/core/dist/chunk-S4NDHW3Q.js"() {
17265
17057
  "use strict";
@@ -17269,7 +17061,7 @@ var init_chunk_S4NDHW3Q = __esm({
17269
17061
  CASE_VERSION_DECISION_REASON_MAX_LENGTH = 2e3;
17270
17062
  CASE_VERSION_DECISIONS = ["adopt", "keep"];
17271
17063
  caseVersionDecisionReason = external_exports.string().trim().min(1).max(CASE_VERSION_DECISION_REASON_MAX_LENGTH);
17272
- reason2 = caseVersionDecisionReason;
17064
+ reason = caseVersionDecisionReason;
17273
17065
  lineNumber2 = casePassageLineSchema;
17274
17066
  recordCaseReferenceBody = external_exports.object({
17275
17067
  document_id: uuidSchema,
@@ -17289,25 +17081,26 @@ var init_chunk_S4NDHW3Q = __esm({
17289
17081
  decision: external_exports.enum(CASE_VERSION_DECISIONS),
17290
17082
  /** The newer version its decider read as current. */
17291
17083
  expect_version_id: uuidSchema,
17292
- reason: reason2.nullable().default(null)
17084
+ reason: reason.nullable().default(null)
17293
17085
  }).strict().superRefine((body, ctx) => {
17294
17086
  if (body.decision === "keep" && body.reason === null) ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "A version kept needs its reason", path: ["reason"] });
17295
17087
  });
17296
17088
  }
17297
17089
  });
17298
17090
 
17299
- // ../../packages/core/dist/chunk-W4XY3TYX.js
17300
- var caseInputLinkParam, linkCaseInputBody, CASE_COLLECTION_CASES_PAGE_MAX, caseCollectionCasesQuery, CASE_REFERENCES_PAGE_MAX, caseReferencesQuery;
17301
- var init_chunk_W4XY3TYX = __esm({
17302
- "../../packages/core/dist/chunk-W4XY3TYX.js"() {
17091
+ // ../../packages/core/dist/chunk-UZ72OHQN.js
17092
+ var caseInputLinkParam, caseCollectionDocumentOfCaseParam, linkCaseInputBody, CASE_COLLECTION_CASES_PAGE_MAX, caseCollectionCasesQuery, CASE_REFERENCES_PAGE_MAX, caseReferencesQuery;
17093
+ var init_chunk_UZ72OHQN = __esm({
17094
+ "../../packages/core/dist/chunk-UZ72OHQN.js"() {
17303
17095
  "use strict";
17304
- init_chunk_PMBOHJKA();
17096
+ init_chunk_6CHDJVQ6();
17305
17097
  init_chunk_S4NDHW3Q();
17306
17098
  init_chunk_733K4J4G();
17307
17099
  init_chunk_3T3D7LTE();
17308
17100
  init_chunk_HZ6CADSY();
17309
17101
  init_zod();
17310
17102
  caseInputLinkParam = caseRecordParam.extend({ input_id: uuidSchema });
17103
+ caseCollectionDocumentOfCaseParam = caseRecordParam.extend({ document_id: uuidSchema });
17311
17104
  linkCaseInputBody = external_exports.object({
17312
17105
  document_id: uuidSchema,
17313
17106
  /** The document's version its writer read as current, or an earlier one it keeps, with its `reason`. */
@@ -17326,6 +17119,329 @@ var init_chunk_W4XY3TYX = __esm({
17326
17119
  }
17327
17120
  });
17328
17121
 
17122
+ // ../../packages/core/dist/chunk-H6V7NEWR.js
17123
+ function isCaseDueDate(value) {
17124
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
17125
+ if (!match) return false;
17126
+ const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
17127
+ if (year < CASE_DUE_DATE_MIN_YEAR || year > CASE_DUE_DATE_MAX_YEAR) return false;
17128
+ const date = new Date(Date.UTC(year, month - 1, day));
17129
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
17130
+ }
17131
+ function setCaseDeadlinesProblem(body) {
17132
+ const seen = /* @__PURE__ */ new Set();
17133
+ for (const [index, phase] of body.phases.entries()) {
17134
+ if (seen.has(phase.phase_id)) return { reason: "phase_repeated", at: `phases.${index}.phase_id` };
17135
+ seen.add(phase.phase_id);
17136
+ }
17137
+ return null;
17138
+ }
17139
+ var CASE_DUE_DATE_MIN_YEAR, CASE_DUE_DATE_MAX_YEAR, CASE_DEADLINES_PHASES_MAX, CASE_OVERDUE_CASES_MAX, caseDueDateSchema, setCaseDeadlinesShape, setCaseDeadlinesBody, setCaseTaskPlanBody, setCaseOwnerBody, caseOverdueQuery;
17140
+ var init_chunk_H6V7NEWR = __esm({
17141
+ "../../packages/core/dist/chunk-H6V7NEWR.js"() {
17142
+ "use strict";
17143
+ init_chunk_3T3D7LTE();
17144
+ init_chunk_HZ6CADSY();
17145
+ init_zod();
17146
+ CASE_DUE_DATE_MIN_YEAR = 2e3;
17147
+ CASE_DUE_DATE_MAX_YEAR = 2100;
17148
+ CASE_DEADLINES_PHASES_MAX = 50;
17149
+ CASE_OVERDUE_CASES_MAX = 50;
17150
+ caseDueDateSchema = external_exports.string().refine(isCaseDueDate, "Not a calendar date (YYYY-MM-DD)");
17151
+ setCaseDeadlinesShape = external_exports.object({
17152
+ phases: external_exports.array(external_exports.object({ phase_id: uuidSchema, due_on: caseDueDateSchema.nullable() }).strict()).min(1).max(CASE_DEADLINES_PHASES_MAX)
17153
+ }).strict();
17154
+ setCaseDeadlinesBody = setCaseDeadlinesShape.superRefine((body, ctx) => {
17155
+ const found = setCaseDeadlinesProblem(body);
17156
+ if (found) {
17157
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: found.reason, path: found.at.split("."), params: { case_deadlines_reason: found.reason } });
17158
+ }
17159
+ });
17160
+ setCaseTaskPlanBody = external_exports.object({
17161
+ owner_person_id: uuidSchema.nullable(),
17162
+ due_on: caseDueDateSchema.nullable()
17163
+ }).strict();
17164
+ setCaseOwnerBody = external_exports.object({ owner_person_id: uuidSchema.nullable() }).strict();
17165
+ caseOverdueQuery = casePageQuery.extend({
17166
+ limit: external_exports.coerce.number().int().min(1).max(CASE_OVERDUE_CASES_MAX).optional()
17167
+ });
17168
+ }
17169
+ });
17170
+
17171
+ // ../../packages/core/dist/chunk-ZVIMTUGZ.js
17172
+ var CASE_GUEST_EMAIL_MAX, CASE_GUEST_INVITATIONS_PAGE_MAX, CASE_GUEST_INVITE_TOKEN_LENGTH, caseGuestEmailSchema, caseGuestInviteTokenSchema, inviteCaseGuestBody, caseGuestInvitationParam, caseGuestInvitationsQuery, joinCaseSpaceBody, caseJoinSearchParams;
17173
+ var init_chunk_ZVIMTUGZ = __esm({
17174
+ "../../packages/core/dist/chunk-ZVIMTUGZ.js"() {
17175
+ "use strict";
17176
+ init_chunk_3T3D7LTE();
17177
+ init_chunk_HZ6CADSY();
17178
+ init_zod();
17179
+ CASE_GUEST_EMAIL_MAX = 320;
17180
+ CASE_GUEST_INVITATIONS_PAGE_MAX = 100;
17181
+ CASE_GUEST_INVITE_TOKEN_LENGTH = 43;
17182
+ caseGuestEmailSchema = external_exports.string().trim().toLowerCase().max(CASE_GUEST_EMAIL_MAX).email();
17183
+ caseGuestInviteTokenSchema = external_exports.string().regex(new RegExp(`^[A-Za-z0-9_-]{${CASE_GUEST_INVITE_TOKEN_LENGTH}}$`));
17184
+ inviteCaseGuestBody = external_exports.object({ email: caseGuestEmailSchema }).strict();
17185
+ caseGuestInvitationParam = caseSpaceParam.extend({ invitation_id: uuidSchema });
17186
+ caseGuestInvitationsQuery = casePageQuery.extend({
17187
+ limit: external_exports.coerce.number().int().min(1).max(CASE_GUEST_INVITATIONS_PAGE_MAX).optional()
17188
+ });
17189
+ joinCaseSpaceBody = external_exports.object({ invite: caseGuestInviteTokenSchema }).strict();
17190
+ caseJoinSearchParams = external_exports.object({ org: uuidSchema, space: uuidSchema, invite: caseGuestInviteTokenSchema });
17191
+ }
17192
+ });
17193
+
17194
+ // ../../packages/core/dist/chunk-BVQCYBU6.js
17195
+ var CASE_RELATION_TYPE_CODE_PATTERN, CASE_RELATION_TYPE_CODE_MAX_LENGTH, CASE_RELATION_TYPE_NAME_MAX_LENGTH, CASE_RELATION_TYPES_PER_SPACE_MAX, CASE_RELATION_DESCRIPTION_MAX_LENGTH, CASE_RELATION_SIDES, CASE_EXTERNAL_SYSTEM_PATTERN, CASE_EXTERNAL_NUMBER_MAX_LENGTH, CASE_EXTERNAL_URL_MAX_LENGTH, trimmedName2, relationTypeFields, createCaseRelationTypeBody, updateCaseRelationTypeBody, relateCasesBody, addCaseExternalReferenceBody, caseRelationTypeParam, caseRelationParam, caseExternalReferenceParam, caseRelationTypesQuery;
17196
+ var init_chunk_BVQCYBU6 = __esm({
17197
+ "../../packages/core/dist/chunk-BVQCYBU6.js"() {
17198
+ "use strict";
17199
+ init_chunk_733K4J4G();
17200
+ init_chunk_3T3D7LTE();
17201
+ init_chunk_HZ6CADSY();
17202
+ init_zod();
17203
+ CASE_RELATION_TYPE_CODE_PATTERN = /^[a-z0-9]+(_[a-z0-9]+)*$/;
17204
+ CASE_RELATION_TYPE_CODE_MAX_LENGTH = 64;
17205
+ CASE_RELATION_TYPE_NAME_MAX_LENGTH = 200;
17206
+ CASE_RELATION_TYPES_PER_SPACE_MAX = 100;
17207
+ CASE_RELATION_DESCRIPTION_MAX_LENGTH = 500;
17208
+ CASE_RELATION_SIDES = ["origin", "destination"];
17209
+ CASE_EXTERNAL_SYSTEM_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]{0,30}$/;
17210
+ CASE_EXTERNAL_NUMBER_MAX_LENGTH = 120;
17211
+ CASE_EXTERNAL_URL_MAX_LENGTH = 2048;
17212
+ trimmedName2 = external_exports.string().trim().min(1).max(CASE_RELATION_TYPE_NAME_MAX_LENGTH);
17213
+ relationTypeFields = { name: trimmedName2, inverse_name: trimmedName2, active: external_exports.boolean().default(true) };
17214
+ createCaseRelationTypeBody = external_exports.object({
17215
+ code: external_exports.string().trim().max(CASE_RELATION_TYPE_CODE_MAX_LENGTH).regex(CASE_RELATION_TYPE_CODE_PATTERN),
17216
+ ...relationTypeFields
17217
+ }).strict();
17218
+ updateCaseRelationTypeBody = external_exports.object({ ...relationTypeFields, expected_updated_at: timestampSchema.optional() }).strict();
17219
+ relateCasesBody = external_exports.object({
17220
+ relation_type_id: uuidSchema,
17221
+ other_code: external_exports.string().max(CASE_RECORD_CODE_MAX_LENGTH).regex(CASE_RECORD_CODE_PATTERN),
17222
+ /** This case's side: `origin` reads the type's name ("continues"), `destination` its inverse. */
17223
+ side: external_exports.enum(CASE_RELATION_SIDES).default("origin"),
17224
+ description: external_exports.string().trim().min(1).max(CASE_RELATION_DESCRIPTION_MAX_LENGTH).nullable().default(null)
17225
+ }).strict();
17226
+ addCaseExternalReferenceBody = external_exports.object({
17227
+ system: external_exports.string().trim().regex(CASE_EXTERNAL_SYSTEM_PATTERN),
17228
+ number: external_exports.string().trim().min(1).max(CASE_EXTERNAL_NUMBER_MAX_LENGTH),
17229
+ url: external_exports.string().trim().max(CASE_EXTERNAL_URL_MAX_LENGTH).url().refine((url) => url.startsWith("https://"), "An https link").nullable().default(null)
17230
+ }).strict();
17231
+ caseRelationTypeParam = caseSpaceParam.extend({ relation_type_id: uuidSchema });
17232
+ caseRelationParam = caseRecordParam.extend({ relation_id: uuidSchema });
17233
+ caseExternalReferenceParam = caseRecordParam.extend({ reference_id: uuidSchema });
17234
+ caseRelationTypesQuery = casePageQuery.extend({
17235
+ limit: external_exports.coerce.number().int().min(1).max(CASE_RELATION_TYPES_PER_SPACE_MAX).optional()
17236
+ });
17237
+ }
17238
+ });
17239
+
17240
+ // ../../packages/core/dist/chunk-Z3SV3XTC.js
17241
+ var caseAccessQuery;
17242
+ var init_chunk_Z3SV3XTC = __esm({
17243
+ "../../packages/core/dist/chunk-Z3SV3XTC.js"() {
17244
+ "use strict";
17245
+ init_chunk_HZ6CADSY();
17246
+ init_zod();
17247
+ caseAccessQuery = external_exports.object({ with_team_id: uuidSchema.optional() }).strict();
17248
+ }
17249
+ });
17250
+
17251
+ // ../../packages/core/dist/chunk-NHC27NIE.js
17252
+ var CASE_ADJUSTMENT_REASON_MAX_LENGTH, CASE_ADJUSTMENT_DISPENSATION_KINDS, reason2, activateCasePhaseBody, dispenseCaseBody, addCaseTaskBody, addCaseInputBody, caseOwnItemSchema, addCaseItemBody;
17253
+ var init_chunk_NHC27NIE = __esm({
17254
+ "../../packages/core/dist/chunk-NHC27NIE.js"() {
17255
+ "use strict";
17256
+ init_chunk_PFPADFUC();
17257
+ init_chunk_HZ6CADSY();
17258
+ init_zod();
17259
+ CASE_ADJUSTMENT_REASON_MAX_LENGTH = 2e3;
17260
+ CASE_ADJUSTMENT_DISPENSATION_KINDS = ["phase", "item", "output", "input"];
17261
+ reason2 = external_exports.string().trim().min(1).max(CASE_ADJUSTMENT_REASON_MAX_LENGTH);
17262
+ activateCasePhaseBody = external_exports.object({ phase_id: uuidSchema, reason: reason2 }).strict();
17263
+ dispenseCaseBody = external_exports.object({ kind: external_exports.enum(CASE_ADJUSTMENT_DISPENSATION_KINDS), target_id: uuidSchema, reason: reason2 }).strict();
17264
+ addCaseTaskBody = external_exports.object({
17265
+ phase_id: uuidSchema,
17266
+ name: external_exports.string().trim().min(1).max(CASE_TASK_NAME_MAX_LENGTH),
17267
+ required: external_exports.boolean().default(false),
17268
+ /** Tasks of the same phase it waits for. */
17269
+ depends_on: external_exports.array(uuidSchema).max(CASE_TASK_DEPENDENCIES_MAX).default([])
17270
+ }).strict();
17271
+ addCaseInputBody = external_exports.object({
17272
+ phase_id: uuidSchema,
17273
+ input: casePhaseInputSchema.extend({ agenda_group: caseAgendaGroupCodeSchema.nullable().default(null) }),
17274
+ reason: reason2
17275
+ }).strict();
17276
+ caseOwnItemSchema = caseOutputItemSchema.omit({ waivable: true, template_mode: true, fixed_text: true }).extend({ agenda_group: caseAgendaGroupCodeSchema.nullable().default(null) });
17277
+ addCaseItemBody = external_exports.object({
17278
+ phase_id: uuidSchema,
17279
+ /** The phase's output it goes in. */
17280
+ output_id: uuidSchema,
17281
+ item: caseOwnItemSchema,
17282
+ reason: reason2
17283
+ }).strict();
17284
+ }
17285
+ });
17286
+
17287
+ // ../../packages/core/dist/chunk-UMAPAGFH.js
17288
+ var CASE_AGENDA_VALUE_MAX_LENGTH, CASE_AGENDA_JUSTIFICATION_MAX_LENGTH, CASE_AGENDA_EVIDENCE_MAX_LENGTH, CASE_AGENDA_COMMENT_MAX_LENGTH, CASE_AGENDA_VERDICTS, comment, caseAgendaGroupParam, caseAgendaDecisionParam, caseAgendaQuery, caseApprovedDecisionsQuery, proposeCaseAgendaValueBody, decideCaseAgendaBody, dispenseCaseAgendaBody, addCaseDecisionBody;
17289
+ var init_chunk_UMAPAGFH = __esm({
17290
+ "../../packages/core/dist/chunk-UMAPAGFH.js"() {
17291
+ "use strict";
17292
+ init_chunk_733K4J4G();
17293
+ init_chunk_PFPADFUC();
17294
+ init_chunk_3T3D7LTE();
17295
+ init_chunk_M2T55BV6();
17296
+ init_chunk_HZ6CADSY();
17297
+ init_zod();
17298
+ CASE_AGENDA_VALUE_MAX_LENGTH = 2e3;
17299
+ CASE_AGENDA_JUSTIFICATION_MAX_LENGTH = 2e3;
17300
+ CASE_AGENDA_EVIDENCE_MAX_LENGTH = 500;
17301
+ CASE_AGENDA_COMMENT_MAX_LENGTH = 2e3;
17302
+ CASE_AGENDA_VERDICTS = ["approve", "return"];
17303
+ comment = external_exports.string().trim().min(1).max(CASE_AGENDA_COMMENT_MAX_LENGTH);
17304
+ caseAgendaGroupParam = caseRecordParam.extend({ group_id: uuidSchema });
17305
+ caseAgendaDecisionParam = caseRecordParam.extend({ decision_code: caseDecisionCodeSchema });
17306
+ caseAgendaQuery = external_exports.object({
17307
+ phase_id: uuidSchema,
17308
+ cursor: external_exports.string().min(1).max(CASE_PAGE_CURSOR_MAX_LENGTH).optional()
17309
+ });
17310
+ caseApprovedDecisionsQuery = external_exports.object({
17311
+ confidential: external_exports.enum(["true", "false"]).optional().transform((value) => value === "true")
17312
+ });
17313
+ proposeCaseAgendaValueBody = external_exports.object({
17314
+ /** As written: a numeric type also takes a string of digits with a `.` or `,` decimal mark (Rito's). */
17315
+ value: external_exports.union([external_exports.number(), external_exports.boolean(), external_exports.string().max(CASE_AGENDA_VALUE_MAX_LENGTH)]),
17316
+ justification: external_exports.string().trim().min(1).max(CASE_AGENDA_JUSTIFICATION_MAX_LENGTH),
17317
+ evidence: external_exports.string().trim().max(CASE_AGENDA_EVIDENCE_MAX_LENGTH).nullable().default(null).transform((text5) => text5 || null),
17318
+ /** Required on an approved group: why it is revised. */
17319
+ reason: comment.nullable().default(null)
17320
+ }).strict();
17321
+ decideCaseAgendaBody = external_exports.object({
17322
+ decision: external_exports.enum(CASE_AGENDA_VERDICTS),
17323
+ /** The sending its decider read (`CaseAgendaGroupView.sending_id`). */
17324
+ sending_id: uuidSchema,
17325
+ comment: comment.nullable().default(null)
17326
+ }).strict().superRefine((body, ctx) => {
17327
+ if (body.decision === "return" && body.comment === null) ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "A return needs its comment", path: ["comment"] });
17328
+ });
17329
+ dispenseCaseAgendaBody = external_exports.object({ reason: comment }).strict();
17330
+ addCaseDecisionBody = external_exports.object({ decision: caseAgendaDecisionSchema, reason: comment }).strict();
17331
+ }
17332
+ });
17333
+
17334
+ // ../../packages/core/dist/chunk-2PZIF56U.js
17335
+ var analyticsHubIdParam, analyticsVariableIdParam, updateVariablePinBody, updateAnalyticsViewBody, NUMERIC_FILTER_OPS, TEXT_FILTER_OPS, CATEGORICAL_FILTER_OPS, VARIABLE_FILTER_OPS, STRUCTURED_QUERY_OPS, STRUCTURED_QUERY_AGGREGATIONS, filterValueSchema, conversationsBody, analyticsConversationIdParam, messagesQuery, conversationDetailDataQuery, analyticsDataBody, structuredQueryBody, analyticsSqlBody, analyticsSqlTable, analyticsSqlSchemaQuery;
17336
+ var init_chunk_2PZIF56U = __esm({
17337
+ "../../packages/core/dist/chunk-2PZIF56U.js"() {
17338
+ "use strict";
17339
+ init_zod();
17340
+ analyticsHubIdParam = external_exports.object({
17341
+ hubId: external_exports.string().uuid()
17342
+ });
17343
+ analyticsVariableIdParam = external_exports.object({
17344
+ variableId: external_exports.string().uuid()
17345
+ });
17346
+ updateVariablePinBody = external_exports.object({
17347
+ pin: external_exports.union([external_exports.boolean(), external_exports.string()])
17348
+ });
17349
+ updateAnalyticsViewBody = external_exports.object({
17350
+ // 64 covers UUIDs (36) and the `sys:{name}` synthetic IDs for system variables.
17351
+ selected_variable_ids: external_exports.array(external_exports.string().min(1).max(64)).max(200)
17352
+ });
17353
+ NUMERIC_FILTER_OPS = ["eq", "neq", "gt", "gte", "lt", "lte"];
17354
+ TEXT_FILTER_OPS = ["equals", "not_equals", "contains", "not_contains", "starts_with", "ends_with"];
17355
+ CATEGORICAL_FILTER_OPS = ["is", "is_not", "in", "not_in"];
17356
+ VARIABLE_FILTER_OPS = [
17357
+ ...NUMERIC_FILTER_OPS,
17358
+ ...TEXT_FILTER_OPS,
17359
+ ...CATEGORICAL_FILTER_OPS
17360
+ ];
17361
+ STRUCTURED_QUERY_OPS = ["eq", "neq", "gt", "gte", "lt", "lte", "in", "not_in", "like"];
17362
+ STRUCTURED_QUERY_AGGREGATIONS = ["avg", "sum", "min", "max", "count", "quantile", "stddevPop", "corr", "uniq"];
17363
+ filterValueSchema = external_exports.object({
17364
+ variable_id: external_exports.string(),
17365
+ filter_type: external_exports.enum(VARIABLE_FILTER_OPS),
17366
+ filter_value: external_exports.union([external_exports.string(), external_exports.number()])
17367
+ });
17368
+ conversationsBody = external_exports.object({
17369
+ hub_id: external_exports.string().uuid(),
17370
+ time_interval: external_exports.object({
17371
+ start: external_exports.string().optional(),
17372
+ end: external_exports.string().optional()
17373
+ }).optional(),
17374
+ filters: external_exports.array(filterValueSchema).optional(),
17375
+ limit: external_exports.number().int().positive().max(500).default(50),
17376
+ offset: external_exports.number().int().min(0).default(0)
17377
+ });
17378
+ analyticsConversationIdParam = external_exports.object({
17379
+ conversationId: external_exports.string().uuid()
17380
+ });
17381
+ messagesQuery = external_exports.object({
17382
+ hub_id: external_exports.string().uuid(),
17383
+ limit: external_exports.string().regex(/^\d+$/).optional(),
17384
+ offset: external_exports.string().regex(/^\d+$/).optional()
17385
+ });
17386
+ conversationDetailDataQuery = external_exports.object({
17387
+ hub_id: external_exports.string().uuid()
17388
+ });
17389
+ analyticsDataBody = external_exports.object({
17390
+ hub_id: external_exports.string().uuid(),
17391
+ periodicity: external_exports.enum(["daily", "weekly", "monthly", "yearly"]),
17392
+ time_interval: external_exports.object({
17393
+ start: external_exports.string(),
17394
+ end: external_exports.string()
17395
+ }),
17396
+ trend_analysis: external_exports.boolean(),
17397
+ filters: external_exports.array(filterValueSchema).optional(),
17398
+ selected_variables: external_exports.array(external_exports.string()),
17399
+ include_summary: external_exports.boolean().optional(),
17400
+ include_variables: external_exports.boolean().optional(),
17401
+ variable_origin: external_exports.enum(["agent", "system", "annotation"]).optional(),
17402
+ variable_category: external_exports.string().optional(),
17403
+ variables_only: external_exports.boolean().optional()
17404
+ });
17405
+ structuredQueryBody = external_exports.object({
17406
+ hub_id: external_exports.string().uuid(),
17407
+ metrics: external_exports.array(external_exports.object({
17408
+ column: external_exports.string(),
17409
+ aggregation: external_exports.enum(STRUCTURED_QUERY_AGGREGATIONS),
17410
+ alias: external_exports.string().optional(),
17411
+ corr_with: external_exports.string().optional(),
17412
+ quantile_level: external_exports.number().min(0).max(1).optional()
17413
+ })).min(1),
17414
+ group_by: external_exports.array(external_exports.string()).optional(),
17415
+ order_by: external_exports.array(external_exports.object({
17416
+ column: external_exports.string(),
17417
+ direction: external_exports.enum(["asc", "desc"]).optional()
17418
+ })).optional(),
17419
+ filters: external_exports.array(external_exports.object({
17420
+ column: external_exports.string(),
17421
+ operator: external_exports.enum(STRUCTURED_QUERY_OPS),
17422
+ value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])
17423
+ })).optional(),
17424
+ time_range: external_exports.object({
17425
+ start: external_exports.string(),
17426
+ end: external_exports.string()
17427
+ }).optional(),
17428
+ limit: external_exports.number().int().positive().max(1e4).optional()
17429
+ });
17430
+ analyticsSqlBody = external_exports.object({
17431
+ hub_id: external_exports.string().uuid(),
17432
+ // Hard size cap before the validator runs — keeps lex/parse work bounded.
17433
+ sql: external_exports.string().min(1).max(8e3),
17434
+ limit: external_exports.number().int().positive().max(1e4).optional()
17435
+ });
17436
+ analyticsSqlTable = external_exports.enum(["conversation", "message"]);
17437
+ analyticsSqlSchemaQuery = external_exports.object({
17438
+ hub_id: external_exports.string().uuid(),
17439
+ // Defaulted so a client that predates the message table keeps its old response.
17440
+ table: analyticsSqlTable.default("conversation")
17441
+ });
17442
+ }
17443
+ });
17444
+
17329
17445
  // ../../packages/core/dist/chunk-UEJOG2Q7.js
17330
17446
  var archiveHubIdParam, archiveConversationParams, archiveListQuery, archiveMessageObservabilityParams;
17331
17447
  var init_chunk_UEJOG2Q7 = __esm({
@@ -18231,117 +18347,6 @@ var init_chunk_A4YOU7H6 = __esm({
18231
18347
  }
18232
18348
  });
18233
18349
 
18234
- // ../../packages/core/dist/chunk-2PZIF56U.js
18235
- var analyticsHubIdParam, analyticsVariableIdParam, updateVariablePinBody, updateAnalyticsViewBody, NUMERIC_FILTER_OPS, TEXT_FILTER_OPS, CATEGORICAL_FILTER_OPS, VARIABLE_FILTER_OPS, STRUCTURED_QUERY_OPS, STRUCTURED_QUERY_AGGREGATIONS, filterValueSchema, conversationsBody, analyticsConversationIdParam, messagesQuery, conversationDetailDataQuery, analyticsDataBody, structuredQueryBody, analyticsSqlBody, analyticsSqlTable, analyticsSqlSchemaQuery;
18236
- var init_chunk_2PZIF56U = __esm({
18237
- "../../packages/core/dist/chunk-2PZIF56U.js"() {
18238
- "use strict";
18239
- init_zod();
18240
- analyticsHubIdParam = external_exports.object({
18241
- hubId: external_exports.string().uuid()
18242
- });
18243
- analyticsVariableIdParam = external_exports.object({
18244
- variableId: external_exports.string().uuid()
18245
- });
18246
- updateVariablePinBody = external_exports.object({
18247
- pin: external_exports.union([external_exports.boolean(), external_exports.string()])
18248
- });
18249
- updateAnalyticsViewBody = external_exports.object({
18250
- // 64 covers UUIDs (36) and the `sys:{name}` synthetic IDs for system variables.
18251
- selected_variable_ids: external_exports.array(external_exports.string().min(1).max(64)).max(200)
18252
- });
18253
- NUMERIC_FILTER_OPS = ["eq", "neq", "gt", "gte", "lt", "lte"];
18254
- TEXT_FILTER_OPS = ["equals", "not_equals", "contains", "not_contains", "starts_with", "ends_with"];
18255
- CATEGORICAL_FILTER_OPS = ["is", "is_not", "in", "not_in"];
18256
- VARIABLE_FILTER_OPS = [
18257
- ...NUMERIC_FILTER_OPS,
18258
- ...TEXT_FILTER_OPS,
18259
- ...CATEGORICAL_FILTER_OPS
18260
- ];
18261
- STRUCTURED_QUERY_OPS = ["eq", "neq", "gt", "gte", "lt", "lte", "in", "not_in", "like"];
18262
- STRUCTURED_QUERY_AGGREGATIONS = ["avg", "sum", "min", "max", "count", "quantile", "stddevPop", "corr", "uniq"];
18263
- filterValueSchema = external_exports.object({
18264
- variable_id: external_exports.string(),
18265
- filter_type: external_exports.enum(VARIABLE_FILTER_OPS),
18266
- filter_value: external_exports.union([external_exports.string(), external_exports.number()])
18267
- });
18268
- conversationsBody = external_exports.object({
18269
- hub_id: external_exports.string().uuid(),
18270
- time_interval: external_exports.object({
18271
- start: external_exports.string().optional(),
18272
- end: external_exports.string().optional()
18273
- }).optional(),
18274
- filters: external_exports.array(filterValueSchema).optional(),
18275
- limit: external_exports.number().int().positive().max(500).default(50),
18276
- offset: external_exports.number().int().min(0).default(0)
18277
- });
18278
- analyticsConversationIdParam = external_exports.object({
18279
- conversationId: external_exports.string().uuid()
18280
- });
18281
- messagesQuery = external_exports.object({
18282
- hub_id: external_exports.string().uuid(),
18283
- limit: external_exports.string().regex(/^\d+$/).optional(),
18284
- offset: external_exports.string().regex(/^\d+$/).optional()
18285
- });
18286
- conversationDetailDataQuery = external_exports.object({
18287
- hub_id: external_exports.string().uuid()
18288
- });
18289
- analyticsDataBody = external_exports.object({
18290
- hub_id: external_exports.string().uuid(),
18291
- periodicity: external_exports.enum(["daily", "weekly", "monthly", "yearly"]),
18292
- time_interval: external_exports.object({
18293
- start: external_exports.string(),
18294
- end: external_exports.string()
18295
- }),
18296
- trend_analysis: external_exports.boolean(),
18297
- filters: external_exports.array(filterValueSchema).optional(),
18298
- selected_variables: external_exports.array(external_exports.string()),
18299
- include_summary: external_exports.boolean().optional(),
18300
- include_variables: external_exports.boolean().optional(),
18301
- variable_origin: external_exports.enum(["agent", "system", "annotation"]).optional(),
18302
- variable_category: external_exports.string().optional(),
18303
- variables_only: external_exports.boolean().optional()
18304
- });
18305
- structuredQueryBody = external_exports.object({
18306
- hub_id: external_exports.string().uuid(),
18307
- metrics: external_exports.array(external_exports.object({
18308
- column: external_exports.string(),
18309
- aggregation: external_exports.enum(STRUCTURED_QUERY_AGGREGATIONS),
18310
- alias: external_exports.string().optional(),
18311
- corr_with: external_exports.string().optional(),
18312
- quantile_level: external_exports.number().min(0).max(1).optional()
18313
- })).min(1),
18314
- group_by: external_exports.array(external_exports.string()).optional(),
18315
- order_by: external_exports.array(external_exports.object({
18316
- column: external_exports.string(),
18317
- direction: external_exports.enum(["asc", "desc"]).optional()
18318
- })).optional(),
18319
- filters: external_exports.array(external_exports.object({
18320
- column: external_exports.string(),
18321
- operator: external_exports.enum(STRUCTURED_QUERY_OPS),
18322
- value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean()])
18323
- })).optional(),
18324
- time_range: external_exports.object({
18325
- start: external_exports.string(),
18326
- end: external_exports.string()
18327
- }).optional(),
18328
- limit: external_exports.number().int().positive().max(1e4).optional()
18329
- });
18330
- analyticsSqlBody = external_exports.object({
18331
- hub_id: external_exports.string().uuid(),
18332
- // Hard size cap before the validator runs — keeps lex/parse work bounded.
18333
- sql: external_exports.string().min(1).max(8e3),
18334
- limit: external_exports.number().int().positive().max(1e4).optional()
18335
- });
18336
- analyticsSqlTable = external_exports.enum(["conversation", "message"]);
18337
- analyticsSqlSchemaQuery = external_exports.object({
18338
- hub_id: external_exports.string().uuid(),
18339
- // Defaulted so a client that predates the message table keeps its old response.
18340
- table: analyticsSqlTable.default("conversation")
18341
- });
18342
- }
18343
- });
18344
-
18345
18350
  // ../../packages/core/dist/chunk-ZRXP6OOJ.js
18346
18351
  function capped(max, field) {
18347
18352
  return (value, ctx) => {
@@ -18403,17 +18408,18 @@ var init_contracts = __esm({
18403
18408
  init_chunk_C7UAGRXF();
18404
18409
  init_chunk_IPXBFWUU();
18405
18410
  init_chunk_63UWXV4T();
18411
+ init_chunk_WTIGECE5();
18406
18412
  init_chunk_WDAXZDJO();
18407
18413
  init_chunk_ZC6YGHNX();
18414
+ init_chunk_5DGHIY7L();
18408
18415
  init_chunk_ITIQ7XWD();
18409
18416
  init_chunk_IPDOHAZ5();
18410
18417
  init_chunk_PFGVH2CX();
18411
18418
  init_chunk_TVUDMGWV();
18412
- init_chunk_WTIGECE5();
18413
18419
  init_chunk_ZXK6N2HN();
18414
18420
  init_chunk_Y7CFCYX4();
18415
18421
  init_chunk_MGBAXT5Y();
18416
- init_chunk_5DGHIY7L();
18422
+ init_chunk_YUZFHVB2();
18417
18423
  init_chunk_I3O2RACG();
18418
18424
  init_chunk_CMRECH67();
18419
18425
  init_chunk_34LE6P7E();
@@ -18422,19 +18428,20 @@ var init_contracts = __esm({
18422
18428
  init_chunk_SSPK6ISL();
18423
18429
  init_chunk_SY6PLCPK();
18424
18430
  init_chunk_2ZZZHXZR();
18425
- init_chunk_YUZFHVB2();
18431
+ init_chunk_KSTYTQ7I();
18426
18432
  init_chunk_LKBSHANA();
18427
18433
  init_chunk_LX3D5LCB();
18428
18434
  init_chunk_C4HEZ7ZI();
18429
18435
  init_chunk_IR2NOSI3();
18430
18436
  init_chunk_OPETF4GS();
18437
+ init_chunk_UCYWGWQT();
18431
18438
  init_chunk_YULHXJ5M();
18432
18439
  init_chunk_V4FRPRH5();
18433
18440
  init_chunk_LWMLR2WI();
18434
18441
  init_chunk_ACGAI25T();
18435
18442
  init_chunk_MH4O3YEX();
18436
18443
  init_chunk_QEEQN2NE();
18437
- init_chunk_KSTYTQ7I();
18444
+ init_chunk_NNC2ZECG();
18438
18445
  init_chunk_7CYHPF35();
18439
18446
  init_chunk_NETRUHZF();
18440
18447
  init_chunk_EO5MKW7Q();
@@ -18444,29 +18451,29 @@ var init_contracts = __esm({
18444
18451
  init_chunk_2YEGUQR7();
18445
18452
  init_chunk_AHISKXHA();
18446
18453
  init_chunk_JDJ4EUOL();
18447
- init_chunk_UCYWGWQT();
18448
18454
  init_chunk_6AYIXGDT();
18449
18455
  init_chunk_Q7NWJA2G();
18450
18456
  init_chunk_K3PD6AOF();
18451
18457
  init_chunk_KVMROYDC();
18452
18458
  init_chunk_M2IF4G6X();
18453
- init_chunk_NNC2ZECG();
18459
+ init_chunk_UOPCLXCU();
18454
18460
  init_chunk_7CZSLDOE();
18455
18461
  init_chunk_2YVCHUBL();
18456
18462
  init_chunk_BT77VXJU();
18457
- init_chunk_ZB7W3DKK();
18463
+ init_chunk_WYCUCSD5();
18464
+ init_chunk_UZ72OHQN();
18465
+ init_chunk_6CHDJVQ6();
18466
+ init_chunk_U3X3BIQH();
18467
+ init_chunk_EYOBPUDN();
18458
18468
  init_chunk_H6V7NEWR();
18459
18469
  init_chunk_ZVIMTUGZ();
18460
18470
  init_chunk_BVQCYBU6();
18461
- init_chunk_UOPCLXCU();
18471
+ init_chunk_5PKKFSSF();
18462
18472
  init_chunk_Z3SV3XTC();
18463
18473
  init_chunk_NHC27NIE();
18464
18474
  init_chunk_UMAPAGFH();
18465
- init_chunk_W4XY3TYX();
18466
- init_chunk_PMBOHJKA();
18467
- init_chunk_U3X3BIQH();
18468
- init_chunk_3LMWOJQX();
18469
18475
  init_chunk_S4NDHW3Q();
18476
+ init_chunk_2PZIF56U();
18470
18477
  init_chunk_UEJOG2Q7();
18471
18478
  init_chunk_KEN2DASI();
18472
18479
  init_chunk_YFNR2VM4();
@@ -18478,7 +18485,6 @@ var init_contracts = __esm({
18478
18485
  init_chunk_PZPOUXJR();
18479
18486
  init_chunk_LBDH7LCG();
18480
18487
  init_chunk_4LXDRTO4();
18481
- init_chunk_5PKKFSSF();
18482
18488
  init_chunk_NVKU5PPQ();
18483
18489
  init_chunk_A4YOU7H6();
18484
18490
  init_chunk_FECLIZTY();
@@ -18489,7 +18495,6 @@ var init_contracts = __esm({
18489
18495
  init_chunk_X5PZZVTS();
18490
18496
  init_chunk_PIZTARVG();
18491
18497
  init_chunk_OMPT4ZHR();
18492
- init_chunk_2PZIF56U();
18493
18498
  init_chunk_6J742GLA();
18494
18499
  init_chunk_ZRXP6OOJ();
18495
18500
  init_chunk_BGNWWR6B();
@@ -19693,15 +19698,15 @@ function unreadArgumentRefusal(invocation, args2, reads, splitsAtFirstLongFlag)
19693
19698
  function entryFlagRefusal(command2, args2, dataNamespaces) {
19694
19699
  if (command2 === void 0 || HELP_AND_VERSION.includes(command2)) return null;
19695
19700
  if (dataNamespaces.has(command2)) return null;
19696
- const words = [command2];
19701
+ const words2 = [command2];
19697
19702
  for (const arg of args2.slice(0, 2)) {
19698
19703
  if (!/^[a-z][a-z-]*$/.test(arg)) break;
19699
- words.push(arg);
19704
+ words2.push(arg);
19700
19705
  }
19701
- let named = words.length;
19702
- let reads = PARSER_READS.get(words.join(" "));
19703
- while (reads === void 0 && --named > 0) reads = PARSER_READS.get(words.slice(0, named).join(" "));
19704
- const invocation = `wayai ${words.slice(0, named || words.length).join(" ")}`;
19706
+ let named = words2.length;
19707
+ let reads = PARSER_READS.get(words2.join(" "));
19708
+ while (reads === void 0 && --named > 0) reads = PARSER_READS.get(words2.slice(0, named).join(" "));
19709
+ const invocation = `wayai ${words2.slice(0, named || words2.length).join(" ")}`;
19705
19710
  if (reads === "all") return null;
19706
19711
  const dryRuns = args2.filter(isDryRunToken);
19707
19712
  const readsBare = typeof reads === "object" && reads.dryRun === true;
@@ -20036,9 +20041,9 @@ function oldLayoutEntries(root, skills, oldLayout) {
20036
20041
  function assertOldLayoutConvertible(root, skills, oldLayout, pullCommand3) {
20037
20042
  const { leftover } = oldLayoutEntries(root, skills, oldLayout);
20038
20043
  if (leftover.length === 0) return;
20039
- const one3 = leftover.length === 1;
20044
+ const one5 = leftover.length === 1;
20040
20045
  throw expected(
20041
- `${leftover.sort().join(", ")} would be removed or overwritten unseen. Converting a folder an older CLI wrote, \`${pullCommand3}\` writes ${SKILLS_DIR}/ from the platform and removes from ${OLD_RESOURCES_DIR}/ only the folders named after the skills it writes. Move ${one3 ? "it" : "them"} out of ${path8.basename(root)}/ (a knowledge backup belongs outside the workspace), then run \`${pullCommand3}\` again. Nothing was written.`
20046
+ `${leftover.sort().join(", ")} would be removed or overwritten unseen. Converting a folder an older CLI wrote, \`${pullCommand3}\` writes ${SKILLS_DIR}/ from the platform and removes from ${OLD_RESOURCES_DIR}/ only the folders named after the skills it writes. Move ${one5 ? "it" : "them"} out of ${path8.basename(root)}/ (a knowledge backup belongs outside the workspace), then run \`${pullCommand3}\` again. Nothing was written.`
20042
20047
  );
20043
20048
  }
20044
20049
  function removeConvertedOldResources(root, skills, log, opts = {}) {
@@ -20294,10 +20299,10 @@ var init_resource_files = __esm({
20294
20299
  var init_case_received_documents = __esm({
20295
20300
  "../../packages/core/dist/contracts/case-received-documents.js"() {
20296
20301
  "use strict";
20297
- init_chunk_ZB7W3DKK();
20298
- init_chunk_PMBOHJKA();
20302
+ init_chunk_WYCUCSD5();
20303
+ init_chunk_6CHDJVQ6();
20299
20304
  init_chunk_U3X3BIQH();
20300
- init_chunk_3LMWOJQX();
20305
+ init_chunk_EYOBPUDN();
20301
20306
  init_chunk_VROZDNLV();
20302
20307
  init_chunk_733K4J4G();
20303
20308
  init_chunk_PFPADFUC();
@@ -20355,10 +20360,10 @@ function toDataProxyPath(v1Path) {
20355
20360
  }
20356
20361
  return `${DATA_PROXY_PREFIX}${v1Path.slice(REKOR_V1_PREFIX.length)}`;
20357
20362
  }
20358
- function withOrgSelector(path50, orgId) {
20359
- if (!orgId) return path50;
20360
- const separator = path50.includes("?") ? "&" : "?";
20361
- return `${path50}${separator}${DATA_PROXY_ORG_QUERY_PARAM}=${encodeURIComponent(orgId)}`;
20363
+ function withOrgSelector(path51, orgId) {
20364
+ if (!orgId) return path51;
20365
+ const separator = path51.includes("?") ? "&" : "?";
20366
+ return `${path51}${separator}${DATA_PROXY_ORG_QUERY_PARAM}=${encodeURIComponent(orgId)}`;
20362
20367
  }
20363
20368
  function dataErrorMessage(err) {
20364
20369
  if (!(err instanceof ApiError)) return null;
@@ -20398,13 +20403,13 @@ var init_api_client = __esm({
20398
20403
  * telling them apart by body shape misreads one for the other.
20399
20404
  */
20400
20405
  path;
20401
- constructor(method, path50, status, body) {
20406
+ constructor(method, path51, status, body) {
20402
20407
  const safeBody = maskSecretsInMessage(body);
20403
- super(`API request failed: ${method} ${path50} (${status}): ${safeBody}`);
20408
+ super(`API request failed: ${method} ${path51} (${status}): ${safeBody}`);
20404
20409
  this.name = "ApiError";
20405
20410
  this.status = status;
20406
20411
  this.body = safeBody;
20407
- this.path = path50;
20412
+ this.path = path51;
20408
20413
  }
20409
20414
  /** True when the status code is a 4xx client error (expected user-facing condition, not a bug). */
20410
20415
  get isExpected() {
@@ -20564,6 +20569,10 @@ var init_api_client = __esm({
20564
20569
  async getCasePhaseWork(ref, phaseId) {
20565
20570
  return this.request("GET", `${casePath(ref)}/phases/${encodeURIComponent(phaseId)}/work`);
20566
20571
  }
20572
+ /** A phase's newest submission and its manifest, or null when it has none. */
20573
+ async getCaseDelivery(ref, phaseId) {
20574
+ return this.request("GET", `${casePath(ref)}/phases/${encodeURIComponent(phaseId)}/delivery`);
20575
+ }
20567
20576
  /** A page of one phase's agenda groups. */
20568
20577
  async getCaseAgenda(ref, phaseId, cursor) {
20569
20578
  const params = new URLSearchParams({ phase_id: phaseId });
@@ -20579,6 +20588,14 @@ var init_api_client = __esm({
20579
20588
  const qs = outputId ? `?${new URLSearchParams({ output_id: outputId })}` : "";
20580
20589
  return this.request("GET", `${casePath(ref)}/phases/${encodeURIComponent(phaseId)}/checks${qs}`);
20581
20590
  }
20591
+ /** Graph review's graph (D12); confidential content only when `confidential` is asked, which only its caller decides. */
20592
+ async getCaseReview(ref, confidential) {
20593
+ return this.request("GET", `${casePath(ref)}/review${confidential ? "?confidential=true" : ""}`);
20594
+ }
20595
+ /** A verdict on one pair of the graph, named by the revision and hashes it was read at; the server derives its round. */
20596
+ async recordCaseItemReview(ref, body) {
20597
+ return this.request("POST", `${casePath(ref)}/review/verdicts`, body);
20598
+ }
20582
20599
  /** Register a received document: its fields, its file under the name it is kept by, and its Markdown text, in one multipart request. */
20583
20600
  async registerCaseReceivedDocument(ref, document, file, text5) {
20584
20601
  const form2 = new FormData();
@@ -20596,8 +20613,8 @@ var init_api_client = __esm({
20596
20613
  return this.request("GET", `${casePath(ref)}/files${qs ? `?${qs}` : ""}`);
20597
20614
  }
20598
20615
  /** A case file's bytes as the case holds them now. */
20599
- async getCaseFileContent(ref, path50) {
20600
- return (await this.download(`${casePath(ref)}/files/content?${new URLSearchParams({ path: path50 })}`)).bytes;
20616
+ async getCaseFileContent(ref, path51) {
20617
+ return (await this.download(`${casePath(ref)}/files/content?${new URLSearchParams({ path: path51 })}`)).bytes;
20601
20618
  }
20602
20619
  /**
20603
20620
  * One revision of the case's files, in one multipart request: the revision's JSON, and each content it sends as a
@@ -20805,8 +20822,8 @@ var init_api_client = __esm({
20805
20822
  ...opts?.check && { check: true }
20806
20823
  });
20807
20824
  }
20808
- async lookup(path50, opts) {
20809
- const params = new URLSearchParams({ path: path50 });
20825
+ async lookup(path51, opts) {
20826
+ const params = new URLSearchParams({ path: path51 });
20810
20827
  if (opts?.organizationId) params.set("organization_id", opts.organizationId);
20811
20828
  return this.request("GET", `/api/ci/lookup?${params.toString()}`);
20812
20829
  }
@@ -21346,9 +21363,9 @@ var init_api_client = __esm({
21346
21363
  `/api/admin/data-explorer/debug/observability/${encodeURIComponent(hubId)}/conversations/${encodeURIComponent(conversationId)}${qs}`
21347
21364
  );
21348
21365
  }
21349
- async request(method, path50, body, extraHeaders, contentType) {
21350
- addApiBreadcrumb(method, path50);
21351
- const url = `${this.apiUrl}${path50}`;
21366
+ async request(method, path51, body, extraHeaders, contentType) {
21367
+ addApiBreadcrumb(method, path51);
21368
+ const url = `${this.apiUrl}${path51}`;
21352
21369
  let refreshedOn401 = false;
21353
21370
  for (let retry = 0; ; retry++) {
21354
21371
  let response = await this.send(url, method, body, extraHeaders, contentType);
@@ -21373,7 +21390,7 @@ var init_api_client = __esm({
21373
21390
  await delay(RETRYABLE_BACKOFF_MS[retry]);
21374
21391
  continue;
21375
21392
  }
21376
- throw new ApiError(method, path50, response.status, errorBody);
21393
+ throw new ApiError(method, path51, response.status, errorBody);
21377
21394
  }
21378
21395
  }
21379
21396
  /**
@@ -21443,9 +21460,9 @@ var init_api_client = __esm({
21443
21460
  return this.download(withOrgSelector(toDataProxyPath(v1Path), orgId));
21444
21461
  }
21445
21462
  /** A backend path's raw bytes (`dataDownload`'s read, for any path). */
21446
- async download(path50) {
21447
- addApiBreadcrumb("GET", path50);
21448
- const url = `${this.apiUrl}${path50}`;
21463
+ async download(path51) {
21464
+ addApiBreadcrumb("GET", path51);
21465
+ const url = `${this.apiUrl}${path51}`;
21449
21466
  let response = await this.send(url, "GET");
21450
21467
  if (response.status === 401 && this.onUnauthorized) {
21451
21468
  let refreshed;
@@ -21459,7 +21476,7 @@ var init_api_client = __esm({
21459
21476
  }
21460
21477
  }
21461
21478
  if (!response.ok) {
21462
- throw new ApiError("GET", path50, response.status, await response.text());
21479
+ throw new ApiError("GET", path51, response.status, await response.text());
21463
21480
  }
21464
21481
  return {
21465
21482
  bytes: new Uint8Array(await response.arrayBuffer()),
@@ -21902,9 +21919,9 @@ function getVersionCachePath(filename = CLI_CACHE_FILE) {
21902
21919
  }
21903
21920
  function readVersionCache(filename = CLI_CACHE_FILE) {
21904
21921
  try {
21905
- const path50 = getVersionCachePath(filename);
21906
- if (!existsSync4(path50)) return null;
21907
- const parsed = JSON.parse(readFileSync6(path50, "utf-8"));
21922
+ const path51 = getVersionCachePath(filename);
21923
+ if (!existsSync4(path51)) return null;
21924
+ const parsed = JSON.parse(readFileSync6(path51, "utf-8"));
21908
21925
  if (typeof parsed.lastCheck !== "number") return null;
21909
21926
  if (parsed.latest !== null && typeof parsed.latest !== "string") return null;
21910
21927
  return parsed;
@@ -21924,10 +21941,10 @@ function isVersionCacheStale(filename = CLI_CACHE_FILE, maxAgeMs = MAX_AGE_24H_M
21924
21941
  return Date.now() - cache.lastCheck > maxAgeMs;
21925
21942
  }
21926
21943
  function writeVersionCache(filename, cache) {
21927
- const path50 = getVersionCachePath(filename);
21928
- const dir = dirname6(path50);
21944
+ const path51 = getVersionCachePath(filename);
21945
+ const dir = dirname6(path51);
21929
21946
  if (!existsSync4(dir)) mkdirSync2(dir, { recursive: true });
21930
- writeFileSync2(path50, JSON.stringify(cache));
21947
+ writeFileSync2(path51, JSON.stringify(cache));
21931
21948
  }
21932
21949
  function touchVersionCache(filename) {
21933
21950
  writeVersionCache(filename, { lastCheck: Date.now(), latest: readVersionCache(filename)?.latest ?? null });
@@ -21966,14 +21983,14 @@ function parseFrontmatterVersion(content) {
21966
21983
  function findInstalledSkills(projectRoot, paths = SKILL_INSTALL_PATHS) {
21967
21984
  const found = [];
21968
21985
  for (const rel of paths) {
21969
- const path50 = join9(projectRoot, rel);
21970
- if (!existsSync5(path50)) continue;
21986
+ const path51 = join9(projectRoot, rel);
21987
+ if (!existsSync5(path51)) continue;
21971
21988
  let version = null;
21972
21989
  try {
21973
- version = parseFrontmatterVersion(readFileSync7(path50, "utf-8"));
21990
+ version = parseFrontmatterVersion(readFileSync7(path51, "utf-8"));
21974
21991
  } catch {
21975
21992
  }
21976
- found.push({ path: path50, version });
21993
+ found.push({ path: path51, version });
21977
21994
  }
21978
21995
  return found;
21979
21996
  }
@@ -22387,8 +22404,8 @@ function generateCodeVerifier() {
22387
22404
  return crypto3.randomBytes(32).toString("base64url");
22388
22405
  }
22389
22406
  async function generateCodeChallenge(verifier) {
22390
- const hash = crypto3.createHash("sha256").update(verifier).digest();
22391
- return hash.toString("base64url");
22407
+ const hash2 = crypto3.createHash("sha256").update(verifier).digest();
22408
+ return hash2.toString("base64url");
22392
22409
  }
22393
22410
  function generateState() {
22394
22411
  return crypto3.randomBytes(16).toString("base64url");
@@ -23219,7 +23236,7 @@ function buildWorkspaceState(resolved) {
23219
23236
  return { scoped: true, path: resolved.path, hub_count: hubCount };
23220
23237
  }
23221
23238
  async function statusCommand(args2, pkg2) {
23222
- const { json } = parseArgs2(args2);
23239
+ const { json: json2 } = parseArgs2(args2);
23223
23240
  const config = readConfig();
23224
23241
  const resolvedRepo = resolveRepoConfig();
23225
23242
  const repoConfig = resolvedRepo?.config ?? null;
@@ -23252,7 +23269,7 @@ async function statusCommand(args2, pkg2) {
23252
23269
  worktree_binding: { hub_id: boundHubId },
23253
23270
  worktree_lock: { hub_id: boundHubId }
23254
23271
  };
23255
- if (json) {
23272
+ if (json2) {
23256
23273
  console.log(JSON.stringify(snapshot2, null, 2));
23257
23274
  } else {
23258
23275
  console.log("Not logged in. Run `wayai login`.");
@@ -23309,7 +23326,7 @@ async function statusCommand(args2, pkg2) {
23309
23326
  worktree_binding: { hub_id: boundHubId },
23310
23327
  worktree_lock: { hub_id: boundHubId }
23311
23328
  };
23312
- if (json) {
23329
+ if (json2) {
23313
23330
  console.log(JSON.stringify(snapshot, null, 2));
23314
23331
  return;
23315
23332
  }
@@ -23385,11 +23402,11 @@ function parseArgs3(args2) {
23385
23402
  return { json: args2.includes("--json") };
23386
23403
  }
23387
23404
  async function whoamiCommand(args2) {
23388
- const { json } = parseArgs3(args2);
23405
+ const { json: json2 } = parseArgs3(args2);
23389
23406
  const { config, accessToken } = await requireAuth();
23390
23407
  const client = new ApiClient({ apiUrl: config.api_url, accessToken });
23391
23408
  const me = await client.me();
23392
- if (json) {
23409
+ if (json2) {
23393
23410
  console.log(JSON.stringify(me, null, 2));
23394
23411
  return;
23395
23412
  }
@@ -23712,13 +23729,13 @@ function resolveTurnAttachments(hubFolder, turn, label3, bytesByHash) {
23712
23729
  );
23713
23730
  }
23714
23731
  const data = fs11.readFileSync(abs);
23715
- const hash = computeHash(data);
23732
+ const hash2 = computeHash(data);
23716
23733
  const fileName = path14.basename(abs);
23717
23734
  const mimeType = guessMimeType(fileName) ?? "application/octet-stream";
23718
- refs.push({ hash, file_name: fileName, mime_type: mimeType, file_size: stat2.size });
23719
- if (!bytesByHash.has(hash)) {
23720
- bytesByHash.set(hash, {
23721
- hash,
23735
+ refs.push({ hash: hash2, file_name: fileName, mime_type: mimeType, file_size: stat2.size });
23736
+ if (!bytesByHash.has(hash2)) {
23737
+ bytesByHash.set(hash2, {
23738
+ hash: hash2,
23722
23739
  content_base64: data.toString("base64"),
23723
23740
  file_name: fileName,
23724
23741
  mime_type: mimeType,
@@ -23896,10 +23913,10 @@ function applyCallOpeningFiles(hubFolder, payload) {
23896
23913
  throw expected(`${label3}: file "${opening.file}" is ${(stat2.size / 1024 / 1024).toFixed(1)} MB, over the ${CALL_OPENING_MAX_BYTES / 1024 / 1024} MB limit.`);
23897
23914
  }
23898
23915
  const bytes = fs12.readFileSync(abs);
23899
- const hash = computeHash(bytes);
23916
+ const hash2 = computeHash(bytes);
23900
23917
  const { file: _file, ...rest } = opening;
23901
- openings[language] = { ...rest, hash };
23902
- if (!carriers.has(hash)) carriers.set(hash, { hash, content_base64: bytes.toString("base64") });
23918
+ openings[language] = { ...rest, hash: hash2 };
23919
+ if (!carriers.has(hash2)) carriers.set(hash2, { hash: hash2, content_base64: bytes.toString("base64") });
23903
23920
  }
23904
23921
  }
23905
23922
  if (carriers.size > 0) payload.call_opening_files = [...carriers.values()];
@@ -23916,9 +23933,9 @@ function rewriteCallOpeningsToLocalPaths(payload) {
23916
23933
  const carrier = byHash.get(opening.hash);
23917
23934
  const ext = carrier?.content_type === "audio/mp4" ? ".m4a" : ".mp3";
23918
23935
  const relPath = `${CALL_OPENINGS_DIR}/${slugify2(agent.name)}-${language}${ext}`;
23919
- const { hash, ...rest } = opening;
23936
+ const { hash: hash2, ...rest } = opening;
23920
23937
  openings[language] = { ...rest, file: relPath };
23921
- if (carrier?.download_url) downloads.push({ relPath, url: carrier.download_url, hash });
23938
+ if (carrier?.download_url) downloads.push({ relPath, url: carrier.download_url, hash: hash2 });
23922
23939
  }
23923
23940
  }
23924
23941
  delete payload.call_opening_files;
@@ -25294,8 +25311,8 @@ function readCss(source, attribute) {
25294
25311
  stack.push({ prelude: text5.trim(), body: "" });
25295
25312
  text5 = "";
25296
25313
  } else if (ch === "}") {
25297
- const block = stack.pop();
25298
- if (block) declare(block.body + text5, [...stack.map((b) => b.prelude), block.prelude]);
25314
+ const block2 = stack.pop();
25315
+ if (block2) declare(block2.body + text5, [...stack.map((b) => b.prelude), block2.prelude]);
25299
25316
  text5 = "";
25300
25317
  } else if (ch === ";") {
25301
25318
  if (stack.length > 0) stack[stack.length - 1].body += `${text5};`;
@@ -25906,12 +25923,12 @@ async function createDataClient(orgId, opts = {}) {
25906
25923
  return orgId2;
25907
25924
  }
25908
25925
  return {
25909
- async request(method, path50, body, headers) {
25910
- const envelope = await api.dataRequest(method, path50, body, org, headers);
25926
+ async request(method, path51, body, headers) {
25927
+ const envelope = await api.dataRequest(method, path51, body, org, headers);
25911
25928
  return envelope.data;
25912
25929
  },
25913
- async requestRaw(method, path50, body) {
25914
- const body_ = await api.dataRequest(method, path50, body, org);
25930
+ async requestRaw(method, path51, body) {
25931
+ const body_ = await api.dataRequest(method, path51, body, org);
25915
25932
  return body_;
25916
25933
  },
25917
25934
  async collectPages(makePath) {
@@ -30970,8 +30987,8 @@ var init_diff = __esm({
30970
30987
  // src/lib/page-scaffold.ts
30971
30988
  import * as yaml16 from "js-yaml";
30972
30989
  function titleOf(slug) {
30973
- const words = slug.split("-").join(" ");
30974
- return words.charAt(0).toUpperCase() + words.slice(1);
30990
+ const words2 = slug.split("-").join(" ");
30991
+ return words2.charAt(0).toUpperCase() + words2.slice(1);
30975
30992
  }
30976
30993
  function escapeHtml(text5) {
30977
30994
  return text5.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -34253,15 +34270,15 @@ var init_caller_audio = __esm({
34253
34270
  }
34254
34271
  describe;
34255
34272
  async clipFor(line) {
34256
- const path50 = line.clip ? isAbsolute2(line.clip) ? line.clip : resolve10(this.planDir, line.clip) : this.dir ? join33(this.dir, `${line.n}.wav`) : null;
34257
- if (!path50) throw new Error(`Line ${line.n} has no clip: give --clips <dir>, or a "clip" for it in the plan.`);
34273
+ const path51 = line.clip ? isAbsolute2(line.clip) ? line.clip : resolve10(this.planDir, line.clip) : this.dir ? join33(this.dir, `${line.n}.wav`) : null;
34274
+ if (!path51) throw new Error(`Line ${line.n} has no clip: give --clips <dir>, or a "clip" for it in the plan.`);
34258
34275
  let buf;
34259
34276
  try {
34260
- buf = readFileSync17(path50);
34277
+ buf = readFileSync17(path51);
34261
34278
  } catch {
34262
- throw new Error(`Line ${line.n}'s clip ${path50} cannot be read.`);
34279
+ throw new Error(`Line ${line.n}'s clip ${path51} cannot be read.`);
34263
34280
  }
34264
- return parseWav(buf, path50);
34281
+ return parseWav(buf, path51);
34265
34282
  }
34266
34283
  };
34267
34284
  OPENAI_PCM_SAMPLE_RATE = 24e3;
@@ -34291,17 +34308,17 @@ ${text5}`).digest("hex");
34291
34308
  return join33(this.cacheDir, `${key}.pcm`);
34292
34309
  }
34293
34310
  clipFor(line) {
34294
- const path50 = this.cachePath(line.say);
34295
- let pending = this.inFlight.get(path50);
34311
+ const path51 = this.cachePath(line.say);
34312
+ let pending = this.inFlight.get(path51);
34296
34313
  if (!pending) {
34297
- pending = this.readOrSynthesize(line, path50);
34298
- this.inFlight.set(path50, pending);
34314
+ pending = this.readOrSynthesize(line, path51);
34315
+ this.inFlight.set(path51, pending);
34299
34316
  }
34300
34317
  return pending;
34301
34318
  }
34302
- async readOrSynthesize(line, path50) {
34319
+ async readOrSynthesize(line, path51) {
34303
34320
  try {
34304
- return pcmClip(readFileSync17(path50));
34321
+ return pcmClip(readFileSync17(path51));
34305
34322
  } catch {
34306
34323
  }
34307
34324
  const res = await this.doFetch("https://api.openai.com/v1/audio/speech", {
@@ -34315,10 +34332,10 @@ ${text5}`).digest("hex");
34315
34332
  }
34316
34333
  const buf = Buffer.from(await res.arrayBuffer());
34317
34334
  if (buf.length < 2) throw new Error(`OpenAI speech synthesis returned no audio for line ${line.n}.`);
34318
- mkdirSync12(dirname12(path50), { recursive: true });
34319
- const tmp = `${path50}.${process.pid}.tmp`;
34335
+ mkdirSync12(dirname12(path51), { recursive: true });
34336
+ const tmp = `${path51}.${process.pid}.tmp`;
34320
34337
  writeFileSync7(tmp, buf);
34321
- renameSync5(tmp, path50);
34338
+ renameSync5(tmp, path51);
34322
34339
  return pcmClip(buf);
34323
34340
  }
34324
34341
  };
@@ -35256,9 +35273,9 @@ function factLabel(fact) {
35256
35273
  return `${fact.kind}:${fact.raw}`;
35257
35274
  }
35258
35275
  function tokens(text5) {
35259
- const words = normalizeText(text5).split(/[^a-z0-9]+/).filter((w) => w.length > 1 && !/^\d+$/.test(w) && !isNumberWord(w));
35276
+ const words2 = normalizeText(text5).split(/[^a-z0-9]+/).filter((w) => w.length > 1 && !/^\d+$/.test(w) && !isNumberWord(w));
35260
35277
  const facts = extractFacts(text5).map((f) => `#${f.kind}:${f.key}`);
35261
- return /* @__PURE__ */ new Set([...words, ...facts]);
35278
+ return /* @__PURE__ */ new Set([...words2, ...facts]);
35262
35279
  }
35263
35280
  function similarity(a, b) {
35264
35281
  const ta = tokens(a);
@@ -35297,8 +35314,8 @@ function percentile(values, p) {
35297
35314
  function styleProblem(reply, maxSentenceWords) {
35298
35315
  if (markdownToPlainText(reply) !== reply || LIST_MARKER.test(reply)) return "markdown";
35299
35316
  for (const sentence of reply.split(/(?<=[.!?…])\s+|\n+/)) {
35300
- const words = sentence.trim().split(/\s+/).filter(Boolean).length;
35301
- if (words > maxSentenceWords) return `a sentence of ${words} words`;
35317
+ const words2 = sentence.trim().split(/\s+/).filter(Boolean).length;
35318
+ if (words2 > maxSentenceWords) return `a sentence of ${words2} words`;
35302
35319
  }
35303
35320
  return null;
35304
35321
  }
@@ -35883,15 +35900,15 @@ function parseEvalCallArgs(args2) {
35883
35900
  if (parsed.jsonPath) checkReportPath(parsed.jsonPath);
35884
35901
  return parsed;
35885
35902
  }
35886
- function checkReportPath(path50) {
35887
- const target = resolve11(path50);
35903
+ function checkReportPath(path51) {
35904
+ const target = resolve11(path51);
35888
35905
  const dir = dirname13(target);
35889
- if (!existsSync17(dir) || !statSync8(dir).isDirectory()) fail(`--json ${path50}: the folder ${dir} does not exist.`);
35890
- if (existsSync17(target) && statSync8(target).isDirectory()) fail(`--json ${path50} is a folder; name a file.`);
35906
+ if (!existsSync17(dir) || !statSync8(dir).isDirectory()) fail(`--json ${path51}: the folder ${dir} does not exist.`);
35907
+ if (existsSync17(target) && statSync8(target).isDirectory()) fail(`--json ${path51} is a folder; name a file.`);
35891
35908
  try {
35892
35909
  accessSync(existsSync17(target) ? target : dir, fsConstants.W_OK);
35893
35910
  } catch {
35894
- fail(`--json ${path50} cannot be written here.`);
35911
+ fail(`--json ${path51} cannot be written here.`);
35895
35912
  }
35896
35913
  }
35897
35914
  function suiteExitCode(report2, runs, reportWritten) {
@@ -37880,7 +37897,7 @@ function getFlagValue(args2, flag) {
37880
37897
  return idx !== -1 ? args2[idx + 1] : void 0;
37881
37898
  }
37882
37899
  async function orgCreate(args2) {
37883
- const json = args2.includes("--json");
37900
+ const json2 = args2.includes("--json");
37884
37901
  const name = firstPositional(args2);
37885
37902
  if (!name) {
37886
37903
  console.error('Usage: wayai org create "<name>" [--region <region>] [--json]');
@@ -37889,9 +37906,9 @@ async function orgCreate(args2) {
37889
37906
  const region = getFlagValue(args2, "--region");
37890
37907
  const { config, accessToken } = await requireAuth();
37891
37908
  const client = new ApiClient({ apiUrl: config.api_url, accessToken });
37892
- if (!json) console.log(`Creating organization "${name}"...`);
37909
+ if (!json2) console.log(`Creating organization "${name}"...`);
37893
37910
  const { organization } = await client.createOrganization(name, region);
37894
- if (json) {
37911
+ if (json2) {
37895
37912
  console.log(JSON.stringify(organization, null, 2));
37896
37913
  return;
37897
37914
  }
@@ -38012,24 +38029,24 @@ __export(list_exports, {
38012
38029
  });
38013
38030
  function parseArgs23(args2) {
38014
38031
  let orgId;
38015
- let json = false;
38032
+ let json2 = false;
38016
38033
  for (let i = 0; i < args2.length; i++) {
38017
38034
  if (args2[i] === "--org" && args2[i + 1]) {
38018
38035
  orgId = args2[++i];
38019
38036
  } else if (args2[i] === "--json") {
38020
- json = true;
38037
+ json2 = true;
38021
38038
  }
38022
38039
  }
38023
- return { orgId, json };
38040
+ return { orgId, json: json2 };
38024
38041
  }
38025
38042
  async function listCommand(args2) {
38026
- const { orgId, json } = parseArgs23(args2);
38043
+ const { orgId, json: json2 } = parseArgs23(args2);
38027
38044
  const { config, accessToken } = await requireAuth();
38028
38045
  const client = new ApiClient({ apiUrl: config.api_url, accessToken });
38029
38046
  const { organizations } = await client.organizations();
38030
38047
  const orgsToList = orgId ? organizations.filter((o) => o.id === orgId) : organizations;
38031
38048
  if (orgsToList.length === 0) {
38032
- if (json) {
38049
+ if (json2) {
38033
38050
  console.log(JSON.stringify({ organizations: [] }, null, 2));
38034
38051
  } else {
38035
38052
  console.log(orgId ? `Organization ${orgId} not found.` : "No organizations found.");
@@ -38039,7 +38056,7 @@ async function listCommand(args2) {
38039
38056
  const results = await Promise.all(
38040
38057
  orgsToList.map((org) => client.listHubs(org.id).then((r) => ({ org, hubs: r.hubs })))
38041
38058
  );
38042
- if (json) {
38059
+ if (json2) {
38043
38060
  const payload = {
38044
38061
  organizations: results.map(({ org, hubs }) => ({
38045
38062
  organization_id: org.id,
@@ -38140,7 +38157,7 @@ async function communitiesCommand(args2) {
38140
38157
  console.log(USAGE3);
38141
38158
  return;
38142
38159
  }
38143
- const { positionals, org, json, yes } = parse(args2);
38160
+ const { positionals, org, json: json2, yes } = parse(args2);
38144
38161
  const [sub, ...rest] = positionals;
38145
38162
  if (sub === void 0) throw usageError2("No subcommand given.");
38146
38163
  if (!SUBCOMMANDS.includes(sub)) throw usageError2(`Unknown subcommand ${JSON.stringify(sub)}.`);
@@ -38157,19 +38174,19 @@ async function communitiesCommand(args2) {
38157
38174
  switch (sub) {
38158
38175
  case "list":
38159
38176
  if (rest.length > 0) throw usageError2(`Unexpected argument ${JSON.stringify(rest[0])}.`);
38160
- return runList(resolveOrgId(org), json);
38177
+ return runList(resolveOrgId(org), json2);
38161
38178
  case "join-link": {
38162
38179
  const [, selector, ...extra] = rest;
38163
38180
  if (selector === void 0 || extra.length > 0) throw usageError2(`join-link ${action} takes one <community>.`);
38164
38181
  if (changesLink && !yes && !isInteractive()) {
38165
38182
  throw usageError2(`join-link ${action} asks before it changes the link; pass -y when not running in a terminal.`);
38166
38183
  }
38167
- return runJoinLink(action, targetOf(selector, org), { json, yes });
38184
+ return runJoinLink(action, targetOf(selector, org), { json: json2, yes });
38168
38185
  }
38169
38186
  case "stats": {
38170
38187
  const [selector, ...extra] = rest;
38171
38188
  if (selector === void 0 || extra.length > 0) throw usageError2("stats takes one <community>.");
38172
- return runStats(targetOf(selector, org), json);
38189
+ return runStats(targetOf(selector, org), json2);
38173
38190
  }
38174
38191
  case "access": {
38175
38192
  const [, selector, ...emails] = rest;
@@ -38182,16 +38199,16 @@ async function communitiesCommand(args2) {
38182
38199
  throw usageError2("access remove asks before it removes anyone; pass -y when not running in a terminal.");
38183
38200
  }
38184
38201
  const target = targetOf(selector, org);
38185
- if (action === "list") return runAccessList(target, json);
38186
- if (action === "add") return runAccessAdd(target, valid, json);
38187
- return runAccessRemove(target, valid[0], { json, yes });
38202
+ if (action === "list") return runAccessList(target, json2);
38203
+ if (action === "add") return runAccessAdd(target, valid, json2);
38204
+ return runAccessRemove(target, valid[0], { json: json2, yes });
38188
38205
  }
38189
38206
  }
38190
38207
  }
38191
- async function runList(orgId, json) {
38208
+ async function runList(orgId, json2) {
38192
38209
  const api = await communitiesClient();
38193
38210
  const { data } = await callCommunities(api.listOrgCommunities(orgId), orgNotFound(orgId));
38194
- if (json) {
38211
+ if (json2) {
38195
38212
  console.log(JSON.stringify(data, null, 2));
38196
38213
  return;
38197
38214
  }
@@ -38203,13 +38220,13 @@ async function runList(orgId, json) {
38203
38220
  `);
38204
38221
  printRows(data.map((c) => ({ name: c.name, community_id: c.community_id, created_at: c.created_at })));
38205
38222
  }
38206
- async function runJoinLink(action, target, { json, yes }) {
38223
+ async function runJoinLink(action, target, { json: json2, yes }) {
38207
38224
  const api = await communitiesClient();
38208
38225
  const { id, label: label3 } = await resolveCommunity(api, target);
38209
38226
  const notFound = communityNotFound(label3);
38210
38227
  if (action === "get") {
38211
38228
  const { data: data2 } = await callCommunities(api.getCommunityJoinLink(id), notFound);
38212
- printLink(data2, label3, json);
38229
+ printLink(data2, label3, json2);
38213
38230
  return;
38214
38231
  }
38215
38232
  await warnThenAsk(
@@ -38224,14 +38241,14 @@ async function runJoinLink(action, target, { json, yes }) {
38224
38241
  action === "rotate" ? api.replaceCommunityJoinLink(id) : api.disableCommunityJoinLink(id),
38225
38242
  notFound
38226
38243
  );
38227
- printLink(data, label3, json);
38244
+ printLink(data, label3, json2);
38228
38245
  }
38229
38246
  async function warnThenAsk(warning, yes, aborted) {
38230
38247
  for (const line of warning) console.error(line);
38231
38248
  if (!yes && !await confirm("Proceed?")) throw expected(aborted);
38232
38249
  }
38233
- function printLink(link, label3, json) {
38234
- if (json) {
38250
+ function printLink(link, label3, json2) {
38251
+ if (json2) {
38235
38252
  console.log(JSON.stringify(link, null, 2));
38236
38253
  return;
38237
38254
  }
@@ -38242,11 +38259,11 @@ function printLink(link, label3, json) {
38242
38259
  }
38243
38260
  console.log(`The join link of ${label3} is off. \`wayai communities join-link rotate\` makes a new one.`);
38244
38261
  }
38245
- async function runStats(target, json) {
38262
+ async function runStats(target, json2) {
38246
38263
  const api = await communitiesClient();
38247
38264
  const { id, label: label3 } = await resolveCommunity(api, target);
38248
38265
  const { data } = await callCommunities(api.getCommunityStats(id), communityNotFound(label3));
38249
- if (json) {
38266
+ if (json2) {
38250
38267
  console.log(JSON.stringify(data, null, 2));
38251
38268
  return;
38252
38269
  }
@@ -38326,12 +38343,12 @@ async function* accessPages(api, id, notFound) {
38326
38343
  cursor = data.next_cursor ?? void 0;
38327
38344
  } while (cursor !== void 0);
38328
38345
  }
38329
- async function runAccessList(target, json) {
38346
+ async function runAccessList(target, json2) {
38330
38347
  const api = await communitiesClient();
38331
38348
  const { id, label: label3 } = await resolveCommunity(api, target);
38332
38349
  const entries = [];
38333
38350
  for await (const page of accessPages(api, id, communityNotFound(label3))) entries.push(...page);
38334
- if (json) {
38351
+ if (json2) {
38335
38352
  console.log(JSON.stringify(entries, null, 2));
38336
38353
  return;
38337
38354
  }
@@ -38343,11 +38360,11 @@ async function runAccessList(target, json) {
38343
38360
  `);
38344
38361
  printRows(entries.map((entry) => ({ email: entry.email, added: entry.created_at })));
38345
38362
  }
38346
- async function runAccessAdd(target, emails, json) {
38363
+ async function runAccessAdd(target, emails, json2) {
38347
38364
  const api = await communitiesClient();
38348
38365
  const { id, label: label3 } = await resolveCommunity(api, target);
38349
38366
  const { data } = await callAccess(api.addCommunityAccess(id, { emails }), communityNotFound(label3), label3);
38350
- if (json) {
38367
+ if (json2) {
38351
38368
  console.log(JSON.stringify(data, null, 2));
38352
38369
  return;
38353
38370
  }
@@ -38355,7 +38372,7 @@ async function runAccessAdd(target, emails, json) {
38355
38372
  const listed3 = already === 0 ? "" : `; ${already} ${already === 1 ? "was" : "were"} already on it`;
38356
38373
  console.log(`Added ${added.length} email(s) to the access list of ${label3}${listed3}.`);
38357
38374
  }
38358
- async function runAccessRemove(target, email, { json, yes }) {
38375
+ async function runAccessRemove(target, email, { json: json2, yes }) {
38359
38376
  const api = await communitiesClient();
38360
38377
  const { id, label: label3 } = await resolveCommunity(api, target);
38361
38378
  let entry;
@@ -38374,7 +38391,7 @@ async function runAccessRemove(target, email, { json, yes }) {
38374
38391
  `${email} is no longer on the access list of ${label3}, or you are not an owner or admin of its organization. Nothing was removed.`,
38375
38392
  label3
38376
38393
  );
38377
- if (json) {
38394
+ if (json2) {
38378
38395
  console.log(JSON.stringify(entry, null, 2));
38379
38396
  return;
38380
38397
  }
@@ -38705,6 +38722,66 @@ var init_case_records = __esm({
38705
38722
  }
38706
38723
  });
38707
38724
 
38725
+ // ../../packages/core/dist/contracts/case-review.js
38726
+ var CASE_REVIEW_ROUNDS_MAX, CASE_REVIEW_REASON_MAX_LENGTH, CASE_REVIEW_PAIR_UNKNOWN_REASON, CASE_REVIEW_CHAIN_STOPPED_REASON, CASE_REVIEW_TOO_LARGE_REASON, CASE_REVIEW_VERDICTS_FULL_REASON, CASE_REVIEW_CONFIDENTIAL_OMITTED, caseReviewItemKeySchema, hash, caseReviewQuery, pairFields, recordCaseItemReviewBody, keepCaseItemBody, acceptCaseReviewChainBody;
38727
+ var init_case_review = __esm({
38728
+ "../../packages/core/dist/contracts/case-review.js"() {
38729
+ "use strict";
38730
+ init_chunk_VROZDNLV();
38731
+ init_chunk_PFPADFUC();
38732
+ init_chunk_KWRHZBGU();
38733
+ init_chunk_3T3D7LTE();
38734
+ init_chunk_M2T55BV6();
38735
+ init_chunk_VYINA6YP();
38736
+ init_chunk_ZVXO3XL6();
38737
+ init_chunk_FBV7NLKO();
38738
+ init_chunk_WEXVYJ5H();
38739
+ init_chunk_HZ6CADSY();
38740
+ init_chunk_ICYO56QW();
38741
+ init_chunk_WFQDSQJK();
38742
+ init_chunk_ZTNFLGW5();
38743
+ init_zod();
38744
+ CASE_REVIEW_ROUNDS_MAX = 5;
38745
+ CASE_REVIEW_REASON_MAX_LENGTH = 8 * 1024;
38746
+ CASE_REVIEW_PAIR_UNKNOWN_REASON = "review_pair_unknown";
38747
+ CASE_REVIEW_CHAIN_STOPPED_REASON = "review_chain_stopped";
38748
+ CASE_REVIEW_TOO_LARGE_REASON = "review_too_large";
38749
+ CASE_REVIEW_VERDICTS_FULL_REASON = "verdicts_full";
38750
+ CASE_REVIEW_CONFIDENTIAL_OMITTED = "confidential_omitted";
38751
+ caseReviewItemKeySchema = external_exports.string().max(CASE_CODE_MAX_LENGTH * 2 + 1).refine((key) => {
38752
+ const slash = key.indexOf("/");
38753
+ return slash > 0 && CASE_PHASE_FOLDER_PATTERN.test(key.slice(0, slash)) && CASE_CODE_PATTERN.test(key.slice(slash + 1));
38754
+ }, "An item is named by its phase folder and code");
38755
+ hash = caseFileShaSchema;
38756
+ caseReviewQuery = external_exports.object({
38757
+ confidential: external_exports.enum(["true", "false"]).optional().transform((value) => value === "true")
38758
+ });
38759
+ pairFields = {
38760
+ /** The revision the pair was computed at, as the graph read named it. */
38761
+ revision_id: uuidSchema,
38762
+ source: caseReviewItemKeySchema,
38763
+ source_hash: hash,
38764
+ neighbor: caseReviewItemKeySchema,
38765
+ neighbor_hash: hash,
38766
+ reason: external_exports.string().trim().min(1).max(CASE_REVIEW_REASON_MAX_LENGTH),
38767
+ /**
38768
+ * The writer's own mark: the verdict reaches only holders of the Confidential right asking for it. Taken only with
38769
+ * `confidential: true` (the right, asking); otherwise 400 `confidential_mark_refused`.
38770
+ */
38771
+ mark_confidential: external_exports.boolean().default(false),
38772
+ /** The graph it was computed on was read with `confidential=true`. */
38773
+ confidential: external_exports.boolean().default(false)
38774
+ };
38775
+ recordCaseItemReviewBody = external_exports.object({ ...pairFields, verdict: external_exports.enum(["consistent", "needs_change"]) }).strict();
38776
+ keepCaseItemBody = external_exports.object(pairFields).strict();
38777
+ acceptCaseReviewChainBody = external_exports.object({
38778
+ item: caseReviewItemKeySchema,
38779
+ revision_id: uuidSchema,
38780
+ confidential: external_exports.boolean().default(false)
38781
+ }).strict();
38782
+ }
38783
+ });
38784
+
38708
38785
  // src/cases/case-local-files.ts
38709
38786
  import * as fs30 from "fs";
38710
38787
  import * as path42 from "path";
@@ -39939,25 +40016,25 @@ var init_plan = __esm({
39939
40016
  constructor(paths = []) {
39940
40017
  for (const p of paths) this.add(p);
39941
40018
  }
39942
- add(path50) {
39943
- this.cases.add(path50);
39944
- this.files.add(path50);
39945
- const segments = path50.split("/");
40019
+ add(path51) {
40020
+ this.cases.add(path51);
40021
+ this.files.add(path51);
40022
+ const segments = path51.split("/");
39946
40023
  for (let i = 1; i < segments.length; i++) {
39947
40024
  const folder = segments.slice(0, i).join("/");
39948
- if (!this.folders.has(folder)) this.folders.set(folder, path50);
40025
+ if (!this.folders.has(folder)) this.folders.set(folder, path51);
39949
40026
  }
39950
40027
  }
39951
40028
  /** The path `path` would collide with, and how; undefined when it collides with none. */
39952
- clash(path50) {
39953
- const twin = this.cases.twinOf(path50);
40029
+ clash(path51) {
40030
+ const twin = this.cases.twinOf(path51);
39954
40031
  if (twin !== void 0) return { reason: "case_twin", other: twin };
39955
- const segments = path50.split("/");
40032
+ const segments = path51.split("/");
39956
40033
  for (let i = 1; i < segments.length; i++) {
39957
40034
  const folder = segments.slice(0, i).join("/");
39958
40035
  if (this.files.has(folder)) return { reason: "file_folder", other: folder };
39959
40036
  }
39960
- const inside = this.folders.get(path50);
40037
+ const inside = this.folders.get(path51);
39961
40038
  return inside === void 0 ? void 0 : { reason: "file_folder", other: inside };
39962
40039
  }
39963
40040
  };
@@ -39966,13 +40043,13 @@ var init_plan = __esm({
39966
40043
 
39967
40044
  // src/data/files-sync/headers.ts
39968
40045
  function ifMatchValue(raw) {
39969
- const hash = raw.trim().replace(/^W\//, "").replace(/^"(.*)"$/, "$1");
39970
- if (!/^[\x21\x23-\x7e]+$/.test(hash)) {
40046
+ const hash2 = raw.trim().replace(/^W\//, "").replace(/^"(.*)"$/, "$1");
40047
+ if (!/^[\x21\x23-\x7e]+$/.test(hash2)) {
39971
40048
  throw expected(
39972
40049
  `--if-match must be the file's content hash (its ETag, or content_sha256 from \`wayai files get --meta\`), got ${JSON.stringify(raw)}.`
39973
40050
  );
39974
40051
  }
39975
- return `"${hash}"`;
40052
+ return `"${hash2}"`;
39976
40053
  }
39977
40054
  function labelValue(raw) {
39978
40055
  if (raw.length === 0 || !/^[\x20-\x7e]+$/.test(raw)) {
@@ -40021,9 +40098,9 @@ async function openRemote2() {
40021
40098
  )
40022
40099
  });
40023
40100
  return {
40024
- request: (method, path50, body, headers) => pacer.run(() => client.request(method, path50, body, headers)),
40025
- upload: (path50, bytes, contentType, headers) => pacer.run(() => client.upload(path50, bytes, contentType, headers)),
40026
- download: (path50) => pacer.run(() => client.download(path50))
40101
+ request: (method, path51, body, headers) => pacer.run(() => client.request(method, path51, body, headers)),
40102
+ upload: (path51, bytes, contentType, headers) => pacer.run(() => client.upload(path51, bytes, contentType, headers)),
40103
+ download: (path51) => pacer.run(() => client.download(path51))
40027
40104
  };
40028
40105
  }
40029
40106
  function filesRoot(t) {
@@ -40156,13 +40233,13 @@ async function pullFiles(opts) {
40156
40233
  conflicts.push({ rel: w.rel, ...clash });
40157
40234
  continue;
40158
40235
  }
40159
- const path50 = filePath2(target, w.rel);
40236
+ const path51 = filePath2(target, w.rel);
40160
40237
  let bytes;
40161
40238
  let version = w.remote.version;
40162
40239
  try {
40163
- bytes = (await client.download(path50)).bytes;
40240
+ bytes = (await client.download(path51)).bytes;
40164
40241
  if (computeHash(bytes) !== w.remote.content_sha256) {
40165
- const meta = await client.request("GET", `${path50}?meta=1`);
40242
+ const meta = await client.request("GET", `${path51}?meta=1`);
40166
40243
  if (meta?.content_sha256 !== computeHash(bytes)) {
40167
40244
  changedWhilePulling.push(w.rel);
40168
40245
  continue;
@@ -40178,9 +40255,9 @@ async function pullFiles(opts) {
40178
40255
  conflicts.push({ rel: w.rel, reason: "edited_while_pulling" });
40179
40256
  continue;
40180
40257
  }
40181
- const hash = computeHash(bytes);
40258
+ const hash2 = computeHash(bytes);
40182
40259
  writeLocal(dir, w.rel, bytes);
40183
- record.files[w.rel] = { version, content_sha256: hash };
40260
+ record.files[w.rel] = { version, content_sha256: hash2 };
40184
40261
  changes.push(`${local.has(w.rel) ? MARK.update : MARK.create} ${safe(w.rel)}`);
40185
40262
  }
40186
40263
  } finally {
@@ -40291,7 +40368,7 @@ Push ${n} change${n === 1 ? "" : "s"} to ${describeSync(target)}?`, opts.yes)) {
40291
40368
  let pushed = 0;
40292
40369
  const refusedDeletes = /* @__PURE__ */ new Set();
40293
40370
  for (const step of plan.steps) {
40294
- const path50 = filePath2(target, step.rel);
40371
+ const path51 = filePath2(target, step.rel);
40295
40372
  const blockedBy = step.op === "create" ? step.after?.find((d) => refusedDeletes.has(d.rel)) : void 0;
40296
40373
  if (blockedBy !== void 0) {
40297
40374
  const conflict = { rel: step.rel, reason: blockedBy.reason, other: blockedBy.rel };
@@ -40301,7 +40378,7 @@ Push ${n} change${n === 1 ? "" : "s"} to ${describeSync(target)}?`, opts.yes)) {
40301
40378
  }
40302
40379
  try {
40303
40380
  if (step.op === "delete") {
40304
- await client.request("DELETE", path50, void 0, fileWriteHeaders({ ifMatch: step.ifMatch }));
40381
+ await client.request("DELETE", path51, void 0, fileWriteHeaders({ ifMatch: step.ifMatch }));
40305
40382
  delete record.files[step.rel];
40306
40383
  } else {
40307
40384
  const bytes = readLocal2(dir, step.rel);
@@ -40310,7 +40387,7 @@ Push ${n} change${n === 1 ? "" : "s"} to ${describeSync(target)}?`, opts.yes)) {
40310
40387
  }
40311
40388
  const contentType = step.op === "update" ? step.remote.content_type : guessMimeType(step.rel) ?? "application/octet-stream";
40312
40389
  const row = await client.upload(
40313
- path50,
40390
+ path51,
40314
40391
  bytes,
40315
40392
  contentType,
40316
40393
  fileWriteHeaders({ ...step.op === "update" ? { ifMatch: step.ifMatch } : { createOnly: true }, label: label3 })
@@ -40397,9 +40474,420 @@ var init_sync3 = __esm({
40397
40474
  }
40398
40475
  });
40399
40476
 
40400
- // src/cases/case-files.ts
40477
+ // src/cases/case-mirror.ts
40478
+ import * as crypto4 from "crypto";
40401
40479
  import * as fs35 from "fs";
40480
+ import * as os4 from "os";
40402
40481
  import * as path47 from "path";
40482
+ function shownEntries(revision, confidential) {
40483
+ return confidential ? revision.entries : revision.entries.filter((e) => !e.confidential && !isConfPath(e.path));
40484
+ }
40485
+ function isBaseline(b) {
40486
+ return isObject(b) && typeof b.at === "string" && typeof b.confidential === "boolean" && (b.revision_at === null || typeof b.revision_at === "string") && (b.status === null || typeof b.status === "string") && isStringMap(b.phases) && isStringMap(b.tasks) && isStringMap(b.groups) && isDeliveries(b.deliveries);
40487
+ }
40488
+ function isMirrorRecord(v) {
40489
+ return isObject(v) && typeof v.org_id === "string" && typeof v.space_id === "string" && typeof v.code === "string" && (v.last_pull === null || isBaseline(v.last_pull));
40490
+ }
40491
+ function mirrorFolder(root) {
40492
+ const dir = path47.join(root, CASE_MIRROR_DIR);
40493
+ let st;
40494
+ try {
40495
+ st = fs35.lstatSync(dir);
40496
+ } catch {
40497
+ return null;
40498
+ }
40499
+ if (!st.isDirectory()) {
40500
+ throw expected(`${safe2(dir)} is a symlink or not a folder. It is the case's mirror, which the CLI writes: move it aside, then pull again.`);
40501
+ }
40502
+ requireOwn(dir);
40503
+ return dir;
40504
+ }
40505
+ function readBaseline(root, detail, record) {
40506
+ const dir = mirrorFolder(root);
40507
+ if (!dir) return null;
40508
+ const file = path47.join(dir, RECORD_FILE2);
40509
+ requireOwn(file);
40510
+ const text5 = readRealFileOrThrow(root, file);
40511
+ if (text5 === null) return null;
40512
+ let parsed;
40513
+ try {
40514
+ parsed = JSON.parse(text5);
40515
+ } catch {
40516
+ return null;
40517
+ }
40518
+ if (!isMirrorRecord(parsed)) return null;
40519
+ if (parsed.org_id !== record.org_id || parsed.space_id !== record.space_id || parsed.code !== detail.code) return null;
40520
+ return parsed.last_pull;
40521
+ }
40522
+ async function readAgenda(calls, phaseId) {
40523
+ const { api, connection } = calls.session;
40524
+ const groups = [];
40525
+ let cursor;
40526
+ for (let page = 0; page < AGENDA_PAGES_READ2; page++) {
40527
+ const { groups: got, next_cursor } = (await calls.run(() => api.getCaseAgenda(connection, phaseId, cursor))).data;
40528
+ groups.push(...got);
40529
+ if (!next_cursor) return { groups, more: false };
40530
+ cursor = next_cursor;
40531
+ }
40532
+ return { groups, more: true };
40533
+ }
40534
+ async function readWork(calls, detail, confidential) {
40535
+ const { api, connection } = calls.session;
40536
+ const state = (await calls.run(() => api.getCaseState(connection))).data;
40537
+ if (state.view !== "work") return { state, phases: [], approved: [] };
40538
+ const folders = new Map(detail.phases.map((p) => [p.phase_id, p.folder]));
40539
+ const underWay = state.state.phases.filter((p) => p.status === "in_progress").map((p) => p.phase_id);
40540
+ const [phases, approved] = await Promise.all([
40541
+ Promise.all(underWay.map(async (phaseId) => {
40542
+ const [work, agenda, delivery] = await Promise.all([
40543
+ calls.run(() => api.getCasePhaseWork(connection, phaseId)),
40544
+ readAgenda(calls, phaseId),
40545
+ calls.run(() => api.getCaseDelivery(connection, phaseId))
40546
+ ]);
40547
+ return { phase_id: phaseId, folder: folders.get(phaseId) ?? "", work: work.data, groups: agenda.groups, more_groups: agenda.more, delivery: delivery.data };
40548
+ })),
40549
+ calls.run(() => api.listCaseApprovedDecisions(connection, confidential))
40550
+ ]);
40551
+ return { state, phases, approved: approved.data };
40552
+ }
40553
+ async function revisionsSince(calls, after, confidential) {
40554
+ const { api, connection } = calls.session;
40555
+ const out = [];
40556
+ let newest = after ?? null;
40557
+ let cursor;
40558
+ const pages = after === void 0 ? 1 : SUMMARY_REVISION_PAGES;
40559
+ for (let page = 0; page < pages; page++) {
40560
+ const { revisions, next_cursor } = (await calls.run(() => api.listCaseRevisions(connection, { cursor, limit: CASE_REVISIONS_PAGE_MAX }))).data;
40561
+ for (const revision of revisions) {
40562
+ if (after !== void 0 && after !== null && revision.created_at <= after) return { revisions: out, more: false, newest_at: newest };
40563
+ const entries = shownEntries(revision, confidential);
40564
+ if (entries.length === 0) continue;
40565
+ if (newest === null || revision.created_at > newest) newest = revision.created_at;
40566
+ if (after !== void 0) out.push({ ...revision, entries });
40567
+ }
40568
+ if (!next_cursor) return { revisions: out, more: false, newest_at: newest };
40569
+ cursor = next_cursor;
40570
+ }
40571
+ return { revisions: out, more: after !== void 0, newest_at: newest };
40572
+ }
40573
+ function snapshotOf(work) {
40574
+ if (!work) return { status: null, phases: {}, tasks: {}, groups: {}, deliveries: {} };
40575
+ if (work.state.view === "phases") {
40576
+ return { status: work.state.status, phases: Object.fromEntries(work.state.phases.map((p) => [p.phase_id, p.status])), tasks: {}, groups: {}, deliveries: {} };
40577
+ }
40578
+ const { state } = work.state;
40579
+ return {
40580
+ status: state.status,
40581
+ phases: Object.fromEntries(state.phases.map((p) => [p.phase_id, p.status])),
40582
+ tasks: Object.fromEntries(state.tasks.map((t) => [t.case_task_id, t.status])),
40583
+ groups: Object.fromEntries(state.agenda_groups.map((g) => [g.agenda_group_id, g.status])),
40584
+ deliveries: Object.fromEntries(work.phases.map((p) => [p.phase_id, p.delivery ? { submission_id: p.delivery.submission_id, state: p.delivery.state } : null]))
40585
+ };
40586
+ }
40587
+ function statusSections(detail, work, before, now) {
40588
+ const phase = new Map(detail.phases.map((p) => [p.phase_id, `${one2(p.folder)} (${one2(p.name)})`]));
40589
+ const task = new Map((detail.tasks ?? []).map((t) => [t.case_task_id, `${one2(t.name)} [${t.case_task_id}]`]));
40590
+ const group = new Map(work.phases.flatMap((p) => p.groups.map((g) => [g.agenda_group_id, `${one2(g.code)} (${one2(g.name)})`])));
40591
+ const changes = (prev, next, name, added) => Object.entries(next).flatMap(([id, status]) => {
40592
+ const was = prev[id];
40593
+ if (was === void 0) return added ? [`${name(id)}: new, ${words(status)}`] : [];
40594
+ return was === status ? [] : [`${name(id)}: ${words(was)} \u2192 ${words(status)}`];
40595
+ });
40596
+ const sections = [];
40597
+ if (before.status !== null && now.status !== null && before.status !== now.status) {
40598
+ sections.push({ title: "The case", lines: [`${words(before.status)} \u2192 ${words(now.status)}`] });
40599
+ }
40600
+ sections.push({ title: "Phases", lines: changes(before.phases, now.phases, (id) => phase.get(id) ?? "a phase", false) });
40601
+ sections.push({ title: "Tasks", lines: changes(before.tasks, now.tasks, (id) => task.get(id) ?? `a task [${id}]`, true) });
40602
+ sections.push({ title: "Agenda groups", lines: changes(before.groups, now.groups, (id) => group.get(id) ?? "an agenda group of a phase not under way", false) });
40603
+ const deliveries = work.phases.flatMap((p) => {
40604
+ if (!(p.phase_id in before.deliveries) || !p.delivery) return [];
40605
+ const was = before.deliveries[p.phase_id];
40606
+ if (was?.submission_id === p.delivery.submission_id && was.state === p.delivery.state) return [];
40607
+ const change = was?.submission_id === p.delivery.submission_id ? `its submission is now ${words(p.delivery.state)}` : `a new submission, ${words(p.delivery.state)}`;
40608
+ return [`${phase.get(p.phase_id) ?? "a phase"}: ${change}`];
40609
+ });
40610
+ sections.push({ title: "Deliveries", lines: deliveries });
40611
+ return sections;
40612
+ }
40613
+ function filesSection(input) {
40614
+ const now = new Map(input.files.filter((f) => input.inRun(f.path)).map((f) => [f.path, f.sha]));
40615
+ const before = new Map(Object.entries(input.record.files).filter(([rel]) => input.inRun(rel)).map(([rel, f]) => [rel, f.sha]));
40616
+ const lines = [];
40617
+ for (const [rel, sha] of now) {
40618
+ if (!before.has(rel)) lines.push(`+ ${safe2(rel)}`);
40619
+ else if (before.get(rel) !== sha) lines.push(`~ ${safe2(rel)}`);
40620
+ }
40621
+ for (const rel of before.keys()) if (!now.has(rel)) lines.push(`- ${safe2(rel)} (removed, or no longer readable here)`);
40622
+ return { title: "Files on the case that differ from what this clone last pulled", lines: lines.sort((a, b) => a.slice(2) < b.slice(2) ? -1 : 1) };
40623
+ }
40624
+ function revisionsSection(since, hideMessages) {
40625
+ const lines = since.revisions.flatMap((r) => {
40626
+ const author = r.author?.display_name ? one2(r.author.display_name) : "a person no longer named";
40627
+ const message = r.message !== null && !hideMessages ? `: ${one2(r.message)}` : "";
40628
+ return [`revision ${r.revision_id}, ${r.created_at}, ${author} (${r.channel})${message}`, ...r.entries.map((e) => ` ${safe2(e.path)}${e.sha === null ? " (removed)" : ""}`)];
40629
+ });
40630
+ if (since.more) lines.push("\u2026 and older ones: `wayai cases log` lists them all.");
40631
+ return { title: "Revisions", lines };
40632
+ }
40633
+ function renderSections(sections) {
40634
+ return sections.filter((s) => s.lines.length > 0).flatMap((s) => [`${s.title}:`, ...s.lines.map((l) => ` ${l}`)]);
40635
+ }
40636
+ function readme(detail, at, withheld, confidential) {
40637
+ const parts = withheld ? [
40638
+ "This authorization holds the Confidential right, and the case's own reads give it confidential content whatever",
40639
+ "it asks: without --confidential this mirror holds none of them (case, status, evidence, agenda, deliveries)."
40640
+ ] : [
40641
+ "- `case.json`: the case: its type and version, owner, parties, phases and their folders, tasks, and your access.",
40642
+ "- `status.json`: its status: each phase's, task's and agenda group's, why each is not done, and who can move it.",
40643
+ "- `evidence.json`: each phase under way: its inputs with their links, its outputs and its items.",
40644
+ "- `agenda.json`: each phase under way: its agenda groups and decisions; and the approved decisions.",
40645
+ "- `deliveries.json`: each phase under way: its newest submission and manifest."
40646
+ ];
40647
+ return [
40648
+ `# Case ${safe2(detail.code)}: read-only mirror`,
40649
+ "",
40650
+ `Written ${at} by \`wayai cases clone\` or \`pull\`. Every pull rewrites this folder whole, and \`wayai cases push\` never sends`,
40651
+ "anything in it: an edit here is lost and never reaches the case.",
40652
+ "",
40653
+ `- \`${SUMMARY_FILE}\`: what changed on the case since your last pull.`,
40654
+ ...parts,
40655
+ `- \`${CASE_MIRROR_HOOK_FILE}\`: the session-start hook. It refreshes this folder, never with --confidential.`,
40656
+ `- \`${RECORD_FILE2}\`: what the next pull compares with.`,
40657
+ "",
40658
+ "Not here: the registered texts of linked inputs (no read of a collection document's text reaches a case token yet),",
40659
+ "and the drafting checks (`wayai cases check --phase <folder>` reads them live).",
40660
+ ...confidential ? [] : ["", MIRROR_CONFIDENTIAL_NOTICE],
40661
+ ""
40662
+ ].join("\n");
40663
+ }
40664
+ function lockOwnerStopped(text5) {
40665
+ const owner = text5 === null ? null : /^(\d+) (\S+) [0-9a-f]+$/.exec(text5) ?? null;
40666
+ if (!owner || owner[2] !== os4.hostname()) return false;
40667
+ try {
40668
+ process.kill(Number(owner[1]), 0);
40669
+ return false;
40670
+ } catch (err) {
40671
+ return err.code === "ESRCH";
40672
+ }
40673
+ }
40674
+ async function lockMirror(root) {
40675
+ const dir = path47.join(root, CASE_MIRROR_DIR);
40676
+ if (!mirrorFolder(root)) {
40677
+ try {
40678
+ fs35.mkdirSync(dir, { mode: CASE_FOLDER_MODE });
40679
+ fs35.chmodSync(dir, CASE_FOLDER_MODE);
40680
+ } catch (err) {
40681
+ if (err.code !== "EEXIST") throw err;
40682
+ }
40683
+ mirrorFolder(root);
40684
+ }
40685
+ const lock = path47.join(dir, LOCK_FILE);
40686
+ const mine = `${process.pid} ${os4.hostname()} ${crypto4.randomBytes(16).toString("hex")}`;
40687
+ const held = (file) => {
40688
+ try {
40689
+ return fs35.readFileSync(file, "utf-8");
40690
+ } catch {
40691
+ return null;
40692
+ }
40693
+ };
40694
+ const refusal2 = (err) => {
40695
+ const code2 = err.code;
40696
+ return code2 === "EACCES" || code2 === "EPERM" || code2 === "EROFS" ? expected(`The mirror's folder ${safe2(dir)} cannot be written (${code2}). Make it writable by you (it is the CLI's to write), then pull again.`) : err;
40697
+ };
40698
+ const deadline = Date.now() + LOCK_WAIT_MS;
40699
+ for (; ; ) {
40700
+ try {
40701
+ const fd = fs35.openSync(lock, "wx", 420);
40702
+ try {
40703
+ fs35.writeFileSync(fd, mine);
40704
+ } finally {
40705
+ fs35.closeSync(fd);
40706
+ }
40707
+ return () => {
40708
+ if (held(lock) === mine) fs35.rmSync(lock, { force: true });
40709
+ };
40710
+ } catch (err) {
40711
+ if (err.code !== "EEXIST") throw refusal2(err);
40712
+ }
40713
+ const judged = held(lock);
40714
+ let age = 0;
40715
+ try {
40716
+ age = Date.now() - fs35.lstatSync(lock).mtimeMs;
40717
+ } catch (err) {
40718
+ if (err.code === "ENOENT") continue;
40719
+ throw refusal2(err);
40720
+ }
40721
+ if (judged !== null && (lockOwnerStopped(judged) || age > LOCK_STALE_MS)) {
40722
+ const aside = path47.join(dir, `${LOCK_FILE}.stale-${mine.split(" ")[2]}`);
40723
+ try {
40724
+ fs35.renameSync(lock, aside);
40725
+ } catch (err) {
40726
+ if (err.code === "ENOENT") continue;
40727
+ throw refusal2(err);
40728
+ }
40729
+ if (held(aside) !== judged) {
40730
+ try {
40731
+ fs35.linkSync(aside, lock);
40732
+ } catch {
40733
+ }
40734
+ }
40735
+ fs35.rmSync(aside, { force: true });
40736
+ continue;
40737
+ }
40738
+ if (Date.now() > deadline) {
40739
+ throw expected(`Another run has held the mirror at ${safe2(dir)} for ${Math.round(age / 1e3)} s. Pull again once it ends.`);
40740
+ }
40741
+ await new Promise((resolve16) => setTimeout(resolve16, LOCK_POLL_MS));
40742
+ }
40743
+ }
40744
+ function writeMirror(root, files) {
40745
+ const id = crypto4.randomBytes(8).toString("hex");
40746
+ const dir = path47.join(root, CASE_MIRROR_DIR);
40747
+ const temp = (name) => `.tmp-${id}-${name}`;
40748
+ try {
40749
+ for (const f of files) {
40750
+ writeCaseLocalFile(root, `${CASE_MIRROR_DIR}/${temp(f.name)}`, f.data);
40751
+ if (f.mode !== void 0) fs35.chmodSync(path47.join(dir, temp(f.name)), f.mode);
40752
+ }
40753
+ for (const f of files) {
40754
+ const target = path47.join(dir, f.name);
40755
+ let st;
40756
+ try {
40757
+ st = fs35.lstatSync(target);
40758
+ } catch {
40759
+ st = void 0;
40760
+ }
40761
+ if (st?.isDirectory()) fs35.rmSync(target, { recursive: true, force: true });
40762
+ fs35.renameSync(path47.join(dir, temp(f.name)), target);
40763
+ }
40764
+ const names = new Set(files.map((f) => f.name));
40765
+ for (const name of fs35.readdirSync(dir)) {
40766
+ if (!names.has(name) && name !== LOCK_FILE) fs35.rmSync(path47.join(dir, name), { recursive: true, force: true });
40767
+ }
40768
+ } finally {
40769
+ for (const f of files) fs35.rmSync(path47.join(dir, temp(f.name)), { force: true });
40770
+ }
40771
+ }
40772
+ async function writeCaseMirror(calls, input) {
40773
+ const { root, detail, confidential, mode } = input;
40774
+ const before = mode === "clone" ? null : readBaseline(root, detail, input.record);
40775
+ const withheld = detail.access.capabilities.includes("read_confidential") && !confidential;
40776
+ const readsRevisions = before !== null || mode !== "mirror-only";
40777
+ const [work, since] = await Promise.all([
40778
+ withheld ? null : readWork(calls, detail, confidential),
40779
+ readsRevisions ? revisionsSince(calls, before ? before.revision_at : void 0, confidential) : NO_REVISIONS
40780
+ ]);
40781
+ const now = snapshotOf(work);
40782
+ const at = nowIso();
40783
+ let baseline;
40784
+ if (mode !== "mirror-only") {
40785
+ baseline = { at, confidential, revision_at: since.newest_at, ...now };
40786
+ } else if (before && before.confidential && !confidential) {
40787
+ baseline = {
40788
+ ...before,
40789
+ confidential: false,
40790
+ status: now.status === null ? null : before.status,
40791
+ phases: within(before.phases, now.phases),
40792
+ tasks: within(before.tasks, now.tasks),
40793
+ groups: within(before.groups, now.groups),
40794
+ deliveries: within(before.deliveries, now.deliveries)
40795
+ };
40796
+ } else {
40797
+ baseline = before;
40798
+ }
40799
+ const sections = [];
40800
+ if (before) sections.push(revisionsSection(since, withheld));
40801
+ if (mode !== "clone") sections.push(filesSection(input));
40802
+ if (before && work) sections.push(...statusSections(detail, work, before, now));
40803
+ const lines = renderSections(sections);
40804
+ const heading = mode === "clone" ? "This is the clone's first pull: there is nothing earlier to compare with." : before ? `Since the last pull (${before.at}):` : "No record of an earlier pull is in this clone's mirror: only its files are compared.";
40805
+ const summary = [heading, ...lines.length ? lines : before ? ["Nothing changed."] : []];
40806
+ const notice = confidential ? [] : ["", MIRROR_CONFIDENTIAL_NOTICE];
40807
+ const files = [
40808
+ { name: "README.md", data: Buffer.from(readme(detail, at, withheld, confidential), "utf-8") },
40809
+ { name: SUMMARY_FILE, data: Buffer.from(`# Case ${safe2(detail.code)}: since the last pull
40810
+
40811
+ ${[...summary, ...notice].join("\n")}
40812
+ `, "utf-8") },
40813
+ { name: CASE_MIRROR_HOOK_FILE, data: Buffer.from(HOOK_SCRIPT, "utf-8"), mode: 493 },
40814
+ { name: RECORD_FILE2, data: json({ org_id: input.record.org_id, space_id: input.record.space_id, code: detail.code, last_pull: baseline }) }
40815
+ ];
40816
+ if (work) {
40817
+ files.push(
40818
+ { name: "case.json", data: json(detail) },
40819
+ { name: "status.json", data: json(work.state) },
40820
+ { name: "evidence.json", data: json({ phases: work.phases.map((p) => ({ phase_id: p.phase_id, folder: p.folder, work: p.work })) }) },
40821
+ { name: "agenda.json", data: json({ phases: work.phases.map((p) => ({ phase_id: p.phase_id, folder: p.folder, groups: p.groups, more_groups: p.more_groups })), approved: work.approved }) },
40822
+ { name: "deliveries.json", data: json({ phases: work.phases.map((p) => ({ phase_id: p.phase_id, folder: p.folder, delivery: p.delivery })) }) }
40823
+ );
40824
+ }
40825
+ writeMirror(root, files);
40826
+ console.log(`
40827
+ Mirror of case ${safe2(detail.code)} written to ${safe2(path47.join(root, CASE_MIRROR_DIR))} (read-only: every pull rewrites it).`);
40828
+ for (const line of mode === "mirror-only" ? [...summary, ...notice] : summary) console.log(line);
40829
+ }
40830
+ async function withMirrorLock(root, step) {
40831
+ const unlock = await lockMirror(root);
40832
+ try {
40833
+ return await step();
40834
+ } finally {
40835
+ unlock();
40836
+ }
40837
+ }
40838
+ function printHookSetup(root) {
40839
+ const script = path47.join(root, CASE_MIRROR_DIR, CASE_MIRROR_HOOK_FILE);
40840
+ const command2 = `sh '${script.replaceAll("'", "'\\''")}'`;
40841
+ const settings = JSON.stringify({ hooks: { SessionStart: [{ hooks: [{ type: "command", command: command2 }] }] } });
40842
+ console.log(`
40843
+ Session-start hook: ${safe2(script)} refreshes the mirror (never with --confidential).`);
40844
+ console.log(`For Claude Code, add it to ${safe2(path47.join(root, ".claude", "settings.json"))}:`);
40845
+ console.log(` ${safe2(settings)}`);
40846
+ console.log(`For another agent, run at the start of each session: ${safe2(command2)}`);
40847
+ }
40848
+ var CASE_MIRROR_DIR, CASE_MIRROR_HOOK_FILE, RECORD_FILE2, SUMMARY_FILE, LOCK_FILE, LOCK_WAIT_MS, LOCK_STALE_MS, LOCK_POLL_MS, AGENDA_PAGES_READ2, SUMMARY_REVISION_PAGES, MIRROR_CONFIDENTIAL_NOTICE, safe2, one2, words, isConfPath, isObject, isStringMap, isDeliveries, NO_REVISIONS, within, HOOK_SCRIPT, json;
40849
+ var init_case_mirror = __esm({
40850
+ "src/cases/case-mirror.ts"() {
40851
+ "use strict";
40852
+ init_dist();
40853
+ init_case_files();
40854
+ init_expected();
40855
+ init_fs_safety();
40856
+ init_terminal_output();
40857
+ init_case_local_files();
40858
+ CASE_MIRROR_DIR = ".wayai-mirror";
40859
+ CASE_MIRROR_HOOK_FILE = "session-start.sh";
40860
+ RECORD_FILE2 = "record.json";
40861
+ SUMMARY_FILE = "since-last-pull.md";
40862
+ LOCK_FILE = ".lock";
40863
+ LOCK_WAIT_MS = 12e4;
40864
+ LOCK_STALE_MS = 10 * 6e4;
40865
+ LOCK_POLL_MS = 50;
40866
+ AGENDA_PAGES_READ2 = 5;
40867
+ SUMMARY_REVISION_PAGES = 2;
40868
+ MIRROR_CONFIDENTIAL_NOTICE = "Confidential content is left out unless you pass --confidential.";
40869
+ safe2 = (text5) => sanitizeTerminalText(text5);
40870
+ one2 = (text5) => sanitizeTerminalText(text5).replace(/\s*\n\s*/g, " ");
40871
+ words = (status) => status.replaceAll("_", " ");
40872
+ isConfPath = (rel) => rel.split("/")[0] === "conf";
40873
+ isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
40874
+ isStringMap = (v) => isObject(v) && Object.values(v).every((x) => typeof x === "string");
40875
+ isDeliveries = (v) => isObject(v) && Object.values(v).every((d) => d === null || isObject(d) && typeof d.submission_id === "string" && typeof d.state === "string");
40876
+ NO_REVISIONS = { revisions: [], more: false, newest_at: null };
40877
+ within = (prev, now) => Object.fromEntries(Object.entries(prev).filter(([key]) => key in now));
40878
+ HOOK_SCRIPT = `#!/bin/sh
40879
+ # Written by \`wayai cases clone\` and every \`wayai cases pull\` (this folder is rewritten whole: do not edit it).
40880
+ # The session-start hook: refreshes this clone's read-only mirror of its case. It never passes --confidential.
40881
+ exec wayai cases pull --mirror-only --dir "$(dirname "$0")/.."
40882
+ `;
40883
+ json = (value) => Buffer.from(`${JSON.stringify(value, null, 2)}
40884
+ `, "utf-8");
40885
+ }
40886
+ });
40887
+
40888
+ // src/cases/case-files.ts
40889
+ import * as fs36 from "fs";
40890
+ import * as path48 from "path";
40403
40891
  function casesRequestsPerMinute() {
40404
40892
  const budget = getEndpointConfig("/api/cases/org/space/cases/code/files")?.userLimit;
40405
40893
  return budget ? Math.max(1, Math.floor(budget * 4 / 5)) : 48;
@@ -40412,7 +40900,7 @@ function assertWritableCasePaths(paths, phaseFolders) {
40412
40900
  for (const rel of paths) {
40413
40901
  const check = checkCaseFilePath({ path: rel, type: "file" }, phaseFolders);
40414
40902
  if (!check.ok) {
40415
- problems2.push(`${JSON.stringify(safe2(rel))}: a case path cannot be that (${check.reason})`);
40903
+ problems2.push(`${JSON.stringify(safe3(rel))}: a case path cannot be that (${check.reason})`);
40416
40904
  continue;
40417
40905
  }
40418
40906
  const folded = check.fold_key.split("/");
@@ -40424,7 +40912,7 @@ function assertWritableCasePaths(paths, phaseFolders) {
40424
40912
  if (known === void 0) {
40425
40913
  spelled.set(key, spelling);
40426
40914
  } else if (known !== spelling) {
40427
- problems2.push(`${JSON.stringify(safe2(known))} and ${JSON.stringify(safe2(spelling))} differ only in case, so they would be one entry here`);
40915
+ problems2.push(`${JSON.stringify(safe3(known))} and ${JSON.stringify(safe3(spelling))} differ only in case, so they would be one entry here`);
40428
40916
  break;
40429
40917
  }
40430
40918
  }
@@ -40435,7 +40923,7 @@ function assertWritableCasePaths(paths, phaseFolders) {
40435
40923
  const segments = key.split("/");
40436
40924
  for (let i = 1; i < segments.length; i++) {
40437
40925
  if (keys.has(segments.slice(0, i).join("/"))) {
40438
- problems2.push(`${JSON.stringify(safe2(rel))} lies in a folder that is also a file`);
40926
+ problems2.push(`${JSON.stringify(safe3(rel))} lies in a folder that is also a file`);
40439
40927
  break;
40440
40928
  }
40441
40929
  }
@@ -40447,20 +40935,20 @@ function assertWritableCasePaths(paths, phaseFolders) {
40447
40935
  }
40448
40936
  function linkRefusal(rel) {
40449
40937
  return expected(
40450
- `${safe2(rel)} is a symlink, or not a regular file or folder. The CLI never follows one in a clone: replace it with the file or folder itself, or move it out of the clone.`
40938
+ `${safe3(rel)} is a symlink, or not a regular file or folder. The CLI never follows one in a clone: replace it with the file or folder itself, or move it out of the clone.`
40451
40939
  );
40452
40940
  }
40453
40941
  function scanClone(root, phaseFolders, confidential = true) {
40454
40942
  const out = /* @__PURE__ */ new Map();
40455
40943
  const walk = (abs, rel) => {
40456
- for (const name of fs35.readdirSync(abs).sort()) {
40944
+ for (const name of fs36.readdirSync(abs).sort()) {
40457
40945
  if (name.startsWith(".")) continue;
40458
- const childAbs = path47.join(abs, name);
40946
+ const childAbs = path48.join(abs, name);
40459
40947
  const childRel = `${rel}/${name}`;
40460
- const st = fs35.lstatSync(childAbs);
40948
+ const st = fs36.lstatSync(childAbs);
40461
40949
  if (st.isDirectory() || st.isFile()) {
40462
40950
  const problem = ownProblem(st);
40463
- if (problem) throw expected(`Refused ${safe2(childRel)}: ${problem}. A case is read and written only in folders and files you own, never in one every user can write to.`);
40951
+ if (problem) throw expected(`Refused ${safe3(childRel)}: ${problem}. A case is read and written only in folders and files you own, never in one every user can write to.`);
40464
40952
  }
40465
40953
  if (st.isDirectory()) {
40466
40954
  walk(childAbs, childRel);
@@ -40474,16 +40962,16 @@ function scanClone(root, phaseFolders, confidential = true) {
40474
40962
  }
40475
40963
  };
40476
40964
  requireOwn(root);
40477
- const top = new Set(fs35.readdirSync(root));
40965
+ const top = new Set(fs36.readdirSync(root));
40478
40966
  const areas = [.../* @__PURE__ */ new Set([...phaseFolders, "analysis", ...confidential ? ["conf"] : []])].filter((area) => top.has(area));
40479
40967
  if (top.has("instructions")) {
40480
- if (!fs35.lstatSync(path47.join(root, "instructions")).isDirectory()) throw linkRefusal("instructions");
40481
- if (fs35.readdirSync(path47.join(root, "instructions")).includes("case")) areas.push("instructions/case");
40968
+ if (!fs36.lstatSync(path48.join(root, "instructions")).isDirectory()) throw linkRefusal("instructions");
40969
+ if (fs36.readdirSync(path48.join(root, "instructions")).includes("case")) areas.push("instructions/case");
40482
40970
  }
40483
40971
  for (const rel of areas) {
40484
- const abs = path47.join(root, ...rel.split("/"));
40485
- if (!fs35.lstatSync(abs).isDirectory()) throw linkRefusal(rel);
40486
- if (rel === "instructions/case") requireOwn(path47.join(root, "instructions"));
40972
+ const abs = path48.join(root, ...rel.split("/"));
40973
+ if (!fs36.lstatSync(abs).isDirectory()) throw linkRefusal(rel);
40974
+ if (rel === "instructions/case") requireOwn(path48.join(root, "instructions"));
40487
40975
  requireOwn(abs);
40488
40976
  walk(abs, rel);
40489
40977
  }
@@ -40515,11 +41003,11 @@ function sidesOf(record, local, files, confidential) {
40515
41003
  function requireFiles(detail, confidential) {
40516
41004
  const can = detail.access.capabilities;
40517
41005
  if (!can.includes("view_work")) {
40518
- throw expected(`Your access to case ${safe2(detail.code)} does not reach its files: no team of yours reads its work.`);
41006
+ throw expected(`Your access to case ${safe3(detail.code)} does not reach its files: no team of yours reads its work.`);
40519
41007
  }
40520
41008
  if (confidential && !can.includes("read_confidential")) {
40521
41009
  throw expected(
40522
- `This machine's authorization on case ${safe2(detail.code)} does not hold the Confidential right, so --confidential reads nothing more. Run it without --confidential.`
41010
+ `This machine's authorization on case ${safe3(detail.code)} does not hold the Confidential right, so --confidential reads nothing more. Run it without --confidential.`
40523
41011
  );
40524
41012
  }
40525
41013
  }
@@ -40528,6 +41016,7 @@ async function pullInto(calls, detail, record, opts) {
40528
41016
  const files = await calls.files();
40529
41017
  assertWritableCasePaths([...sidesOf(record, /* @__PURE__ */ new Map(), files, opts.confidential).listed.keys()], phaseFolders);
40530
41018
  const root = opts.root();
41019
+ mirrorFolder(root);
40531
41020
  const local = scanClone(root, phaseFolders, opts.confidential);
40532
41021
  const { synced: synced2, local: localIn, remote, listed: listed3, theirsListed } = sidesOf(record, local, files, opts.confidential);
40533
41022
  const plan = planPull({ synced: synced2, local: localIn, remote, overwrite: opts.overwrite });
@@ -40536,7 +41025,7 @@ async function pullInto(calls, detail, record, opts) {
40536
41025
  const replaced = [...plan.replacedLocal, ...opts.overwrite ? theirsLeft : []];
40537
41026
  if (replaced.length > 0) {
40538
41027
  console.log("These local changes would be replaced with the case's copies, or removed:");
40539
- for (const rel of replaced) console.log(` ${safe2(rel)}`);
41028
+ for (const rel of replaced) console.log(` ${safe3(rel)}`);
40540
41029
  if (!await agree(`Replace or remove ${replaced.length} local file(s)?`, opts.yes)) {
40541
41030
  console.log("Cancelled.");
40542
41031
  return;
@@ -40564,7 +41053,7 @@ async function pullInto(calls, detail, record, opts) {
40564
41053
  conflicts.push({ rel, reason: "unresolved" });
40565
41054
  } else if (matchesScan(root, rel, local.get(rel))) {
40566
41055
  removeLocal(root, rel);
40567
- changes.push(`${MARK.delete} ${safe2(rel)}`);
41056
+ changes.push(`${MARK.delete} ${safe3(rel)}`);
40568
41057
  } else {
40569
41058
  conflicts.push({ rel, reason: "edited_while_pulling" });
40570
41059
  }
@@ -40576,7 +41065,7 @@ async function pullInto(calls, detail, record, opts) {
40576
41065
  }
40577
41066
  removeLocal(root, rel);
40578
41067
  delete next.files[rel];
40579
- changes.push(`${MARK.delete} ${safe2(rel)}`);
41068
+ changes.push(`${MARK.delete} ${safe3(rel)}`);
40580
41069
  }
40581
41070
  for (const w of plan.writes) {
40582
41071
  const clash = diskClash(root, w.rel);
@@ -40592,7 +41081,7 @@ async function pullInto(calls, detail, record, opts) {
40592
41081
  }
40593
41082
  writeCaseLocalFile(root, w.rel, Buffer.from(bytes));
40594
41083
  next.files[w.rel] = recordedFile(listed3.get(w.rel));
40595
- changes.push(`${local.has(w.rel) ? MARK.update : MARK.create} ${safe2(w.rel)}`);
41084
+ changes.push(`${local.has(w.rel) ? MARK.update : MARK.create} ${safe3(w.rel)}`);
40596
41085
  }
40597
41086
  for (const c of plan.conflicts) {
40598
41087
  if (c.reason === "both_changed" || c.reason === "exists_locally") {
@@ -40615,24 +41104,33 @@ async function pullInto(calls, detail, record, opts) {
40615
41104
  }
40616
41105
  const named = conflicts.filter((c) => !(c.reason === "unresolved" && rewritten.has(c.rel)));
40617
41106
  const count = Object.keys(next.files).length;
40618
- console.log(safe2(`${opts.verb} case ${record.code} into ${root} (${count} file${count === 1 ? "" : "s"} recorded).`));
41107
+ console.log(safe3(`${opts.verb} case ${record.code} into ${root} (${count} file${count === 1 ? "" : "s"} recorded).`));
40619
41108
  printSection("Changes:", changes);
40620
- printSection("Kept: your local changes, not pushed yet:", plan.kept.map((k) => `${safe2(k.rel)}: ${k.reason === "edited" ? "edited here" : "deleted here (push --prune removes it from the case)"}`));
41109
+ printSection("Kept: your local changes, not pushed yet:", plan.kept.map((k) => `${safe3(k.rel)}: ${k.reason === "edited" ? "edited here" : "deleted here (push --prune removes it from the case)"}`));
40621
41110
  printSection(
40622
41111
  "Conflicts: your copy is kept. Resolve each, deleting any copy beside it, then push; or take the case's copies with `wayai cases pull --overwrite`:",
40623
41112
  named.map((c) => conflictLine(c, PULL_CONFLICT2))
40624
41113
  );
40625
- printSection("Changed on the case while pulling: left as is; pull again to take it:", changedWhilePulling.map(safe2));
40626
- printSection(`Not pulled: case paths ending in ${THEIRS_SUFFIX}, the name a conflict's copy takes here:`, theirsListed.map(safe2));
41114
+ printSection("Changed on the case while pulling: left as is; pull again to take it:", changedWhilePulling.map(safe3));
41115
+ printSection(`Not pulled: case paths ending in ${THEIRS_SUFFIX}, the name a conflict's copy takes here:`, theirsListed.map(safe3));
40627
41116
  if (!opts.confidential) console.log(`
40628
41117
  ${CONFIDENTIAL_NOTICE}`);
40629
41118
  if (named.length > 0) process.exitCode = 1;
41119
+ await withMirrorLock(root, () => writeCaseMirror(calls, {
41120
+ root,
41121
+ detail,
41122
+ files,
41123
+ record,
41124
+ inRun: inRunOf(outside),
41125
+ confidential: opts.confidential,
41126
+ mode: opts.verb === "Cloned" ? "clone" : "pull"
41127
+ }));
40630
41128
  }
40631
41129
  function cloneAt(dir) {
40632
41130
  if (dir !== void 0) {
40633
41131
  const root = caseLocalRoot(dir);
40634
41132
  const record = readCloneRecord(root);
40635
- if (!record) throw expected(`${safe2(dir)} is not a case clone: it holds no ${CASE_CLONE_RECORD_FILE}. Clone the case with \`wayai cases clone\`.`);
41133
+ if (!record) throw expected(`${safe3(dir)} is not a case clone: it holds no ${CASE_CLONE_RECORD_FILE}. Clone the case with \`wayai cases clone\`.`);
40636
41134
  return { root, record };
40637
41135
  }
40638
41136
  const clone = findCaseClone(process.cwd());
@@ -40647,43 +41145,64 @@ async function caseClone(selector, opts) {
40647
41145
  const calls = new CaseCalls(session);
40648
41146
  const detail = await calls.detail();
40649
41147
  requireFiles(detail, opts.confidential);
40650
- const dir = path47.resolve(opts.dir ?? session.connection.code);
41148
+ const dir = path48.resolve(opts.dir ?? session.connection.code);
40651
41149
  let exists = true;
40652
41150
  let st;
40653
41151
  try {
40654
- st = fs35.lstatSync(dir);
41152
+ st = fs36.lstatSync(dir);
40655
41153
  } catch {
40656
41154
  exists = false;
40657
41155
  }
40658
- if (st && !st.isDirectory()) throw expected(`${safe2(dir)} is a symlink or not a folder: clone into a folder of its own.`);
41156
+ if (st && !st.isDirectory()) throw expected(`${safe3(dir)} is a symlink or not a folder: clone into a folder of its own.`);
40659
41157
  if (exists) {
40660
41158
  const existing = readCloneRecord(caseLocalRoot(dir));
40661
41159
  if (existing) {
40662
- throw expected(sameCase(existing, session.connection) ? `${safe2(dir)} is a clone of case ${safe2(existing.code)} already: run \`wayai cases pull\` there.` : `${safe2(dir)} is a clone of case ${safe2(existing.code)}: clone into another folder.`);
41160
+ throw expected(sameCase(existing, session.connection) ? `${safe3(dir)} is a clone of case ${safe3(existing.code)} already: run \`wayai cases pull\` there.` : `${safe3(dir)} is a clone of case ${safe3(existing.code)}: clone into another folder.`);
40663
41161
  }
40664
41162
  }
40665
- const outer = findCaseClone(path47.dirname(dir));
40666
- if (outer) throw expected(`${safe2(dir)} lies inside the clone of case ${safe2(outer.record.code)} at ${safe2(outer.root)}: clone outside it.`);
41163
+ const outer = findCaseClone(path48.dirname(dir));
41164
+ if (outer) throw expected(`${safe3(dir)} lies inside the clone of case ${safe3(outer.record.code)} at ${safe3(outer.root)}: clone outside it.`);
40667
41165
  const record = { org_id: session.connection.org_id, space_id: session.connection.space_id, code: session.connection.code, files: {} };
40668
41166
  await pullInto(calls, detail, record, {
40669
41167
  confidential: opts.confidential,
40670
41168
  overwrite: false,
40671
41169
  yes: false,
40672
41170
  root: () => {
40673
- if (!exists) fs35.mkdirSync(dir, { recursive: true, mode: CASE_FOLDER_MODE });
41171
+ if (!exists) fs36.mkdirSync(dir, { recursive: true, mode: CASE_FOLDER_MODE });
40674
41172
  return caseLocalRoot(dir);
40675
41173
  },
40676
41174
  verb: "Cloned"
40677
41175
  });
41176
+ printHookSetup(caseLocalRoot(dir));
40678
41177
  }
40679
- async function casePull(opts) {
40680
- const { root, record } = cloneAt(opts.dir);
40681
- const session = await cloneSession(root);
40682
- const calls = new CaseCalls(session);
41178
+ async function openClone(dir, confidential) {
41179
+ const { root, record } = cloneAt(dir);
41180
+ const calls = new CaseCalls(await cloneSession(root));
40683
41181
  const detail = await calls.detail();
40684
- requireFiles(detail, opts.confidential);
41182
+ requireFiles(detail, confidential);
41183
+ return { root, record, calls, detail };
41184
+ }
41185
+ async function casePull(opts) {
41186
+ const { root, record, calls, detail } = await openClone(opts.dir, opts.confidential);
40685
41187
  await pullInto(calls, detail, record, { ...opts, root: () => root, verb: "Pulled" });
40686
41188
  }
41189
+ async function casePullMirror(opts) {
41190
+ const { root, record: opened, calls, detail } = await openClone(opts.dir, opts.confidential);
41191
+ mirrorFolder(root);
41192
+ await withMirrorLock(root, async () => {
41193
+ const record = readCloneRecord(root) ?? opened;
41194
+ const files = await calls.files();
41195
+ await writeCaseMirror(calls, {
41196
+ root,
41197
+ detail,
41198
+ files,
41199
+ record,
41200
+ inRun: inRunOf(outsideRun(record, files, opts.confidential)),
41201
+ confidential: opts.confidential,
41202
+ mode: "mirror-only"
41203
+ });
41204
+ });
41205
+ }
40687
41206
  function leftOutReason(rel, phaseFolders, detail) {
40688
41207
  const check = checkCaseFilePath({ path: rel, type: "file" }, phaseFolders);
40689
41208
  if (!check.ok) return `the case takes no such path (${check.reason})`;
@@ -40709,7 +41228,7 @@ function uploadRefusal(err, session, entries) {
40709
41228
  const reason3 = extractApiErrorReason(err);
40710
41229
  const { at, paths } = refusalDetails(err, sent);
40711
41230
  const list2 = paths.map((p) => `
40712
- ${safe2(p)}`).join("");
41231
+ ${safe3(p)}`).join("");
40713
41232
  if (err.status === 409 && reason3 === CASE_FILE_CONFLICT_REASON) {
40714
41233
  return expected(`These files changed on the case since your last pull:${list2}
40715
41234
  ${nothing} Run \`wayai cases pull\`, then push again.`);
@@ -40727,7 +41246,7 @@ ${nothing} Write those files under other paths.`
40727
41246
  if (err.status === 400 && reason3) {
40728
41247
  const index = at === null ? null : /^entries\.(\d+)/.exec(at);
40729
41248
  const where = index ? entries[Number(index[1])]?.path : void 0;
40730
- return expected(`The case refused the revision (${safe2(reason3)}${where ? `, at ${safe2(where)}` : ""}). ${nothing}`);
41249
+ return expected(`The case refused the revision (${safe3(reason3)}${where ? `, at ${safe3(where)}` : ""}). ${nothing}`);
40731
41250
  }
40732
41251
  return caseCallFailure(err, session.connection);
40733
41252
  }
@@ -40751,7 +41270,7 @@ async function casePush(opts) {
40751
41270
  const detail = await calls.detail();
40752
41271
  requireFiles(detail, opts.confidential);
40753
41272
  if (!detail.access.capabilities.includes("upload_document")) {
40754
- throw expected(`Your access to case ${safe2(detail.code)} does not write its files: that takes Edit level, on an open case.`);
41273
+ throw expected(`Your access to case ${safe3(detail.code)} does not write its files: that takes Edit level, on an open case.`);
40755
41274
  }
40756
41275
  const phaseFolders = phaseFoldersOf(detail);
40757
41276
  const scanned = scanClone(root, phaseFolders, opts.confidential);
@@ -40761,7 +41280,7 @@ async function casePush(opts) {
40761
41280
  if (theirs.length > 0) {
40762
41281
  throw expected(
40763
41282
  `Resolve these conflicts first: merge each into the file beside it, then delete the ${THEIRS_SUFFIX} copy.${theirs.map((t) => `
40764
- ${safe2(t)}`).join("")}
41283
+ ${safe3(t)}`).join("")}
40765
41284
  Nothing was pushed.`
40766
41285
  );
40767
41286
  }
@@ -40774,7 +41293,7 @@ Nothing was pushed.`
40774
41293
  const file = scanned.get(rel);
40775
41294
  const reason3 = record.files[rel]?.sha === file?.content_sha256 ? null : leftOutReason(rel, phaseFolders, detail);
40776
41295
  if (reason3) {
40777
- leftOut.push(`${safe2(rel)}: ${reason3}`);
41296
+ leftOut.push(`${safe3(rel)}: ${reason3}`);
40778
41297
  leftOutPaths.add(rel);
40779
41298
  } else if (file) {
40780
41299
  local.set(rel, file);
@@ -40784,13 +41303,13 @@ Nothing was pushed.`
40784
41303
  const recordIn = { ...record, files: Object.fromEntries(Object.entries(record.files).filter(([rel]) => !leftOutPaths.has(rel))) };
40785
41304
  const { synced: synced2, local: localIn, remote, listed: listed3 } = sidesOf(recordIn, local, files, opts.confidential);
40786
41305
  const plan = planPush({ synced: synced2, local: localIn, remote, prune: opts.prune });
40787
- console.log(safe2(`Push ${root} \u2192 case ${record.code}`));
40788
- const steps = plan.steps.map((s) => `${MARK[s.op]} ${safe2(s.rel)}${s.op === "create" ? ` (new, ${s.local.size} bytes)` : ""}`);
41306
+ console.log(safe3(`Push ${root} \u2192 case ${record.code}`));
41307
+ const steps = plan.steps.map((s) => `${MARK[s.op]} ${safe3(s.rel)}${s.op === "create" ? ` (new, ${s.local.size} bytes)` : ""}`);
40789
41308
  printSection("Changes:", steps);
40790
- printSection("Changed on the case since your last pull: left as is; pull to take it:", plan.changedOnBase.map(safe2));
40791
- printSection("Deleted on the case since your last pull, or no longer readable here: left as is; pull to remove your copy:", plan.deletedOnBase.map(safe2));
40792
- printSection("On the case, not in your clone: left as is; pull to fetch it:", plan.onlyOnBase.map(safe2));
40793
- printSection("Deleted in your clone: kept on the case; push with --prune to remove it:", plan.keptOnBase.map(safe2));
41309
+ printSection("Changed on the case since your last pull: left as is; pull to take it:", plan.changedOnBase.map(safe3));
41310
+ printSection("Deleted on the case since your last pull, or no longer readable here: left as is; pull to remove your copy:", plan.deletedOnBase.map(safe3));
41311
+ printSection("On the case, not in your clone: left as is; pull to fetch it:", plan.onlyOnBase.map(safe3));
41312
+ printSection("Deleted in your clone: kept on the case; push with --prune to remove it:", plan.keptOnBase.map(safe3));
40794
41313
  printSection("Left out: not pushed from this clone:", leftOut);
40795
41314
  printSection("Conflicts: not pushed:", plan.conflicts.map((c) => conflictLine(c, PUSH_CONFLICT2)));
40796
41315
  if (!opts.confidential) console.log(`
@@ -40826,9 +41345,9 @@ ${CONFIDENTIAL_NOTICE}`);
40826
41345
  entries.push({ path: step.rel, type: "file", expect_sha: step.ifMatch, sha: null });
40827
41346
  continue;
40828
41347
  }
40829
- const bytes = readFileNoFollow(root, path47.join(root, ...step.rel.split("/")));
41348
+ const bytes = readFileNoFollow(root, path48.join(root, ...step.rel.split("/")));
40830
41349
  if (!bytes || computeHash(bytes) !== step.local.content_sha256) {
40831
- throw expected(`${safe2(step.rel)} changed while the push ran. Nothing was pushed; push again.`);
41350
+ throw expected(`${safe3(step.rel)} changed while the push ran. Nothing was pushed; push again.`);
40832
41351
  }
40833
41352
  parts.set(step.local.content_sha256, bytes);
40834
41353
  entries.push({ path: step.rel, type: "file", expect_sha: step.op === "update" ? step.ifMatch : null, sha: step.local.content_sha256 });
@@ -40848,7 +41367,7 @@ ${CONFIDENTIAL_NOTICE}`);
40848
41367
  }
40849
41368
  writeCloneRecord(root, next);
40850
41369
  console.log(`
40851
- Pushed revision ${saved.revision_id}: ${entries.length} change${entries.length === 1 ? "" : "s"} to case ${safe2(record.code)}.`);
41370
+ Pushed revision ${saved.revision_id}: ${entries.length} change${entries.length === 1 ? "" : "s"} to case ${safe3(record.code)}.`);
40852
41371
  }
40853
41372
  async function caseLog(selector, opts) {
40854
41373
  const limit = opts.limit ?? LOG_DEFAULT;
@@ -40863,7 +41382,7 @@ async function caseLog(selector, opts) {
40863
41382
  for (let page = 0; page < MAX_LOG_PAGES && shown3.length < limit; page++) {
40864
41383
  const { revisions, next_cursor } = (await calls.run(() => session.api.listCaseRevisions(session.connection, { cursor, limit: CASE_REVISIONS_PAGE_MAX }))).data;
40865
41384
  for (const revision of revisions) {
40866
- const entries = opts.confidential ? revision.entries : revision.entries.filter((e) => !e.confidential && !isConfPath(e.path));
41385
+ const entries = shownEntries(revision, opts.confidential);
40867
41386
  if (entries.length === 0) continue;
40868
41387
  if (shown3.length === limit) {
40869
41388
  more = true;
@@ -40879,21 +41398,21 @@ async function caseLog(selector, opts) {
40879
41398
  console.log(JSON.stringify({ revisions: shown3, more }, null, 2));
40880
41399
  return;
40881
41400
  }
40882
- if (shown3.length === 0) console.log(`Case ${safe2(detail.code)} has no revision you read here.`);
41401
+ if (shown3.length === 0) console.log(`Case ${safe3(detail.code)} has no revision you read here.`);
40883
41402
  for (const r of shown3) {
40884
- const author = r.author?.display_name ? one2(r.author.display_name) : "a person no longer named";
41403
+ const author = r.author?.display_name ? one3(r.author.display_name) : "a person no longer named";
40885
41404
  console.log(`revision ${r.revision_id} ${r.created_at} ${author} (${r.channel})`);
40886
- if (r.message !== null) console.log(` ${one2(r.message)}`);
41405
+ if (r.message !== null) console.log(` ${one3(r.message)}`);
40887
41406
  else console.log(hideMessages ? " (message not shown without --confidential)" : " (message hidden)");
40888
- if (r.session) console.log(` session: ${one2(r.session)}`);
40889
- for (const e of r.entries) console.log(` ${safe2(e.path)}${e.sha === null ? " (removed)" : ""}`);
41407
+ if (r.session) console.log(` session: ${one3(r.session)}`);
41408
+ for (const e of r.entries) console.log(` ${safe3(e.path)}${e.sha === null ? " (removed)" : ""}`);
40890
41409
  }
40891
41410
  if (more && shown3.length > 0) console.log(`
40892
41411
  Older revisions follow: --limit ${Math.min(LOG_MAX, limit * 2)} shows more.`);
40893
41412
  if (!opts.confidential) console.log(`
40894
41413
  ${CONFIDENTIAL_NOTICE}`);
40895
41414
  }
40896
- var THEIRS_SUFFIX, MAX_LIST_PAGES2, LOG_DEFAULT, LOG_MAX, MAX_LOG_PAGES, PART_OVERHEAD_BYTES, CONFIDENTIAL_NOTICE, safe2, one2, CaseCalls, phaseFoldersOf, isConfPath, isTheirs, recordedFile, PULL_CONFLICT2, PUSH_CONFLICT2;
41415
+ var THEIRS_SUFFIX, MAX_LIST_PAGES2, LOG_DEFAULT, LOG_MAX, MAX_LOG_PAGES, PART_OVERHEAD_BYTES, CONFIDENTIAL_NOTICE, safe3, one3, CaseCalls, phaseFoldersOf, isTheirs, recordedFile, PULL_CONFLICT2, inRunOf, PUSH_CONFLICT2;
40897
41416
  var init_case_files2 = __esm({
40898
41417
  "src/cases/case-files.ts"() {
40899
41418
  "use strict";
@@ -40914,6 +41433,7 @@ var init_case_files2 = __esm({
40914
41433
  init_case_session();
40915
41434
  init_case_local_files();
40916
41435
  init_case_clone_record();
41436
+ init_case_mirror();
40917
41437
  THEIRS_SUFFIX = ".theirs";
40918
41438
  MAX_LIST_PAGES2 = 200;
40919
41439
  LOG_DEFAULT = 20;
@@ -40921,8 +41441,8 @@ var init_case_files2 = __esm({
40921
41441
  MAX_LOG_PAGES = 40;
40922
41442
  PART_OVERHEAD_BYTES = 512;
40923
41443
  CONFIDENTIAL_NOTICE = "Confidential files are left out unless you pass --confidential.";
40924
- safe2 = (text5) => sanitizeTerminalText(text5);
40925
- one2 = (text5) => sanitizeTerminalText(text5).replace(/\s*\n\s*/g, " ");
41444
+ safe3 = (text5) => sanitizeTerminalText(text5);
41445
+ one3 = (text5) => sanitizeTerminalText(text5).replace(/\s*\n\s*/g, " ");
40926
41446
  CaseCalls = class {
40927
41447
  constructor(session) {
40928
41448
  this.session = session;
@@ -40934,9 +41454,9 @@ var init_case_files2 = __esm({
40934
41454
  }
40935
41455
  pacer;
40936
41456
  /** One call, paced; `raw` lets the caller read the `ApiError` itself. */
40937
- async run(call2, raw = false) {
41457
+ async run(call3, raw = false) {
40938
41458
  try {
40939
- return await this.pacer.run(call2);
41459
+ return await this.pacer.run(call3);
40940
41460
  } catch (err) {
40941
41461
  throw raw ? err : caseCallFailure(err, this.session.connection);
40942
41462
  }
@@ -40970,7 +41490,6 @@ var init_case_files2 = __esm({
40970
41490
  }
40971
41491
  };
40972
41492
  phaseFoldersOf = (detail) => detail.phases.map((p) => p.folder);
40973
- isConfPath = (rel) => rel.split("/")[0] === "conf";
40974
41493
  isTheirs = (rel) => rel.toLowerCase().endsWith(THEIRS_SUFFIX);
40975
41494
  recordedFile = (f) => ({ sha: f.sha, confidential: f.confidential || isConfPath(f.path) });
40976
41495
  PULL_CONFLICT2 = {
@@ -40983,6 +41502,7 @@ var init_case_files2 = __esm({
40983
41502
  edited_while_pulling: "changed here while pulling: kept; pull again",
40984
41503
  unresolved: "the case's copy of a conflict, still beside your file: merge it into that file, then delete it"
40985
41504
  };
41505
+ inRunOf = (outside) => (rel) => !outside(rel) && !isTheirs(rel);
40986
41506
  PUSH_CONFLICT2 = {
40987
41507
  changed_on_base: "changed on the case since your last pull",
40988
41508
  deleted_on_base: "deleted on the case since your last pull, or no longer readable by this authorization",
@@ -40993,6 +41513,206 @@ var init_case_files2 = __esm({
40993
41513
  }
40994
41514
  });
40995
41515
 
41516
+ // src/cases/case-review.ts
41517
+ function reviewFailure(err, session) {
41518
+ if (err instanceof ApiError && err.status >= 400 && err.status < 500) {
41519
+ const code2 = session.connection.code;
41520
+ switch (extractApiErrorReason(err)) {
41521
+ case CASE_REVIEW_TOO_LARGE_REASON:
41522
+ return expected(`Case ${code2}'s review is larger than one review may read, so it cannot be computed.`);
41523
+ case CASE_REVIEW_PAIR_UNKNOWN_REASON:
41524
+ return expected(
41525
+ "The case's review holds no pair of those items with those hashes at that revision (a value not copied as the review printed it, or --confidential not as the review was read). Nothing was recorded. Run the command `wayai cases review` prints for the pair."
41526
+ );
41527
+ case CASE_REVIEW_CHAIN_STOPPED_REASON:
41528
+ return expected(`This pair's chain stopped after ${CASE_REVIEW_ROUNDS_MAX} rounds, so it takes no verdict. ${WEB_ONLY_NOTICE}`);
41529
+ case CASE_REVIEW_VERDICTS_FULL_REASON:
41530
+ return expected(`Case ${code2} holds as many verdicts as it may: nothing was recorded.`);
41531
+ case CASE_CLOSED_REASON:
41532
+ return expected(`Case ${code2} is closed: it takes no verdict.`);
41533
+ case "revision_unknown":
41534
+ return expected(`Case ${code2} has no revision of that id you may read. Read the review again: \`wayai cases review\`.`);
41535
+ case "reason_too_long":
41536
+ return expected("The reason is longer than the case takes.");
41537
+ }
41538
+ }
41539
+ return caseCallFailure(err, session.connection);
41540
+ }
41541
+ async function call2(session, run) {
41542
+ try {
41543
+ return await run();
41544
+ } catch (err) {
41545
+ throw reviewFailure(err, session);
41546
+ }
41547
+ }
41548
+ async function requireConfidential(session) {
41549
+ const detail = (await call2(session, () => session.api.getCase(session.connection))).data;
41550
+ if (!detail.access.capabilities.includes("read_confidential")) {
41551
+ throw expected(
41552
+ `This machine's authorization on case ${one4(detail.code)} does not hold the Confidential right, so --confidential reads nothing more. Run it without --confidential.`
41553
+ );
41554
+ }
41555
+ }
41556
+ function block(label3, text5, none) {
41557
+ if (text5 === null) {
41558
+ console.log(` ${label3}: ${none}`);
41559
+ return;
41560
+ }
41561
+ console.log(` ${label3}:`);
41562
+ for (const line of sanitizeTerminalText(text5).split("\n")) console.log(` | ${line}`);
41563
+ }
41564
+ function verdictCommand(connection, graph, pair) {
41565
+ return `wayai cases review verdict <${VERDICTS.join("|")}> ${one4(pair.source)} ${one4(pair.neighbor)} --revision ${one4(graph.revision_id ?? "")} --source-hash ${one4(pair.source_hash)} --neighbor-hash ${one4(pair.neighbor_hash)}${graph.confidential ? " --confidential" : ""} --case ${one4(connection.code)} --org ${one4(connection.org_id)} --space ${one4(connection.space_id)} --reason "<why>"`;
41566
+ }
41567
+ async function caseReview(session, opts) {
41568
+ if (opts.confidential) await requireConfidential(session);
41569
+ const graph = (await call2(session, () => session.api.getCaseReview(session.connection, opts.confidential))).data;
41570
+ if (graph.stopped.length > 0) process.exitCode = 1;
41571
+ if (opts.json) {
41572
+ console.log(JSON.stringify(graph, null, 2));
41573
+ return;
41574
+ }
41575
+ printReview(session.connection, graph);
41576
+ }
41577
+ function printReview(connection, graph) {
41578
+ const { code: code2 } = connection;
41579
+ const omitted = graph.warnings.some((w) => w.code === CASE_REVIEW_CONFIDENTIAL_OMITTED);
41580
+ const notice = () => {
41581
+ if (omitted) console.log("\nConfidential content is left out of this review unless you pass --confidential.");
41582
+ };
41583
+ if (graph.revision_id === null) {
41584
+ console.log(`Case ${code2} has no revision you read here: nothing to review.`);
41585
+ notice();
41586
+ return;
41587
+ }
41588
+ console.log(`Review of case ${code2} at revision ${one4(graph.revision_id)}${graph.confidential ? ", with confidential content" : ""}.`);
41589
+ console.log(graph.base_revision_id ? `Base: revision ${one4(graph.base_revision_id)}. Nothing you read here is pending.` : "Base: each item's own, below. Something you read here is pending.");
41590
+ const titles = new Map(graph.items.map((item) => [item.key, item.title]));
41591
+ if (graph.items.length) {
41592
+ console.log(`
41593
+ Changed items (${graph.items.length}):`);
41594
+ for (const item of graph.items) {
41595
+ console.log(` ${one4(item.key)}, "${one4(item.title)}" (${item.state}, round ${item.round}), in ${one4(item.path)}${item.base_revision_id ? `, since revision ${one4(item.base_revision_id)}` : ""}`);
41596
+ if (item.causes.length) console.log(` because: ${item.causes.map(one4).join("; ")}`);
41597
+ block("before", item.before, "not there at its base");
41598
+ block("now", item.text, "removed");
41599
+ }
41600
+ }
41601
+ if (graph.pairs.length) {
41602
+ console.log(`
41603
+ Pairs awaiting a verdict (${graph.pairs.length}):`);
41604
+ for (const pair of graph.pairs) {
41605
+ const source = titles.get(pair.source);
41606
+ console.log(` ${one4(pair.source)}${source ? ` "${one4(source)}"` : ""} \u2192 ${one4(pair.neighbor)} "${one4(pair.neighbor_title)}" (round ${pair.round} of ${CASE_REVIEW_ROUNDS_MAX}), in ${one4(pair.path)}`);
41607
+ if (pair.reasons.length) console.log(` connected: ${pair.reasons.map(one4).join("; ")}`);
41608
+ console.log(` ${verdictCommand(connection, graph, pair)}`);
41609
+ }
41610
+ }
41611
+ if (graph.waiting.length) {
41612
+ console.log(`
41613
+ Waiting for a change (${graph.waiting.length}):`);
41614
+ for (const w of graph.waiting) {
41615
+ console.log(` ${one4(w.source)} \u2192 ${one4(w.neighbor)} (round ${w.round}): needs a change: ${one4(w.reason)}`);
41616
+ console.log(` waits until ${one4(w.neighbor)} changes`);
41617
+ }
41618
+ }
41619
+ if (graph.stopped.length) {
41620
+ console.log(`
41621
+ Stopped chains (${graph.stopped.length}): each took more than ${CASE_REVIEW_ROUNDS_MAX} rounds, so it takes no verdict.`);
41622
+ for (const s of graph.stopped) {
41623
+ const waiting = s.waiting_sources.length ? `; waiting on it: ${s.waiting_sources.map(one4).join(", ")}` : "";
41624
+ console.log(` ${one4(s.key)}, "${one4(s.title)}" (round ${s.round})${s.base_revision_id ? `, since revision ${one4(s.base_revision_id)}` : ""}${waiting}`);
41625
+ }
41626
+ console.log(` ${WEB_ONLY_NOTICE}`);
41627
+ }
41628
+ const warnings = graph.warnings.filter((w) => w.code !== CASE_REVIEW_CONFIDENTIAL_OMITTED);
41629
+ if (warnings.length) {
41630
+ console.log(`
41631
+ For a person to look at (${warnings.length}):`);
41632
+ for (const w of warnings) {
41633
+ const where = [w.path && one4(w.path), w.subject && one4(w.subject)].filter(Boolean).join(": ");
41634
+ console.log(` ${WARNINGS[w.code] ?? one4(w.code)}${where ? ` [${where}]` : ""}`);
41635
+ }
41636
+ }
41637
+ if (!graph.items.length && !graph.pairs.length && !graph.waiting.length && !graph.stopped.length) console.log("Nothing awaits review.");
41638
+ notice();
41639
+ }
41640
+ function verdictBody(opts) {
41641
+ if (!VERDICTS.includes(opts.verdict)) {
41642
+ throw expected(opts.verdict === "keep" ? `Keep is a person's, in the WayAI web app: this CLI records ${VERDICTS.join(" or ")}.` : `A verdict is ${VERDICTS.join(" or ")}.`);
41643
+ }
41644
+ if (opts.markConfidential && !opts.confidential) {
41645
+ throw expected("--mark-confidential is taken only with --confidential, on a pair read with it.");
41646
+ }
41647
+ const parsed = recordCaseItemReviewBody.safeParse({
41648
+ verdict: opts.verdict,
41649
+ source: opts.source,
41650
+ neighbor: opts.neighbor,
41651
+ revision_id: opts.revision,
41652
+ source_hash: opts.sourceHash,
41653
+ neighbor_hash: opts.neighborHash,
41654
+ reason: opts.reason,
41655
+ mark_confidential: opts.markConfidential,
41656
+ confidential: opts.confidential
41657
+ });
41658
+ if (parsed.success) return parsed.data;
41659
+ const issue = parsed.error.issues[0];
41660
+ if (issue?.path[0] === "reason" && issue.code === "too_big") {
41661
+ throw expected(`--reason is longer than ${CASE_REVIEW_REASON_MAX_LENGTH} characters: shorten it.`);
41662
+ }
41663
+ const FIELDS = {
41664
+ source: "<source> is an item as the review names it: {phase folder}/{code}",
41665
+ neighbor: "<neighbor> is an item as the review names it: {phase folder}/{code}",
41666
+ revision_id: "--revision takes the revision the review was read at, as `wayai cases review` prints it",
41667
+ source_hash: "--source-hash takes the source's hash, as `wayai cases review` prints it",
41668
+ neighbor_hash: "--neighbor-hash takes the neighbor's hash, as `wayai cases review` prints it",
41669
+ reason: "--reason takes why, in words: it is required, and cannot be empty"
41670
+ };
41671
+ const field = String(issue?.path[0] ?? "");
41672
+ throw expected(FIELDS[field] ?? `The verdict is refused: ${issue?.message ?? "not of its shape"}.`);
41673
+ }
41674
+ async function caseReviewVerdict(session, body, opts) {
41675
+ if (body.confidential) await requireConfidential(session);
41676
+ const review = (await call2(session, () => session.api.recordCaseItemReview(session.connection, body))).data;
41677
+ if (opts.json) {
41678
+ console.log(JSON.stringify(review, null, 2));
41679
+ return;
41680
+ }
41681
+ console.log(`Recorded ${review.verdict === "needs_change" ? "needs change" : review.verdict} on ${one4(review.source)} \u2192 ${one4(review.neighbor)}, round ${review.round} of ${CASE_REVIEW_ROUNDS_MAX}${review.confidential ? ", confidential" : ""}: ${review.review_id}`);
41682
+ if (review.verdict === "needs_change") {
41683
+ console.log(`The pair waits until ${one4(review.neighbor)} changes: change it, push, then read the review again.`);
41684
+ }
41685
+ }
41686
+ var VERDICTS, WEB_ONLY_NOTICE, one4, WARNINGS;
41687
+ var init_case_review2 = __esm({
41688
+ "src/cases/case-review.ts"() {
41689
+ "use strict";
41690
+ init_api_client();
41691
+ init_errors3();
41692
+ init_expected();
41693
+ init_terminal_output();
41694
+ init_case_session();
41695
+ init_case_records();
41696
+ init_case_review();
41697
+ VERDICTS = recordCaseItemReviewBody.shape.verdict.options;
41698
+ WEB_ONLY_NOTICE = "Keep and accepting a stopped chain are a person's, in the WayAI web app (the phase page's review): this CLI offers neither.";
41699
+ one4 = (value) => sanitizeTerminalText(value).replace(/\s*\n\s*/g, " ");
41700
+ WARNINGS = {
41701
+ outside_item: "text outside any item",
41702
+ new_document_outside_item: "a new document with text outside any item",
41703
+ front_matter_changed: "its header changed",
41704
+ document_removed: "a document was removed",
41705
+ title_changed: "a title changed",
41706
+ item_unknown: "it cites an item no document holds",
41707
+ documents_unreadable: "documents that could not be read",
41708
+ piece_changed: "a file piece changed",
41709
+ csv_unreadable: "a CSV that could not be read",
41710
+ name_without_item: "a CSV name no item cites",
41711
+ [CASE_REVIEW_CONFIDENTIAL_OMITTED]: "confidential content was left out"
41712
+ };
41713
+ }
41714
+ });
41715
+
40996
41716
  // src/commands/cases.ts
40997
41717
  var cases_exports = {};
40998
41718
  __export(cases_exports, {
@@ -41002,8 +41722,8 @@ __export(cases_exports, {
41002
41722
  waitForPickup: () => waitForPickup,
41003
41723
  webOrigin: () => webOrigin
41004
41724
  });
41005
- import * as crypto4 from "crypto";
41006
- import * as os4 from "os";
41725
+ import * as crypto5 from "crypto";
41726
+ import * as os5 from "os";
41007
41727
  import { parseArgs as parseArgs26 } from "util";
41008
41728
  function usageError4(message) {
41009
41729
  return expected(`${message}
@@ -41024,9 +41744,10 @@ async function casesCommand(args2) {
41024
41744
  const { values, positionals } = parsed;
41025
41745
  const [sub, ...rest] = positionals;
41026
41746
  if (sub === void 0) throw usageError4("No subcommand given.");
41027
- const twoWords = sub === "note" && rest[0] === "done" || sub === "received" && rest[0] === "add";
41747
+ const twoWords = sub === "note" && rest[0] === "done" || sub === "received" && rest[0] === "add" || sub === "review" && rest[0] === "verdict";
41028
41748
  const name = twoWords ? `${sub} ${rest[0]}` : sub;
41029
41749
  const operands = twoWords ? rest.slice(1) : rest;
41750
+ if (sub === "review" && (rest[0] === "keep" || rest[0] === "accept")) throw expected(WEB_ONLY_NOTICE);
41030
41751
  const admitted = ADMITS[name];
41031
41752
  if (!admitted) throw usageError4(`Unknown subcommand ${JSON.stringify(sanitizeTerminalText(name))}.`);
41032
41753
  const extra = Object.keys(values).filter((key) => values[key] !== void 0 && !admitted.includes(key));
@@ -41041,24 +41762,24 @@ async function casesCommand(args2) {
41041
41762
  return disconnect(operands[0], { org: values.org, space: values.space });
41042
41763
  }
41043
41764
  const selector = { case: values.case, org: values.org, space: values.space };
41044
- const json = values.json === true;
41765
+ const json2 = values.json === true;
41045
41766
  const takesNone = () => {
41046
41767
  if (operands.length) throw usageError4(`${name} takes no argument.`);
41047
41768
  };
41048
41769
  switch (name) {
41049
41770
  case "brief":
41050
41771
  takesNone();
41051
- return caseBrief(await openCaseSession(selector), { json });
41772
+ return caseBrief(await openCaseSession(selector), { json: json2 });
41052
41773
  case "next":
41053
41774
  takesNone();
41054
- return caseNext(await openCaseSession(selector), { json });
41775
+ return caseNext(await openCaseSession(selector), { json: json2 });
41055
41776
  case "explain":
41056
41777
  takesNone();
41057
- return caseExplain(await openCaseSession(selector), { json, phase: values.phase });
41778
+ return caseExplain(await openCaseSession(selector), { json: json2, phase: values.phase });
41058
41779
  case "check":
41059
41780
  takesNone();
41060
41781
  if (values.phase === void 0) throw usageError4("check takes --phase <folder>.");
41061
- return caseCheck(await openCaseSession(selector), { json, phase: values.phase, output: values.output });
41782
+ return caseCheck(await openCaseSession(selector), { json: json2, phase: values.phase, output: values.output });
41062
41783
  case "decisions": {
41063
41784
  takesNone();
41064
41785
  const session = await openCaseSession(selector);
@@ -41069,9 +41790,15 @@ async function casesCommand(args2) {
41069
41790
  case "clone":
41070
41791
  takesNone();
41071
41792
  return caseClone(selector, { dir: values.dir, confidential: values.confidential === true });
41072
- case "pull":
41793
+ case "pull": {
41073
41794
  takesNone();
41074
- return casePull({ dir: values.dir, overwrite: values.overwrite === true, yes: values.yes === true, confidential: values.confidential === true });
41795
+ const confidential = values.confidential === true;
41796
+ if (values["mirror-only"] === true) {
41797
+ if (values.overwrite !== void 0 || values.yes !== void 0) throw usageError4("pull --mirror-only writes no file of the case: it takes neither --overwrite nor --yes.");
41798
+ return casePullMirror({ dir: values.dir, confidential });
41799
+ }
41800
+ return casePull({ dir: values.dir, overwrite: values.overwrite === true, yes: values.yes === true, confidential });
41801
+ }
41075
41802
  case "push":
41076
41803
  takesNone();
41077
41804
  if (values.message === void 0 && values["dry-run"] !== true) throw usageError4('push takes a message: -m "<what this revision does>".');
@@ -41087,7 +41814,26 @@ async function casesCommand(args2) {
41087
41814
  takesNone();
41088
41815
  const limit = values.limit === void 0 ? void 0 : /^[0-9]+$/.test(values.limit) ? Number(values.limit) : NaN;
41089
41816
  if (limit !== void 0 && !(limit >= 1 && limit <= LOG_MAX)) throw usageError4(`--limit takes 1 to ${LOG_MAX}.`);
41090
- return caseLog(selector, { limit, json, confidential: values.confidential === true });
41817
+ return caseLog(selector, { limit, json: json2, confidential: values.confidential === true });
41818
+ }
41819
+ case "review":
41820
+ takesNone();
41821
+ return caseReview(await openCaseSession(selector), { json: json2, confidential: values.confidential === true });
41822
+ case "review verdict": {
41823
+ if (operands.length !== 3) throw usageError4("review verdict takes consistent|needs_change, then <source> and <neighbor>.");
41824
+ const [verdict, source, neighbor] = operands;
41825
+ const body = verdictBody({
41826
+ verdict,
41827
+ source,
41828
+ neighbor,
41829
+ reason: values.reason,
41830
+ revision: values.revision,
41831
+ sourceHash: values["source-hash"],
41832
+ neighborHash: values["neighbor-hash"],
41833
+ markConfidential: values["mark-confidential"] === true,
41834
+ confidential: values.confidential === true
41835
+ });
41836
+ return caseReviewVerdict(await openCaseSession(selector), body, { json: json2 });
41091
41837
  }
41092
41838
  case "note":
41093
41839
  if (operands.length !== 1) throw usageError4("note takes its text as one argument: quote it.");
@@ -41120,7 +41866,7 @@ function caseRef(orgId, spaceId, code2) {
41120
41866
  return parsed.data;
41121
41867
  }
41122
41868
  function machineLabel2(flag) {
41123
- const parsed = createCaseAgentRequestBody.shape.machine_label.safeParse(flag ?? os4.hostname().slice(0, CASE_AGENT_MACHINE_LABEL_MAX));
41869
+ const parsed = createCaseAgentRequestBody.shape.machine_label.safeParse(flag ?? os5.hostname().slice(0, CASE_AGENT_MACHINE_LABEL_MAX));
41124
41870
  if (parsed.success) return parsed.data;
41125
41871
  if (flag === void 0) throw usageError4("This machine's hostname cannot name it at approval: pass --label <machine>.");
41126
41872
  throw usageError4(`--label takes 1 to ${CASE_AGENT_MACHINE_LABEL_MAX} characters, none of them a control character.`);
@@ -41138,13 +41884,13 @@ function webOrigin(apiUrl) {
41138
41884
  else return null;
41139
41885
  return `${url.protocol}//${host}${url.port ? `:${url.port}` : ""}`;
41140
41886
  }
41141
- function webLocation(apiUrl, path50) {
41887
+ function webLocation(apiUrl, path51) {
41142
41888
  const origin = webOrigin(apiUrl);
41143
- return origin ? `${origin}${path50}` : `${path50} (in the WayAI web app)`;
41889
+ return origin ? `${origin}${path51}` : `${path51} (in the WayAI web app)`;
41144
41890
  }
41145
41891
  function pickupSecret() {
41146
- const bytes = crypto4.randomBytes(32);
41147
- return { secret: bytes.toString("hex"), challenge: crypto4.createHash("sha256").update(bytes).digest("hex") };
41892
+ const bytes = crypto5.randomBytes(32);
41893
+ return { secret: bytes.toString("hex"), challenge: crypto5.createHash("sha256").update(bytes).digest("hex") };
41148
41894
  }
41149
41895
  function connectFailure(err, stage) {
41150
41896
  if (!(err instanceof ApiError)) return err;
@@ -41296,6 +42042,7 @@ var init_cases = __esm({
41296
42042
  "use strict";
41297
42043
  init_case_agents();
41298
42044
  init_case_records();
42045
+ init_case_review();
41299
42046
  init_api_client();
41300
42047
  init_auth();
41301
42048
  init_errors3();
@@ -41307,6 +42054,8 @@ var init_cases = __esm({
41307
42054
  init_case_session();
41308
42055
  init_case_work();
41309
42056
  init_case_files2();
42057
+ init_case_mirror();
42058
+ init_case_review2();
41310
42059
  init_case_clone_record();
41311
42060
  init_case_tokens();
41312
42061
  PICKUP_POLL_INTERVAL_MS = 5e3;
@@ -41319,10 +42068,17 @@ Usage:
41319
42068
 
41320
42069
  wayai cases clone [--dir <folder>] [--confidential]
41321
42070
  wayai cases pull [--dir <clone>] [--overwrite] [--yes] [--confidential]
42071
+ wayai cases pull --mirror-only [--dir <clone>] [--confidential]
41322
42072
  wayai cases push -m "<message>" [--session <tag>] [--prune] [--dry-run]
41323
42073
  [--dir <clone>] [--confidential]
41324
42074
  wayai cases log [--limit <n>] [--json] [--confidential]
41325
42075
 
42076
+ wayai cases review [--json] [--confidential]
42077
+ wayai cases review verdict consistent|needs_change <source> <neighbor>
42078
+ --reason "<why>" --revision <revision_id>
42079
+ --source-hash <hash> --neighbor-hash <hash>
42080
+ [--confidential [--mark-confidential]] [--json]
42081
+
41326
42082
  wayai cases brief [--json]
41327
42083
  wayai cases next [--json]
41328
42084
  wayai cases explain [--phase <folder>] [--json]
@@ -41350,7 +42106,8 @@ when codes repeat).
41350
42106
  clone Make a folder bound to the case (--dir, default ./<code>) and
41351
42107
  write the case's files into it: its phase folders, analysis/,
41352
42108
  conf/ and instructions/case/. Nothing else in the folder is read
41353
- or written.
42109
+ or written, but the mirror. It prints the session-start hook to
42110
+ add to your agent.
41354
42111
  pull Bring the clone up to date, keeping your local changes. A file
41355
42112
  changed on both sides keeps yours, and the case's copy lands
41356
42113
  beside it as <path>.theirs: merge it, then delete it. Pull exits 1
@@ -41358,6 +42115,13 @@ pull Bring the clone up to date, keeping your local changes. A file
41358
42115
  with --confidential). --overwrite takes the case's copies
41359
42116
  over your changes and removes those copies, after asking (--yes
41360
42117
  agrees without a terminal).
42118
+ Clone and every pull then rewrite the clone's read-only mirror,
42119
+ ${CASE_MIRROR_DIR}/: the case, its status, evidence, agenda and
42120
+ deliveries of the phases under way, and what changed since the
42121
+ last pull. Push never sends it; an edit there is lost.
42122
+ --mirror-only rewrites the mirror alone, leaving your files as
42123
+ they are: the session-start hook runs it, never with
42124
+ --confidential.
41361
42125
  push Send the clone's changes as one revision, all of it or none. Each
41362
42126
  file is checked against the copy you last pulled: if the case
41363
42127
  changed since, nothing is pushed and nothing here changes; pull
@@ -41365,6 +42129,21 @@ push Send the clone's changes as one revision, all of it or none. Each
41365
42129
  --prune. --dry-run shows what would be sent. A symlink is never
41366
42130
  followed: one in the clone refuses the push.
41367
42131
  log The case's revisions, newest first (--limit, default 20).
42132
+ review Graph review, as WayAI computes it over the case's files: each item
42133
+ changed, removed or affected since its base (its text before and
42134
+ now), each pair of it and a connected item awaiting a verdict, the
42135
+ pairs waiting for a change, and the stopped chains. Each pair
42136
+ prints the exact \`review verdict\` command that records a verdict
42137
+ on it. Exits 1 when a chain stopped: past ${CASE_REVIEW_ROUNDS_MAX} rounds it takes no
42138
+ verdict until a person accepts it, in the web app.
42139
+ review verdict Record consistent or needs_change on one pair, with a reason,
42140
+ naming the revision and hashes the review printed, so it holds
42141
+ for the text you read: if the case changed since, the changed
42142
+ pair awaits a verdict again in the next review. WayAI counts
42143
+ the round. --mark-confidential (with --confidential) lets
42144
+ only holders of the Confidential right read it. Keeping an item
42145
+ and accepting a stopped chain are a person's, in the web app:
42146
+ this CLI offers neither.
41368
42147
  brief The case at a glance: status, phases under way, deadlines, open
41369
42148
  tasks, open pending items and next steps.
41370
42149
  next What to do next on the phases under way, then what waits on
@@ -41386,7 +42165,8 @@ received add Register a document a party sent, in one phase, with its
41386
42165
  confidential, if the case lets you write one.
41387
42166
 
41388
42167
  Confidential content is never asked for unless you pass --confidential:
41389
- without it, clone, pull, push and log leave every confidential file alone.
42168
+ without it, clone, pull, push and log leave every confidential file alone,
42169
+ and review and the mirror leave out confidential content.
41390
42170
  The case's agents page in the web app shows the exact connect command.
41391
42171
  After connecting, this machine still holds your \`wayai login\`:
41392
42172
  \`wayai logout\` is the recommended next step, and the case token does not
@@ -41414,7 +42194,13 @@ need it.
41414
42194
  "dry-run": { type: "boolean" },
41415
42195
  message: { type: "string", short: "m" },
41416
42196
  session: { type: "string" },
41417
- limit: { type: "string" }
42197
+ limit: { type: "string" },
42198
+ reason: { type: "string" },
42199
+ revision: { type: "string" },
42200
+ "source-hash": { type: "string" },
42201
+ "neighbor-hash": { type: "string" },
42202
+ "mark-confidential": { type: "boolean" },
42203
+ "mirror-only": { type: "boolean" }
41418
42204
  };
41419
42205
  SELECT = ["case", "org", "space"];
41420
42206
  ADMITS = {
@@ -41430,9 +42216,11 @@ need it.
41430
42216
  "received add": [...SELECT, "text", "phase", "type", "title", "confidential"],
41431
42217
  clone: [...SELECT, "dir", "confidential"],
41432
42218
  // A clone names its case: pull and push take the clone (--dir), never a case.
41433
- pull: ["dir", "overwrite", "yes", "confidential"],
42219
+ pull: ["dir", "overwrite", "yes", "confidential", "mirror-only"],
41434
42220
  push: ["dir", "message", "session", "prune", "dry-run", "confidential"],
41435
- log: [...SELECT, "limit", "json", "confidential"]
42221
+ log: [...SELECT, "limit", "json", "confidential"],
42222
+ review: [...SELECT, "json", "confidential"],
42223
+ "review verdict": [...SELECT, "reason", "revision", "source-hash", "neighbor-hash", "mark-confidential", "confidential", "json"]
41436
42224
  };
41437
42225
  casePagePath = (ref) => `/cases/${ref.org_id}/${ref.space_id}/${ref.code}`;
41438
42226
  delay2 = (ms) => new Promise((resolve16) => setTimeout(resolve16, ms));
@@ -41974,8 +42762,8 @@ refresh-preview: make the knowledge base's preview hold its production base's fi
41974
42762
  });
41975
42763
 
41976
42764
  // src/lib/file-map.ts
41977
- import * as fs36 from "fs";
41978
- import * as path48 from "path";
42765
+ import * as fs37 from "fs";
42766
+ import * as path49 from "path";
41979
42767
  function isSafeRelPath(rel) {
41980
42768
  if (rel.length === 0 || rel.length > 300) return false;
41981
42769
  if (rel.startsWith("/") || rel.includes("\\")) return false;
@@ -41990,9 +42778,9 @@ function writeFileMap(targetDir, files) {
41990
42778
  if (!isSafeRelPath(rel)) {
41991
42779
  throw new Error(`Refusing to write unsafe path: ${rel}`);
41992
42780
  }
41993
- const abs = path48.join(targetDir, rel);
41994
- fs36.mkdirSync(path48.dirname(abs), { recursive: true });
41995
- fs36.writeFileSync(abs, body, "utf-8");
42781
+ const abs = path49.join(targetDir, rel);
42782
+ fs37.mkdirSync(path49.dirname(abs), { recursive: true });
42783
+ fs37.writeFileSync(abs, body, "utf-8");
41996
42784
  written.push(rel);
41997
42785
  }
41998
42786
  return written;
@@ -42082,8 +42870,8 @@ var admin_exports = {};
42082
42870
  __export(admin_exports, {
42083
42871
  adminCommand: () => adminCommand
42084
42872
  });
42085
- import * as fs37 from "fs";
42086
- import * as path49 from "path";
42873
+ import * as fs38 from "fs";
42874
+ import * as path50 from "path";
42087
42875
  async function adminCommand(args2) {
42088
42876
  const [group, ...afterGroup] = args2;
42089
42877
  if (!group) {
@@ -42724,13 +43512,13 @@ async function runSkillInstall(positional) {
42724
43512
  throw err;
42725
43513
  }
42726
43514
  const root = findGitRoot() ?? process.cwd();
42727
- const present = HARNESS_SKILL_DIRS.filter((dir) => fs37.existsSync(path49.join(root, dir)));
43515
+ const present = HARNESS_SKILL_DIRS.filter((dir) => fs38.existsSync(path50.join(root, dir)));
42728
43516
  const targets = present.length > 0 ? present : HARNESS_SKILL_DIRS;
42729
43517
  const fileCount = Object.keys(res.files).length;
42730
43518
  const relDirs = targets.map((harness) => {
42731
- const targetDir = path49.join(root, harness, "skills", name);
43519
+ const targetDir = path50.join(root, harness, "skills", name);
42732
43520
  writeFileMap(targetDir, res.files);
42733
- return `${path49.relative(root, targetDir)}/`;
43521
+ return `${path50.relative(root, targetDir)}/`;
42734
43522
  });
42735
43523
  console.log(`Installed skill "${name}" (${fileCount} file${fileCount === 1 ? "" : "s"}) \u2192 ${relDirs.join(", ")}`);
42736
43524
  console.log("Reload your agent (e.g. restart Claude Code) to pick up the skill.");
@@ -44978,12 +45766,12 @@ async function reportEditCommand(args2) {
44978
45766
  }
44979
45767
  async function reportListCommand(args2) {
44980
45768
  const status = flagValue2(args2, "--status");
44981
- const json = args2.includes("--json");
45769
+ const json2 = args2.includes("--json");
44982
45770
  const { config, accessToken } = await requireAuth();
44983
45771
  const client = new ApiClient({ apiUrl: config.api_url, accessToken });
44984
45772
  try {
44985
45773
  const result = await client.listMyReports(status);
44986
- if (json) {
45774
+ if (json2) {
44987
45775
  console.log(JSON.stringify(result, null, 2));
44988
45776
  return;
44989
45777
  }
@@ -45001,7 +45789,7 @@ async function reportListCommand(args2) {
45001
45789
  }
45002
45790
  async function reportGetCommand(args2) {
45003
45791
  const reportId = args2.find((a) => !a.startsWith("--"));
45004
- const json = args2.includes("--json");
45792
+ const json2 = args2.includes("--json");
45005
45793
  if (!reportId) {
45006
45794
  console.error("Usage: wayai report get <report_id> [--json]");
45007
45795
  process.exit(1);
@@ -45010,7 +45798,7 @@ async function reportGetCommand(args2) {
45010
45798
  const client = new ApiClient({ apiUrl: config.api_url, accessToken });
45011
45799
  try {
45012
45800
  const result = await client.getMyReport(reportId);
45013
- if (json) {
45801
+ if (json2) {
45014
45802
  console.log(JSON.stringify(result, null, 2));
45015
45803
  return;
45016
45804
  }
@@ -45213,7 +46001,7 @@ var init_actions = __esm({
45213
46001
 
45214
46002
  // src/data/commands/attachments.ts
45215
46003
  import { Command as Command3 } from "commander";
45216
- import { readFileSync as readFileSync21 } from "fs";
46004
+ import { readFileSync as readFileSync22 } from "fs";
45217
46005
  function findAttachmentByFilename(attachments, filename) {
45218
46006
  return attachments.find((a) => a.key.endsWith(`/${filename}`)) ?? null;
45219
46007
  }
@@ -45254,7 +46042,7 @@ function buildAttachmentsCommand() {
45254
46042
  printOutput(data, outputFormat(this));
45255
46043
  return;
45256
46044
  }
45257
- const body = readFileSync21(opts.file);
46045
+ const body = readFileSync22(opts.file);
45258
46046
  await client.upload(uploadPathFrom(data?.upload_url), body, opts.contentType);
45259
46047
  printOutput({ ...data, uploaded: true }, outputFormat(this));
45260
46048
  });
@@ -45671,7 +46459,7 @@ var init_import = __esm({
45671
46459
 
45672
46460
  // src/data/commands/providers.ts
45673
46461
  import { Command as Command6 } from "commander";
45674
- import { writeFileSync as writeFileSync12 } from "fs";
46462
+ import { writeFileSync as writeFileSync13 } from "fs";
45675
46463
  function providerSegment(provider) {
45676
46464
  if (!VALID_PROVIDERS.includes(provider)) {
45677
46465
  throw expected(`Unknown provider ${JSON.stringify(provider)}. Expected one of: ${VALID_PROVIDERS_HELP}.`);
@@ -45704,7 +46492,7 @@ function buildBasesProvidersCommand() {
45704
46492
  );
45705
46493
  if (opts.to) {
45706
46494
  try {
45707
- writeFileSync12(opts.to, JSON.stringify(data, null, 2));
46495
+ writeFileSync13(opts.to, JSON.stringify(data, null, 2));
45708
46496
  } catch (e) {
45709
46497
  throw expected(`--to ${opts.to}: ${e instanceof Error ? e.message : "could not be written"}`);
45710
46498
  }
@@ -45825,7 +46613,7 @@ var init_credentials = __esm({
45825
46613
 
45826
46614
  // src/data/commands/sql.ts
45827
46615
  import { Command as Command8 } from "commander";
45828
- import { readFileSync as readFileSync22 } from "fs";
46616
+ import { readFileSync as readFileSync23 } from "fs";
45829
46617
  function buildBasesSqlCommand() {
45830
46618
  return withBaseOption(new Command8("sql")).description("Execute a read-only SQL query against base data").argument("[query]", "SQL query (SELECT only)").option("--file <path>", "Read SQL from a file instead of the argument").option(
45831
46619
  "--param <kv...>",
@@ -45835,7 +46623,7 @@ function buildBasesSqlCommand() {
45835
46623
  let query;
45836
46624
  if (opts.file) {
45837
46625
  try {
45838
- query = readFileSync22(opts.file, "utf-8").trim();
46626
+ query = readFileSync23(opts.file, "utf-8").trim();
45839
46627
  } catch (e) {
45840
46628
  throw expected(`--file ${opts.file}: ${e instanceof Error ? e.message : "could not be read"}`);
45841
46629
  }
@@ -45995,16 +46783,16 @@ MCP URL: ${toolsetMcpUrl(slug)}`);
45995
46783
  ).option("--force", "Revoke even if the token appears to be in live use").action(async function(tokenId, opts) {
45996
46784
  const client = await createDataClient();
45997
46785
  const id = pathSegment(tokenId, "token id");
45998
- const path50 = (force) => `/v1/tokens/${id}${force ? "?force=true" : ""}`;
46786
+ const path51 = (force) => `/v1/tokens/${id}${force ? "?force=true" : ""}`;
45999
46787
  const format = outputFormat(this);
46000
46788
  const revoked = (forced) => printOutput({ token_id: tokenId, revoked: true, forced }, format);
46001
46789
  if (opts.force) {
46002
- await client.request("DELETE", path50(true));
46790
+ await client.request("DELETE", path51(true));
46003
46791
  revoked(true);
46004
46792
  return;
46005
46793
  }
46006
46794
  try {
46007
- await client.request("DELETE", path50(false));
46795
+ await client.request("DELETE", path51(false));
46008
46796
  revoked(false);
46009
46797
  } catch (err) {
46010
46798
  if (!(err instanceof ApiError) || err.status !== 409 || dataErrorDetails(err)?.requires_force !== true) {
@@ -46019,7 +46807,7 @@ MCP URL: ${toolsetMcpUrl(slug)}`);
46019
46807
  console.error("Aborted.");
46020
46808
  return process.exit(1);
46021
46809
  }
46022
- await client.request("DELETE", path50(true));
46810
+ await client.request("DELETE", path51(true));
46023
46811
  revoked(true);
46024
46812
  }
46025
46813
  });
@@ -46067,29 +46855,29 @@ MCP URL: ${toolsetMcpUrl(slug)}`);
46067
46855
  }
46068
46856
  }
46069
46857
  const format = outputFormat(this);
46070
- const json = format === "json";
46071
- const note = (line) => json ? console.error(line) : console.log(line);
46858
+ const json2 = format === "json";
46859
+ const note = (line) => json2 ? console.error(line) : console.log(line);
46072
46860
  const printPreview = () => {
46073
46861
  if (targets.length === 0) {
46074
46862
  note("Nothing to prune.");
46075
46863
  } else {
46076
46864
  note(`Would revoke ${targets.length} token(s):`);
46077
- if (!json) printOutput(targets, format);
46865
+ if (!json2) printOutput(targets, format);
46078
46866
  }
46079
46867
  if (skipped.length === 0) return;
46080
46868
  note(`
46081
46869
  Skipped ${skipped.length} stale token(s):`);
46082
- if (!json) printOutput(skipped, format);
46870
+ if (!json2) printOutput(skipped, format);
46083
46871
  };
46084
46872
  printPreview();
46085
46873
  if (targets.length === 0) {
46086
- if (json) printOutput({ revoked: 0, failed: 0, targets, skipped }, format);
46874
+ if (json2) printOutput({ revoked: 0, failed: 0, targets, skipped }, format);
46087
46875
  return;
46088
46876
  }
46089
46877
  if (!opts.yes) {
46090
46878
  if (!isInteractive()) {
46091
46879
  console.error("\nPreview only \u2014 re-run with --yes to revoke these tokens.");
46092
- if (json) printOutput({ preview: true, revoked: 0, failed: 0, targets, skipped }, format);
46880
+ if (json2) printOutput({ preview: true, revoked: 0, failed: 0, targets, skipped }, format);
46093
46881
  return process.exit(1);
46094
46882
  }
46095
46883
  if (!await confirm(`
@@ -46114,7 +46902,7 @@ Revoke ${targets.length} token(s)?`)) {
46114
46902
  );
46115
46903
  }
46116
46904
  }
46117
- if (json) printOutput({ revoked, failed, targets, skipped }, format);
46905
+ if (json2) printOutput({ revoked, failed, targets, skipped }, format);
46118
46906
  else console.log(`Revoked ${revoked} token(s)${failed > 0 ? `, ${failed} failed` : ""}.`);
46119
46907
  if (failed > 0) return process.exit(1);
46120
46908
  });
@@ -46171,9 +46959,9 @@ var init_base_tags = __esm({
46171
46959
 
46172
46960
  // src/data/commands/bases.ts
46173
46961
  import { Command as Command10 } from "commander";
46174
- function pageOf(path50, cursor) {
46175
- if (!cursor) return path50;
46176
- return `${path50}${path50.includes("?") ? "&" : "?"}cursor=${encodeURIComponent(cursor)}`;
46962
+ function pageOf(path51, cursor) {
46963
+ if (!cursor) return path51;
46964
+ return `${path51}${path51.includes("?") ? "&" : "?"}cursor=${encodeURIComponent(cursor)}`;
46177
46965
  }
46178
46966
  function parseEnum(flag, value, allowed) {
46179
46967
  if (value === void 0) return void 0;
@@ -46330,9 +47118,9 @@ function buildBasesCommand() {
46330
47118
  });
46331
47119
  bases.command("list-previews <origin-id>").description("List preview bases cloned from a base (production or preview)").action(async function(originId) {
46332
47120
  const client = await createDataClient();
46333
- const path50 = `/v1/${pathSegment(originId, "origin base id")}/previews`;
47121
+ const path51 = `/v1/${pathSegment(originId, "origin base id")}/previews`;
46334
47122
  printOutput(
46335
- await client.collectPages((cursor) => pageOf(path50, cursor)),
47123
+ await client.collectPages((cursor) => pageOf(path51, cursor)),
46336
47124
  outputFormat(this)
46337
47125
  );
46338
47126
  });
@@ -46371,9 +47159,9 @@ function buildBasesCommand() {
46371
47159
  });
46372
47160
  bases.command("promotions <production-id>").description("List promotion history for a production base").action(async function(productionId) {
46373
47161
  const client = await createDataClient();
46374
- const path50 = `/v1/${pathSegment(productionId, "production base id")}/promotions`;
47162
+ const path51 = `/v1/${pathSegment(productionId, "production base id")}/promotions`;
46375
47163
  printOutput(
46376
- await client.collectPages((cursor) => pageOf(path50, cursor)),
47164
+ await client.collectPages((cursor) => pageOf(path51, cursor)),
46377
47165
  outputFormat(this)
46378
47166
  );
46379
47167
  });
@@ -46514,7 +47302,7 @@ var init_file_types = __esm({
46514
47302
 
46515
47303
  // src/data/commands/files.ts
46516
47304
  import { Command as Command12 } from "commander";
46517
- import { readFileSync as readFileSync23, writeFileSync as writeFileSync13 } from "fs";
47305
+ import { readFileSync as readFileSync24, writeFileSync as writeFileSync14 } from "fs";
46518
47306
  import { basename as basename30 } from "path";
46519
47307
  function renderFileDiff(fileType, filePath3, from, to, d) {
46520
47308
  console.log(sanitizeTerminalText(`${fileType}/${filePath3}: v${from} \u2192 v${to}`));
@@ -46571,7 +47359,7 @@ function buildFilesCommand() {
46571
47359
  label: opts.label,
46572
47360
  metadata: opts.metadata === void 0 ? void 0 : parseData(opts.metadata, "--metadata")
46573
47361
  });
46574
- const body = readFileSync23(opts.file);
47362
+ const body = readFileSync24(opts.file);
46575
47363
  const client = await createDataClient();
46576
47364
  printOutput(
46577
47365
  await client.upload(
@@ -46603,7 +47391,7 @@ function buildFilesCommand() {
46603
47391
  const { bytes } = await client.download(
46604
47392
  `/v1/${base}/files/${pathSegment(fileType, "file_type")}/${encoded}${versionQs ? `?${versionQs}` : ""}`
46605
47393
  );
46606
- writeFileSync13(out, bytes);
47394
+ writeFileSync14(out, bytes);
46607
47395
  console.log(`Downloaded to ${out}`);
46608
47396
  });
46609
47397
  files.command("history <file_type> <path>").description("List the content versions of a file (newest first)").option("--limit <n>", "Max versions to return").option("--offset <n>", "Pagination offset").action(async function(fileType, filePath3, opts) {
@@ -46943,8 +47731,8 @@ function buildRecordsCommand() {
46943
47731
  const body = { data: parseData(opts.data) };
46944
47732
  if (opts.externalId) body.external_id = opts.externalId;
46945
47733
  if (opts.externalSource) body.external_source = opts.externalSource;
46946
- const path50 = opts.id ? `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${pathSegment(opts.id, "--id")}` : `/v1/${base}/records/${pathSegment(recordType2, "record_type")}`;
46947
- printOutput(await client.request("PUT", path50, body), outputFormat(this));
47734
+ const path51 = opts.id ? `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${pathSegment(opts.id, "--id")}` : `/v1/${base}/records/${pathSegment(recordType2, "record_type")}`;
47735
+ printOutput(await client.request("PUT", path51, body), outputFormat(this));
46948
47736
  });
46949
47737
  records.command("query <record_type>").description("List/search records: exact filters + fuzzy `search`, sorting, pagination").option(
46950
47738
  "--external-source <source>",
@@ -46979,9 +47767,9 @@ function buildRecordsCommand() {
46979
47767
  ).action(async function(recordType2, id, opts) {
46980
47768
  const base = pathSegment(requireBase(this), "--base");
46981
47769
  const client = await createDataClient();
46982
- let path50 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
46983
- if (opts.externalSource) path50 += `?external_source=${encodeURIComponent(opts.externalSource)}`;
46984
- printOutput(await client.request("GET", path50), outputFormat(this));
47770
+ let path51 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
47771
+ if (opts.externalSource) path51 += `?external_source=${encodeURIComponent(opts.externalSource)}`;
47772
+ printOutput(await client.request("GET", path51), outputFormat(this));
46985
47773
  });
46986
47774
  records.command("delete <record_type> <id>").description(
46987
47775
  "Delete a record by internal ID, or by external_id (pass --external-source to scope it)"
@@ -46995,11 +47783,11 @@ function buildRecordsCommand() {
46995
47783
  }
46996
47784
  const base = pathSegment(requireBase(this), "--base");
46997
47785
  const client = await createDataClient();
46998
- let path50 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
47786
+ let path51 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
46999
47787
  if (opts.externalSource) {
47000
- path50 += `?external_source=${encodeURIComponent(opts.externalSource)}&external_id=${encodeURIComponent(id)}`;
47788
+ path51 += `?external_source=${encodeURIComponent(opts.externalSource)}&external_id=${encodeURIComponent(id)}`;
47001
47789
  }
47002
- await client.request("DELETE", path50);
47790
+ await client.request("DELETE", path51);
47003
47791
  console.log("Deleted");
47004
47792
  });
47005
47793
  records.command("history <id>").description(
@@ -47164,8 +47952,8 @@ function buildRelationshipsCommand() {
47164
47952
  if (opts.data) body.data = parseData(opts.data);
47165
47953
  const base = pathSegment(requireBase(this), "--base");
47166
47954
  const client = await createDataClient();
47167
- const path50 = opts.id ? `/v1/${base}/relationships/${pathSegment(opts.id, "--id")}` : `/v1/${base}/relationships`;
47168
- printOutput(await client.request("PUT", path50, body), outputFormat(this));
47955
+ const path51 = opts.id ? `/v1/${base}/relationships/${pathSegment(opts.id, "--id")}` : `/v1/${base}/relationships`;
47956
+ printOutput(await client.request("PUT", path51, body), outputFormat(this));
47169
47957
  });
47170
47958
  relationships.command("get <id>").description(
47171
47959
  "Get a relationship by ID (or by its external key: pass the external_id with --rel-type)"
@@ -47398,8 +48186,8 @@ function buildToolsetsCommand() {
47398
48186
  toolsets.command("get <slug>").description("Get a toolset").option("--resolved", "Include resolved record_type schemas").action(async function(slug, opts) {
47399
48187
  const base = pathSegment(requireBase(this), "--base");
47400
48188
  const client = await createDataClient();
47401
- const path50 = opts.resolved ? `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}/resolved` : `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}`;
47402
- printOutput(await client.request("GET", path50), outputFormat(this));
48189
+ const path51 = opts.resolved ? `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}/resolved` : `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}`;
48190
+ printOutput(await client.request("GET", path51), outputFormat(this));
47403
48191
  });
47404
48192
  toolsets.command("list").description("List all toolsets").action(async function() {
47405
48193
  const base = pathSegment(requireBase(this), "--base");
@@ -47534,9 +48322,9 @@ init_errors3();
47534
48322
  init_mask_secrets();
47535
48323
  init_utils();
47536
48324
  init_registry();
47537
- import { readFileSync as readFileSync24 } from "fs";
48325
+ import { readFileSync as readFileSync25 } from "fs";
47538
48326
  import { fileURLToPath as fileURLToPath2 } from "url";
47539
- import { dirname as dirname20, join as join44 } from "path";
48327
+ import { dirname as dirname20, join as join45 } from "path";
47540
48328
 
47541
48329
  // src/lib/version-refresh.ts
47542
48330
  init_version_cache();
@@ -47692,7 +48480,7 @@ Run \`wayai admin skill install\` to update.`);
47692
48480
 
47693
48481
  // src/index.ts
47694
48482
  var __dirname = dirname20(fileURLToPath2(import.meta.url));
47695
- var pkg = JSON.parse(readFileSync24(join44(__dirname, "..", "package.json"), "utf-8"));
48483
+ var pkg = JSON.parse(readFileSync25(join45(__dirname, "..", "package.json"), "utf-8"));
47696
48484
  var [, , command, ...args] = process.argv;
47697
48485
  var isBackgroundRefresh = command === REFRESH_COMMAND;
47698
48486
  if (!isBackgroundRefresh) initSentry(command, pkg.version);