@wayai/cli 0.3.334 → 0.3.336

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
  }
@@ -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() {
@@ -4978,8 +4978,8 @@ function ensureRealSubdirNoSymlink(root, target, create) {
4978
4978
  const rel = path.relative(rootResolved, targetResolved);
4979
4979
  if (rel === "") return true;
4980
4980
  let cur = rootResolved;
4981
- for (const segment of rel.split(path.sep)) {
4982
- cur = path.join(cur, segment);
4981
+ for (const segment2 of rel.split(path.sep)) {
4982
+ cur = path.join(cur, segment2);
4983
4983
  let st;
4984
4984
  try {
4985
4985
  st = fs.lstatSync(cur);
@@ -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
  }
@@ -6433,28 +6436,28 @@ var init_chunk_5FO3GNKP = __esm({
6433
6436
  });
6434
6437
 
6435
6438
  // ../../packages/core/dist/chunk-7AYJHO5P.js
6436
- function matchPath(pattern, path50) {
6437
- const pathSegments2 = path50.replace(/\/$/, "").split("/");
6439
+ function matchPath(pattern, path51) {
6440
+ const pathSegments2 = path51.replace(/\/$/, "").split("/");
6438
6441
  const isPrefix = pattern.endsWith("/*");
6439
6442
  const patternSegments = (isPrefix ? pattern.slice(0, -2) : pattern).split("/");
6440
6443
  if (isPrefix ? pathSegments2.length < patternSegments.length : pathSegments2.length !== patternSegments.length) {
6441
6444
  return false;
6442
6445
  }
6443
- return patternSegments.every((segment, i) => segment === "*" ? pathSegments2[i] !== "" : segment === pathSegments2[i]);
6446
+ return patternSegments.every((segment2, i) => segment2 === "*" ? pathSegments2[i] !== "" : segment2 === pathSegments2[i]);
6444
6447
  }
6445
- function getEndpointConfig(path50) {
6448
+ function getEndpointConfig(path51) {
6446
6449
  for (const excluded of EXCLUDED_PATHS) {
6447
- if (matchPath(excluded, path50)) {
6450
+ if (matchPath(excluded, path51)) {
6448
6451
  return null;
6449
6452
  }
6450
6453
  }
6451
- const normalizedPath = path50.replace(/\/$/, "");
6454
+ const normalizedPath = path51.replace(/\/$/, "");
6452
6455
  if (!normalizedPath.endsWith("/*") && Object.prototype.hasOwnProperty.call(ENDPOINT_CONFIGS, normalizedPath)) {
6453
6456
  return ENDPOINT_CONFIGS[normalizedPath];
6454
6457
  }
6455
6458
  const sortedPatterns = Object.keys(ENDPOINT_CONFIGS).sort((a, b) => b.length - a.length);
6456
6459
  for (const pattern of sortedPatterns) {
6457
- if (matchPath(pattern, path50)) {
6460
+ if (matchPath(pattern, path51)) {
6458
6461
  return ENDPOINT_CONFIGS[pattern];
6459
6462
  }
6460
6463
  }
@@ -8057,16 +8060,16 @@ function parseCommunityLessonVideoUrl(url) {
8057
8060
  const parts = /^https?:\/\/([^/?#]+)([^?#]*)(?:\?([^#]*))?(?:#.*)?$/i.exec(url.trim());
8058
8061
  if (!parts) return null;
8059
8062
  const host = parts[1].toLowerCase();
8060
- const path50 = parts[2] ?? "";
8063
+ const path51 = parts[2] ?? "";
8061
8064
  const query = parts[3] ?? "";
8062
8065
  let id;
8063
8066
  if (host === YOUTU_BE) {
8064
- id = /^\/([A-Za-z0-9_-]{11})\/?$/.exec(path50)?.[1];
8067
+ id = /^\/([A-Za-z0-9_-]{11})\/?$/.exec(path51)?.[1];
8065
8068
  } else if (YOUTUBE_HOSTS.has(host)) {
8066
- if (path50 === "/watch" || path50 === "/watch/") {
8069
+ if (path51 === "/watch" || path51 === "/watch/") {
8067
8070
  id = query.split("&").find((param) => param.startsWith("v="))?.slice(2);
8068
8071
  } else {
8069
- id = YOUTUBE_ID_PATH.exec(path50)?.[1];
8072
+ id = YOUTUBE_ID_PATH.exec(path51)?.[1];
8070
8073
  }
8071
8074
  }
8072
8075
  return id !== void 0 && YOUTUBE_ID.test(id) ? { provider: "youtube", id } : null;
@@ -8264,12 +8267,12 @@ function typeMatches(typeField, allowed) {
8264
8267
  if (Array.isArray(typeField)) return typeField.every((t) => typeof t === "string" && allowed.has(t));
8265
8268
  return false;
8266
8269
  }
8267
- function validateSchema(schema, path50, errors, opts = {}) {
8270
+ function validateSchema(schema, path51, errors, opts = {}) {
8268
8271
  if (typeof schema === "boolean") return;
8269
8272
  const depth = opts.depth ?? 0;
8270
8273
  if (depth > MAX_SCHEMA_DEPTH) {
8271
8274
  errors.push({
8272
- path: path50 || "<root>",
8275
+ path: path51 || "<root>",
8273
8276
  message: `schema nesting exceeds ${MAX_SCHEMA_DEPTH} levels`,
8274
8277
  suggestion: "Flatten the schema; LLM providers reject deeply nested tool input_schemas."
8275
8278
  });
@@ -8277,7 +8280,7 @@ function validateSchema(schema, path50, errors, opts = {}) {
8277
8280
  }
8278
8281
  if (!isRecord(schema)) {
8279
8282
  errors.push({
8280
- path: path50,
8283
+ path: path51,
8281
8284
  message: `expected object, got ${schema === null ? "null" : typeof schema}`
8282
8285
  });
8283
8286
  return;
@@ -8285,14 +8288,14 @@ function validateSchema(schema, path50, errors, opts = {}) {
8285
8288
  if (opts.isRoot) {
8286
8289
  if ("type" in schema && schema.type !== "object") {
8287
8290
  errors.push({
8288
- path: path50 ? `${path50}.type` : "type",
8291
+ path: path51 ? `${path51}.type` : "type",
8289
8292
  message: `root type must be 'object', got ${JSON.stringify(schema.type)}`,
8290
8293
  suggestion: "Tool parameters at the root must be an object: `{ type: 'object', properties: { ... } }`."
8291
8294
  });
8292
8295
  }
8293
8296
  } else if ("type" in schema && !typeMatches(schema.type, ALLOWED_TYPES)) {
8294
8297
  errors.push({
8295
- path: `${path50}.type`,
8298
+ path: `${path51}.type`,
8296
8299
  message: `type must be one of ${[...ALLOWED_TYPES].join("/")} or an array of those, got ${JSON.stringify(schema.type)}`
8297
8300
  });
8298
8301
  }
@@ -8302,25 +8305,25 @@ function validateSchema(schema, path50, errors, opts = {}) {
8302
8305
  const isPlaceholder = PLACEHOLDER_TOKENS.includes(e);
8303
8306
  const isOutcomePlaceholder = e === "[KANBAN_OUTCOME_VALUES]";
8304
8307
  errors.push({
8305
- path: `${path50}.enum`,
8308
+ path: `${path51}.enum`,
8306
8309
  message: `enum must be a non-empty array of primitives, got string ${JSON.stringify(e)}`,
8307
8310
  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
8311
  });
8309
8312
  } else if (!Array.isArray(e)) {
8310
8313
  errors.push({
8311
- path: `${path50}.enum`,
8314
+ path: `${path51}.enum`,
8312
8315
  message: `enum must be a non-empty array of primitives, got ${typeof e}`
8313
8316
  });
8314
8317
  } else if (e.length === 0) {
8315
8318
  errors.push({
8316
- path: `${path50}.enum`,
8319
+ path: `${path51}.enum`,
8317
8320
  message: "enum must not be empty"
8318
8321
  });
8319
8322
  } else {
8320
8323
  for (let i = 0; i < e.length; i++) {
8321
8324
  if (!isPrimitive(e[i])) {
8322
8325
  errors.push({
8323
- path: `${path50}.enum[${i}]`,
8326
+ path: `${path51}.enum[${i}]`,
8324
8327
  message: `enum entry must be a primitive (string/number/boolean/null), got ${typeof e[i]}`
8325
8328
  });
8326
8329
  }
@@ -8330,7 +8333,7 @@ function validateSchema(schema, path50, errors, opts = {}) {
8330
8333
  for (const key of ["exclusiveMinimum", "exclusiveMaximum"]) {
8331
8334
  if (key in schema && typeof schema[key] === "boolean") {
8332
8335
  errors.push({
8333
- path: `${path50}.${key}`,
8336
+ path: `${path51}.${key}`,
8334
8337
  message: `${key} as boolean is draft-04 syntax; draft 2020-12 requires a numeric value`,
8335
8338
  suggestion: `Replace with the numeric bound, e.g. \`${key}: 0\`.`
8336
8339
  });
@@ -8339,45 +8342,45 @@ function validateSchema(schema, path50, errors, opts = {}) {
8339
8342
  if ("properties" in schema) {
8340
8343
  if (!isRecord(schema.properties)) {
8341
8344
  errors.push({
8342
- path: `${path50}.properties`,
8345
+ path: `${path51}.properties`,
8343
8346
  message: `properties must be an object, got ${Array.isArray(schema.properties) ? "array" : typeof schema.properties}`
8344
8347
  });
8345
8348
  } else {
8346
8349
  for (const [propName, propSchema] of Object.entries(schema.properties)) {
8347
- validateSchema(propSchema, `${path50}.properties.${propName}`, errors, { depth: depth + 1 });
8350
+ validateSchema(propSchema, `${path51}.properties.${propName}`, errors, { depth: depth + 1 });
8348
8351
  }
8349
8352
  }
8350
8353
  }
8351
8354
  if (schemaTypeIncludes(schema, "array") && "items" in schema) {
8352
8355
  if (Array.isArray(schema.items)) {
8353
- schema.items.forEach((sub, i) => validateSchema(sub, `${path50}.items[${i}]`, errors, { depth: depth + 1 }));
8356
+ schema.items.forEach((sub, i) => validateSchema(sub, `${path51}.items[${i}]`, errors, { depth: depth + 1 }));
8354
8357
  } else {
8355
- validateSchema(schema.items, `${path50}.items`, errors, { depth: depth + 1 });
8358
+ validateSchema(schema.items, `${path51}.items`, errors, { depth: depth + 1 });
8356
8359
  }
8357
8360
  }
8358
8361
  for (const key of SUBSCHEMA_OBJECT_KEYWORDS) {
8359
8362
  if (key in schema && isRecord(schema[key])) {
8360
- validateSchema(schema[key], `${path50}.${key}`, errors, { depth: depth + 1 });
8363
+ validateSchema(schema[key], `${path51}.${key}`, errors, { depth: depth + 1 });
8361
8364
  }
8362
8365
  }
8363
8366
  for (const key of SUBSCHEMA_LIST_KEYWORDS) {
8364
8367
  const list2 = schema[key];
8365
8368
  if (Array.isArray(list2)) {
8366
- list2.forEach((sub, i) => validateSchema(sub, `${path50}.${key}[${i}]`, errors, { depth: depth + 1 }));
8369
+ list2.forEach((sub, i) => validateSchema(sub, `${path51}.${key}[${i}]`, errors, { depth: depth + 1 }));
8367
8370
  }
8368
8371
  }
8369
8372
  for (const key of SUBSCHEMA_MAP_KEYWORDS) {
8370
8373
  const map = schema[key];
8371
8374
  if (isRecord(map)) {
8372
8375
  for (const [name, sub] of Object.entries(map)) {
8373
- validateSchema(sub, `${path50}.${key}.${name}`, errors, { depth: depth + 1 });
8376
+ validateSchema(sub, `${path51}.${key}.${name}`, errors, { depth: depth + 1 });
8374
8377
  }
8375
8378
  }
8376
8379
  }
8377
8380
  const reportedPaths = new Set(errors.map((e) => e.path));
8378
8381
  for (const [k, v] of Object.entries(schema)) {
8379
8382
  if (typeof v !== "string") continue;
8380
- const fieldPath = `${path50}.${k}`;
8383
+ const fieldPath = `${path51}.${k}`;
8381
8384
  if (reportedPaths.has(fieldPath)) continue;
8382
8385
  for (const token of PLACEHOLDER_TOKENS) {
8383
8386
  if (v === token) {
@@ -12188,9 +12191,9 @@ function monitorRuleActions(monitorConfig) {
12188
12191
  if (!monitorConfig || typeof monitorConfig !== "object") return [];
12189
12192
  const config = monitorConfig;
12190
12193
  const found = [];
12191
- const visit = (action, path50) => {
12194
+ const visit = (action, path51) => {
12192
12195
  if (!action || typeof action !== "object" || Array.isArray(action)) return;
12193
- found.push({ action, path: path50 });
12196
+ found.push({ action, path: path51 });
12194
12197
  };
12195
12198
  if (Array.isArray(config.rules)) {
12196
12199
  config.rules.forEach((rule, index) => {
@@ -12222,25 +12225,25 @@ function collectMonitorRuleIssues(monitorConfig) {
12222
12225
  const trigger = resolveMonitorTrigger(monitorConfig);
12223
12226
  const kinds = monitorRuleActionKinds(trigger);
12224
12227
  const issues = [...callUtteranceRuleIssues(monitorConfig), ...automationGateIssues(monitorConfig)];
12225
- for (const { action, path: path50 } of monitorRuleActions(monitorConfig)) {
12226
- if (trigger === "call_utterance" && path50[0] === "fallback") continue;
12228
+ for (const { action, path: path51 } of monitorRuleActions(monitorConfig)) {
12229
+ if (trigger === "call_utterance" && path51[0] === "fallback") continue;
12227
12230
  const kind = action.kind;
12228
12231
  if (typeof kind === "string" && !kinds.includes(kind)) {
12229
- issues.push({ path: [...path50, "kind"], message: monitorActionKindMessage(kind, trigger) });
12232
+ issues.push({ path: [...path51, "kind"], message: monitorActionKindMessage(kind, trigger) });
12230
12233
  }
12231
12234
  const toolName = action.tool_name;
12232
12235
  if (kind === "call_tool" && typeof toolName === "string" && isRefusedNativeToolName(toolName, trigger)) {
12233
- issues.push({ path: [...path50, "tool_name"], message: monitorRuleToolNotAllowedMessage(toolName, trigger) });
12236
+ issues.push({ path: [...path51, "tool_name"], message: monitorRuleToolNotAllowedMessage(toolName, trigger) });
12234
12237
  continue;
12235
12238
  }
12236
12239
  if (kind === "call_tool" && toolName === INSERT_NOTE_TOOL_NAME) {
12237
- issues.push(...insertNoteArgumentIssues(action, path50));
12240
+ issues.push(...insertNoteArgumentIssues(action, path51));
12238
12241
  }
12239
12242
  if (kind === "call_tool" && toolName === RUN_MONITOR_TOOL_NAME) {
12240
12243
  const callee = readRunMonitorCallee(action);
12241
12244
  if (!callee.ok) {
12242
12245
  issues.push({
12243
- path: [...path50, "args", "monitor_name"],
12246
+ path: [...path51, "args", "monitor_name"],
12244
12247
  message: runMonitorCalleeMessage(callee.reason)
12245
12248
  });
12246
12249
  }
@@ -12300,11 +12303,11 @@ function insertNoteTemplateMessage(reason3) {
12300
12303
  return `insert_note's template is longer than the ${MONITOR_NOTE_TEMPLATE_MAX}-character limit.`;
12301
12304
  }
12302
12305
  }
12303
- function insertNoteArgumentIssues(action, path50) {
12306
+ function insertNoteArgumentIssues(action, path51) {
12304
12307
  const result = readInsertNoteTemplate(action);
12305
12308
  if (result.ok) return [];
12306
12309
  return [{
12307
- path: [...path50, "args", "template"],
12310
+ path: [...path51, "args", "template"],
12308
12311
  message: insertNoteTemplateMessage(result.reason)
12309
12312
  }];
12310
12313
  }
@@ -13278,8 +13281,8 @@ function evalInitialStateError(input) {
13278
13281
  const parsed = evalInitialStateEntry.safeParse(entries[i]);
13279
13282
  if (!parsed.success) {
13280
13283
  const issue = parsed.error.issues[0];
13281
- const path50 = issue?.path.join(".") || "?";
13282
- return `initial_state[${i}].${path50} is invalid: ${issue?.message ?? "malformed"}`;
13284
+ const path51 = issue?.path.join(".") || "?";
13285
+ return `initial_state[${i}].${path51} is invalid: ${issue?.message ?? "malformed"}`;
13283
13286
  }
13284
13287
  if (seenSlugs.has(parsed.data.slug)) {
13285
13288
  return `initial_state[${i}].slug "${parsed.data.slug}" is declared more than once`;
@@ -13805,12 +13808,12 @@ function validateFollowupLinks(followups, label3, ctx) {
13805
13808
  const linkTargets = /* @__PURE__ */ new Set();
13806
13809
  followups.forEach((followup, i) => {
13807
13810
  const ref = followup?.after_followup_id;
13808
- const path50 = ["followups", i, "after_followup_id"];
13811
+ const path51 = ["followups", i, "after_followup_id"];
13809
13812
  if (followup?.type !== "inactivity_after_before_event") {
13810
13813
  if (ref !== void 0) {
13811
13814
  ctx.addIssue({
13812
13815
  code: external_exports.ZodIssueCode.custom,
13813
- path: path50,
13816
+ path: path51,
13814
13817
  message: `kanban status ${label3}: after_followup_id is only valid on inactivity_after_before_event followups (this one is ${followup?.type})`
13815
13818
  });
13816
13819
  }
@@ -13819,7 +13822,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13819
13822
  if (ref === void 0) {
13820
13823
  ctx.addIssue({
13821
13824
  code: external_exports.ZodIssueCode.custom,
13822
- path: path50,
13825
+ path: path51,
13823
13826
  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
13827
  });
13825
13828
  return;
@@ -13829,7 +13832,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13829
13832
  if (matches.length > 1) {
13830
13833
  ctx.addIssue({
13831
13834
  code: external_exports.ZodIssueCode.custom,
13832
- path: path50,
13835
+ path: path51,
13833
13836
  message: `kanban status ${label3}: after_followup_id "${ref}" matches ${matches.length} followups \u2014 a link must name exactly one`
13834
13837
  });
13835
13838
  return;
@@ -13841,7 +13844,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13841
13844
  );
13842
13845
  ctx.addIssue({
13843
13846
  code: external_exports.ZodIssueCode.custom,
13844
- path: path50,
13847
+ path: path51,
13845
13848
  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
13849
  });
13847
13850
  return;
@@ -13849,7 +13852,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13849
13852
  if (target.type !== "before_event") {
13850
13853
  ctx.addIssue({
13851
13854
  code: external_exports.ZodIssueCode.custom,
13852
- path: path50,
13855
+ path: path51,
13853
13856
  message: `kanban status ${label3}: after_followup_id "${ref}" points at a ${target.type} followup \u2014 only before_event followups can anchor a chain`
13854
13857
  });
13855
13858
  }
@@ -14642,10 +14645,10 @@ function refineHubAsCodePersons(config, ctx) {
14642
14645
  function refineHubAsCodeEvalAttachments(config, ctx) {
14643
14646
  const cfg = config;
14644
14647
  const referencedHashes = /* @__PURE__ */ new Set();
14645
- const addTurnIssue = (path50, turn, name) => {
14648
+ const addTurnIssue = (path51, turn, name) => {
14646
14649
  const error = evalTurnAttachmentsError(turn);
14647
14650
  if (error) {
14648
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path50, message: `${name}: ${error}` });
14651
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path51, message: `${name}: ${error}` });
14649
14652
  return;
14650
14653
  }
14651
14654
  for (const hash2 of collectTurnAttachmentHashes(turn)) referencedHashes.add(hash2);
@@ -14746,17 +14749,17 @@ function refineHubAsCodeCallOpenings(config, ctx) {
14746
14749
  const agent = entry;
14747
14750
  const openings = agent?.call_openings;
14748
14751
  if (openings === void 0 || openings === null) return;
14749
- const path50 = ["agents", a, "call_openings"];
14752
+ const path51 = ["agents", a, "call_openings"];
14750
14753
  const name = `agent "${typeof agent?.name === "string" ? agent.name : "<unnamed>"}"`;
14751
14754
  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` });
14755
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path51, message: `${name}: call_openings must map a language to an opening` });
14753
14756
  return;
14754
14757
  }
14755
14758
  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` });
14759
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path51, message: `${name}: only a pilot_voice agent has call_openings` });
14757
14760
  }
14758
14761
  for (const [language, raw] of Object.entries(openings)) {
14759
- const at = [...path50, language];
14762
+ const at = [...path51, language];
14760
14763
  if (!callOpeningLanguage.safeParse(language).success) {
14761
14764
  ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: at, message: `${name}: call_openings language must be one of ${CALL_OPENING_LANGUAGES.join(", ")}` });
14762
14765
  continue;
@@ -14892,11 +14895,11 @@ function refineHubAsCodeDelegation(config, ctx) {
14892
14895
  }
14893
14896
  }
14894
14897
  if (del.context_boundary === void 0) return;
14895
- const path50 = ["agents", agentIndex, "tools", "delegation", delIndex, "context_boundary"];
14898
+ const path51 = ["agents", agentIndex, "tools", "delegation", delIndex, "context_boundary"];
14896
14899
  if (del.type !== "hub") {
14897
14900
  ctx.addIssue({
14898
14901
  code: external_exports.ZodIssueCode.custom,
14899
- path: path50,
14902
+ path: path51,
14900
14903
  message: `context_boundary applies only to \`type: hub\` delegations (got type "${got(del.type)}")`
14901
14904
  });
14902
14905
  return;
@@ -14904,18 +14907,18 @@ function refineHubAsCodeDelegation(config, ctx) {
14904
14907
  if (!CONTEXT_BOUNDARIES.includes(del.context_boundary)) {
14905
14908
  ctx.addIssue({
14906
14909
  code: external_exports.ZodIssueCode.custom,
14907
- path: path50,
14910
+ path: path51,
14908
14911
  message: `context_boundary must be one of: ${CONTEXT_BOUNDARIES.join(", ")}`
14909
14912
  });
14910
14913
  }
14911
14914
  });
14912
14915
  });
14913
14916
  }
14914
- function refuseNonBooleanFlag(ctx, subject, entry, key, path50) {
14917
+ function refuseNonBooleanFlag(ctx, subject, entry, key, path51) {
14915
14918
  const value = entry[key];
14916
14919
  if (value === void 0 || typeof value === "boolean") return;
14917
14920
  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}` });
14921
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: [...path51, key], message: `${subject}: ${key} must be true or false, got ${shown3}` });
14919
14922
  }
14920
14923
  function refineHubAsCodeFlags(config, ctx) {
14921
14924
  const { agents, connections, evals, journeys, teams } = config;
@@ -15106,11 +15109,11 @@ function pathPastDepth(root, levels) {
15106
15109
  function refusedNesting(value, at, ctx) {
15107
15110
  const past = pathPastDepth(value, MAX_HUB_AS_CODE_DEPTH - at.length);
15108
15111
  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);
15112
+ const path51 = [...at, ...past].slice(0, NAMED_DEPTH_SEGMENTS).map((key) => typeof key === "string" ? key.slice(0, NAMED_DEPTH_KEY_CHARS) : key);
15110
15113
  ctx.addIssue({
15111
15114
  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`,
15115
+ path: path51,
15116
+ message: `${fieldName(path51)}\u2026 nests deeper than ${MAX_HUB_AS_CODE_DEPTH} levels of arrays and objects`,
15114
15117
  fatal: true
15115
15118
  });
15116
15119
  return true;
@@ -15127,15 +15130,15 @@ function refusedStringConfigNesting(config, ctx) {
15127
15130
  }
15128
15131
  function refusedUnreadableSection(config, ctx) {
15129
15132
  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 });
15133
+ const refused = (path51, must) => {
15134
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path51, message: `${fieldName(path51)} must ${must}`, fatal: true });
15132
15135
  return true;
15133
15136
  };
15134
- const badList = (value, path50, reads = {}) => {
15137
+ const badList = (value, path51, reads = {}) => {
15135
15138
  if (value === void 0 || value === null && reads.nullSection !== false) return false;
15136
- if (!Array.isArray(value)) return refused(path50, "be an array");
15139
+ if (!Array.isArray(value)) return refused(path51, "be an array");
15137
15140
  const nullAt = reads.nullEntries ? -1 : value.indexOf(null);
15138
- return nullAt !== -1 && refused([...path50, nullAt], "not be null");
15141
+ return nullAt !== -1 && refused([...path51, nullAt], "not be null");
15139
15142
  };
15140
15143
  const entries = (section) => Array.isArray(section) ? section : [];
15141
15144
  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 +15314,7 @@ var init_chunk_EO5MKW7Q = __esm({
15311
15314
  MAX_HUB_AS_CODE_DEPTH = 128;
15312
15315
  NAMED_DEPTH_SEGMENTS = 12;
15313
15316
  NAMED_DEPTH_KEY_CHARS = 64;
15314
- fieldName = (path50) => path50.reduce(
15317
+ fieldName = (path51) => path51.reduce(
15315
15318
  (name, key) => typeof key === "number" ? `${name}[${key}]` : name ? `${name}.${key}` : key,
15316
15319
  ""
15317
15320
  );
@@ -15550,8 +15553,8 @@ var init_chunk_5Y2NNQHX = __esm({
15550
15553
  });
15551
15554
 
15552
15555
  // ../../packages/core/dist/chunk-KWRHZBGU.js
15553
- function fold(segment) {
15554
- return segment.toUpperCase().toLowerCase().replace(/ς/g, "\u03C3").replace(/ß/g, "ss").normalize("NFC");
15556
+ function fold(segment2) {
15557
+ return segment2.toUpperCase().toLowerCase().replace(/ς/g, "\u03C3").replace(/ß/g, "ss").normalize("NFC");
15555
15558
  }
15556
15559
  function hasLoneSurrogate(text5) {
15557
15560
  for (let i = 0; i < text5.length; i++) {
@@ -15564,9 +15567,9 @@ function hasLoneSurrogate(text5) {
15564
15567
  }
15565
15568
  return false;
15566
15569
  }
15567
- function isShortNameAlias(segment) {
15568
- const dot = segment.lastIndexOf(".");
15569
- const [stem, extension] = dot > 0 ? [segment.slice(0, dot), segment.slice(dot + 1)] : [segment, ""];
15570
+ function isShortNameAlias(segment2) {
15571
+ const dot = segment2.lastIndexOf(".");
15572
+ const [stem, extension] = dot > 0 ? [segment2.slice(0, dot), segment2.slice(dot + 1)] : [segment2, ""];
15570
15573
  return stem.length <= 8 && /~[0-9]+$/.test(stem) && extension.length <= 3;
15571
15574
  }
15572
15575
  function isCaseInstructions(segments) {
@@ -15588,7 +15591,7 @@ function checkCaseFilePathUnder(rules, entry, phaseFolders) {
15588
15591
  const segments = entry.path.split("/");
15589
15592
  for (const rule of rules) {
15590
15593
  if (rule.on !== "segment") continue;
15591
- const index = segments.findIndex((segment, i) => rule.refuses(segment, i, segments));
15594
+ const index = segments.findIndex((segment2, i) => rule.refuses(segment2, i, segments));
15592
15595
  if (index >= 0) return { ok: false, reason: rule.reason, segment: index };
15593
15596
  }
15594
15597
  const confidential = segments[0] === "conf";
@@ -15629,30 +15632,30 @@ var init_chunk_KWRHZBGU = __esm({
15629
15632
  { reason: "malformed_unicode", on: "entry", refuses: (entry) => hasLoneSurrogate(entry.path) },
15630
15633
  { reason: "too_long", on: "entry", refuses: (entry) => utf8ByteLength(entry.path) > CASE_FILE_PATH_MAX_BYTES },
15631
15634
  { reason: "not_nfc", on: "entry", refuses: (entry) => entry.path !== entry.path.normalize("NFC") },
15632
- { reason: "absolute", on: "segment", refuses: (segment, index) => index === 0 && segment === "" },
15633
- { reason: "empty_segment", on: "segment", refuses: (segment) => segment === "" },
15634
- { reason: "traversal", on: "segment", refuses: (segment) => segment === "." || segment === ".." },
15635
- { reason: "segment_too_long", on: "segment", refuses: (segment) => utf8ByteLength(segment) > CASE_FILE_SEGMENT_MAX_BYTES },
15636
- { reason: "backslash", on: "segment", refuses: (segment) => segment.includes("\\") },
15637
- { reason: "control_character", on: "segment", refuses: (segment) => CONTROL.test(segment) },
15638
- { reason: "invisible_character", on: "segment", refuses: (segment) => INVISIBLE.test(segment) },
15639
- { reason: "percent_encoded", on: "segment", refuses: (segment) => PERCENT_ESCAPE.test(segment) },
15640
- { reason: "reserved_character", on: "segment", refuses: (segment) => WINDOWS_RESERVED_CHARACTER.test(segment) },
15641
- { reason: "trailing_dot_or_space", on: "segment", refuses: (segment) => /[. ]$/.test(segment) },
15642
- { reason: "reserved_device_name", on: "segment", refuses: (segment) => WINDOWS_DEVICE_NAME.test(fold(segment)) },
15643
- { reason: "short_name_alias", on: "segment", refuses: (segment) => isShortNameAlias(segment) },
15644
- { reason: "dot_directory", on: "segment", refuses: (segment, index, segments) => segment.startsWith(".") && !isLast(index, segments) },
15645
- { reason: "dot_file", on: "segment", refuses: (segment, index, segments) => segment.startsWith(".") && isLast(index, segments) },
15646
- { reason: "agent_instruction_file", on: "segment", refuses: (segment) => AGENT_INSTRUCTION_FILE.test(fold(segment)) },
15635
+ { reason: "absolute", on: "segment", refuses: (segment2, index) => index === 0 && segment2 === "" },
15636
+ { reason: "empty_segment", on: "segment", refuses: (segment2) => segment2 === "" },
15637
+ { reason: "traversal", on: "segment", refuses: (segment2) => segment2 === "." || segment2 === ".." },
15638
+ { reason: "segment_too_long", on: "segment", refuses: (segment2) => utf8ByteLength(segment2) > CASE_FILE_SEGMENT_MAX_BYTES },
15639
+ { reason: "backslash", on: "segment", refuses: (segment2) => segment2.includes("\\") },
15640
+ { reason: "control_character", on: "segment", refuses: (segment2) => CONTROL.test(segment2) },
15641
+ { reason: "invisible_character", on: "segment", refuses: (segment2) => INVISIBLE.test(segment2) },
15642
+ { reason: "percent_encoded", on: "segment", refuses: (segment2) => PERCENT_ESCAPE.test(segment2) },
15643
+ { reason: "reserved_character", on: "segment", refuses: (segment2) => WINDOWS_RESERVED_CHARACTER.test(segment2) },
15644
+ { reason: "trailing_dot_or_space", on: "segment", refuses: (segment2) => /[. ]$/.test(segment2) },
15645
+ { reason: "reserved_device_name", on: "segment", refuses: (segment2) => WINDOWS_DEVICE_NAME.test(fold(segment2)) },
15646
+ { reason: "short_name_alias", on: "segment", refuses: (segment2) => isShortNameAlias(segment2) },
15647
+ { reason: "dot_directory", on: "segment", refuses: (segment2, index, segments) => segment2.startsWith(".") && !isLast(index, segments) },
15648
+ { reason: "dot_file", on: "segment", refuses: (segment2, index, segments) => segment2.startsWith(".") && isLast(index, segments) },
15649
+ { reason: "agent_instruction_file", on: "segment", refuses: (segment2) => AGENT_INSTRUCTION_FILE.test(fold(segment2)) },
15647
15650
  {
15648
15651
  reason: "tools_directory",
15649
15652
  on: "segment",
15650
- refuses: (segment, index, segments) => fold(segment) === "tools" && !isLast(index, segments)
15653
+ refuses: (segment2, index, segments) => fold(segment2) === "tools" && !isLast(index, segments)
15651
15654
  },
15652
15655
  {
15653
15656
  reason: "generated_instructions",
15654
15657
  on: "segment",
15655
- refuses: (segment, index, segments) => fold(segment) === "instructions" && !(index === 0 && isCaseInstructions(segments))
15658
+ refuses: (segment2, index, segments) => fold(segment2) === "instructions" && !(index === 0 && isCaseInstructions(segments))
15656
15659
  }
15657
15660
  ]);
15658
15661
  }
@@ -15795,8 +15798,8 @@ var init_chunk_VROZDNLV = __esm({
15795
15798
  CASE_UPLOADS_BUSY_REASON = "case_uploads_busy";
15796
15799
  isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob;
15797
15800
  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] });
15801
+ const refuse2 = (message, path51) => {
15802
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path51] });
15800
15803
  return external_exports.NEVER;
15801
15804
  };
15802
15805
  const text5 = form2[CASE_UPLOAD_REVISION_FIELD];
@@ -16005,17 +16008,17 @@ function fixedTextProblem(text5) {
16005
16008
  }
16006
16009
  return null;
16007
16010
  }
16008
- function casePieceSidecar(path50) {
16009
- if (/\.yaml$/i.test(path50)) return null;
16010
- const sidecar = path50.replace(/\.[^./]+$/, ".yaml");
16011
- return sidecar === path50 ? null : sidecar;
16011
+ function casePieceSidecar(path51) {
16012
+ if (/\.yaml$/i.test(path51)) return null;
16013
+ const sidecar = path51.replace(/\.[^./]+$/, ".yaml");
16014
+ return sidecar === path51 ? null : sidecar;
16012
16015
  }
16013
16016
  function pathsOverlap(a, b) {
16014
16017
  return a === b || a.endsWith("/") && b.startsWith(a) || b.endsWith("/") && a.startsWith(b);
16015
16018
  }
16016
- function boundPathKey(path50, folders) {
16017
- const folder = path50.endsWith("/");
16018
- const checked = checkCaseFilePath({ path: folder ? `${path50}${CHAPTER_PROBE}` : path50, type: "file" }, folders);
16019
+ function boundPathKey(path51, folders) {
16020
+ const folder = path51.endsWith("/");
16021
+ const checked = checkCaseFilePath({ path: folder ? `${path51}${CHAPTER_PROBE}` : path51, type: "file" }, folders);
16019
16022
  if (!checked.ok || checked.received) return null;
16020
16023
  return folder ? checked.fold_key.slice(0, -CHAPTER_PROBE.length) : checked.fold_key;
16021
16024
  }
@@ -16068,11 +16071,11 @@ function caseTypeDefinitionProblem(definition) {
16068
16071
  if (output.format === "file" && output.output_items.length > 0) return problem("file_output_with_items", outputAt);
16069
16072
  if (output.format === "file" && output.case_items_allowed) return problem("file_output_with_case_items", outputAt);
16070
16073
  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);
16074
+ for (const path51 of output.file_paths) {
16075
+ if (!path51.startsWith(`${phase.folder}/`)) return problem("file_path_outside_phase", outputAt);
16076
+ const key = boundPathKey(path51, folders);
16074
16077
  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);
16078
+ if (output.format === "file" && path51.endsWith("/")) return problem("file_path_folder_for_file", outputAt);
16076
16079
  if (paths.some((held) => pathsOverlap(held, key))) return problem("file_path_overlaps", outputAt);
16077
16080
  paths.push(key);
16078
16081
  }
@@ -16193,9 +16196,9 @@ var init_chunk_PFPADFUC = __esm({
16193
16196
  const { folder, code: targetCode } = resolveItemLink("", target);
16194
16197
  return (!target.includes("/") || CASE_PHASE_FOLDER_PATTERN.test(folder)) && CASE_CODE_PATTERN.test(targetCode);
16195
16198
  }, "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("/");
16198
- 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
+ filePath = external_exports.string().min(1).max(CASE_FILE_PATH_MAX_LENGTH).refine((path51) => {
16200
+ const segments = (path51.endsWith("/") ? path51.slice(0, -1) : path51).split("/");
16201
+ return segments.length >= 2 && segments.length <= 8 && CASE_PHASE_FOLDER_PATTERN.test(segments[0]) && segments.slice(1).every((segment2) => FILE_PATH_SEGMENT_PATTERN.test(segment2));
16199
16202
  }, "A file path is the phase folder, then letters, digits, dots, dashes and underscores");
16200
16203
  caseTypePartyRoleSchema = external_exports.object({
16201
16204
  code,
@@ -16622,7 +16625,7 @@ var init_chunk_U3X3BIQH = __esm({
16622
16625
  }
16623
16626
  });
16624
16627
 
16625
- // ../../packages/core/dist/chunk-3LMWOJQX.js
16628
+ // ../../packages/core/dist/chunk-EYOBPUDN.js
16626
16629
  function withProblem(shape, problemOf) {
16627
16630
  return shape.superRefine((value, ctx) => {
16628
16631
  const found = problemOf(value);
@@ -16659,8 +16662,8 @@ ${party.role}`);
16659
16662
  return new Set(keys).size === keys.length ? null : { reason: "instrument_party_repeated", at: "parties" };
16660
16663
  }
16661
16664
  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;
16662
- var init_chunk_3LMWOJQX = __esm({
16663
- "../../packages/core/dist/chunk-3LMWOJQX.js"() {
16665
+ var init_chunk_EYOBPUDN = __esm({
16666
+ "../../packages/core/dist/chunk-EYOBPUDN.js"() {
16664
16667
  "use strict";
16665
16668
  init_chunk_3T3D7LTE();
16666
16669
  init_chunk_M2T55BV6();
@@ -16754,11 +16757,11 @@ var init_chunk_3LMWOJQX = __esm({
16754
16757
  }
16755
16758
  });
16756
16759
 
16757
- // ../../packages/core/dist/chunk-PMBOHJKA.js
16760
+ // ../../packages/core/dist/chunk-6CHDJVQ6.js
16758
16761
  function collectionUploadForm(field, shape) {
16759
16762
  return external_exports.record(external_exports.string(), external_exports.unknown()).transform((form2, ctx) => {
16760
- const refuse2 = (message, path50) => {
16761
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path50] });
16763
+ const refuse2 = (message, path51) => {
16764
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path51] });
16762
16765
  return external_exports.NEVER;
16763
16766
  };
16764
16767
  const text5 = form2[field];
@@ -16794,11 +16797,11 @@ function caseCollectionFileName(sent) {
16794
16797
  return name || "document";
16795
16798
  }
16796
16799
  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;
16797
- var init_chunk_PMBOHJKA = __esm({
16798
- "../../packages/core/dist/chunk-PMBOHJKA.js"() {
16800
+ var init_chunk_6CHDJVQ6 = __esm({
16801
+ "../../packages/core/dist/chunk-6CHDJVQ6.js"() {
16799
16802
  "use strict";
16800
16803
  init_chunk_U3X3BIQH();
16801
- init_chunk_3LMWOJQX();
16804
+ init_chunk_EYOBPUDN();
16802
16805
  init_chunk_VROZDNLV();
16803
16806
  init_chunk_3T3D7LTE();
16804
16807
  init_chunk_M2T55BV6();
@@ -16860,7 +16863,7 @@ var init_chunk_PMBOHJKA = __esm({
16860
16863
  }
16861
16864
  });
16862
16865
 
16863
- // ../../packages/core/dist/chunk-ZB7W3DKK.js
16866
+ // ../../packages/core/dist/chunk-WYCUCSD5.js
16864
16867
  function caseReceivedFormat(fileName) {
16865
16868
  const dot = fileName.lastIndexOf(".");
16866
16869
  if (dot < 0) return null;
@@ -16868,10 +16871,10 @@ function caseReceivedFormat(fileName) {
16868
16871
  return isCaseReceivedFormat(extension) ? extension : null;
16869
16872
  }
16870
16873
  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;
16871
- var init_chunk_ZB7W3DKK = __esm({
16872
- "../../packages/core/dist/chunk-ZB7W3DKK.js"() {
16874
+ var init_chunk_WYCUCSD5 = __esm({
16875
+ "../../packages/core/dist/chunk-WYCUCSD5.js"() {
16873
16876
  "use strict";
16874
- init_chunk_PMBOHJKA();
16877
+ init_chunk_6CHDJVQ6();
16875
16878
  init_chunk_U3X3BIQH();
16876
16879
  init_chunk_VROZDNLV();
16877
16880
  init_chunk_733K4J4G();
@@ -16909,8 +16912,8 @@ var init_chunk_ZB7W3DKK = __esm({
16909
16912
  confidential: external_exports.boolean().default(false)
16910
16913
  }).strict();
16911
16914
  caseReceivedUploadForm = external_exports.record(external_exports.string(), external_exports.unknown()).transform((form2, ctx) => {
16912
- const refuse2 = (message, path50) => {
16913
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path50] });
16915
+ const refuse2 = (message, path51) => {
16916
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path51] });
16914
16917
  return external_exports.NEVER;
16915
16918
  };
16916
16919
  const text5 = form2[CASE_RECEIVED_DOCUMENT_FIELD];
@@ -17219,6 +17222,11 @@ var init_chunk_7TQYAKCB = __esm({
17219
17222
  });
17220
17223
 
17221
17224
  // ../../packages/core/dist/chunk-S7UAXLHJ.js
17225
+ function casePassageLines(text5) {
17226
+ const lines = text5.replace(/\r\n/g, "\n").split("\n");
17227
+ if (lines.at(-1) === "") lines.pop();
17228
+ return lines;
17229
+ }
17222
17230
  var CASE_COMMENT_TEXT_MAX_LENGTH, CASE_COMMENTS_PAGE_MAX, CASE_COMMENT_LINE_MAX, casePassageLineSchema, lineNumber, addCaseCommentShape, CASE_COMMENT_REVERSED_REASON, addCaseCommentBody, caseCommentsQuery;
17223
17231
  var init_chunk_S7UAXLHJ = __esm({
17224
17232
  "../../packages/core/dist/chunk-S7UAXLHJ.js"() {
@@ -17297,18 +17305,19 @@ var init_chunk_S4NDHW3Q = __esm({
17297
17305
  }
17298
17306
  });
17299
17307
 
17300
- // ../../packages/core/dist/chunk-W4XY3TYX.js
17301
- var caseInputLinkParam, linkCaseInputBody, CASE_COLLECTION_CASES_PAGE_MAX, caseCollectionCasesQuery, CASE_REFERENCES_PAGE_MAX, caseReferencesQuery;
17302
- var init_chunk_W4XY3TYX = __esm({
17303
- "../../packages/core/dist/chunk-W4XY3TYX.js"() {
17308
+ // ../../packages/core/dist/chunk-UZ72OHQN.js
17309
+ var caseInputLinkParam, caseCollectionDocumentOfCaseParam, linkCaseInputBody, CASE_COLLECTION_CASES_PAGE_MAX, caseCollectionCasesQuery, CASE_REFERENCES_PAGE_MAX, caseReferencesQuery;
17310
+ var init_chunk_UZ72OHQN = __esm({
17311
+ "../../packages/core/dist/chunk-UZ72OHQN.js"() {
17304
17312
  "use strict";
17305
- init_chunk_PMBOHJKA();
17313
+ init_chunk_6CHDJVQ6();
17306
17314
  init_chunk_S4NDHW3Q();
17307
17315
  init_chunk_733K4J4G();
17308
17316
  init_chunk_3T3D7LTE();
17309
17317
  init_chunk_HZ6CADSY();
17310
17318
  init_zod();
17311
17319
  caseInputLinkParam = caseRecordParam.extend({ input_id: uuidSchema });
17320
+ caseCollectionDocumentOfCaseParam = caseRecordParam.extend({ document_id: uuidSchema });
17312
17321
  linkCaseInputBody = external_exports.object({
17313
17322
  document_id: uuidSchema,
17314
17323
  /** The document's version its writer read as current, or an earlier one it keeps, with its `reason`. */
@@ -18455,7 +18464,7 @@ var init_contracts = __esm({
18455
18464
  init_chunk_7CZSLDOE();
18456
18465
  init_chunk_2YVCHUBL();
18457
18466
  init_chunk_BT77VXJU();
18458
- init_chunk_ZB7W3DKK();
18467
+ init_chunk_WYCUCSD5();
18459
18468
  init_chunk_H6V7NEWR();
18460
18469
  init_chunk_ZVIMTUGZ();
18461
18470
  init_chunk_BVQCYBU6();
@@ -18463,10 +18472,10 @@ var init_contracts = __esm({
18463
18472
  init_chunk_Z3SV3XTC();
18464
18473
  init_chunk_NHC27NIE();
18465
18474
  init_chunk_UMAPAGFH();
18466
- init_chunk_W4XY3TYX();
18467
- init_chunk_PMBOHJKA();
18475
+ init_chunk_UZ72OHQN();
18476
+ init_chunk_6CHDJVQ6();
18468
18477
  init_chunk_U3X3BIQH();
18469
- init_chunk_3LMWOJQX();
18478
+ init_chunk_EYOBPUDN();
18470
18479
  init_chunk_S4NDHW3Q();
18471
18480
  init_chunk_UEJOG2Q7();
18472
18481
  init_chunk_KEN2DASI();
@@ -19694,15 +19703,15 @@ function unreadArgumentRefusal(invocation, args2, reads, splitsAtFirstLongFlag)
19694
19703
  function entryFlagRefusal(command2, args2, dataNamespaces) {
19695
19704
  if (command2 === void 0 || HELP_AND_VERSION.includes(command2)) return null;
19696
19705
  if (dataNamespaces.has(command2)) return null;
19697
- const words = [command2];
19706
+ const words2 = [command2];
19698
19707
  for (const arg of args2.slice(0, 2)) {
19699
19708
  if (!/^[a-z][a-z-]*$/.test(arg)) break;
19700
- words.push(arg);
19709
+ words2.push(arg);
19701
19710
  }
19702
- let named = words.length;
19703
- let reads = PARSER_READS.get(words.join(" "));
19704
- while (reads === void 0 && --named > 0) reads = PARSER_READS.get(words.slice(0, named).join(" "));
19705
- const invocation = `wayai ${words.slice(0, named || words.length).join(" ")}`;
19711
+ let named = words2.length;
19712
+ let reads = PARSER_READS.get(words2.join(" "));
19713
+ while (reads === void 0 && --named > 0) reads = PARSER_READS.get(words2.slice(0, named).join(" "));
19714
+ const invocation = `wayai ${words2.slice(0, named || words2.length).join(" ")}`;
19706
19715
  if (reads === "all") return null;
19707
19716
  const dryRuns = args2.filter(isDryRunToken);
19708
19717
  const readsBare = typeof reads === "object" && reads.dryRun === true;
@@ -20037,9 +20046,9 @@ function oldLayoutEntries(root, skills, oldLayout) {
20037
20046
  function assertOldLayoutConvertible(root, skills, oldLayout, pullCommand3) {
20038
20047
  const { leftover } = oldLayoutEntries(root, skills, oldLayout);
20039
20048
  if (leftover.length === 0) return;
20040
- const one4 = leftover.length === 1;
20049
+ const one5 = leftover.length === 1;
20041
20050
  throw expected(
20042
- `${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 ${one4 ? "it" : "them"} out of ${path8.basename(root)}/ (a knowledge backup belongs outside the workspace), then run \`${pullCommand3}\` again. Nothing was written.`
20051
+ `${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.`
20043
20052
  );
20044
20053
  }
20045
20054
  function removeConvertedOldResources(root, skills, log, opts = {}) {
@@ -20295,10 +20304,10 @@ var init_resource_files = __esm({
20295
20304
  var init_case_received_documents = __esm({
20296
20305
  "../../packages/core/dist/contracts/case-received-documents.js"() {
20297
20306
  "use strict";
20298
- init_chunk_ZB7W3DKK();
20299
- init_chunk_PMBOHJKA();
20307
+ init_chunk_WYCUCSD5();
20308
+ init_chunk_6CHDJVQ6();
20300
20309
  init_chunk_U3X3BIQH();
20301
- init_chunk_3LMWOJQX();
20310
+ init_chunk_EYOBPUDN();
20302
20311
  init_chunk_VROZDNLV();
20303
20312
  init_chunk_733K4J4G();
20304
20313
  init_chunk_PFPADFUC();
@@ -20356,10 +20365,10 @@ function toDataProxyPath(v1Path) {
20356
20365
  }
20357
20366
  return `${DATA_PROXY_PREFIX}${v1Path.slice(REKOR_V1_PREFIX.length)}`;
20358
20367
  }
20359
- function withOrgSelector(path50, orgId) {
20360
- if (!orgId) return path50;
20361
- const separator = path50.includes("?") ? "&" : "?";
20362
- return `${path50}${separator}${DATA_PROXY_ORG_QUERY_PARAM}=${encodeURIComponent(orgId)}`;
20368
+ function withOrgSelector(path51, orgId) {
20369
+ if (!orgId) return path51;
20370
+ const separator = path51.includes("?") ? "&" : "?";
20371
+ return `${path51}${separator}${DATA_PROXY_ORG_QUERY_PARAM}=${encodeURIComponent(orgId)}`;
20363
20372
  }
20364
20373
  function dataErrorMessage(err) {
20365
20374
  if (!(err instanceof ApiError)) return null;
@@ -20399,13 +20408,13 @@ var init_api_client = __esm({
20399
20408
  * telling them apart by body shape misreads one for the other.
20400
20409
  */
20401
20410
  path;
20402
- constructor(method, path50, status, body) {
20411
+ constructor(method, path51, status, body) {
20403
20412
  const safeBody = maskSecretsInMessage(body);
20404
- super(`API request failed: ${method} ${path50} (${status}): ${safeBody}`);
20413
+ super(`API request failed: ${method} ${path51} (${status}): ${safeBody}`);
20405
20414
  this.name = "ApiError";
20406
20415
  this.status = status;
20407
20416
  this.body = safeBody;
20408
- this.path = path50;
20417
+ this.path = path51;
20409
20418
  }
20410
20419
  /** True when the status code is a 4xx client error (expected user-facing condition, not a bug). */
20411
20420
  get isExpected() {
@@ -20565,6 +20574,10 @@ var init_api_client = __esm({
20565
20574
  async getCasePhaseWork(ref, phaseId) {
20566
20575
  return this.request("GET", `${casePath(ref)}/phases/${encodeURIComponent(phaseId)}/work`);
20567
20576
  }
20577
+ /** A phase's newest submission and its manifest, or null when it has none. */
20578
+ async getCaseDelivery(ref, phaseId) {
20579
+ return this.request("GET", `${casePath(ref)}/phases/${encodeURIComponent(phaseId)}/delivery`);
20580
+ }
20568
20581
  /** A page of one phase's agenda groups. */
20569
20582
  async getCaseAgenda(ref, phaseId, cursor) {
20570
20583
  const params = new URLSearchParams({ phase_id: phaseId });
@@ -20596,6 +20609,20 @@ var init_api_client = __esm({
20596
20609
  form2.set("text", new Blob([text5], { type: "text/markdown" }), "text.md");
20597
20610
  return this.request("POST", `${casePath(ref)}/received/uploads`, form2);
20598
20611
  }
20612
+ /** An input's link: the document and version it names, its decisions and its cited passages (each a line range and hash). */
20613
+ async getCaseInputLink(ref, inputId) {
20614
+ return this.request("GET", `${casePath(ref)}/inputs/${encodeURIComponent(inputId)}/link`);
20615
+ }
20616
+ /**
20617
+ * One part of a collection document's version, through the case's own path, with the SHA-256 the space registered for
20618
+ * it when the part was stored (the answer's `ETag`, `"<sha>"`); `sha` is null when no such tag is answered.
20619
+ */
20620
+ async getCaseCollectionContent(ref, documentId, query) {
20621
+ const params = new URLSearchParams({ part: query.part });
20622
+ if (query.version_id !== void 0) params.set("version_id", query.version_id);
20623
+ const { bytes, etag } = await this.download(`${casePath(ref)}/collection/${encodeURIComponent(documentId)}/content?${params}`);
20624
+ return { bytes, sha: etag === null ? null : /^(?:W\/)?"([0-9a-f]{64})"$/.exec(etag)?.[1] ?? null };
20625
+ }
20599
20626
  /** A page of the files the case holds now, by path. */
20600
20627
  async listCaseFiles(ref, query = {}) {
20601
20628
  const params = new URLSearchParams();
@@ -20605,8 +20632,8 @@ var init_api_client = __esm({
20605
20632
  return this.request("GET", `${casePath(ref)}/files${qs ? `?${qs}` : ""}`);
20606
20633
  }
20607
20634
  /** A case file's bytes as the case holds them now. */
20608
- async getCaseFileContent(ref, path50) {
20609
- return (await this.download(`${casePath(ref)}/files/content?${new URLSearchParams({ path: path50 })}`)).bytes;
20635
+ async getCaseFileContent(ref, path51) {
20636
+ return (await this.download(`${casePath(ref)}/files/content?${new URLSearchParams({ path: path51 })}`)).bytes;
20610
20637
  }
20611
20638
  /**
20612
20639
  * One revision of the case's files, in one multipart request: the revision's JSON, and each content it sends as a
@@ -20814,8 +20841,8 @@ var init_api_client = __esm({
20814
20841
  ...opts?.check && { check: true }
20815
20842
  });
20816
20843
  }
20817
- async lookup(path50, opts) {
20818
- const params = new URLSearchParams({ path: path50 });
20844
+ async lookup(path51, opts) {
20845
+ const params = new URLSearchParams({ path: path51 });
20819
20846
  if (opts?.organizationId) params.set("organization_id", opts.organizationId);
20820
20847
  return this.request("GET", `/api/ci/lookup?${params.toString()}`);
20821
20848
  }
@@ -21355,9 +21382,9 @@ var init_api_client = __esm({
21355
21382
  `/api/admin/data-explorer/debug/observability/${encodeURIComponent(hubId)}/conversations/${encodeURIComponent(conversationId)}${qs}`
21356
21383
  );
21357
21384
  }
21358
- async request(method, path50, body, extraHeaders, contentType) {
21359
- addApiBreadcrumb(method, path50);
21360
- const url = `${this.apiUrl}${path50}`;
21385
+ async request(method, path51, body, extraHeaders, contentType) {
21386
+ addApiBreadcrumb(method, path51);
21387
+ const url = `${this.apiUrl}${path51}`;
21361
21388
  let refreshedOn401 = false;
21362
21389
  for (let retry = 0; ; retry++) {
21363
21390
  let response = await this.send(url, method, body, extraHeaders, contentType);
@@ -21382,7 +21409,7 @@ var init_api_client = __esm({
21382
21409
  await delay(RETRYABLE_BACKOFF_MS[retry]);
21383
21410
  continue;
21384
21411
  }
21385
- throw new ApiError(method, path50, response.status, errorBody);
21412
+ throw new ApiError(method, path51, response.status, errorBody);
21386
21413
  }
21387
21414
  }
21388
21415
  /**
@@ -21452,9 +21479,9 @@ var init_api_client = __esm({
21452
21479
  return this.download(withOrgSelector(toDataProxyPath(v1Path), orgId));
21453
21480
  }
21454
21481
  /** A backend path's raw bytes (`dataDownload`'s read, for any path). */
21455
- async download(path50) {
21456
- addApiBreadcrumb("GET", path50);
21457
- const url = `${this.apiUrl}${path50}`;
21482
+ async download(path51) {
21483
+ addApiBreadcrumb("GET", path51);
21484
+ const url = `${this.apiUrl}${path51}`;
21458
21485
  let response = await this.send(url, "GET");
21459
21486
  if (response.status === 401 && this.onUnauthorized) {
21460
21487
  let refreshed;
@@ -21468,11 +21495,12 @@ var init_api_client = __esm({
21468
21495
  }
21469
21496
  }
21470
21497
  if (!response.ok) {
21471
- throw new ApiError("GET", path50, response.status, await response.text());
21498
+ throw new ApiError("GET", path51, response.status, await response.text());
21472
21499
  }
21473
21500
  return {
21474
21501
  bytes: new Uint8Array(await response.arrayBuffer()),
21475
- contentType: response.headers.get("Content-Type") ?? "application/octet-stream"
21502
+ contentType: response.headers.get("Content-Type") ?? "application/octet-stream",
21503
+ etag: response.headers.get("ETag")
21476
21504
  };
21477
21505
  }
21478
21506
  /**
@@ -21911,9 +21939,9 @@ function getVersionCachePath(filename = CLI_CACHE_FILE) {
21911
21939
  }
21912
21940
  function readVersionCache(filename = CLI_CACHE_FILE) {
21913
21941
  try {
21914
- const path50 = getVersionCachePath(filename);
21915
- if (!existsSync4(path50)) return null;
21916
- const parsed = JSON.parse(readFileSync6(path50, "utf-8"));
21942
+ const path51 = getVersionCachePath(filename);
21943
+ if (!existsSync4(path51)) return null;
21944
+ const parsed = JSON.parse(readFileSync6(path51, "utf-8"));
21917
21945
  if (typeof parsed.lastCheck !== "number") return null;
21918
21946
  if (parsed.latest !== null && typeof parsed.latest !== "string") return null;
21919
21947
  return parsed;
@@ -21933,10 +21961,10 @@ function isVersionCacheStale(filename = CLI_CACHE_FILE, maxAgeMs = MAX_AGE_24H_M
21933
21961
  return Date.now() - cache.lastCheck > maxAgeMs;
21934
21962
  }
21935
21963
  function writeVersionCache(filename, cache) {
21936
- const path50 = getVersionCachePath(filename);
21937
- const dir = dirname6(path50);
21964
+ const path51 = getVersionCachePath(filename);
21965
+ const dir = dirname6(path51);
21938
21966
  if (!existsSync4(dir)) mkdirSync2(dir, { recursive: true });
21939
- writeFileSync2(path50, JSON.stringify(cache));
21967
+ writeFileSync2(path51, JSON.stringify(cache));
21940
21968
  }
21941
21969
  function touchVersionCache(filename) {
21942
21970
  writeVersionCache(filename, { lastCheck: Date.now(), latest: readVersionCache(filename)?.latest ?? null });
@@ -21975,14 +22003,14 @@ function parseFrontmatterVersion(content) {
21975
22003
  function findInstalledSkills(projectRoot, paths = SKILL_INSTALL_PATHS) {
21976
22004
  const found = [];
21977
22005
  for (const rel of paths) {
21978
- const path50 = join9(projectRoot, rel);
21979
- if (!existsSync5(path50)) continue;
22006
+ const path51 = join9(projectRoot, rel);
22007
+ if (!existsSync5(path51)) continue;
21980
22008
  let version = null;
21981
22009
  try {
21982
- version = parseFrontmatterVersion(readFileSync7(path50, "utf-8"));
22010
+ version = parseFrontmatterVersion(readFileSync7(path51, "utf-8"));
21983
22011
  } catch {
21984
22012
  }
21985
- found.push({ path: path50, version });
22013
+ found.push({ path: path51, version });
21986
22014
  }
21987
22015
  return found;
21988
22016
  }
@@ -23228,7 +23256,7 @@ function buildWorkspaceState(resolved) {
23228
23256
  return { scoped: true, path: resolved.path, hub_count: hubCount };
23229
23257
  }
23230
23258
  async function statusCommand(args2, pkg2) {
23231
- const { json } = parseArgs2(args2);
23259
+ const { json: json2 } = parseArgs2(args2);
23232
23260
  const config = readConfig();
23233
23261
  const resolvedRepo = resolveRepoConfig();
23234
23262
  const repoConfig = resolvedRepo?.config ?? null;
@@ -23261,7 +23289,7 @@ async function statusCommand(args2, pkg2) {
23261
23289
  worktree_binding: { hub_id: boundHubId },
23262
23290
  worktree_lock: { hub_id: boundHubId }
23263
23291
  };
23264
- if (json) {
23292
+ if (json2) {
23265
23293
  console.log(JSON.stringify(snapshot2, null, 2));
23266
23294
  } else {
23267
23295
  console.log("Not logged in. Run `wayai login`.");
@@ -23318,7 +23346,7 @@ async function statusCommand(args2, pkg2) {
23318
23346
  worktree_binding: { hub_id: boundHubId },
23319
23347
  worktree_lock: { hub_id: boundHubId }
23320
23348
  };
23321
- if (json) {
23349
+ if (json2) {
23322
23350
  console.log(JSON.stringify(snapshot, null, 2));
23323
23351
  return;
23324
23352
  }
@@ -23394,11 +23422,11 @@ function parseArgs3(args2) {
23394
23422
  return { json: args2.includes("--json") };
23395
23423
  }
23396
23424
  async function whoamiCommand(args2) {
23397
- const { json } = parseArgs3(args2);
23425
+ const { json: json2 } = parseArgs3(args2);
23398
23426
  const { config, accessToken } = await requireAuth();
23399
23427
  const client = new ApiClient({ apiUrl: config.api_url, accessToken });
23400
23428
  const me = await client.me();
23401
- if (json) {
23429
+ if (json2) {
23402
23430
  console.log(JSON.stringify(me, null, 2));
23403
23431
  return;
23404
23432
  }
@@ -25915,12 +25943,12 @@ async function createDataClient(orgId, opts = {}) {
25915
25943
  return orgId2;
25916
25944
  }
25917
25945
  return {
25918
- async request(method, path50, body, headers) {
25919
- const envelope = await api.dataRequest(method, path50, body, org, headers);
25946
+ async request(method, path51, body, headers) {
25947
+ const envelope = await api.dataRequest(method, path51, body, org, headers);
25920
25948
  return envelope.data;
25921
25949
  },
25922
- async requestRaw(method, path50, body) {
25923
- const body_ = await api.dataRequest(method, path50, body, org);
25950
+ async requestRaw(method, path51, body) {
25951
+ const body_ = await api.dataRequest(method, path51, body, org);
25924
25952
  return body_;
25925
25953
  },
25926
25954
  async collectPages(makePath) {
@@ -26004,7 +26032,7 @@ function foreignSegment(value, label3 = "id") {
26004
26032
  return encodeURIComponent(value);
26005
26033
  }
26006
26034
  function pathSegments(value, label3 = "path") {
26007
- return value.split("/").map((segment) => foreignSegment(segment, label3)).join("/");
26035
+ return value.split("/").map((segment2) => foreignSegment(segment2, label3)).join("/");
26008
26036
  }
26009
26037
  function parseData(data, flag) {
26010
26038
  const prefix = flag ? `${flag}: ` : "";
@@ -30979,8 +31007,8 @@ var init_diff = __esm({
30979
31007
  // src/lib/page-scaffold.ts
30980
31008
  import * as yaml16 from "js-yaml";
30981
31009
  function titleOf(slug) {
30982
- const words = slug.split("-").join(" ");
30983
- return words.charAt(0).toUpperCase() + words.slice(1);
31010
+ const words2 = slug.split("-").join(" ");
31011
+ return words2.charAt(0).toUpperCase() + words2.slice(1);
30984
31012
  }
30985
31013
  function escapeHtml(text5) {
30986
31014
  return text5.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
@@ -34262,15 +34290,15 @@ var init_caller_audio = __esm({
34262
34290
  }
34263
34291
  describe;
34264
34292
  async clipFor(line) {
34265
- const path50 = line.clip ? isAbsolute2(line.clip) ? line.clip : resolve10(this.planDir, line.clip) : this.dir ? join33(this.dir, `${line.n}.wav`) : null;
34266
- if (!path50) throw new Error(`Line ${line.n} has no clip: give --clips <dir>, or a "clip" for it in the plan.`);
34293
+ const path51 = line.clip ? isAbsolute2(line.clip) ? line.clip : resolve10(this.planDir, line.clip) : this.dir ? join33(this.dir, `${line.n}.wav`) : null;
34294
+ if (!path51) throw new Error(`Line ${line.n} has no clip: give --clips <dir>, or a "clip" for it in the plan.`);
34267
34295
  let buf;
34268
34296
  try {
34269
- buf = readFileSync17(path50);
34297
+ buf = readFileSync17(path51);
34270
34298
  } catch {
34271
- throw new Error(`Line ${line.n}'s clip ${path50} cannot be read.`);
34299
+ throw new Error(`Line ${line.n}'s clip ${path51} cannot be read.`);
34272
34300
  }
34273
- return parseWav(buf, path50);
34301
+ return parseWav(buf, path51);
34274
34302
  }
34275
34303
  };
34276
34304
  OPENAI_PCM_SAMPLE_RATE = 24e3;
@@ -34300,17 +34328,17 @@ ${text5}`).digest("hex");
34300
34328
  return join33(this.cacheDir, `${key}.pcm`);
34301
34329
  }
34302
34330
  clipFor(line) {
34303
- const path50 = this.cachePath(line.say);
34304
- let pending = this.inFlight.get(path50);
34331
+ const path51 = this.cachePath(line.say);
34332
+ let pending = this.inFlight.get(path51);
34305
34333
  if (!pending) {
34306
- pending = this.readOrSynthesize(line, path50);
34307
- this.inFlight.set(path50, pending);
34334
+ pending = this.readOrSynthesize(line, path51);
34335
+ this.inFlight.set(path51, pending);
34308
34336
  }
34309
34337
  return pending;
34310
34338
  }
34311
- async readOrSynthesize(line, path50) {
34339
+ async readOrSynthesize(line, path51) {
34312
34340
  try {
34313
- return pcmClip(readFileSync17(path50));
34341
+ return pcmClip(readFileSync17(path51));
34314
34342
  } catch {
34315
34343
  }
34316
34344
  const res = await this.doFetch("https://api.openai.com/v1/audio/speech", {
@@ -34324,10 +34352,10 @@ ${text5}`).digest("hex");
34324
34352
  }
34325
34353
  const buf = Buffer.from(await res.arrayBuffer());
34326
34354
  if (buf.length < 2) throw new Error(`OpenAI speech synthesis returned no audio for line ${line.n}.`);
34327
- mkdirSync12(dirname12(path50), { recursive: true });
34328
- const tmp = `${path50}.${process.pid}.tmp`;
34355
+ mkdirSync12(dirname12(path51), { recursive: true });
34356
+ const tmp = `${path51}.${process.pid}.tmp`;
34329
34357
  writeFileSync7(tmp, buf);
34330
- renameSync5(tmp, path50);
34358
+ renameSync5(tmp, path51);
34331
34359
  return pcmClip(buf);
34332
34360
  }
34333
34361
  };
@@ -35265,9 +35293,9 @@ function factLabel(fact) {
35265
35293
  return `${fact.kind}:${fact.raw}`;
35266
35294
  }
35267
35295
  function tokens(text5) {
35268
- const words = normalizeText(text5).split(/[^a-z0-9]+/).filter((w) => w.length > 1 && !/^\d+$/.test(w) && !isNumberWord(w));
35296
+ const words2 = normalizeText(text5).split(/[^a-z0-9]+/).filter((w) => w.length > 1 && !/^\d+$/.test(w) && !isNumberWord(w));
35269
35297
  const facts = extractFacts(text5).map((f) => `#${f.kind}:${f.key}`);
35270
- return /* @__PURE__ */ new Set([...words, ...facts]);
35298
+ return /* @__PURE__ */ new Set([...words2, ...facts]);
35271
35299
  }
35272
35300
  function similarity(a, b) {
35273
35301
  const ta = tokens(a);
@@ -35306,8 +35334,8 @@ function percentile(values, p) {
35306
35334
  function styleProblem(reply, maxSentenceWords) {
35307
35335
  if (markdownToPlainText(reply) !== reply || LIST_MARKER.test(reply)) return "markdown";
35308
35336
  for (const sentence of reply.split(/(?<=[.!?…])\s+|\n+/)) {
35309
- const words = sentence.trim().split(/\s+/).filter(Boolean).length;
35310
- if (words > maxSentenceWords) return `a sentence of ${words} words`;
35337
+ const words2 = sentence.trim().split(/\s+/).filter(Boolean).length;
35338
+ if (words2 > maxSentenceWords) return `a sentence of ${words2} words`;
35311
35339
  }
35312
35340
  return null;
35313
35341
  }
@@ -35892,15 +35920,15 @@ function parseEvalCallArgs(args2) {
35892
35920
  if (parsed.jsonPath) checkReportPath(parsed.jsonPath);
35893
35921
  return parsed;
35894
35922
  }
35895
- function checkReportPath(path50) {
35896
- const target = resolve11(path50);
35923
+ function checkReportPath(path51) {
35924
+ const target = resolve11(path51);
35897
35925
  const dir = dirname13(target);
35898
- if (!existsSync17(dir) || !statSync8(dir).isDirectory()) fail(`--json ${path50}: the folder ${dir} does not exist.`);
35899
- if (existsSync17(target) && statSync8(target).isDirectory()) fail(`--json ${path50} is a folder; name a file.`);
35926
+ if (!existsSync17(dir) || !statSync8(dir).isDirectory()) fail(`--json ${path51}: the folder ${dir} does not exist.`);
35927
+ if (existsSync17(target) && statSync8(target).isDirectory()) fail(`--json ${path51} is a folder; name a file.`);
35900
35928
  try {
35901
35929
  accessSync(existsSync17(target) ? target : dir, fsConstants.W_OK);
35902
35930
  } catch {
35903
- fail(`--json ${path50} cannot be written here.`);
35931
+ fail(`--json ${path51} cannot be written here.`);
35904
35932
  }
35905
35933
  }
35906
35934
  function suiteExitCode(report2, runs, reportWritten) {
@@ -37889,7 +37917,7 @@ function getFlagValue(args2, flag) {
37889
37917
  return idx !== -1 ? args2[idx + 1] : void 0;
37890
37918
  }
37891
37919
  async function orgCreate(args2) {
37892
- const json = args2.includes("--json");
37920
+ const json2 = args2.includes("--json");
37893
37921
  const name = firstPositional(args2);
37894
37922
  if (!name) {
37895
37923
  console.error('Usage: wayai org create "<name>" [--region <region>] [--json]');
@@ -37898,9 +37926,9 @@ async function orgCreate(args2) {
37898
37926
  const region = getFlagValue(args2, "--region");
37899
37927
  const { config, accessToken } = await requireAuth();
37900
37928
  const client = new ApiClient({ apiUrl: config.api_url, accessToken });
37901
- if (!json) console.log(`Creating organization "${name}"...`);
37929
+ if (!json2) console.log(`Creating organization "${name}"...`);
37902
37930
  const { organization } = await client.createOrganization(name, region);
37903
- if (json) {
37931
+ if (json2) {
37904
37932
  console.log(JSON.stringify(organization, null, 2));
37905
37933
  return;
37906
37934
  }
@@ -38021,24 +38049,24 @@ __export(list_exports, {
38021
38049
  });
38022
38050
  function parseArgs23(args2) {
38023
38051
  let orgId;
38024
- let json = false;
38052
+ let json2 = false;
38025
38053
  for (let i = 0; i < args2.length; i++) {
38026
38054
  if (args2[i] === "--org" && args2[i + 1]) {
38027
38055
  orgId = args2[++i];
38028
38056
  } else if (args2[i] === "--json") {
38029
- json = true;
38057
+ json2 = true;
38030
38058
  }
38031
38059
  }
38032
- return { orgId, json };
38060
+ return { orgId, json: json2 };
38033
38061
  }
38034
38062
  async function listCommand(args2) {
38035
- const { orgId, json } = parseArgs23(args2);
38063
+ const { orgId, json: json2 } = parseArgs23(args2);
38036
38064
  const { config, accessToken } = await requireAuth();
38037
38065
  const client = new ApiClient({ apiUrl: config.api_url, accessToken });
38038
38066
  const { organizations } = await client.organizations();
38039
38067
  const orgsToList = orgId ? organizations.filter((o) => o.id === orgId) : organizations;
38040
38068
  if (orgsToList.length === 0) {
38041
- if (json) {
38069
+ if (json2) {
38042
38070
  console.log(JSON.stringify({ organizations: [] }, null, 2));
38043
38071
  } else {
38044
38072
  console.log(orgId ? `Organization ${orgId} not found.` : "No organizations found.");
@@ -38048,7 +38076,7 @@ async function listCommand(args2) {
38048
38076
  const results = await Promise.all(
38049
38077
  orgsToList.map((org) => client.listHubs(org.id).then((r) => ({ org, hubs: r.hubs })))
38050
38078
  );
38051
- if (json) {
38079
+ if (json2) {
38052
38080
  const payload = {
38053
38081
  organizations: results.map(({ org, hubs }) => ({
38054
38082
  organization_id: org.id,
@@ -38149,7 +38177,7 @@ async function communitiesCommand(args2) {
38149
38177
  console.log(USAGE3);
38150
38178
  return;
38151
38179
  }
38152
- const { positionals, org, json, yes } = parse(args2);
38180
+ const { positionals, org, json: json2, yes } = parse(args2);
38153
38181
  const [sub, ...rest] = positionals;
38154
38182
  if (sub === void 0) throw usageError2("No subcommand given.");
38155
38183
  if (!SUBCOMMANDS.includes(sub)) throw usageError2(`Unknown subcommand ${JSON.stringify(sub)}.`);
@@ -38166,19 +38194,19 @@ async function communitiesCommand(args2) {
38166
38194
  switch (sub) {
38167
38195
  case "list":
38168
38196
  if (rest.length > 0) throw usageError2(`Unexpected argument ${JSON.stringify(rest[0])}.`);
38169
- return runList(resolveOrgId(org), json);
38197
+ return runList(resolveOrgId(org), json2);
38170
38198
  case "join-link": {
38171
38199
  const [, selector, ...extra] = rest;
38172
38200
  if (selector === void 0 || extra.length > 0) throw usageError2(`join-link ${action} takes one <community>.`);
38173
38201
  if (changesLink && !yes && !isInteractive()) {
38174
38202
  throw usageError2(`join-link ${action} asks before it changes the link; pass -y when not running in a terminal.`);
38175
38203
  }
38176
- return runJoinLink(action, targetOf(selector, org), { json, yes });
38204
+ return runJoinLink(action, targetOf(selector, org), { json: json2, yes });
38177
38205
  }
38178
38206
  case "stats": {
38179
38207
  const [selector, ...extra] = rest;
38180
38208
  if (selector === void 0 || extra.length > 0) throw usageError2("stats takes one <community>.");
38181
- return runStats(targetOf(selector, org), json);
38209
+ return runStats(targetOf(selector, org), json2);
38182
38210
  }
38183
38211
  case "access": {
38184
38212
  const [, selector, ...emails] = rest;
@@ -38191,16 +38219,16 @@ async function communitiesCommand(args2) {
38191
38219
  throw usageError2("access remove asks before it removes anyone; pass -y when not running in a terminal.");
38192
38220
  }
38193
38221
  const target = targetOf(selector, org);
38194
- if (action === "list") return runAccessList(target, json);
38195
- if (action === "add") return runAccessAdd(target, valid, json);
38196
- return runAccessRemove(target, valid[0], { json, yes });
38222
+ if (action === "list") return runAccessList(target, json2);
38223
+ if (action === "add") return runAccessAdd(target, valid, json2);
38224
+ return runAccessRemove(target, valid[0], { json: json2, yes });
38197
38225
  }
38198
38226
  }
38199
38227
  }
38200
- async function runList(orgId, json) {
38228
+ async function runList(orgId, json2) {
38201
38229
  const api = await communitiesClient();
38202
38230
  const { data } = await callCommunities(api.listOrgCommunities(orgId), orgNotFound(orgId));
38203
- if (json) {
38231
+ if (json2) {
38204
38232
  console.log(JSON.stringify(data, null, 2));
38205
38233
  return;
38206
38234
  }
@@ -38212,13 +38240,13 @@ async function runList(orgId, json) {
38212
38240
  `);
38213
38241
  printRows(data.map((c) => ({ name: c.name, community_id: c.community_id, created_at: c.created_at })));
38214
38242
  }
38215
- async function runJoinLink(action, target, { json, yes }) {
38243
+ async function runJoinLink(action, target, { json: json2, yes }) {
38216
38244
  const api = await communitiesClient();
38217
38245
  const { id, label: label3 } = await resolveCommunity(api, target);
38218
38246
  const notFound = communityNotFound(label3);
38219
38247
  if (action === "get") {
38220
38248
  const { data: data2 } = await callCommunities(api.getCommunityJoinLink(id), notFound);
38221
- printLink(data2, label3, json);
38249
+ printLink(data2, label3, json2);
38222
38250
  return;
38223
38251
  }
38224
38252
  await warnThenAsk(
@@ -38233,14 +38261,14 @@ async function runJoinLink(action, target, { json, yes }) {
38233
38261
  action === "rotate" ? api.replaceCommunityJoinLink(id) : api.disableCommunityJoinLink(id),
38234
38262
  notFound
38235
38263
  );
38236
- printLink(data, label3, json);
38264
+ printLink(data, label3, json2);
38237
38265
  }
38238
38266
  async function warnThenAsk(warning, yes, aborted) {
38239
38267
  for (const line of warning) console.error(line);
38240
38268
  if (!yes && !await confirm("Proceed?")) throw expected(aborted);
38241
38269
  }
38242
- function printLink(link, label3, json) {
38243
- if (json) {
38270
+ function printLink(link, label3, json2) {
38271
+ if (json2) {
38244
38272
  console.log(JSON.stringify(link, null, 2));
38245
38273
  return;
38246
38274
  }
@@ -38251,11 +38279,11 @@ function printLink(link, label3, json) {
38251
38279
  }
38252
38280
  console.log(`The join link of ${label3} is off. \`wayai communities join-link rotate\` makes a new one.`);
38253
38281
  }
38254
- async function runStats(target, json) {
38282
+ async function runStats(target, json2) {
38255
38283
  const api = await communitiesClient();
38256
38284
  const { id, label: label3 } = await resolveCommunity(api, target);
38257
38285
  const { data } = await callCommunities(api.getCommunityStats(id), communityNotFound(label3));
38258
- if (json) {
38286
+ if (json2) {
38259
38287
  console.log(JSON.stringify(data, null, 2));
38260
38288
  return;
38261
38289
  }
@@ -38335,12 +38363,12 @@ async function* accessPages(api, id, notFound) {
38335
38363
  cursor = data.next_cursor ?? void 0;
38336
38364
  } while (cursor !== void 0);
38337
38365
  }
38338
- async function runAccessList(target, json) {
38366
+ async function runAccessList(target, json2) {
38339
38367
  const api = await communitiesClient();
38340
38368
  const { id, label: label3 } = await resolveCommunity(api, target);
38341
38369
  const entries = [];
38342
38370
  for await (const page of accessPages(api, id, communityNotFound(label3))) entries.push(...page);
38343
- if (json) {
38371
+ if (json2) {
38344
38372
  console.log(JSON.stringify(entries, null, 2));
38345
38373
  return;
38346
38374
  }
@@ -38352,11 +38380,11 @@ async function runAccessList(target, json) {
38352
38380
  `);
38353
38381
  printRows(entries.map((entry) => ({ email: entry.email, added: entry.created_at })));
38354
38382
  }
38355
- async function runAccessAdd(target, emails, json) {
38383
+ async function runAccessAdd(target, emails, json2) {
38356
38384
  const api = await communitiesClient();
38357
38385
  const { id, label: label3 } = await resolveCommunity(api, target);
38358
38386
  const { data } = await callAccess(api.addCommunityAccess(id, { emails }), communityNotFound(label3), label3);
38359
- if (json) {
38387
+ if (json2) {
38360
38388
  console.log(JSON.stringify(data, null, 2));
38361
38389
  return;
38362
38390
  }
@@ -38364,7 +38392,7 @@ async function runAccessAdd(target, emails, json) {
38364
38392
  const listed3 = already === 0 ? "" : `; ${already} ${already === 1 ? "was" : "were"} already on it`;
38365
38393
  console.log(`Added ${added.length} email(s) to the access list of ${label3}${listed3}.`);
38366
38394
  }
38367
- async function runAccessRemove(target, email, { json, yes }) {
38395
+ async function runAccessRemove(target, email, { json: json2, yes }) {
38368
38396
  const api = await communitiesClient();
38369
38397
  const { id, label: label3 } = await resolveCommunity(api, target);
38370
38398
  let entry;
@@ -38383,7 +38411,7 @@ async function runAccessRemove(target, email, { json, yes }) {
38383
38411
  `${email} is no longer on the access list of ${label3}, or you are not an owner or admin of its organization. Nothing was removed.`,
38384
38412
  label3
38385
38413
  );
38386
- if (json) {
38414
+ if (json2) {
38387
38415
  console.log(JSON.stringify(entry, null, 2));
38388
38416
  return;
38389
38417
  }
@@ -38802,9 +38830,9 @@ function caseLocalPathProblem(rel) {
38802
38830
  if (rel.includes("\0")) return "it holds a NUL";
38803
38831
  if (rel.includes("\\")) return "it holds a backslash";
38804
38832
  if (rel.startsWith("/") || /^[A-Za-z]:/.test(rel)) return "it is absolute";
38805
- for (const segment of rel.split("/")) {
38806
- if (segment === "") return "it has an empty segment";
38807
- if (segment === "." || segment === "..") return `it has a "${segment}" segment`;
38833
+ for (const segment2 of rel.split("/")) {
38834
+ if (segment2 === "") return "it has an empty segment";
38835
+ if (segment2 === "." || segment2 === "..") return `it has a "${segment2}" segment`;
38808
38836
  }
38809
38837
  return null;
38810
38838
  }
@@ -38826,8 +38854,8 @@ function writeCaseLocalFile(root, rel, data) {
38826
38854
  const target = path42.join(root, ...rel.split("/"));
38827
38855
  requireOwn(root);
38828
38856
  let folder = root;
38829
- for (const segment of rel.split("/").slice(0, -1)) {
38830
- folder = path42.join(folder, segment);
38857
+ for (const segment2 of rel.split("/").slice(0, -1)) {
38858
+ folder = path42.join(folder, segment2);
38831
38859
  let st;
38832
38860
  try {
38833
38861
  st = fs30.lstatSync(folder);
@@ -39599,14 +39627,14 @@ var init_case_file_paths = __esm({
39599
39627
  // src/data/files-sync/local.ts
39600
39628
  import * as fs34 from "fs";
39601
39629
  import * as path46 from "path";
39602
- function foldSegment(segment) {
39603
- return segment.normalize("NFC").toLowerCase().replace(/[. ]+$/, "");
39630
+ function foldSegment(segment2) {
39631
+ return segment2.normalize("NFC").toLowerCase().replace(/[. ]+$/, "");
39604
39632
  }
39605
39633
  function foldPath(rel) {
39606
39634
  return rel.split("/").map(foldSegment).join("/");
39607
39635
  }
39608
39636
  function isOutsideSync(rel) {
39609
- return rel.split("/").some((segment) => OUTSIDE_SYNC_FOLDED.has(foldSegment(segment)));
39637
+ return rel.split("/").some((segment2) => OUTSIDE_SYNC_FOLDED.has(foldSegment(segment2)));
39610
39638
  }
39611
39639
  function isCleanPath(segments) {
39612
39640
  return segments.every((s) => s !== "" && s !== "." && s !== ".." && !/[\\\0]/.test(s));
@@ -39632,10 +39660,10 @@ function describeSync(r) {
39632
39660
  const where = r.folder ? `folder "${r.folder}"` : "the whole file type";
39633
39661
  return sanitizeTerminalText(`base "${r.base}", file type "${r.file_type}", ${where}`);
39634
39662
  }
39635
- function isWindowsAlias(segment) {
39636
- if (segment.includes(":")) return true;
39637
- const dot = segment.lastIndexOf(".");
39638
- const [stem, ext] = dot > 0 ? [segment.slice(0, dot), segment.slice(dot + 1)] : [segment, ""];
39663
+ function isWindowsAlias(segment2) {
39664
+ if (segment2.includes(":")) return true;
39665
+ const dot = segment2.lastIndexOf(".");
39666
+ const [stem, ext] = dot > 0 ? [segment2.slice(0, dot), segment2.slice(dot + 1)] : [segment2, ""];
39639
39667
  return stem.length <= 8 && /~\d+$/.test(stem) && ext.length <= 3;
39640
39668
  }
39641
39669
  function assertRepresentable(rels, platform2 = process.platform) {
@@ -40008,25 +40036,25 @@ var init_plan = __esm({
40008
40036
  constructor(paths = []) {
40009
40037
  for (const p of paths) this.add(p);
40010
40038
  }
40011
- add(path50) {
40012
- this.cases.add(path50);
40013
- this.files.add(path50);
40014
- const segments = path50.split("/");
40039
+ add(path51) {
40040
+ this.cases.add(path51);
40041
+ this.files.add(path51);
40042
+ const segments = path51.split("/");
40015
40043
  for (let i = 1; i < segments.length; i++) {
40016
40044
  const folder = segments.slice(0, i).join("/");
40017
- if (!this.folders.has(folder)) this.folders.set(folder, path50);
40045
+ if (!this.folders.has(folder)) this.folders.set(folder, path51);
40018
40046
  }
40019
40047
  }
40020
40048
  /** The path `path` would collide with, and how; undefined when it collides with none. */
40021
- clash(path50) {
40022
- const twin = this.cases.twinOf(path50);
40049
+ clash(path51) {
40050
+ const twin = this.cases.twinOf(path51);
40023
40051
  if (twin !== void 0) return { reason: "case_twin", other: twin };
40024
- const segments = path50.split("/");
40052
+ const segments = path51.split("/");
40025
40053
  for (let i = 1; i < segments.length; i++) {
40026
40054
  const folder = segments.slice(0, i).join("/");
40027
40055
  if (this.files.has(folder)) return { reason: "file_folder", other: folder };
40028
40056
  }
40029
- const inside = this.folders.get(path50);
40057
+ const inside = this.folders.get(path51);
40030
40058
  return inside === void 0 ? void 0 : { reason: "file_folder", other: inside };
40031
40059
  }
40032
40060
  };
@@ -40090,9 +40118,9 @@ async function openRemote2() {
40090
40118
  )
40091
40119
  });
40092
40120
  return {
40093
- request: (method, path50, body, headers) => pacer.run(() => client.request(method, path50, body, headers)),
40094
- upload: (path50, bytes, contentType, headers) => pacer.run(() => client.upload(path50, bytes, contentType, headers)),
40095
- download: (path50) => pacer.run(() => client.download(path50))
40121
+ request: (method, path51, body, headers) => pacer.run(() => client.request(method, path51, body, headers)),
40122
+ upload: (path51, bytes, contentType, headers) => pacer.run(() => client.upload(path51, bytes, contentType, headers)),
40123
+ download: (path51) => pacer.run(() => client.download(path51))
40096
40124
  };
40097
40125
  }
40098
40126
  function filesRoot(t) {
@@ -40225,13 +40253,13 @@ async function pullFiles(opts) {
40225
40253
  conflicts.push({ rel: w.rel, ...clash });
40226
40254
  continue;
40227
40255
  }
40228
- const path50 = filePath2(target, w.rel);
40256
+ const path51 = filePath2(target, w.rel);
40229
40257
  let bytes;
40230
40258
  let version = w.remote.version;
40231
40259
  try {
40232
- bytes = (await client.download(path50)).bytes;
40260
+ bytes = (await client.download(path51)).bytes;
40233
40261
  if (computeHash(bytes) !== w.remote.content_sha256) {
40234
- const meta = await client.request("GET", `${path50}?meta=1`);
40262
+ const meta = await client.request("GET", `${path51}?meta=1`);
40235
40263
  if (meta?.content_sha256 !== computeHash(bytes)) {
40236
40264
  changedWhilePulling.push(w.rel);
40237
40265
  continue;
@@ -40360,7 +40388,7 @@ Push ${n} change${n === 1 ? "" : "s"} to ${describeSync(target)}?`, opts.yes)) {
40360
40388
  let pushed = 0;
40361
40389
  const refusedDeletes = /* @__PURE__ */ new Set();
40362
40390
  for (const step of plan.steps) {
40363
- const path50 = filePath2(target, step.rel);
40391
+ const path51 = filePath2(target, step.rel);
40364
40392
  const blockedBy = step.op === "create" ? step.after?.find((d) => refusedDeletes.has(d.rel)) : void 0;
40365
40393
  if (blockedBy !== void 0) {
40366
40394
  const conflict = { rel: step.rel, reason: blockedBy.reason, other: blockedBy.rel };
@@ -40370,7 +40398,7 @@ Push ${n} change${n === 1 ? "" : "s"} to ${describeSync(target)}?`, opts.yes)) {
40370
40398
  }
40371
40399
  try {
40372
40400
  if (step.op === "delete") {
40373
- await client.request("DELETE", path50, void 0, fileWriteHeaders({ ifMatch: step.ifMatch }));
40401
+ await client.request("DELETE", path51, void 0, fileWriteHeaders({ ifMatch: step.ifMatch }));
40374
40402
  delete record.files[step.rel];
40375
40403
  } else {
40376
40404
  const bytes = readLocal2(dir, step.rel);
@@ -40379,7 +40407,7 @@ Push ${n} change${n === 1 ? "" : "s"} to ${describeSync(target)}?`, opts.yes)) {
40379
40407
  }
40380
40408
  const contentType = step.op === "update" ? step.remote.content_type : guessMimeType(step.rel) ?? "application/octet-stream";
40381
40409
  const row = await client.upload(
40382
- path50,
40410
+ path51,
40383
40411
  bytes,
40384
40412
  contentType,
40385
40413
  fileWriteHeaders({ ...step.op === "update" ? { ifMatch: step.ifMatch } : { createOnly: true }, label: label3 })
@@ -40466,9 +40494,542 @@ var init_sync3 = __esm({
40466
40494
  }
40467
40495
  });
40468
40496
 
40469
- // src/cases/case-files.ts
40497
+ // ../../packages/core/dist/contracts/case-comments.js
40498
+ var init_case_comments = __esm({
40499
+ "../../packages/core/dist/contracts/case-comments.js"() {
40500
+ "use strict";
40501
+ init_chunk_S7UAXLHJ();
40502
+ init_chunk_7TQYAKCB();
40503
+ init_chunk_VROZDNLV();
40504
+ init_chunk_733K4J4G();
40505
+ init_chunk_PFPADFUC();
40506
+ init_chunk_KWRHZBGU();
40507
+ init_chunk_3T3D7LTE();
40508
+ init_chunk_M2T55BV6();
40509
+ init_chunk_VYINA6YP();
40510
+ init_chunk_ZVXO3XL6();
40511
+ init_chunk_FBV7NLKO();
40512
+ init_chunk_WEXVYJ5H();
40513
+ init_chunk_HZ6CADSY();
40514
+ init_chunk_ICYO56QW();
40515
+ init_chunk_WFQDSQJK();
40516
+ init_chunk_ZTNFLGW5();
40517
+ }
40518
+ });
40519
+
40520
+ // ../../packages/core/dist/contracts/case-types.js
40521
+ var init_case_types = __esm({
40522
+ "../../packages/core/dist/contracts/case-types.js"() {
40523
+ "use strict";
40524
+ init_chunk_PFPADFUC();
40525
+ init_chunk_KWRHZBGU();
40526
+ init_chunk_3T3D7LTE();
40527
+ init_chunk_M2T55BV6();
40528
+ init_chunk_VYINA6YP();
40529
+ init_chunk_ZVXO3XL6();
40530
+ init_chunk_FBV7NLKO();
40531
+ init_chunk_WEXVYJ5H();
40532
+ init_chunk_HZ6CADSY();
40533
+ init_chunk_ICYO56QW();
40534
+ init_chunk_WFQDSQJK();
40535
+ init_chunk_ZTNFLGW5();
40536
+ }
40537
+ });
40538
+
40539
+ // src/cases/case-mirror.ts
40540
+ import * as crypto4 from "crypto";
40470
40541
  import * as fs35 from "fs";
40542
+ import * as os4 from "os";
40471
40543
  import * as path47 from "path";
40544
+ function shownEntries(revision, confidential) {
40545
+ return confidential ? revision.entries : revision.entries.filter((e) => !e.confidential && !isConfPath(e.path));
40546
+ }
40547
+ function isBaseline(b) {
40548
+ 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);
40549
+ }
40550
+ function isMirrorRecord(v) {
40551
+ 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));
40552
+ }
40553
+ function mirrorFolder(root) {
40554
+ const dir = path47.join(root, CASE_MIRROR_DIR);
40555
+ let st;
40556
+ try {
40557
+ st = fs35.lstatSync(dir);
40558
+ } catch {
40559
+ return null;
40560
+ }
40561
+ if (!st.isDirectory()) {
40562
+ 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.`);
40563
+ }
40564
+ requireOwn(dir);
40565
+ return dir;
40566
+ }
40567
+ function readBaseline(root, detail, record) {
40568
+ const dir = mirrorFolder(root);
40569
+ if (!dir) return null;
40570
+ const file = path47.join(dir, RECORD_FILE2);
40571
+ requireOwn(file);
40572
+ const text5 = readRealFileOrThrow(root, file);
40573
+ if (text5 === null) return null;
40574
+ let parsed;
40575
+ try {
40576
+ parsed = JSON.parse(text5);
40577
+ } catch {
40578
+ return null;
40579
+ }
40580
+ if (!isMirrorRecord(parsed)) return null;
40581
+ if (parsed.org_id !== record.org_id || parsed.space_id !== record.space_id || parsed.code !== detail.code) return null;
40582
+ return parsed.last_pull;
40583
+ }
40584
+ async function readAgenda(calls, phaseId) {
40585
+ const { api, connection } = calls.session;
40586
+ const groups = [];
40587
+ let cursor;
40588
+ for (let page = 0; page < AGENDA_PAGES_READ2; page++) {
40589
+ const { groups: got, next_cursor } = (await calls.run(() => api.getCaseAgenda(connection, phaseId, cursor))).data;
40590
+ groups.push(...got);
40591
+ if (!next_cursor) return { groups, more: false };
40592
+ cursor = next_cursor;
40593
+ }
40594
+ return { groups, more: true };
40595
+ }
40596
+ async function readInputTexts(calls, folder, work) {
40597
+ const { api, connection } = calls.session;
40598
+ const notFound = (call3) => call3.catch((err) => err instanceof ApiError && err.status === 404 ? null : Promise.reject(err));
40599
+ const linked = work.inputs.filter((input) => input.link?.readable === true);
40600
+ const read = await Promise.all(linked.map(async (input) => {
40601
+ const view = (await calls.run(() => api.getCaseInputLink(connection, input.id))).data;
40602
+ if (!view?.readable) return null;
40603
+ const answered = await calls.run(() => notFound(api.getCaseCollectionContent(connection, view.document_id, { part: "text", version_id: view.version_id })));
40604
+ const passages = view.passages.filter((p) => p.version_id === view.version_id);
40605
+ const base = { input_id: input.id, key: input.key, name: input.name, document_id: view.document_id, version_id: view.version_id };
40606
+ const unmatched = passages.map((p) => ({ passage_id: p.passage_id, line_start: p.line_start, line_end: p.line_end, passage_sha: p.passage_sha, matches: false }));
40607
+ if (!answered) return { text: { ...base, status: "no_text", file: null, sha: null, passages: unmatched }, data: null };
40608
+ if (answered.sha === null || computeHash(answered.bytes) !== answered.sha) {
40609
+ return { text: { ...base, status: "hash_mismatch", file: null, sha: answered.sha, passages: unmatched }, data: null };
40610
+ }
40611
+ const lines = unmatched.length ? casePassageLines(new TextDecoder("utf-8").decode(answered.bytes)) : [];
40612
+ const file = `${INPUTS_DIR}/${folder}/${segment(input.key, CASE_INPUT_KEY_PATTERN, input.id)}.md`;
40613
+ return {
40614
+ text: {
40615
+ ...base,
40616
+ status: "written",
40617
+ file,
40618
+ sha: answered.sha,
40619
+ passages: unmatched.map((p) => {
40620
+ const inRange = p.line_start >= 1 && p.line_end >= p.line_start && p.line_end <= lines.length;
40621
+ const cited = Buffer.from(lines.slice(p.line_start - 1, p.line_end).join("\n"), "utf-8");
40622
+ return { ...p, matches: inRange && computeHash(cited) === p.passage_sha };
40623
+ })
40624
+ },
40625
+ data: Buffer.from(answered.bytes.buffer, answered.bytes.byteOffset, answered.bytes.byteLength)
40626
+ };
40627
+ }));
40628
+ return read.filter((r) => r !== null);
40629
+ }
40630
+ async function readWork(calls, detail, confidential) {
40631
+ const { api, connection } = calls.session;
40632
+ const state = (await calls.run(() => api.getCaseState(connection))).data;
40633
+ if (state.view !== "work") return { state, phases: [], approved: [] };
40634
+ const folders = new Map(detail.phases.map((p) => [p.phase_id, p.folder]));
40635
+ const underWay = state.state.phases.filter((p) => p.status === "in_progress").map((p) => p.phase_id);
40636
+ const [phases, approved] = await Promise.all([
40637
+ Promise.all(underWay.map(async (phaseId) => {
40638
+ const folder = folders.get(phaseId) ?? "";
40639
+ const [{ work, texts }, agenda, delivery] = await Promise.all([
40640
+ calls.run(() => api.getCasePhaseWork(connection, phaseId)).then(async ({ data }) => ({
40641
+ work: data,
40642
+ texts: await readInputTexts(calls, segment(folder, CASE_PHASE_FOLDER_PATTERN, phaseId), data)
40643
+ })),
40644
+ readAgenda(calls, phaseId),
40645
+ calls.run(() => api.getCaseDelivery(connection, phaseId))
40646
+ ]);
40647
+ return { phase_id: phaseId, folder, work, groups: agenda.groups, more_groups: agenda.more, delivery: delivery.data, texts };
40648
+ })),
40649
+ calls.run(() => api.listCaseApprovedDecisions(connection, confidential))
40650
+ ]);
40651
+ return { state, phases, approved: approved.data };
40652
+ }
40653
+ async function revisionsSince(calls, after, confidential) {
40654
+ const { api, connection } = calls.session;
40655
+ const out = [];
40656
+ let newest = after ?? null;
40657
+ let cursor;
40658
+ const pages = after === void 0 ? 1 : SUMMARY_REVISION_PAGES;
40659
+ for (let page = 0; page < pages; page++) {
40660
+ const { revisions, next_cursor } = (await calls.run(() => api.listCaseRevisions(connection, { cursor, limit: CASE_REVISIONS_PAGE_MAX }))).data;
40661
+ for (const revision of revisions) {
40662
+ if (after !== void 0 && after !== null && revision.created_at <= after) return { revisions: out, more: false, newest_at: newest };
40663
+ const entries = shownEntries(revision, confidential);
40664
+ if (entries.length === 0) continue;
40665
+ if (newest === null || revision.created_at > newest) newest = revision.created_at;
40666
+ if (after !== void 0) out.push({ ...revision, entries });
40667
+ }
40668
+ if (!next_cursor) return { revisions: out, more: false, newest_at: newest };
40669
+ cursor = next_cursor;
40670
+ }
40671
+ return { revisions: out, more: after !== void 0, newest_at: newest };
40672
+ }
40673
+ function snapshotOf(work) {
40674
+ if (!work) return { status: null, phases: {}, tasks: {}, groups: {}, deliveries: {} };
40675
+ if (work.state.view === "phases") {
40676
+ return { status: work.state.status, phases: Object.fromEntries(work.state.phases.map((p) => [p.phase_id, p.status])), tasks: {}, groups: {}, deliveries: {} };
40677
+ }
40678
+ const { state } = work.state;
40679
+ return {
40680
+ status: state.status,
40681
+ phases: Object.fromEntries(state.phases.map((p) => [p.phase_id, p.status])),
40682
+ tasks: Object.fromEntries(state.tasks.map((t) => [t.case_task_id, t.status])),
40683
+ groups: Object.fromEntries(state.agenda_groups.map((g) => [g.agenda_group_id, g.status])),
40684
+ deliveries: Object.fromEntries(work.phases.map((p) => [p.phase_id, p.delivery ? { submission_id: p.delivery.submission_id, state: p.delivery.state } : null]))
40685
+ };
40686
+ }
40687
+ function statusSections(detail, work, before, now) {
40688
+ const phase = new Map(detail.phases.map((p) => [p.phase_id, `${one2(p.folder)} (${one2(p.name)})`]));
40689
+ const task = new Map((detail.tasks ?? []).map((t) => [t.case_task_id, `${one2(t.name)} [${t.case_task_id}]`]));
40690
+ const group = new Map(work.phases.flatMap((p) => p.groups.map((g) => [g.agenda_group_id, `${one2(g.code)} (${one2(g.name)})`])));
40691
+ const changes = (prev, next, name, added) => Object.entries(next).flatMap(([id, status]) => {
40692
+ const was = prev[id];
40693
+ if (was === void 0) return added ? [`${name(id)}: new, ${words(status)}`] : [];
40694
+ return was === status ? [] : [`${name(id)}: ${words(was)} \u2192 ${words(status)}`];
40695
+ });
40696
+ const sections = [];
40697
+ if (before.status !== null && now.status !== null && before.status !== now.status) {
40698
+ sections.push({ title: "The case", lines: [`${words(before.status)} \u2192 ${words(now.status)}`] });
40699
+ }
40700
+ sections.push({ title: "Phases", lines: changes(before.phases, now.phases, (id) => phase.get(id) ?? "a phase", false) });
40701
+ sections.push({ title: "Tasks", lines: changes(before.tasks, now.tasks, (id) => task.get(id) ?? `a task [${id}]`, true) });
40702
+ 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) });
40703
+ const deliveries = work.phases.flatMap((p) => {
40704
+ if (!(p.phase_id in before.deliveries) || !p.delivery) return [];
40705
+ const was = before.deliveries[p.phase_id];
40706
+ if (was?.submission_id === p.delivery.submission_id && was.state === p.delivery.state) return [];
40707
+ const change = was?.submission_id === p.delivery.submission_id ? `its submission is now ${words(p.delivery.state)}` : `a new submission, ${words(p.delivery.state)}`;
40708
+ return [`${phase.get(p.phase_id) ?? "a phase"}: ${change}`];
40709
+ });
40710
+ sections.push({ title: "Deliveries", lines: deliveries });
40711
+ return sections;
40712
+ }
40713
+ function filesSection(input) {
40714
+ const now = new Map(input.files.filter((f) => input.inRun(f.path)).map((f) => [f.path, f.sha]));
40715
+ const before = new Map(Object.entries(input.record.files).filter(([rel]) => input.inRun(rel)).map(([rel, f]) => [rel, f.sha]));
40716
+ const lines = [];
40717
+ for (const [rel, sha] of now) {
40718
+ if (!before.has(rel)) lines.push(`+ ${safe2(rel)}`);
40719
+ else if (before.get(rel) !== sha) lines.push(`~ ${safe2(rel)}`);
40720
+ }
40721
+ for (const rel of before.keys()) if (!now.has(rel)) lines.push(`- ${safe2(rel)} (removed, or no longer readable here)`);
40722
+ 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) };
40723
+ }
40724
+ function revisionsSection(since, hideMessages) {
40725
+ const lines = since.revisions.flatMap((r) => {
40726
+ const author = r.author?.display_name ? one2(r.author.display_name) : "a person no longer named";
40727
+ const message = r.message !== null && !hideMessages ? `: ${one2(r.message)}` : "";
40728
+ return [`revision ${r.revision_id}, ${r.created_at}, ${author} (${r.channel})${message}`, ...r.entries.map((e) => ` ${safe2(e.path)}${e.sha === null ? " (removed)" : ""}`)];
40729
+ });
40730
+ if (since.more) lines.push("\u2026 and older ones: `wayai cases log` lists them all.");
40731
+ return { title: "Revisions", lines };
40732
+ }
40733
+ function renderSections(sections) {
40734
+ return sections.filter((s) => s.lines.length > 0).flatMap((s) => [`${s.title}:`, ...s.lines.map((l) => ` ${l}`)]);
40735
+ }
40736
+ function unwrittenLines(work) {
40737
+ return (work?.phases ?? []).flatMap((p) => p.texts.flatMap(({ text: text5 }) => {
40738
+ const name = `${one2(p.folder)}, input ${one2(text5.key)} (${one2(text5.name)})`;
40739
+ if (text5.status === "hash_mismatch") {
40740
+ return [`${name}: not written, its bytes do not hash to the SHA-256 the space registered for it${text5.sha === null ? " (none was answered)" : ""}.`];
40741
+ }
40742
+ return text5.status === "no_text" ? [`${name}: the version it links holds no registered text, or is no longer readable here.`] : [];
40743
+ }));
40744
+ }
40745
+ function readme(detail, at, withheld, confidential, unwritten) {
40746
+ const parts = withheld ? [
40747
+ "This authorization holds the Confidential right, and the case's own reads give it confidential content whatever",
40748
+ "it asks: without --confidential this mirror holds none of them (case, status, evidence, agenda, deliveries,",
40749
+ "linked inputs' texts)."
40750
+ ] : [
40751
+ "- `case.json`: the case: its type and version, owner, parties, phases and their folders, tasks, and your access.",
40752
+ "- `status.json`: its status: each phase's, task's and agenda group's, why each is not done, and who can move it.",
40753
+ "- `evidence.json`: each phase under way: its inputs with their links, its outputs and its items.",
40754
+ "- `agenda.json`: each phase under way: its agenda groups and decisions; and the approved decisions.",
40755
+ "- `deliveries.json`: each phase under way: its newest submission and manifest.",
40756
+ `- \`${INPUTS_FILE}\`: each phase under way: each input whose link you may read, the version it links, where its text`,
40757
+ " is here, and its cited passages (lines and hash, and whether they match the text here).",
40758
+ `- \`${INPUTS_DIR}/<phase folder>/<input key>.md\`: each such input's registered text, of the version its link names,`,
40759
+ " byte for byte and checked against the SHA-256 the space registered for it: line N here is the line N a citation",
40760
+ " names (each line ends at a line break).",
40761
+ ...unwritten.length ? ["", "Linked inputs' texts not written:", ...unwritten.map((line) => `- ${line}`)] : []
40762
+ ];
40763
+ return [
40764
+ `# Case ${safe2(detail.code)}: read-only mirror`,
40765
+ "",
40766
+ `Written ${at} by \`wayai cases clone\` or \`pull\`. Every pull rewrites this folder whole, and \`wayai cases push\` never sends`,
40767
+ "anything in it: an edit here is lost and never reaches the case.",
40768
+ "",
40769
+ `- \`${SUMMARY_FILE}\`: what changed on the case since your last pull.`,
40770
+ ...parts,
40771
+ `- \`${CASE_MIRROR_HOOK_FILE}\`: the session-start hook. It refreshes this folder, never with --confidential.`,
40772
+ `- \`${RECORD_FILE2}\`: what the next pull compares with.`,
40773
+ "",
40774
+ "Not here: the drafting checks (`wayai cases check --phase <folder>` reads them live).",
40775
+ ...confidential ? [] : ["", MIRROR_CONFIDENTIAL_NOTICE],
40776
+ ""
40777
+ ].join("\n");
40778
+ }
40779
+ function lockOwnerStopped(text5) {
40780
+ const owner = text5 === null ? null : /^(\d+) (\S+) [0-9a-f]+$/.exec(text5) ?? null;
40781
+ if (!owner || owner[2] !== os4.hostname()) return false;
40782
+ try {
40783
+ process.kill(Number(owner[1]), 0);
40784
+ return false;
40785
+ } catch (err) {
40786
+ return err.code === "ESRCH";
40787
+ }
40788
+ }
40789
+ async function lockMirror(root) {
40790
+ const dir = path47.join(root, CASE_MIRROR_DIR);
40791
+ if (!mirrorFolder(root)) {
40792
+ try {
40793
+ fs35.mkdirSync(dir, { mode: CASE_FOLDER_MODE });
40794
+ fs35.chmodSync(dir, CASE_FOLDER_MODE);
40795
+ } catch (err) {
40796
+ if (err.code !== "EEXIST") throw err;
40797
+ }
40798
+ mirrorFolder(root);
40799
+ }
40800
+ const lock = path47.join(dir, LOCK_FILE);
40801
+ const mine = `${process.pid} ${os4.hostname()} ${crypto4.randomBytes(16).toString("hex")}`;
40802
+ const held = (file) => {
40803
+ try {
40804
+ return fs35.readFileSync(file, "utf-8");
40805
+ } catch {
40806
+ return null;
40807
+ }
40808
+ };
40809
+ const refusal2 = (err) => {
40810
+ const code2 = err.code;
40811
+ 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;
40812
+ };
40813
+ const deadline = Date.now() + LOCK_WAIT_MS;
40814
+ for (; ; ) {
40815
+ try {
40816
+ const fd = fs35.openSync(lock, "wx", 420);
40817
+ try {
40818
+ fs35.writeFileSync(fd, mine);
40819
+ } finally {
40820
+ fs35.closeSync(fd);
40821
+ }
40822
+ return () => {
40823
+ if (held(lock) === mine) fs35.rmSync(lock, { force: true });
40824
+ };
40825
+ } catch (err) {
40826
+ if (err.code !== "EEXIST") throw refusal2(err);
40827
+ }
40828
+ const judged = held(lock);
40829
+ let age = 0;
40830
+ try {
40831
+ age = Date.now() - fs35.lstatSync(lock).mtimeMs;
40832
+ } catch (err) {
40833
+ if (err.code === "ENOENT") continue;
40834
+ throw refusal2(err);
40835
+ }
40836
+ if (judged !== null && (lockOwnerStopped(judged) || age > LOCK_STALE_MS)) {
40837
+ const aside = path47.join(dir, `${LOCK_FILE}.stale-${mine.split(" ")[2]}`);
40838
+ try {
40839
+ fs35.renameSync(lock, aside);
40840
+ } catch (err) {
40841
+ if (err.code === "ENOENT") continue;
40842
+ throw refusal2(err);
40843
+ }
40844
+ if (held(aside) !== judged) {
40845
+ try {
40846
+ fs35.linkSync(aside, lock);
40847
+ } catch {
40848
+ }
40849
+ }
40850
+ fs35.rmSync(aside, { force: true });
40851
+ continue;
40852
+ }
40853
+ if (Date.now() > deadline) {
40854
+ throw expected(`Another run has held the mirror at ${safe2(dir)} for ${Math.round(age / 1e3)} s. Pull again once it ends.`);
40855
+ }
40856
+ await new Promise((resolve16) => setTimeout(resolve16, LOCK_POLL_MS));
40857
+ }
40858
+ }
40859
+ function writeMirror(root, files) {
40860
+ const id = crypto4.randomBytes(8).toString("hex");
40861
+ const dir = path47.join(root, CASE_MIRROR_DIR);
40862
+ const at = (name) => path47.join(dir, ...name.split("/"));
40863
+ const temp = (name) => {
40864
+ const slash = name.lastIndexOf("/");
40865
+ return `${name.slice(0, slash + 1)}.tmp-${id}-${name.slice(slash + 1)}`;
40866
+ };
40867
+ const lstat = (target) => {
40868
+ try {
40869
+ return fs35.lstatSync(target);
40870
+ } catch {
40871
+ return void 0;
40872
+ }
40873
+ };
40874
+ const folders = new Set(files.flatMap((f) => f.name.split("/").slice(0, -1).map((_, i, all) => all.slice(0, i + 1).join("/"))));
40875
+ try {
40876
+ for (const folder of folders) {
40877
+ const st = lstat(at(folder));
40878
+ if (st && !st.isDirectory()) fs35.rmSync(at(folder), { force: true });
40879
+ }
40880
+ for (const f of files) {
40881
+ writeCaseLocalFile(root, `${CASE_MIRROR_DIR}/${temp(f.name)}`, f.data);
40882
+ if (f.mode !== void 0) fs35.chmodSync(at(temp(f.name)), f.mode);
40883
+ }
40884
+ for (const f of files) {
40885
+ if (lstat(at(f.name))?.isDirectory()) fs35.rmSync(at(f.name), { recursive: true, force: true });
40886
+ fs35.renameSync(at(temp(f.name)), at(f.name));
40887
+ }
40888
+ const names = new Set(files.map((f) => f.name));
40889
+ const sweep = (folder) => {
40890
+ for (const name of fs35.readdirSync(folder === null ? dir : at(folder))) {
40891
+ const rel = folder === null ? name : `${folder}/${name}`;
40892
+ if (names.has(rel) || rel === LOCK_FILE) continue;
40893
+ if (folders.has(rel) && lstat(at(rel))?.isDirectory()) sweep(rel);
40894
+ else fs35.rmSync(at(rel), { recursive: true, force: true });
40895
+ }
40896
+ };
40897
+ sweep(null);
40898
+ } finally {
40899
+ for (const f of files) fs35.rmSync(at(temp(f.name)), { force: true });
40900
+ }
40901
+ }
40902
+ async function writeCaseMirror(calls, input) {
40903
+ const { root, detail, confidential, mode } = input;
40904
+ const before = mode === "clone" ? null : readBaseline(root, detail, input.record);
40905
+ const withheld = detail.access.capabilities.includes("read_confidential") && !confidential;
40906
+ const readsRevisions = before !== null || mode !== "mirror-only";
40907
+ const [work, since] = await Promise.all([
40908
+ withheld ? null : readWork(calls, detail, confidential),
40909
+ readsRevisions ? revisionsSince(calls, before ? before.revision_at : void 0, confidential) : NO_REVISIONS
40910
+ ]);
40911
+ const now = snapshotOf(work);
40912
+ const at = nowIso();
40913
+ let baseline;
40914
+ if (mode !== "mirror-only") {
40915
+ baseline = { at, confidential, revision_at: since.newest_at, ...now };
40916
+ } else if (before && before.confidential && !confidential) {
40917
+ baseline = {
40918
+ ...before,
40919
+ confidential: false,
40920
+ status: now.status === null ? null : before.status,
40921
+ phases: within(before.phases, now.phases),
40922
+ tasks: within(before.tasks, now.tasks),
40923
+ groups: within(before.groups, now.groups),
40924
+ deliveries: within(before.deliveries, now.deliveries)
40925
+ };
40926
+ } else {
40927
+ baseline = before;
40928
+ }
40929
+ const sections = [];
40930
+ if (before) sections.push(revisionsSection(since, withheld));
40931
+ if (mode !== "clone") sections.push(filesSection(input));
40932
+ if (before && work) sections.push(...statusSections(detail, work, before, now));
40933
+ const lines = renderSections(sections);
40934
+ 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.";
40935
+ const summary = [heading, ...lines.length ? lines : before ? ["Nothing changed."] : []];
40936
+ const notice = confidential ? [] : ["", MIRROR_CONFIDENTIAL_NOTICE];
40937
+ const unwritten = unwrittenLines(work);
40938
+ const files = [
40939
+ { name: "README.md", data: Buffer.from(readme(detail, at, withheld, confidential, unwritten), "utf-8") },
40940
+ { name: SUMMARY_FILE, data: Buffer.from(`# Case ${safe2(detail.code)}: since the last pull
40941
+
40942
+ ${[...summary, ...notice].join("\n")}
40943
+ `, "utf-8") },
40944
+ { name: CASE_MIRROR_HOOK_FILE, data: Buffer.from(HOOK_SCRIPT, "utf-8"), mode: 493 },
40945
+ { name: RECORD_FILE2, data: json({ org_id: input.record.org_id, space_id: input.record.space_id, code: detail.code, last_pull: baseline }) }
40946
+ ];
40947
+ if (work) {
40948
+ files.push(
40949
+ { name: "case.json", data: json(detail) },
40950
+ { name: "status.json", data: json(work.state) },
40951
+ { name: "evidence.json", data: json({ phases: work.phases.map((p) => ({ phase_id: p.phase_id, folder: p.folder, work: p.work })) }) },
40952
+ { 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 }) },
40953
+ { name: "deliveries.json", data: json({ phases: work.phases.map((p) => ({ phase_id: p.phase_id, folder: p.folder, delivery: p.delivery })) }) },
40954
+ { name: INPUTS_FILE, data: json({ phases: work.phases.map((p) => ({ phase_id: p.phase_id, folder: p.folder, inputs: p.texts.map((t) => t.text) })) }) },
40955
+ ...work.phases.flatMap((p) => p.texts.flatMap(({ text: text5, data }) => text5.file !== null && data !== null ? [{ name: text5.file, data }] : []))
40956
+ );
40957
+ }
40958
+ writeMirror(root, files);
40959
+ console.log(`
40960
+ Mirror of case ${safe2(detail.code)} written to ${safe2(path47.join(root, CASE_MIRROR_DIR))} (read-only: every pull rewrites it).`);
40961
+ for (const line of unwritten) console.log(`Linked input's text: ${line}`);
40962
+ for (const line of mode === "mirror-only" ? [...summary, ...notice] : summary) console.log(line);
40963
+ }
40964
+ async function withMirrorLock(root, step) {
40965
+ const unlock = await lockMirror(root);
40966
+ try {
40967
+ return await step();
40968
+ } finally {
40969
+ unlock();
40970
+ }
40971
+ }
40972
+ function printHookSetup(root) {
40973
+ const script = path47.join(root, CASE_MIRROR_DIR, CASE_MIRROR_HOOK_FILE);
40974
+ const command2 = `sh '${script.replaceAll("'", "'\\''")}'`;
40975
+ const settings = JSON.stringify({ hooks: { SessionStart: [{ hooks: [{ type: "command", command: command2 }] }] } });
40976
+ console.log(`
40977
+ Session-start hook: ${safe2(script)} refreshes the mirror (never with --confidential).`);
40978
+ console.log(`For Claude Code, add it to ${safe2(path47.join(root, ".claude", "settings.json"))}:`);
40979
+ console.log(` ${safe2(settings)}`);
40980
+ console.log(`For another agent, run at the start of each session: ${safe2(command2)}`);
40981
+ }
40982
+ var CASE_MIRROR_DIR, CASE_MIRROR_HOOK_FILE, RECORD_FILE2, SUMMARY_FILE, INPUTS_FILE, INPUTS_DIR, 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, segment, NO_REVISIONS, within, HOOK_SCRIPT, json;
40983
+ var init_case_mirror = __esm({
40984
+ "src/cases/case-mirror.ts"() {
40985
+ "use strict";
40986
+ init_dist();
40987
+ init_case_files();
40988
+ init_case_comments();
40989
+ init_case_types();
40990
+ init_api_client();
40991
+ init_resource_files();
40992
+ init_utils();
40993
+ init_expected();
40994
+ init_fs_safety();
40995
+ init_terminal_output();
40996
+ init_case_local_files();
40997
+ CASE_MIRROR_DIR = ".wayai-mirror";
40998
+ CASE_MIRROR_HOOK_FILE = "session-start.sh";
40999
+ RECORD_FILE2 = "record.json";
41000
+ SUMMARY_FILE = "since-last-pull.md";
41001
+ INPUTS_FILE = "inputs.json";
41002
+ INPUTS_DIR = "inputs";
41003
+ LOCK_FILE = ".lock";
41004
+ LOCK_WAIT_MS = 12e4;
41005
+ LOCK_STALE_MS = 10 * 6e4;
41006
+ LOCK_POLL_MS = 50;
41007
+ AGENDA_PAGES_READ2 = 5;
41008
+ SUMMARY_REVISION_PAGES = 2;
41009
+ MIRROR_CONFIDENTIAL_NOTICE = "Confidential content is left out unless you pass --confidential.";
41010
+ safe2 = (text5) => sanitizeTerminalText(text5);
41011
+ one2 = (text5) => sanitizeTerminalText(text5).replace(/\s*\n\s*/g, " ");
41012
+ words = (status) => status.replaceAll("_", " ");
41013
+ isConfPath = (rel) => rel.split("/")[0] === "conf";
41014
+ isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
41015
+ isStringMap = (v) => isObject(v) && Object.values(v).every((x) => typeof x === "string");
41016
+ isDeliveries = (v) => isObject(v) && Object.values(v).every((d) => d === null || isObject(d) && typeof d.submission_id === "string" && typeof d.state === "string");
41017
+ segment = (name, pattern, id) => pattern.test(name) ? name : UUID_RE3.test(id) ? id : computeHash(Buffer.from(id, "utf-8"));
41018
+ NO_REVISIONS = { revisions: [], more: false, newest_at: null };
41019
+ within = (prev, now) => Object.fromEntries(Object.entries(prev).filter(([key]) => key in now));
41020
+ HOOK_SCRIPT = `#!/bin/sh
41021
+ # Written by \`wayai cases clone\` and every \`wayai cases pull\` (this folder is rewritten whole: do not edit it).
41022
+ # The session-start hook: refreshes this clone's read-only mirror of its case. It never passes --confidential.
41023
+ exec wayai cases pull --mirror-only --dir "$(dirname "$0")/.."
41024
+ `;
41025
+ json = (value) => Buffer.from(`${JSON.stringify(value, null, 2)}
41026
+ `, "utf-8");
41027
+ }
41028
+ });
41029
+
41030
+ // src/cases/case-files.ts
41031
+ import * as fs36 from "fs";
41032
+ import * as path48 from "path";
40472
41033
  function casesRequestsPerMinute() {
40473
41034
  const budget = getEndpointConfig("/api/cases/org/space/cases/code/files")?.userLimit;
40474
41035
  return budget ? Math.max(1, Math.floor(budget * 4 / 5)) : 48;
@@ -40481,7 +41042,7 @@ function assertWritableCasePaths(paths, phaseFolders) {
40481
41042
  for (const rel of paths) {
40482
41043
  const check = checkCaseFilePath({ path: rel, type: "file" }, phaseFolders);
40483
41044
  if (!check.ok) {
40484
- problems2.push(`${JSON.stringify(safe2(rel))}: a case path cannot be that (${check.reason})`);
41045
+ problems2.push(`${JSON.stringify(safe3(rel))}: a case path cannot be that (${check.reason})`);
40485
41046
  continue;
40486
41047
  }
40487
41048
  const folded = check.fold_key.split("/");
@@ -40493,7 +41054,7 @@ function assertWritableCasePaths(paths, phaseFolders) {
40493
41054
  if (known === void 0) {
40494
41055
  spelled.set(key, spelling);
40495
41056
  } else if (known !== spelling) {
40496
- problems2.push(`${JSON.stringify(safe2(known))} and ${JSON.stringify(safe2(spelling))} differ only in case, so they would be one entry here`);
41057
+ problems2.push(`${JSON.stringify(safe3(known))} and ${JSON.stringify(safe3(spelling))} differ only in case, so they would be one entry here`);
40497
41058
  break;
40498
41059
  }
40499
41060
  }
@@ -40504,7 +41065,7 @@ function assertWritableCasePaths(paths, phaseFolders) {
40504
41065
  const segments = key.split("/");
40505
41066
  for (let i = 1; i < segments.length; i++) {
40506
41067
  if (keys.has(segments.slice(0, i).join("/"))) {
40507
- problems2.push(`${JSON.stringify(safe2(rel))} lies in a folder that is also a file`);
41068
+ problems2.push(`${JSON.stringify(safe3(rel))} lies in a folder that is also a file`);
40508
41069
  break;
40509
41070
  }
40510
41071
  }
@@ -40516,20 +41077,20 @@ function assertWritableCasePaths(paths, phaseFolders) {
40516
41077
  }
40517
41078
  function linkRefusal(rel) {
40518
41079
  return expected(
40519
- `${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.`
41080
+ `${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.`
40520
41081
  );
40521
41082
  }
40522
41083
  function scanClone(root, phaseFolders, confidential = true) {
40523
41084
  const out = /* @__PURE__ */ new Map();
40524
41085
  const walk = (abs, rel) => {
40525
- for (const name of fs35.readdirSync(abs).sort()) {
41086
+ for (const name of fs36.readdirSync(abs).sort()) {
40526
41087
  if (name.startsWith(".")) continue;
40527
- const childAbs = path47.join(abs, name);
41088
+ const childAbs = path48.join(abs, name);
40528
41089
  const childRel = `${rel}/${name}`;
40529
- const st = fs35.lstatSync(childAbs);
41090
+ const st = fs36.lstatSync(childAbs);
40530
41091
  if (st.isDirectory() || st.isFile()) {
40531
41092
  const problem = ownProblem(st);
40532
- 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.`);
41093
+ 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.`);
40533
41094
  }
40534
41095
  if (st.isDirectory()) {
40535
41096
  walk(childAbs, childRel);
@@ -40543,16 +41104,16 @@ function scanClone(root, phaseFolders, confidential = true) {
40543
41104
  }
40544
41105
  };
40545
41106
  requireOwn(root);
40546
- const top = new Set(fs35.readdirSync(root));
41107
+ const top = new Set(fs36.readdirSync(root));
40547
41108
  const areas = [.../* @__PURE__ */ new Set([...phaseFolders, "analysis", ...confidential ? ["conf"] : []])].filter((area) => top.has(area));
40548
41109
  if (top.has("instructions")) {
40549
- if (!fs35.lstatSync(path47.join(root, "instructions")).isDirectory()) throw linkRefusal("instructions");
40550
- if (fs35.readdirSync(path47.join(root, "instructions")).includes("case")) areas.push("instructions/case");
41110
+ if (!fs36.lstatSync(path48.join(root, "instructions")).isDirectory()) throw linkRefusal("instructions");
41111
+ if (fs36.readdirSync(path48.join(root, "instructions")).includes("case")) areas.push("instructions/case");
40551
41112
  }
40552
41113
  for (const rel of areas) {
40553
- const abs = path47.join(root, ...rel.split("/"));
40554
- if (!fs35.lstatSync(abs).isDirectory()) throw linkRefusal(rel);
40555
- if (rel === "instructions/case") requireOwn(path47.join(root, "instructions"));
41114
+ const abs = path48.join(root, ...rel.split("/"));
41115
+ if (!fs36.lstatSync(abs).isDirectory()) throw linkRefusal(rel);
41116
+ if (rel === "instructions/case") requireOwn(path48.join(root, "instructions"));
40556
41117
  requireOwn(abs);
40557
41118
  walk(abs, rel);
40558
41119
  }
@@ -40584,11 +41145,11 @@ function sidesOf(record, local, files, confidential) {
40584
41145
  function requireFiles(detail, confidential) {
40585
41146
  const can = detail.access.capabilities;
40586
41147
  if (!can.includes("view_work")) {
40587
- throw expected(`Your access to case ${safe2(detail.code)} does not reach its files: no team of yours reads its work.`);
41148
+ throw expected(`Your access to case ${safe3(detail.code)} does not reach its files: no team of yours reads its work.`);
40588
41149
  }
40589
41150
  if (confidential && !can.includes("read_confidential")) {
40590
41151
  throw expected(
40591
- `This machine's authorization on case ${safe2(detail.code)} does not hold the Confidential right, so --confidential reads nothing more. Run it without --confidential.`
41152
+ `This machine's authorization on case ${safe3(detail.code)} does not hold the Confidential right, so --confidential reads nothing more. Run it without --confidential.`
40592
41153
  );
40593
41154
  }
40594
41155
  }
@@ -40597,6 +41158,7 @@ async function pullInto(calls, detail, record, opts) {
40597
41158
  const files = await calls.files();
40598
41159
  assertWritableCasePaths([...sidesOf(record, /* @__PURE__ */ new Map(), files, opts.confidential).listed.keys()], phaseFolders);
40599
41160
  const root = opts.root();
41161
+ mirrorFolder(root);
40600
41162
  const local = scanClone(root, phaseFolders, opts.confidential);
40601
41163
  const { synced: synced2, local: localIn, remote, listed: listed3, theirsListed } = sidesOf(record, local, files, opts.confidential);
40602
41164
  const plan = planPull({ synced: synced2, local: localIn, remote, overwrite: opts.overwrite });
@@ -40605,7 +41167,7 @@ async function pullInto(calls, detail, record, opts) {
40605
41167
  const replaced = [...plan.replacedLocal, ...opts.overwrite ? theirsLeft : []];
40606
41168
  if (replaced.length > 0) {
40607
41169
  console.log("These local changes would be replaced with the case's copies, or removed:");
40608
- for (const rel of replaced) console.log(` ${safe2(rel)}`);
41170
+ for (const rel of replaced) console.log(` ${safe3(rel)}`);
40609
41171
  if (!await agree(`Replace or remove ${replaced.length} local file(s)?`, opts.yes)) {
40610
41172
  console.log("Cancelled.");
40611
41173
  return;
@@ -40633,7 +41195,7 @@ async function pullInto(calls, detail, record, opts) {
40633
41195
  conflicts.push({ rel, reason: "unresolved" });
40634
41196
  } else if (matchesScan(root, rel, local.get(rel))) {
40635
41197
  removeLocal(root, rel);
40636
- changes.push(`${MARK.delete} ${safe2(rel)}`);
41198
+ changes.push(`${MARK.delete} ${safe3(rel)}`);
40637
41199
  } else {
40638
41200
  conflicts.push({ rel, reason: "edited_while_pulling" });
40639
41201
  }
@@ -40645,7 +41207,7 @@ async function pullInto(calls, detail, record, opts) {
40645
41207
  }
40646
41208
  removeLocal(root, rel);
40647
41209
  delete next.files[rel];
40648
- changes.push(`${MARK.delete} ${safe2(rel)}`);
41210
+ changes.push(`${MARK.delete} ${safe3(rel)}`);
40649
41211
  }
40650
41212
  for (const w of plan.writes) {
40651
41213
  const clash = diskClash(root, w.rel);
@@ -40661,7 +41223,7 @@ async function pullInto(calls, detail, record, opts) {
40661
41223
  }
40662
41224
  writeCaseLocalFile(root, w.rel, Buffer.from(bytes));
40663
41225
  next.files[w.rel] = recordedFile(listed3.get(w.rel));
40664
- changes.push(`${local.has(w.rel) ? MARK.update : MARK.create} ${safe2(w.rel)}`);
41226
+ changes.push(`${local.has(w.rel) ? MARK.update : MARK.create} ${safe3(w.rel)}`);
40665
41227
  }
40666
41228
  for (const c of plan.conflicts) {
40667
41229
  if (c.reason === "both_changed" || c.reason === "exists_locally") {
@@ -40684,24 +41246,33 @@ async function pullInto(calls, detail, record, opts) {
40684
41246
  }
40685
41247
  const named = conflicts.filter((c) => !(c.reason === "unresolved" && rewritten.has(c.rel)));
40686
41248
  const count = Object.keys(next.files).length;
40687
- console.log(safe2(`${opts.verb} case ${record.code} into ${root} (${count} file${count === 1 ? "" : "s"} recorded).`));
41249
+ console.log(safe3(`${opts.verb} case ${record.code} into ${root} (${count} file${count === 1 ? "" : "s"} recorded).`));
40688
41250
  printSection("Changes:", changes);
40689
- 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)"}`));
41251
+ 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)"}`));
40690
41252
  printSection(
40691
41253
  "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`:",
40692
41254
  named.map((c) => conflictLine(c, PULL_CONFLICT2))
40693
41255
  );
40694
- printSection("Changed on the case while pulling: left as is; pull again to take it:", changedWhilePulling.map(safe2));
40695
- printSection(`Not pulled: case paths ending in ${THEIRS_SUFFIX}, the name a conflict's copy takes here:`, theirsListed.map(safe2));
41256
+ printSection("Changed on the case while pulling: left as is; pull again to take it:", changedWhilePulling.map(safe3));
41257
+ printSection(`Not pulled: case paths ending in ${THEIRS_SUFFIX}, the name a conflict's copy takes here:`, theirsListed.map(safe3));
40696
41258
  if (!opts.confidential) console.log(`
40697
41259
  ${CONFIDENTIAL_NOTICE}`);
40698
41260
  if (named.length > 0) process.exitCode = 1;
41261
+ await withMirrorLock(root, () => writeCaseMirror(calls, {
41262
+ root,
41263
+ detail,
41264
+ files,
41265
+ record,
41266
+ inRun: inRunOf(outside),
41267
+ confidential: opts.confidential,
41268
+ mode: opts.verb === "Cloned" ? "clone" : "pull"
41269
+ }));
40699
41270
  }
40700
41271
  function cloneAt(dir) {
40701
41272
  if (dir !== void 0) {
40702
41273
  const root = caseLocalRoot(dir);
40703
41274
  const record = readCloneRecord(root);
40704
- 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\`.`);
41275
+ 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\`.`);
40705
41276
  return { root, record };
40706
41277
  }
40707
41278
  const clone = findCaseClone(process.cwd());
@@ -40716,43 +41287,64 @@ async function caseClone(selector, opts) {
40716
41287
  const calls = new CaseCalls(session);
40717
41288
  const detail = await calls.detail();
40718
41289
  requireFiles(detail, opts.confidential);
40719
- const dir = path47.resolve(opts.dir ?? session.connection.code);
41290
+ const dir = path48.resolve(opts.dir ?? session.connection.code);
40720
41291
  let exists = true;
40721
41292
  let st;
40722
41293
  try {
40723
- st = fs35.lstatSync(dir);
41294
+ st = fs36.lstatSync(dir);
40724
41295
  } catch {
40725
41296
  exists = false;
40726
41297
  }
40727
- if (st && !st.isDirectory()) throw expected(`${safe2(dir)} is a symlink or not a folder: clone into a folder of its own.`);
41298
+ if (st && !st.isDirectory()) throw expected(`${safe3(dir)} is a symlink or not a folder: clone into a folder of its own.`);
40728
41299
  if (exists) {
40729
41300
  const existing = readCloneRecord(caseLocalRoot(dir));
40730
41301
  if (existing) {
40731
- 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.`);
41302
+ 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.`);
40732
41303
  }
40733
41304
  }
40734
- const outer = findCaseClone(path47.dirname(dir));
40735
- if (outer) throw expected(`${safe2(dir)} lies inside the clone of case ${safe2(outer.record.code)} at ${safe2(outer.root)}: clone outside it.`);
41305
+ const outer = findCaseClone(path48.dirname(dir));
41306
+ if (outer) throw expected(`${safe3(dir)} lies inside the clone of case ${safe3(outer.record.code)} at ${safe3(outer.root)}: clone outside it.`);
40736
41307
  const record = { org_id: session.connection.org_id, space_id: session.connection.space_id, code: session.connection.code, files: {} };
40737
41308
  await pullInto(calls, detail, record, {
40738
41309
  confidential: opts.confidential,
40739
41310
  overwrite: false,
40740
41311
  yes: false,
40741
41312
  root: () => {
40742
- if (!exists) fs35.mkdirSync(dir, { recursive: true, mode: CASE_FOLDER_MODE });
41313
+ if (!exists) fs36.mkdirSync(dir, { recursive: true, mode: CASE_FOLDER_MODE });
40743
41314
  return caseLocalRoot(dir);
40744
41315
  },
40745
41316
  verb: "Cloned"
40746
41317
  });
41318
+ printHookSetup(caseLocalRoot(dir));
40747
41319
  }
40748
- async function casePull(opts) {
40749
- const { root, record } = cloneAt(opts.dir);
40750
- const session = await cloneSession(root);
40751
- const calls = new CaseCalls(session);
41320
+ async function openClone(dir, confidential) {
41321
+ const { root, record } = cloneAt(dir);
41322
+ const calls = new CaseCalls(await cloneSession(root));
40752
41323
  const detail = await calls.detail();
40753
- requireFiles(detail, opts.confidential);
41324
+ requireFiles(detail, confidential);
41325
+ return { root, record, calls, detail };
41326
+ }
41327
+ async function casePull(opts) {
41328
+ const { root, record, calls, detail } = await openClone(opts.dir, opts.confidential);
40754
41329
  await pullInto(calls, detail, record, { ...opts, root: () => root, verb: "Pulled" });
40755
41330
  }
41331
+ async function casePullMirror(opts) {
41332
+ const { root, record: opened, calls, detail } = await openClone(opts.dir, opts.confidential);
41333
+ mirrorFolder(root);
41334
+ await withMirrorLock(root, async () => {
41335
+ const record = readCloneRecord(root) ?? opened;
41336
+ const files = await calls.files();
41337
+ await writeCaseMirror(calls, {
41338
+ root,
41339
+ detail,
41340
+ files,
41341
+ record,
41342
+ inRun: inRunOf(outsideRun(record, files, opts.confidential)),
41343
+ confidential: opts.confidential,
41344
+ mode: "mirror-only"
41345
+ });
41346
+ });
41347
+ }
40756
41348
  function leftOutReason(rel, phaseFolders, detail) {
40757
41349
  const check = checkCaseFilePath({ path: rel, type: "file" }, phaseFolders);
40758
41350
  if (!check.ok) return `the case takes no such path (${check.reason})`;
@@ -40778,7 +41370,7 @@ function uploadRefusal(err, session, entries) {
40778
41370
  const reason3 = extractApiErrorReason(err);
40779
41371
  const { at, paths } = refusalDetails(err, sent);
40780
41372
  const list2 = paths.map((p) => `
40781
- ${safe2(p)}`).join("");
41373
+ ${safe3(p)}`).join("");
40782
41374
  if (err.status === 409 && reason3 === CASE_FILE_CONFLICT_REASON) {
40783
41375
  return expected(`These files changed on the case since your last pull:${list2}
40784
41376
  ${nothing} Run \`wayai cases pull\`, then push again.`);
@@ -40796,7 +41388,7 @@ ${nothing} Write those files under other paths.`
40796
41388
  if (err.status === 400 && reason3) {
40797
41389
  const index = at === null ? null : /^entries\.(\d+)/.exec(at);
40798
41390
  const where = index ? entries[Number(index[1])]?.path : void 0;
40799
- return expected(`The case refused the revision (${safe2(reason3)}${where ? `, at ${safe2(where)}` : ""}). ${nothing}`);
41391
+ return expected(`The case refused the revision (${safe3(reason3)}${where ? `, at ${safe3(where)}` : ""}). ${nothing}`);
40800
41392
  }
40801
41393
  return caseCallFailure(err, session.connection);
40802
41394
  }
@@ -40820,7 +41412,7 @@ async function casePush(opts) {
40820
41412
  const detail = await calls.detail();
40821
41413
  requireFiles(detail, opts.confidential);
40822
41414
  if (!detail.access.capabilities.includes("upload_document")) {
40823
- throw expected(`Your access to case ${safe2(detail.code)} does not write its files: that takes Edit level, on an open case.`);
41415
+ throw expected(`Your access to case ${safe3(detail.code)} does not write its files: that takes Edit level, on an open case.`);
40824
41416
  }
40825
41417
  const phaseFolders = phaseFoldersOf(detail);
40826
41418
  const scanned = scanClone(root, phaseFolders, opts.confidential);
@@ -40830,7 +41422,7 @@ async function casePush(opts) {
40830
41422
  if (theirs.length > 0) {
40831
41423
  throw expected(
40832
41424
  `Resolve these conflicts first: merge each into the file beside it, then delete the ${THEIRS_SUFFIX} copy.${theirs.map((t) => `
40833
- ${safe2(t)}`).join("")}
41425
+ ${safe3(t)}`).join("")}
40834
41426
  Nothing was pushed.`
40835
41427
  );
40836
41428
  }
@@ -40843,7 +41435,7 @@ Nothing was pushed.`
40843
41435
  const file = scanned.get(rel);
40844
41436
  const reason3 = record.files[rel]?.sha === file?.content_sha256 ? null : leftOutReason(rel, phaseFolders, detail);
40845
41437
  if (reason3) {
40846
- leftOut.push(`${safe2(rel)}: ${reason3}`);
41438
+ leftOut.push(`${safe3(rel)}: ${reason3}`);
40847
41439
  leftOutPaths.add(rel);
40848
41440
  } else if (file) {
40849
41441
  local.set(rel, file);
@@ -40853,13 +41445,13 @@ Nothing was pushed.`
40853
41445
  const recordIn = { ...record, files: Object.fromEntries(Object.entries(record.files).filter(([rel]) => !leftOutPaths.has(rel))) };
40854
41446
  const { synced: synced2, local: localIn, remote, listed: listed3 } = sidesOf(recordIn, local, files, opts.confidential);
40855
41447
  const plan = planPush({ synced: synced2, local: localIn, remote, prune: opts.prune });
40856
- console.log(safe2(`Push ${root} \u2192 case ${record.code}`));
40857
- const steps = plan.steps.map((s) => `${MARK[s.op]} ${safe2(s.rel)}${s.op === "create" ? ` (new, ${s.local.size} bytes)` : ""}`);
41448
+ console.log(safe3(`Push ${root} \u2192 case ${record.code}`));
41449
+ const steps = plan.steps.map((s) => `${MARK[s.op]} ${safe3(s.rel)}${s.op === "create" ? ` (new, ${s.local.size} bytes)` : ""}`);
40858
41450
  printSection("Changes:", steps);
40859
- printSection("Changed on the case since your last pull: left as is; pull to take it:", plan.changedOnBase.map(safe2));
40860
- 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));
40861
- printSection("On the case, not in your clone: left as is; pull to fetch it:", plan.onlyOnBase.map(safe2));
40862
- printSection("Deleted in your clone: kept on the case; push with --prune to remove it:", plan.keptOnBase.map(safe2));
41451
+ printSection("Changed on the case since your last pull: left as is; pull to take it:", plan.changedOnBase.map(safe3));
41452
+ 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));
41453
+ printSection("On the case, not in your clone: left as is; pull to fetch it:", plan.onlyOnBase.map(safe3));
41454
+ printSection("Deleted in your clone: kept on the case; push with --prune to remove it:", plan.keptOnBase.map(safe3));
40863
41455
  printSection("Left out: not pushed from this clone:", leftOut);
40864
41456
  printSection("Conflicts: not pushed:", plan.conflicts.map((c) => conflictLine(c, PUSH_CONFLICT2)));
40865
41457
  if (!opts.confidential) console.log(`
@@ -40895,9 +41487,9 @@ ${CONFIDENTIAL_NOTICE}`);
40895
41487
  entries.push({ path: step.rel, type: "file", expect_sha: step.ifMatch, sha: null });
40896
41488
  continue;
40897
41489
  }
40898
- const bytes = readFileNoFollow(root, path47.join(root, ...step.rel.split("/")));
41490
+ const bytes = readFileNoFollow(root, path48.join(root, ...step.rel.split("/")));
40899
41491
  if (!bytes || computeHash(bytes) !== step.local.content_sha256) {
40900
- throw expected(`${safe2(step.rel)} changed while the push ran. Nothing was pushed; push again.`);
41492
+ throw expected(`${safe3(step.rel)} changed while the push ran. Nothing was pushed; push again.`);
40901
41493
  }
40902
41494
  parts.set(step.local.content_sha256, bytes);
40903
41495
  entries.push({ path: step.rel, type: "file", expect_sha: step.op === "update" ? step.ifMatch : null, sha: step.local.content_sha256 });
@@ -40917,7 +41509,7 @@ ${CONFIDENTIAL_NOTICE}`);
40917
41509
  }
40918
41510
  writeCloneRecord(root, next);
40919
41511
  console.log(`
40920
- Pushed revision ${saved.revision_id}: ${entries.length} change${entries.length === 1 ? "" : "s"} to case ${safe2(record.code)}.`);
41512
+ Pushed revision ${saved.revision_id}: ${entries.length} change${entries.length === 1 ? "" : "s"} to case ${safe3(record.code)}.`);
40921
41513
  }
40922
41514
  async function caseLog(selector, opts) {
40923
41515
  const limit = opts.limit ?? LOG_DEFAULT;
@@ -40932,7 +41524,7 @@ async function caseLog(selector, opts) {
40932
41524
  for (let page = 0; page < MAX_LOG_PAGES && shown3.length < limit; page++) {
40933
41525
  const { revisions, next_cursor } = (await calls.run(() => session.api.listCaseRevisions(session.connection, { cursor, limit: CASE_REVISIONS_PAGE_MAX }))).data;
40934
41526
  for (const revision of revisions) {
40935
- const entries = opts.confidential ? revision.entries : revision.entries.filter((e) => !e.confidential && !isConfPath(e.path));
41527
+ const entries = shownEntries(revision, opts.confidential);
40936
41528
  if (entries.length === 0) continue;
40937
41529
  if (shown3.length === limit) {
40938
41530
  more = true;
@@ -40948,21 +41540,21 @@ async function caseLog(selector, opts) {
40948
41540
  console.log(JSON.stringify({ revisions: shown3, more }, null, 2));
40949
41541
  return;
40950
41542
  }
40951
- if (shown3.length === 0) console.log(`Case ${safe2(detail.code)} has no revision you read here.`);
41543
+ if (shown3.length === 0) console.log(`Case ${safe3(detail.code)} has no revision you read here.`);
40952
41544
  for (const r of shown3) {
40953
- const author = r.author?.display_name ? one2(r.author.display_name) : "a person no longer named";
41545
+ const author = r.author?.display_name ? one3(r.author.display_name) : "a person no longer named";
40954
41546
  console.log(`revision ${r.revision_id} ${r.created_at} ${author} (${r.channel})`);
40955
- if (r.message !== null) console.log(` ${one2(r.message)}`);
41547
+ if (r.message !== null) console.log(` ${one3(r.message)}`);
40956
41548
  else console.log(hideMessages ? " (message not shown without --confidential)" : " (message hidden)");
40957
- if (r.session) console.log(` session: ${one2(r.session)}`);
40958
- for (const e of r.entries) console.log(` ${safe2(e.path)}${e.sha === null ? " (removed)" : ""}`);
41549
+ if (r.session) console.log(` session: ${one3(r.session)}`);
41550
+ for (const e of r.entries) console.log(` ${safe3(e.path)}${e.sha === null ? " (removed)" : ""}`);
40959
41551
  }
40960
41552
  if (more && shown3.length > 0) console.log(`
40961
41553
  Older revisions follow: --limit ${Math.min(LOG_MAX, limit * 2)} shows more.`);
40962
41554
  if (!opts.confidential) console.log(`
40963
41555
  ${CONFIDENTIAL_NOTICE}`);
40964
41556
  }
40965
- 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;
41557
+ 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;
40966
41558
  var init_case_files2 = __esm({
40967
41559
  "src/cases/case-files.ts"() {
40968
41560
  "use strict";
@@ -40983,6 +41575,7 @@ var init_case_files2 = __esm({
40983
41575
  init_case_session();
40984
41576
  init_case_local_files();
40985
41577
  init_case_clone_record();
41578
+ init_case_mirror();
40986
41579
  THEIRS_SUFFIX = ".theirs";
40987
41580
  MAX_LIST_PAGES2 = 200;
40988
41581
  LOG_DEFAULT = 20;
@@ -40990,8 +41583,8 @@ var init_case_files2 = __esm({
40990
41583
  MAX_LOG_PAGES = 40;
40991
41584
  PART_OVERHEAD_BYTES = 512;
40992
41585
  CONFIDENTIAL_NOTICE = "Confidential files are left out unless you pass --confidential.";
40993
- safe2 = (text5) => sanitizeTerminalText(text5);
40994
- one2 = (text5) => sanitizeTerminalText(text5).replace(/\s*\n\s*/g, " ");
41586
+ safe3 = (text5) => sanitizeTerminalText(text5);
41587
+ one3 = (text5) => sanitizeTerminalText(text5).replace(/\s*\n\s*/g, " ");
40995
41588
  CaseCalls = class {
40996
41589
  constructor(session) {
40997
41590
  this.session = session;
@@ -41039,7 +41632,6 @@ var init_case_files2 = __esm({
41039
41632
  }
41040
41633
  };
41041
41634
  phaseFoldersOf = (detail) => detail.phases.map((p) => p.folder);
41042
- isConfPath = (rel) => rel.split("/")[0] === "conf";
41043
41635
  isTheirs = (rel) => rel.toLowerCase().endsWith(THEIRS_SUFFIX);
41044
41636
  recordedFile = (f) => ({ sha: f.sha, confidential: f.confidential || isConfPath(f.path) });
41045
41637
  PULL_CONFLICT2 = {
@@ -41052,6 +41644,7 @@ var init_case_files2 = __esm({
41052
41644
  edited_while_pulling: "changed here while pulling: kept; pull again",
41053
41645
  unresolved: "the case's copy of a conflict, still beside your file: merge it into that file, then delete it"
41054
41646
  };
41647
+ inRunOf = (outside) => (rel) => !outside(rel) && !isTheirs(rel);
41055
41648
  PUSH_CONFLICT2 = {
41056
41649
  changed_on_base: "changed on the case since your last pull",
41057
41650
  deleted_on_base: "deleted on the case since your last pull, or no longer readable by this authorization",
@@ -41098,7 +41691,7 @@ async function requireConfidential(session) {
41098
41691
  const detail = (await call2(session, () => session.api.getCase(session.connection))).data;
41099
41692
  if (!detail.access.capabilities.includes("read_confidential")) {
41100
41693
  throw expected(
41101
- `This machine's authorization on case ${one3(detail.code)} does not hold the Confidential right, so --confidential reads nothing more. Run it without --confidential.`
41694
+ `This machine's authorization on case ${one4(detail.code)} does not hold the Confidential right, so --confidential reads nothing more. Run it without --confidential.`
41102
41695
  );
41103
41696
  }
41104
41697
  }
@@ -41111,7 +41704,7 @@ function block(label3, text5, none) {
41111
41704
  for (const line of sanitizeTerminalText(text5).split("\n")) console.log(` | ${line}`);
41112
41705
  }
41113
41706
  function verdictCommand(connection, graph, pair) {
41114
- return `wayai cases review verdict <${VERDICTS.join("|")}> ${one3(pair.source)} ${one3(pair.neighbor)} --revision ${one3(graph.revision_id ?? "")} --source-hash ${one3(pair.source_hash)} --neighbor-hash ${one3(pair.neighbor_hash)}${graph.confidential ? " --confidential" : ""} --case ${one3(connection.code)} --org ${one3(connection.org_id)} --space ${one3(connection.space_id)} --reason "<why>"`;
41707
+ 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>"`;
41115
41708
  }
41116
41709
  async function caseReview(session, opts) {
41117
41710
  if (opts.confidential) await requireConfidential(session);
@@ -41134,15 +41727,15 @@ function printReview(connection, graph) {
41134
41727
  notice();
41135
41728
  return;
41136
41729
  }
41137
- console.log(`Review of case ${code2} at revision ${one3(graph.revision_id)}${graph.confidential ? ", with confidential content" : ""}.`);
41138
- console.log(graph.base_revision_id ? `Base: revision ${one3(graph.base_revision_id)}. Nothing you read here is pending.` : "Base: each item's own, below. Something you read here is pending.");
41730
+ console.log(`Review of case ${code2} at revision ${one4(graph.revision_id)}${graph.confidential ? ", with confidential content" : ""}.`);
41731
+ 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.");
41139
41732
  const titles = new Map(graph.items.map((item) => [item.key, item.title]));
41140
41733
  if (graph.items.length) {
41141
41734
  console.log(`
41142
41735
  Changed items (${graph.items.length}):`);
41143
41736
  for (const item of graph.items) {
41144
- console.log(` ${one3(item.key)}, "${one3(item.title)}" (${item.state}, round ${item.round}), in ${one3(item.path)}${item.base_revision_id ? `, since revision ${one3(item.base_revision_id)}` : ""}`);
41145
- if (item.causes.length) console.log(` because: ${item.causes.map(one3).join("; ")}`);
41737
+ 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)}` : ""}`);
41738
+ if (item.causes.length) console.log(` because: ${item.causes.map(one4).join("; ")}`);
41146
41739
  block("before", item.before, "not there at its base");
41147
41740
  block("now", item.text, "removed");
41148
41741
  }
@@ -41152,8 +41745,8 @@ Changed items (${graph.items.length}):`);
41152
41745
  Pairs awaiting a verdict (${graph.pairs.length}):`);
41153
41746
  for (const pair of graph.pairs) {
41154
41747
  const source = titles.get(pair.source);
41155
- console.log(` ${one3(pair.source)}${source ? ` "${one3(source)}"` : ""} \u2192 ${one3(pair.neighbor)} "${one3(pair.neighbor_title)}" (round ${pair.round} of ${CASE_REVIEW_ROUNDS_MAX}), in ${one3(pair.path)}`);
41156
- if (pair.reasons.length) console.log(` connected: ${pair.reasons.map(one3).join("; ")}`);
41748
+ 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)}`);
41749
+ if (pair.reasons.length) console.log(` connected: ${pair.reasons.map(one4).join("; ")}`);
41157
41750
  console.log(` ${verdictCommand(connection, graph, pair)}`);
41158
41751
  }
41159
41752
  }
@@ -41161,16 +41754,16 @@ Pairs awaiting a verdict (${graph.pairs.length}):`);
41161
41754
  console.log(`
41162
41755
  Waiting for a change (${graph.waiting.length}):`);
41163
41756
  for (const w of graph.waiting) {
41164
- console.log(` ${one3(w.source)} \u2192 ${one3(w.neighbor)} (round ${w.round}): needs a change: ${one3(w.reason)}`);
41165
- console.log(` waits until ${one3(w.neighbor)} changes`);
41757
+ console.log(` ${one4(w.source)} \u2192 ${one4(w.neighbor)} (round ${w.round}): needs a change: ${one4(w.reason)}`);
41758
+ console.log(` waits until ${one4(w.neighbor)} changes`);
41166
41759
  }
41167
41760
  }
41168
41761
  if (graph.stopped.length) {
41169
41762
  console.log(`
41170
41763
  Stopped chains (${graph.stopped.length}): each took more than ${CASE_REVIEW_ROUNDS_MAX} rounds, so it takes no verdict.`);
41171
41764
  for (const s of graph.stopped) {
41172
- const waiting = s.waiting_sources.length ? `; waiting on it: ${s.waiting_sources.map(one3).join(", ")}` : "";
41173
- console.log(` ${one3(s.key)}, "${one3(s.title)}" (round ${s.round})${s.base_revision_id ? `, since revision ${one3(s.base_revision_id)}` : ""}${waiting}`);
41765
+ const waiting = s.waiting_sources.length ? `; waiting on it: ${s.waiting_sources.map(one4).join(", ")}` : "";
41766
+ console.log(` ${one4(s.key)}, "${one4(s.title)}" (round ${s.round})${s.base_revision_id ? `, since revision ${one4(s.base_revision_id)}` : ""}${waiting}`);
41174
41767
  }
41175
41768
  console.log(` ${WEB_ONLY_NOTICE}`);
41176
41769
  }
@@ -41179,8 +41772,8 @@ Stopped chains (${graph.stopped.length}): each took more than ${CASE_REVIEW_ROUN
41179
41772
  console.log(`
41180
41773
  For a person to look at (${warnings.length}):`);
41181
41774
  for (const w of warnings) {
41182
- const where = [w.path && one3(w.path), w.subject && one3(w.subject)].filter(Boolean).join(": ");
41183
- console.log(` ${WARNINGS[w.code] ?? one3(w.code)}${where ? ` [${where}]` : ""}`);
41775
+ const where = [w.path && one4(w.path), w.subject && one4(w.subject)].filter(Boolean).join(": ");
41776
+ console.log(` ${WARNINGS[w.code] ?? one4(w.code)}${where ? ` [${where}]` : ""}`);
41184
41777
  }
41185
41778
  }
41186
41779
  if (!graph.items.length && !graph.pairs.length && !graph.waiting.length && !graph.stopped.length) console.log("Nothing awaits review.");
@@ -41227,12 +41820,12 @@ async function caseReviewVerdict(session, body, opts) {
41227
41820
  console.log(JSON.stringify(review, null, 2));
41228
41821
  return;
41229
41822
  }
41230
- console.log(`Recorded ${review.verdict === "needs_change" ? "needs change" : review.verdict} on ${one3(review.source)} \u2192 ${one3(review.neighbor)}, round ${review.round} of ${CASE_REVIEW_ROUNDS_MAX}${review.confidential ? ", confidential" : ""}: ${review.review_id}`);
41823
+ 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}`);
41231
41824
  if (review.verdict === "needs_change") {
41232
- console.log(`The pair waits until ${one3(review.neighbor)} changes: change it, push, then read the review again.`);
41825
+ console.log(`The pair waits until ${one4(review.neighbor)} changes: change it, push, then read the review again.`);
41233
41826
  }
41234
41827
  }
41235
- var VERDICTS, WEB_ONLY_NOTICE, one3, WARNINGS;
41828
+ var VERDICTS, WEB_ONLY_NOTICE, one4, WARNINGS;
41236
41829
  var init_case_review2 = __esm({
41237
41830
  "src/cases/case-review.ts"() {
41238
41831
  "use strict";
@@ -41245,7 +41838,7 @@ var init_case_review2 = __esm({
41245
41838
  init_case_review();
41246
41839
  VERDICTS = recordCaseItemReviewBody.shape.verdict.options;
41247
41840
  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.";
41248
- one3 = (value) => sanitizeTerminalText(value).replace(/\s*\n\s*/g, " ");
41841
+ one4 = (value) => sanitizeTerminalText(value).replace(/\s*\n\s*/g, " ");
41249
41842
  WARNINGS = {
41250
41843
  outside_item: "text outside any item",
41251
41844
  new_document_outside_item: "a new document with text outside any item",
@@ -41271,8 +41864,8 @@ __export(cases_exports, {
41271
41864
  waitForPickup: () => waitForPickup,
41272
41865
  webOrigin: () => webOrigin
41273
41866
  });
41274
- import * as crypto4 from "crypto";
41275
- import * as os4 from "os";
41867
+ import * as crypto5 from "crypto";
41868
+ import * as os5 from "os";
41276
41869
  import { parseArgs as parseArgs26 } from "util";
41277
41870
  function usageError4(message) {
41278
41871
  return expected(`${message}
@@ -41311,24 +41904,24 @@ async function casesCommand(args2) {
41311
41904
  return disconnect(operands[0], { org: values.org, space: values.space });
41312
41905
  }
41313
41906
  const selector = { case: values.case, org: values.org, space: values.space };
41314
- const json = values.json === true;
41907
+ const json2 = values.json === true;
41315
41908
  const takesNone = () => {
41316
41909
  if (operands.length) throw usageError4(`${name} takes no argument.`);
41317
41910
  };
41318
41911
  switch (name) {
41319
41912
  case "brief":
41320
41913
  takesNone();
41321
- return caseBrief(await openCaseSession(selector), { json });
41914
+ return caseBrief(await openCaseSession(selector), { json: json2 });
41322
41915
  case "next":
41323
41916
  takesNone();
41324
- return caseNext(await openCaseSession(selector), { json });
41917
+ return caseNext(await openCaseSession(selector), { json: json2 });
41325
41918
  case "explain":
41326
41919
  takesNone();
41327
- return caseExplain(await openCaseSession(selector), { json, phase: values.phase });
41920
+ return caseExplain(await openCaseSession(selector), { json: json2, phase: values.phase });
41328
41921
  case "check":
41329
41922
  takesNone();
41330
41923
  if (values.phase === void 0) throw usageError4("check takes --phase <folder>.");
41331
- return caseCheck(await openCaseSession(selector), { json, phase: values.phase, output: values.output });
41924
+ return caseCheck(await openCaseSession(selector), { json: json2, phase: values.phase, output: values.output });
41332
41925
  case "decisions": {
41333
41926
  takesNone();
41334
41927
  const session = await openCaseSession(selector);
@@ -41339,9 +41932,15 @@ async function casesCommand(args2) {
41339
41932
  case "clone":
41340
41933
  takesNone();
41341
41934
  return caseClone(selector, { dir: values.dir, confidential: values.confidential === true });
41342
- case "pull":
41935
+ case "pull": {
41343
41936
  takesNone();
41344
- return casePull({ dir: values.dir, overwrite: values.overwrite === true, yes: values.yes === true, confidential: values.confidential === true });
41937
+ const confidential = values.confidential === true;
41938
+ if (values["mirror-only"] === true) {
41939
+ 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.");
41940
+ return casePullMirror({ dir: values.dir, confidential });
41941
+ }
41942
+ return casePull({ dir: values.dir, overwrite: values.overwrite === true, yes: values.yes === true, confidential });
41943
+ }
41345
41944
  case "push":
41346
41945
  takesNone();
41347
41946
  if (values.message === void 0 && values["dry-run"] !== true) throw usageError4('push takes a message: -m "<what this revision does>".');
@@ -41357,11 +41956,11 @@ async function casesCommand(args2) {
41357
41956
  takesNone();
41358
41957
  const limit = values.limit === void 0 ? void 0 : /^[0-9]+$/.test(values.limit) ? Number(values.limit) : NaN;
41359
41958
  if (limit !== void 0 && !(limit >= 1 && limit <= LOG_MAX)) throw usageError4(`--limit takes 1 to ${LOG_MAX}.`);
41360
- return caseLog(selector, { limit, json, confidential: values.confidential === true });
41959
+ return caseLog(selector, { limit, json: json2, confidential: values.confidential === true });
41361
41960
  }
41362
41961
  case "review":
41363
41962
  takesNone();
41364
- return caseReview(await openCaseSession(selector), { json, confidential: values.confidential === true });
41963
+ return caseReview(await openCaseSession(selector), { json: json2, confidential: values.confidential === true });
41365
41964
  case "review verdict": {
41366
41965
  if (operands.length !== 3) throw usageError4("review verdict takes consistent|needs_change, then <source> and <neighbor>.");
41367
41966
  const [verdict, source, neighbor] = operands;
@@ -41376,7 +41975,7 @@ async function casesCommand(args2) {
41376
41975
  markConfidential: values["mark-confidential"] === true,
41377
41976
  confidential: values.confidential === true
41378
41977
  });
41379
- return caseReviewVerdict(await openCaseSession(selector), body, { json });
41978
+ return caseReviewVerdict(await openCaseSession(selector), body, { json: json2 });
41380
41979
  }
41381
41980
  case "note":
41382
41981
  if (operands.length !== 1) throw usageError4("note takes its text as one argument: quote it.");
@@ -41409,7 +42008,7 @@ function caseRef(orgId, spaceId, code2) {
41409
42008
  return parsed.data;
41410
42009
  }
41411
42010
  function machineLabel2(flag) {
41412
- const parsed = createCaseAgentRequestBody.shape.machine_label.safeParse(flag ?? os4.hostname().slice(0, CASE_AGENT_MACHINE_LABEL_MAX));
42011
+ const parsed = createCaseAgentRequestBody.shape.machine_label.safeParse(flag ?? os5.hostname().slice(0, CASE_AGENT_MACHINE_LABEL_MAX));
41413
42012
  if (parsed.success) return parsed.data;
41414
42013
  if (flag === void 0) throw usageError4("This machine's hostname cannot name it at approval: pass --label <machine>.");
41415
42014
  throw usageError4(`--label takes 1 to ${CASE_AGENT_MACHINE_LABEL_MAX} characters, none of them a control character.`);
@@ -41427,13 +42026,13 @@ function webOrigin(apiUrl) {
41427
42026
  else return null;
41428
42027
  return `${url.protocol}//${host}${url.port ? `:${url.port}` : ""}`;
41429
42028
  }
41430
- function webLocation(apiUrl, path50) {
42029
+ function webLocation(apiUrl, path51) {
41431
42030
  const origin = webOrigin(apiUrl);
41432
- return origin ? `${origin}${path50}` : `${path50} (in the WayAI web app)`;
42031
+ return origin ? `${origin}${path51}` : `${path51} (in the WayAI web app)`;
41433
42032
  }
41434
42033
  function pickupSecret() {
41435
- const bytes = crypto4.randomBytes(32);
41436
- return { secret: bytes.toString("hex"), challenge: crypto4.createHash("sha256").update(bytes).digest("hex") };
42034
+ const bytes = crypto5.randomBytes(32);
42035
+ return { secret: bytes.toString("hex"), challenge: crypto5.createHash("sha256").update(bytes).digest("hex") };
41437
42036
  }
41438
42037
  function connectFailure(err, stage) {
41439
42038
  if (!(err instanceof ApiError)) return err;
@@ -41597,6 +42196,7 @@ var init_cases = __esm({
41597
42196
  init_case_session();
41598
42197
  init_case_work();
41599
42198
  init_case_files2();
42199
+ init_case_mirror();
41600
42200
  init_case_review2();
41601
42201
  init_case_clone_record();
41602
42202
  init_case_tokens();
@@ -41610,6 +42210,7 @@ Usage:
41610
42210
 
41611
42211
  wayai cases clone [--dir <folder>] [--confidential]
41612
42212
  wayai cases pull [--dir <clone>] [--overwrite] [--yes] [--confidential]
42213
+ wayai cases pull --mirror-only [--dir <clone>] [--confidential]
41613
42214
  wayai cases push -m "<message>" [--session <tag>] [--prune] [--dry-run]
41614
42215
  [--dir <clone>] [--confidential]
41615
42216
  wayai cases log [--limit <n>] [--json] [--confidential]
@@ -41647,7 +42248,8 @@ when codes repeat).
41647
42248
  clone Make a folder bound to the case (--dir, default ./<code>) and
41648
42249
  write the case's files into it: its phase folders, analysis/,
41649
42250
  conf/ and instructions/case/. Nothing else in the folder is read
41650
- or written.
42251
+ or written, but the mirror. It prints the session-start hook to
42252
+ add to your agent.
41651
42253
  pull Bring the clone up to date, keeping your local changes. A file
41652
42254
  changed on both sides keeps yours, and the case's copy lands
41653
42255
  beside it as <path>.theirs: merge it, then delete it. Pull exits 1
@@ -41655,6 +42257,15 @@ pull Bring the clone up to date, keeping your local changes. A file
41655
42257
  with --confidential). --overwrite takes the case's copies
41656
42258
  over your changes and removes those copies, after asking (--yes
41657
42259
  agrees without a terminal).
42260
+ Clone and every pull then rewrite the clone's read-only mirror,
42261
+ ${CASE_MIRROR_DIR}/: the case, its status, evidence, agenda and
42262
+ deliveries of the phases under way, their linked inputs'
42263
+ registered texts (each checked against its registered hash),
42264
+ and what changed since the last pull. Push never sends it; an
42265
+ edit there is lost.
42266
+ --mirror-only rewrites the mirror alone, leaving your files as
42267
+ they are: the session-start hook runs it, never with
42268
+ --confidential.
41658
42269
  push Send the clone's changes as one revision, all of it or none. Each
41659
42270
  file is checked against the copy you last pulled: if the case
41660
42271
  changed since, nothing is pushed and nothing here changes; pull
@@ -41699,7 +42310,7 @@ received add Register a document a party sent, in one phase, with its
41699
42310
 
41700
42311
  Confidential content is never asked for unless you pass --confidential:
41701
42312
  without it, clone, pull, push and log leave every confidential file alone,
41702
- and review leaves out confidential content.
42313
+ and review and the mirror leave out confidential content.
41703
42314
  The case's agents page in the web app shows the exact connect command.
41704
42315
  After connecting, this machine still holds your \`wayai login\`:
41705
42316
  \`wayai logout\` is the recommended next step, and the case token does not
@@ -41732,7 +42343,8 @@ need it.
41732
42343
  revision: { type: "string" },
41733
42344
  "source-hash": { type: "string" },
41734
42345
  "neighbor-hash": { type: "string" },
41735
- "mark-confidential": { type: "boolean" }
42346
+ "mark-confidential": { type: "boolean" },
42347
+ "mirror-only": { type: "boolean" }
41736
42348
  };
41737
42349
  SELECT = ["case", "org", "space"];
41738
42350
  ADMITS = {
@@ -41748,7 +42360,7 @@ need it.
41748
42360
  "received add": [...SELECT, "text", "phase", "type", "title", "confidential"],
41749
42361
  clone: [...SELECT, "dir", "confidential"],
41750
42362
  // A clone names its case: pull and push take the clone (--dir), never a case.
41751
- pull: ["dir", "overwrite", "yes", "confidential"],
42363
+ pull: ["dir", "overwrite", "yes", "confidential", "mirror-only"],
41752
42364
  push: ["dir", "message", "session", "prune", "dry-run", "confidential"],
41753
42365
  log: [...SELECT, "limit", "json", "confidential"],
41754
42366
  review: [...SELECT, "json", "confidential"],
@@ -42294,8 +42906,8 @@ refresh-preview: make the knowledge base's preview hold its production base's fi
42294
42906
  });
42295
42907
 
42296
42908
  // src/lib/file-map.ts
42297
- import * as fs36 from "fs";
42298
- import * as path48 from "path";
42909
+ import * as fs37 from "fs";
42910
+ import * as path49 from "path";
42299
42911
  function isSafeRelPath(rel) {
42300
42912
  if (rel.length === 0 || rel.length > 300) return false;
42301
42913
  if (rel.startsWith("/") || rel.includes("\\")) return false;
@@ -42310,9 +42922,9 @@ function writeFileMap(targetDir, files) {
42310
42922
  if (!isSafeRelPath(rel)) {
42311
42923
  throw new Error(`Refusing to write unsafe path: ${rel}`);
42312
42924
  }
42313
- const abs = path48.join(targetDir, rel);
42314
- fs36.mkdirSync(path48.dirname(abs), { recursive: true });
42315
- fs36.writeFileSync(abs, body, "utf-8");
42925
+ const abs = path49.join(targetDir, rel);
42926
+ fs37.mkdirSync(path49.dirname(abs), { recursive: true });
42927
+ fs37.writeFileSync(abs, body, "utf-8");
42316
42928
  written.push(rel);
42317
42929
  }
42318
42930
  return written;
@@ -42402,8 +43014,8 @@ var admin_exports = {};
42402
43014
  __export(admin_exports, {
42403
43015
  adminCommand: () => adminCommand
42404
43016
  });
42405
- import * as fs37 from "fs";
42406
- import * as path49 from "path";
43017
+ import * as fs38 from "fs";
43018
+ import * as path50 from "path";
42407
43019
  async function adminCommand(args2) {
42408
43020
  const [group, ...afterGroup] = args2;
42409
43021
  if (!group) {
@@ -43044,13 +43656,13 @@ async function runSkillInstall(positional) {
43044
43656
  throw err;
43045
43657
  }
43046
43658
  const root = findGitRoot() ?? process.cwd();
43047
- const present = HARNESS_SKILL_DIRS.filter((dir) => fs37.existsSync(path49.join(root, dir)));
43659
+ const present = HARNESS_SKILL_DIRS.filter((dir) => fs38.existsSync(path50.join(root, dir)));
43048
43660
  const targets = present.length > 0 ? present : HARNESS_SKILL_DIRS;
43049
43661
  const fileCount = Object.keys(res.files).length;
43050
43662
  const relDirs = targets.map((harness) => {
43051
- const targetDir = path49.join(root, harness, "skills", name);
43663
+ const targetDir = path50.join(root, harness, "skills", name);
43052
43664
  writeFileMap(targetDir, res.files);
43053
- return `${path49.relative(root, targetDir)}/`;
43665
+ return `${path50.relative(root, targetDir)}/`;
43054
43666
  });
43055
43667
  console.log(`Installed skill "${name}" (${fileCount} file${fileCount === 1 ? "" : "s"}) \u2192 ${relDirs.join(", ")}`);
43056
43668
  console.log("Reload your agent (e.g. restart Claude Code) to pick up the skill.");
@@ -45298,12 +45910,12 @@ async function reportEditCommand(args2) {
45298
45910
  }
45299
45911
  async function reportListCommand(args2) {
45300
45912
  const status = flagValue2(args2, "--status");
45301
- const json = args2.includes("--json");
45913
+ const json2 = args2.includes("--json");
45302
45914
  const { config, accessToken } = await requireAuth();
45303
45915
  const client = new ApiClient({ apiUrl: config.api_url, accessToken });
45304
45916
  try {
45305
45917
  const result = await client.listMyReports(status);
45306
- if (json) {
45918
+ if (json2) {
45307
45919
  console.log(JSON.stringify(result, null, 2));
45308
45920
  return;
45309
45921
  }
@@ -45321,7 +45933,7 @@ async function reportListCommand(args2) {
45321
45933
  }
45322
45934
  async function reportGetCommand(args2) {
45323
45935
  const reportId = args2.find((a) => !a.startsWith("--"));
45324
- const json = args2.includes("--json");
45936
+ const json2 = args2.includes("--json");
45325
45937
  if (!reportId) {
45326
45938
  console.error("Usage: wayai report get <report_id> [--json]");
45327
45939
  process.exit(1);
@@ -45330,7 +45942,7 @@ async function reportGetCommand(args2) {
45330
45942
  const client = new ApiClient({ apiUrl: config.api_url, accessToken });
45331
45943
  try {
45332
45944
  const result = await client.getMyReport(reportId);
45333
- if (json) {
45945
+ if (json2) {
45334
45946
  console.log(JSON.stringify(result, null, 2));
45335
45947
  return;
45336
45948
  }
@@ -45533,7 +46145,7 @@ var init_actions = __esm({
45533
46145
 
45534
46146
  // src/data/commands/attachments.ts
45535
46147
  import { Command as Command3 } from "commander";
45536
- import { readFileSync as readFileSync21 } from "fs";
46148
+ import { readFileSync as readFileSync22 } from "fs";
45537
46149
  function findAttachmentByFilename(attachments, filename) {
45538
46150
  return attachments.find((a) => a.key.endsWith(`/${filename}`)) ?? null;
45539
46151
  }
@@ -45574,7 +46186,7 @@ function buildAttachmentsCommand() {
45574
46186
  printOutput(data, outputFormat(this));
45575
46187
  return;
45576
46188
  }
45577
- const body = readFileSync21(opts.file);
46189
+ const body = readFileSync22(opts.file);
45578
46190
  await client.upload(uploadPathFrom(data?.upload_url), body, opts.contentType);
45579
46191
  printOutput({ ...data, uploaded: true }, outputFormat(this));
45580
46192
  });
@@ -45991,7 +46603,7 @@ var init_import = __esm({
45991
46603
 
45992
46604
  // src/data/commands/providers.ts
45993
46605
  import { Command as Command6 } from "commander";
45994
- import { writeFileSync as writeFileSync12 } from "fs";
46606
+ import { writeFileSync as writeFileSync13 } from "fs";
45995
46607
  function providerSegment(provider) {
45996
46608
  if (!VALID_PROVIDERS.includes(provider)) {
45997
46609
  throw expected(`Unknown provider ${JSON.stringify(provider)}. Expected one of: ${VALID_PROVIDERS_HELP}.`);
@@ -46024,7 +46636,7 @@ function buildBasesProvidersCommand() {
46024
46636
  );
46025
46637
  if (opts.to) {
46026
46638
  try {
46027
- writeFileSync12(opts.to, JSON.stringify(data, null, 2));
46639
+ writeFileSync13(opts.to, JSON.stringify(data, null, 2));
46028
46640
  } catch (e) {
46029
46641
  throw expected(`--to ${opts.to}: ${e instanceof Error ? e.message : "could not be written"}`);
46030
46642
  }
@@ -46145,7 +46757,7 @@ var init_credentials = __esm({
46145
46757
 
46146
46758
  // src/data/commands/sql.ts
46147
46759
  import { Command as Command8 } from "commander";
46148
- import { readFileSync as readFileSync22 } from "fs";
46760
+ import { readFileSync as readFileSync23 } from "fs";
46149
46761
  function buildBasesSqlCommand() {
46150
46762
  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(
46151
46763
  "--param <kv...>",
@@ -46155,7 +46767,7 @@ function buildBasesSqlCommand() {
46155
46767
  let query;
46156
46768
  if (opts.file) {
46157
46769
  try {
46158
- query = readFileSync22(opts.file, "utf-8").trim();
46770
+ query = readFileSync23(opts.file, "utf-8").trim();
46159
46771
  } catch (e) {
46160
46772
  throw expected(`--file ${opts.file}: ${e instanceof Error ? e.message : "could not be read"}`);
46161
46773
  }
@@ -46315,16 +46927,16 @@ MCP URL: ${toolsetMcpUrl(slug)}`);
46315
46927
  ).option("--force", "Revoke even if the token appears to be in live use").action(async function(tokenId, opts) {
46316
46928
  const client = await createDataClient();
46317
46929
  const id = pathSegment(tokenId, "token id");
46318
- const path50 = (force) => `/v1/tokens/${id}${force ? "?force=true" : ""}`;
46930
+ const path51 = (force) => `/v1/tokens/${id}${force ? "?force=true" : ""}`;
46319
46931
  const format = outputFormat(this);
46320
46932
  const revoked = (forced) => printOutput({ token_id: tokenId, revoked: true, forced }, format);
46321
46933
  if (opts.force) {
46322
- await client.request("DELETE", path50(true));
46934
+ await client.request("DELETE", path51(true));
46323
46935
  revoked(true);
46324
46936
  return;
46325
46937
  }
46326
46938
  try {
46327
- await client.request("DELETE", path50(false));
46939
+ await client.request("DELETE", path51(false));
46328
46940
  revoked(false);
46329
46941
  } catch (err) {
46330
46942
  if (!(err instanceof ApiError) || err.status !== 409 || dataErrorDetails(err)?.requires_force !== true) {
@@ -46339,7 +46951,7 @@ MCP URL: ${toolsetMcpUrl(slug)}`);
46339
46951
  console.error("Aborted.");
46340
46952
  return process.exit(1);
46341
46953
  }
46342
- await client.request("DELETE", path50(true));
46954
+ await client.request("DELETE", path51(true));
46343
46955
  revoked(true);
46344
46956
  }
46345
46957
  });
@@ -46387,29 +46999,29 @@ MCP URL: ${toolsetMcpUrl(slug)}`);
46387
46999
  }
46388
47000
  }
46389
47001
  const format = outputFormat(this);
46390
- const json = format === "json";
46391
- const note = (line) => json ? console.error(line) : console.log(line);
47002
+ const json2 = format === "json";
47003
+ const note = (line) => json2 ? console.error(line) : console.log(line);
46392
47004
  const printPreview = () => {
46393
47005
  if (targets.length === 0) {
46394
47006
  note("Nothing to prune.");
46395
47007
  } else {
46396
47008
  note(`Would revoke ${targets.length} token(s):`);
46397
- if (!json) printOutput(targets, format);
47009
+ if (!json2) printOutput(targets, format);
46398
47010
  }
46399
47011
  if (skipped.length === 0) return;
46400
47012
  note(`
46401
47013
  Skipped ${skipped.length} stale token(s):`);
46402
- if (!json) printOutput(skipped, format);
47014
+ if (!json2) printOutput(skipped, format);
46403
47015
  };
46404
47016
  printPreview();
46405
47017
  if (targets.length === 0) {
46406
- if (json) printOutput({ revoked: 0, failed: 0, targets, skipped }, format);
47018
+ if (json2) printOutput({ revoked: 0, failed: 0, targets, skipped }, format);
46407
47019
  return;
46408
47020
  }
46409
47021
  if (!opts.yes) {
46410
47022
  if (!isInteractive()) {
46411
47023
  console.error("\nPreview only \u2014 re-run with --yes to revoke these tokens.");
46412
- if (json) printOutput({ preview: true, revoked: 0, failed: 0, targets, skipped }, format);
47024
+ if (json2) printOutput({ preview: true, revoked: 0, failed: 0, targets, skipped }, format);
46413
47025
  return process.exit(1);
46414
47026
  }
46415
47027
  if (!await confirm(`
@@ -46434,7 +47046,7 @@ Revoke ${targets.length} token(s)?`)) {
46434
47046
  );
46435
47047
  }
46436
47048
  }
46437
- if (json) printOutput({ revoked, failed, targets, skipped }, format);
47049
+ if (json2) printOutput({ revoked, failed, targets, skipped }, format);
46438
47050
  else console.log(`Revoked ${revoked} token(s)${failed > 0 ? `, ${failed} failed` : ""}.`);
46439
47051
  if (failed > 0) return process.exit(1);
46440
47052
  });
@@ -46491,9 +47103,9 @@ var init_base_tags = __esm({
46491
47103
 
46492
47104
  // src/data/commands/bases.ts
46493
47105
  import { Command as Command10 } from "commander";
46494
- function pageOf(path50, cursor) {
46495
- if (!cursor) return path50;
46496
- return `${path50}${path50.includes("?") ? "&" : "?"}cursor=${encodeURIComponent(cursor)}`;
47106
+ function pageOf(path51, cursor) {
47107
+ if (!cursor) return path51;
47108
+ return `${path51}${path51.includes("?") ? "&" : "?"}cursor=${encodeURIComponent(cursor)}`;
46497
47109
  }
46498
47110
  function parseEnum(flag, value, allowed) {
46499
47111
  if (value === void 0) return void 0;
@@ -46650,9 +47262,9 @@ function buildBasesCommand() {
46650
47262
  });
46651
47263
  bases.command("list-previews <origin-id>").description("List preview bases cloned from a base (production or preview)").action(async function(originId) {
46652
47264
  const client = await createDataClient();
46653
- const path50 = `/v1/${pathSegment(originId, "origin base id")}/previews`;
47265
+ const path51 = `/v1/${pathSegment(originId, "origin base id")}/previews`;
46654
47266
  printOutput(
46655
- await client.collectPages((cursor) => pageOf(path50, cursor)),
47267
+ await client.collectPages((cursor) => pageOf(path51, cursor)),
46656
47268
  outputFormat(this)
46657
47269
  );
46658
47270
  });
@@ -46691,9 +47303,9 @@ function buildBasesCommand() {
46691
47303
  });
46692
47304
  bases.command("promotions <production-id>").description("List promotion history for a production base").action(async function(productionId) {
46693
47305
  const client = await createDataClient();
46694
- const path50 = `/v1/${pathSegment(productionId, "production base id")}/promotions`;
47306
+ const path51 = `/v1/${pathSegment(productionId, "production base id")}/promotions`;
46695
47307
  printOutput(
46696
- await client.collectPages((cursor) => pageOf(path50, cursor)),
47308
+ await client.collectPages((cursor) => pageOf(path51, cursor)),
46697
47309
  outputFormat(this)
46698
47310
  );
46699
47311
  });
@@ -46834,7 +47446,7 @@ var init_file_types = __esm({
46834
47446
 
46835
47447
  // src/data/commands/files.ts
46836
47448
  import { Command as Command12 } from "commander";
46837
- import { readFileSync as readFileSync23, writeFileSync as writeFileSync13 } from "fs";
47449
+ import { readFileSync as readFileSync24, writeFileSync as writeFileSync14 } from "fs";
46838
47450
  import { basename as basename30 } from "path";
46839
47451
  function renderFileDiff(fileType, filePath3, from, to, d) {
46840
47452
  console.log(sanitizeTerminalText(`${fileType}/${filePath3}: v${from} \u2192 v${to}`));
@@ -46891,7 +47503,7 @@ function buildFilesCommand() {
46891
47503
  label: opts.label,
46892
47504
  metadata: opts.metadata === void 0 ? void 0 : parseData(opts.metadata, "--metadata")
46893
47505
  });
46894
- const body = readFileSync23(opts.file);
47506
+ const body = readFileSync24(opts.file);
46895
47507
  const client = await createDataClient();
46896
47508
  printOutput(
46897
47509
  await client.upload(
@@ -46923,7 +47535,7 @@ function buildFilesCommand() {
46923
47535
  const { bytes } = await client.download(
46924
47536
  `/v1/${base}/files/${pathSegment(fileType, "file_type")}/${encoded}${versionQs ? `?${versionQs}` : ""}`
46925
47537
  );
46926
- writeFileSync13(out, bytes);
47538
+ writeFileSync14(out, bytes);
46927
47539
  console.log(`Downloaded to ${out}`);
46928
47540
  });
46929
47541
  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) {
@@ -47263,8 +47875,8 @@ function buildRecordsCommand() {
47263
47875
  const body = { data: parseData(opts.data) };
47264
47876
  if (opts.externalId) body.external_id = opts.externalId;
47265
47877
  if (opts.externalSource) body.external_source = opts.externalSource;
47266
- const path50 = opts.id ? `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${pathSegment(opts.id, "--id")}` : `/v1/${base}/records/${pathSegment(recordType2, "record_type")}`;
47267
- printOutput(await client.request("PUT", path50, body), outputFormat(this));
47878
+ const path51 = opts.id ? `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${pathSegment(opts.id, "--id")}` : `/v1/${base}/records/${pathSegment(recordType2, "record_type")}`;
47879
+ printOutput(await client.request("PUT", path51, body), outputFormat(this));
47268
47880
  });
47269
47881
  records.command("query <record_type>").description("List/search records: exact filters + fuzzy `search`, sorting, pagination").option(
47270
47882
  "--external-source <source>",
@@ -47299,9 +47911,9 @@ function buildRecordsCommand() {
47299
47911
  ).action(async function(recordType2, id, opts) {
47300
47912
  const base = pathSegment(requireBase(this), "--base");
47301
47913
  const client = await createDataClient();
47302
- let path50 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
47303
- if (opts.externalSource) path50 += `?external_source=${encodeURIComponent(opts.externalSource)}`;
47304
- printOutput(await client.request("GET", path50), outputFormat(this));
47914
+ let path51 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
47915
+ if (opts.externalSource) path51 += `?external_source=${encodeURIComponent(opts.externalSource)}`;
47916
+ printOutput(await client.request("GET", path51), outputFormat(this));
47305
47917
  });
47306
47918
  records.command("delete <record_type> <id>").description(
47307
47919
  "Delete a record by internal ID, or by external_id (pass --external-source to scope it)"
@@ -47315,11 +47927,11 @@ function buildRecordsCommand() {
47315
47927
  }
47316
47928
  const base = pathSegment(requireBase(this), "--base");
47317
47929
  const client = await createDataClient();
47318
- let path50 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
47930
+ let path51 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
47319
47931
  if (opts.externalSource) {
47320
- path50 += `?external_source=${encodeURIComponent(opts.externalSource)}&external_id=${encodeURIComponent(id)}`;
47932
+ path51 += `?external_source=${encodeURIComponent(opts.externalSource)}&external_id=${encodeURIComponent(id)}`;
47321
47933
  }
47322
- await client.request("DELETE", path50);
47934
+ await client.request("DELETE", path51);
47323
47935
  console.log("Deleted");
47324
47936
  });
47325
47937
  records.command("history <id>").description(
@@ -47484,8 +48096,8 @@ function buildRelationshipsCommand() {
47484
48096
  if (opts.data) body.data = parseData(opts.data);
47485
48097
  const base = pathSegment(requireBase(this), "--base");
47486
48098
  const client = await createDataClient();
47487
- const path50 = opts.id ? `/v1/${base}/relationships/${pathSegment(opts.id, "--id")}` : `/v1/${base}/relationships`;
47488
- printOutput(await client.request("PUT", path50, body), outputFormat(this));
48099
+ const path51 = opts.id ? `/v1/${base}/relationships/${pathSegment(opts.id, "--id")}` : `/v1/${base}/relationships`;
48100
+ printOutput(await client.request("PUT", path51, body), outputFormat(this));
47489
48101
  });
47490
48102
  relationships.command("get <id>").description(
47491
48103
  "Get a relationship by ID (or by its external key: pass the external_id with --rel-type)"
@@ -47718,8 +48330,8 @@ function buildToolsetsCommand() {
47718
48330
  toolsets.command("get <slug>").description("Get a toolset").option("--resolved", "Include resolved record_type schemas").action(async function(slug, opts) {
47719
48331
  const base = pathSegment(requireBase(this), "--base");
47720
48332
  const client = await createDataClient();
47721
- const path50 = opts.resolved ? `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}/resolved` : `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}`;
47722
- printOutput(await client.request("GET", path50), outputFormat(this));
48333
+ const path51 = opts.resolved ? `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}/resolved` : `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}`;
48334
+ printOutput(await client.request("GET", path51), outputFormat(this));
47723
48335
  });
47724
48336
  toolsets.command("list").description("List all toolsets").action(async function() {
47725
48337
  const base = pathSegment(requireBase(this), "--base");
@@ -47854,9 +48466,9 @@ init_errors3();
47854
48466
  init_mask_secrets();
47855
48467
  init_utils();
47856
48468
  init_registry();
47857
- import { readFileSync as readFileSync24 } from "fs";
48469
+ import { readFileSync as readFileSync25 } from "fs";
47858
48470
  import { fileURLToPath as fileURLToPath2 } from "url";
47859
- import { dirname as dirname20, join as join44 } from "path";
48471
+ import { dirname as dirname20, join as join45 } from "path";
47860
48472
 
47861
48473
  // src/lib/version-refresh.ts
47862
48474
  init_version_cache();
@@ -48012,7 +48624,7 @@ Run \`wayai admin skill install\` to update.`);
48012
48624
 
48013
48625
  // src/index.ts
48014
48626
  var __dirname = dirname20(fileURLToPath2(import.meta.url));
48015
- var pkg = JSON.parse(readFileSync24(join44(__dirname, "..", "package.json"), "utf-8"));
48627
+ var pkg = JSON.parse(readFileSync25(join45(__dirname, "..", "package.json"), "utf-8"));
48016
48628
  var [, , command, ...args] = process.argv;
48017
48629
  var isBackgroundRefresh = command === REFRESH_COMMAND;
48018
48630
  if (!isBackgroundRefresh) initSentry(command, pkg.version);