@wayai/cli 0.3.331 → 0.3.332

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, path46) {
450
+ function addApiBreadcrumb(method, path48) {
451
451
  if (!initialized) return;
452
452
  Sentry.addBreadcrumb({
453
453
  category: "http",
454
- message: `${method} ${path46}`,
454
+ message: `${method} ${path48}`,
455
455
  level: "info"
456
456
  });
457
457
  }
@@ -1121,8 +1121,8 @@ var init_parseUtil = __esm({
1121
1121
  init_errors2();
1122
1122
  init_en();
1123
1123
  makeIssue = (params) => {
1124
- const { data, path: path46, errorMaps, issueData } = params;
1125
- const fullPath = [...path46, ...issueData.path || []];
1124
+ const { data, path: path48, errorMaps, issueData } = params;
1125
+ const fullPath = [...path48, ...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, path46, key) {
1436
+ constructor(parent, value, path48, key) {
1437
1437
  this._cachedPath = [];
1438
1438
  this.parent = parent;
1439
1439
  this.data = value;
1440
- this._path = path46;
1440
+ this._path = path48;
1441
1441
  this._key = key;
1442
1442
  }
1443
1443
  get path() {
@@ -7111,8 +7111,8 @@ var init_chunk_5FO3GNKP = __esm({
7111
7111
  });
7112
7112
 
7113
7113
  // ../../packages/core/dist/chunk-7AYJHO5P.js
7114
- function matchPath(pattern, path46) {
7115
- const pathSegments2 = path46.replace(/\/$/, "").split("/");
7114
+ function matchPath(pattern, path48) {
7115
+ const pathSegments2 = path48.replace(/\/$/, "").split("/");
7116
7116
  const isPrefix = pattern.endsWith("/*");
7117
7117
  const patternSegments = (isPrefix ? pattern.slice(0, -2) : pattern).split("/");
7118
7118
  if (isPrefix ? pathSegments2.length < patternSegments.length : pathSegments2.length !== patternSegments.length) {
@@ -7120,19 +7120,19 @@ function matchPath(pattern, path46) {
7120
7120
  }
7121
7121
  return patternSegments.every((segment, i) => segment === "*" ? pathSegments2[i] !== "" : segment === pathSegments2[i]);
7122
7122
  }
7123
- function getEndpointConfig(path46) {
7123
+ function getEndpointConfig(path48) {
7124
7124
  for (const excluded of EXCLUDED_PATHS) {
7125
- if (matchPath(excluded, path46)) {
7125
+ if (matchPath(excluded, path48)) {
7126
7126
  return null;
7127
7127
  }
7128
7128
  }
7129
- const normalizedPath = path46.replace(/\/$/, "");
7129
+ const normalizedPath = path48.replace(/\/$/, "");
7130
7130
  if (!normalizedPath.endsWith("/*") && Object.prototype.hasOwnProperty.call(ENDPOINT_CONFIGS, normalizedPath)) {
7131
7131
  return ENDPOINT_CONFIGS[normalizedPath];
7132
7132
  }
7133
7133
  const sortedPatterns = Object.keys(ENDPOINT_CONFIGS).sort((a, b) => b.length - a.length);
7134
7134
  for (const pattern of sortedPatterns) {
7135
- if (matchPath(pattern, path46)) {
7135
+ if (matchPath(pattern, path48)) {
7136
7136
  return ENDPOINT_CONFIGS[pattern];
7137
7137
  }
7138
7138
  }
@@ -8057,16 +8057,16 @@ function parseCommunityLessonVideoUrl(url) {
8057
8057
  const parts = /^https?:\/\/([^/?#]+)([^?#]*)(?:\?([^#]*))?(?:#.*)?$/i.exec(url.trim());
8058
8058
  if (!parts) return null;
8059
8059
  const host = parts[1].toLowerCase();
8060
- const path46 = parts[2] ?? "";
8060
+ const path48 = parts[2] ?? "";
8061
8061
  const query = parts[3] ?? "";
8062
8062
  let id;
8063
8063
  if (host === YOUTU_BE) {
8064
- id = /^\/([A-Za-z0-9_-]{11})\/?$/.exec(path46)?.[1];
8064
+ id = /^\/([A-Za-z0-9_-]{11})\/?$/.exec(path48)?.[1];
8065
8065
  } else if (YOUTUBE_HOSTS.has(host)) {
8066
- if (path46 === "/watch" || path46 === "/watch/") {
8066
+ if (path48 === "/watch" || path48 === "/watch/") {
8067
8067
  id = query.split("&").find((param) => param.startsWith("v="))?.slice(2);
8068
8068
  } else {
8069
- id = YOUTUBE_ID_PATH.exec(path46)?.[1];
8069
+ id = YOUTUBE_ID_PATH.exec(path48)?.[1];
8070
8070
  }
8071
8071
  }
8072
8072
  return id !== void 0 && YOUTUBE_ID.test(id) ? { provider: "youtube", id } : null;
@@ -8264,12 +8264,12 @@ function typeMatches(typeField, allowed) {
8264
8264
  if (Array.isArray(typeField)) return typeField.every((t) => typeof t === "string" && allowed.has(t));
8265
8265
  return false;
8266
8266
  }
8267
- function validateSchema(schema, path46, errors, opts = {}) {
8267
+ function validateSchema(schema, path48, errors, opts = {}) {
8268
8268
  if (typeof schema === "boolean") return;
8269
8269
  const depth = opts.depth ?? 0;
8270
8270
  if (depth > MAX_SCHEMA_DEPTH) {
8271
8271
  errors.push({
8272
- path: path46 || "<root>",
8272
+ path: path48 || "<root>",
8273
8273
  message: `schema nesting exceeds ${MAX_SCHEMA_DEPTH} levels`,
8274
8274
  suggestion: "Flatten the schema; LLM providers reject deeply nested tool input_schemas."
8275
8275
  });
@@ -8277,7 +8277,7 @@ function validateSchema(schema, path46, errors, opts = {}) {
8277
8277
  }
8278
8278
  if (!isRecord(schema)) {
8279
8279
  errors.push({
8280
- path: path46,
8280
+ path: path48,
8281
8281
  message: `expected object, got ${schema === null ? "null" : typeof schema}`
8282
8282
  });
8283
8283
  return;
@@ -8285,14 +8285,14 @@ function validateSchema(schema, path46, errors, opts = {}) {
8285
8285
  if (opts.isRoot) {
8286
8286
  if ("type" in schema && schema.type !== "object") {
8287
8287
  errors.push({
8288
- path: path46 ? `${path46}.type` : "type",
8288
+ path: path48 ? `${path48}.type` : "type",
8289
8289
  message: `root type must be 'object', got ${JSON.stringify(schema.type)}`,
8290
8290
  suggestion: "Tool parameters at the root must be an object: `{ type: 'object', properties: { ... } }`."
8291
8291
  });
8292
8292
  }
8293
8293
  } else if ("type" in schema && !typeMatches(schema.type, ALLOWED_TYPES)) {
8294
8294
  errors.push({
8295
- path: `${path46}.type`,
8295
+ path: `${path48}.type`,
8296
8296
  message: `type must be one of ${[...ALLOWED_TYPES].join("/")} or an array of those, got ${JSON.stringify(schema.type)}`
8297
8297
  });
8298
8298
  }
@@ -8302,25 +8302,25 @@ function validateSchema(schema, path46, errors, opts = {}) {
8302
8302
  const isPlaceholder = PLACEHOLDER_TOKENS.includes(e);
8303
8303
  const isOutcomePlaceholder = e === "[KANBAN_OUTCOME_VALUES]";
8304
8304
  errors.push({
8305
- path: `${path46}.enum`,
8305
+ path: `${path48}.enum`,
8306
8306
  message: `enum must be a non-empty array of primitives, got string ${JSON.stringify(e)}`,
8307
8307
  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
8308
  });
8309
8309
  } else if (!Array.isArray(e)) {
8310
8310
  errors.push({
8311
- path: `${path46}.enum`,
8311
+ path: `${path48}.enum`,
8312
8312
  message: `enum must be a non-empty array of primitives, got ${typeof e}`
8313
8313
  });
8314
8314
  } else if (e.length === 0) {
8315
8315
  errors.push({
8316
- path: `${path46}.enum`,
8316
+ path: `${path48}.enum`,
8317
8317
  message: "enum must not be empty"
8318
8318
  });
8319
8319
  } else {
8320
8320
  for (let i = 0; i < e.length; i++) {
8321
8321
  if (!isPrimitive(e[i])) {
8322
8322
  errors.push({
8323
- path: `${path46}.enum[${i}]`,
8323
+ path: `${path48}.enum[${i}]`,
8324
8324
  message: `enum entry must be a primitive (string/number/boolean/null), got ${typeof e[i]}`
8325
8325
  });
8326
8326
  }
@@ -8330,7 +8330,7 @@ function validateSchema(schema, path46, errors, opts = {}) {
8330
8330
  for (const key of ["exclusiveMinimum", "exclusiveMaximum"]) {
8331
8331
  if (key in schema && typeof schema[key] === "boolean") {
8332
8332
  errors.push({
8333
- path: `${path46}.${key}`,
8333
+ path: `${path48}.${key}`,
8334
8334
  message: `${key} as boolean is draft-04 syntax; draft 2020-12 requires a numeric value`,
8335
8335
  suggestion: `Replace with the numeric bound, e.g. \`${key}: 0\`.`
8336
8336
  });
@@ -8339,45 +8339,45 @@ function validateSchema(schema, path46, errors, opts = {}) {
8339
8339
  if ("properties" in schema) {
8340
8340
  if (!isRecord(schema.properties)) {
8341
8341
  errors.push({
8342
- path: `${path46}.properties`,
8342
+ path: `${path48}.properties`,
8343
8343
  message: `properties must be an object, got ${Array.isArray(schema.properties) ? "array" : typeof schema.properties}`
8344
8344
  });
8345
8345
  } else {
8346
8346
  for (const [propName, propSchema] of Object.entries(schema.properties)) {
8347
- validateSchema(propSchema, `${path46}.properties.${propName}`, errors, { depth: depth + 1 });
8347
+ validateSchema(propSchema, `${path48}.properties.${propName}`, errors, { depth: depth + 1 });
8348
8348
  }
8349
8349
  }
8350
8350
  }
8351
8351
  if (schemaTypeIncludes(schema, "array") && "items" in schema) {
8352
8352
  if (Array.isArray(schema.items)) {
8353
- schema.items.forEach((sub, i) => validateSchema(sub, `${path46}.items[${i}]`, errors, { depth: depth + 1 }));
8353
+ schema.items.forEach((sub, i) => validateSchema(sub, `${path48}.items[${i}]`, errors, { depth: depth + 1 }));
8354
8354
  } else {
8355
- validateSchema(schema.items, `${path46}.items`, errors, { depth: depth + 1 });
8355
+ validateSchema(schema.items, `${path48}.items`, errors, { depth: depth + 1 });
8356
8356
  }
8357
8357
  }
8358
8358
  for (const key of SUBSCHEMA_OBJECT_KEYWORDS) {
8359
8359
  if (key in schema && isRecord(schema[key])) {
8360
- validateSchema(schema[key], `${path46}.${key}`, errors, { depth: depth + 1 });
8360
+ validateSchema(schema[key], `${path48}.${key}`, errors, { depth: depth + 1 });
8361
8361
  }
8362
8362
  }
8363
8363
  for (const key of SUBSCHEMA_LIST_KEYWORDS) {
8364
8364
  const list2 = schema[key];
8365
8365
  if (Array.isArray(list2)) {
8366
- list2.forEach((sub, i) => validateSchema(sub, `${path46}.${key}[${i}]`, errors, { depth: depth + 1 }));
8366
+ list2.forEach((sub, i) => validateSchema(sub, `${path48}.${key}[${i}]`, errors, { depth: depth + 1 }));
8367
8367
  }
8368
8368
  }
8369
8369
  for (const key of SUBSCHEMA_MAP_KEYWORDS) {
8370
8370
  const map = schema[key];
8371
8371
  if (isRecord(map)) {
8372
8372
  for (const [name, sub] of Object.entries(map)) {
8373
- validateSchema(sub, `${path46}.${key}.${name}`, errors, { depth: depth + 1 });
8373
+ validateSchema(sub, `${path48}.${key}.${name}`, errors, { depth: depth + 1 });
8374
8374
  }
8375
8375
  }
8376
8376
  }
8377
8377
  const reportedPaths = new Set(errors.map((e) => e.path));
8378
8378
  for (const [k, v] of Object.entries(schema)) {
8379
8379
  if (typeof v !== "string") continue;
8380
- const fieldPath = `${path46}.${k}`;
8380
+ const fieldPath = `${path48}.${k}`;
8381
8381
  if (reportedPaths.has(fieldPath)) continue;
8382
8382
  for (const token of PLACEHOLDER_TOKENS) {
8383
8383
  if (v === token) {
@@ -12174,9 +12174,9 @@ function monitorRuleActions(monitorConfig) {
12174
12174
  if (!monitorConfig || typeof monitorConfig !== "object") return [];
12175
12175
  const config = monitorConfig;
12176
12176
  const found = [];
12177
- const visit = (action, path46) => {
12177
+ const visit = (action, path48) => {
12178
12178
  if (!action || typeof action !== "object" || Array.isArray(action)) return;
12179
- found.push({ action, path: path46 });
12179
+ found.push({ action, path: path48 });
12180
12180
  };
12181
12181
  if (Array.isArray(config.rules)) {
12182
12182
  config.rules.forEach((rule, index) => {
@@ -12208,25 +12208,25 @@ function collectMonitorRuleIssues(monitorConfig) {
12208
12208
  const trigger = resolveMonitorTrigger(monitorConfig);
12209
12209
  const kinds = monitorRuleActionKinds(trigger);
12210
12210
  const issues = [...callUtteranceRuleIssues(monitorConfig), ...automationGateIssues(monitorConfig)];
12211
- for (const { action, path: path46 } of monitorRuleActions(monitorConfig)) {
12212
- if (trigger === "call_utterance" && path46[0] === "fallback") continue;
12211
+ for (const { action, path: path48 } of monitorRuleActions(monitorConfig)) {
12212
+ if (trigger === "call_utterance" && path48[0] === "fallback") continue;
12213
12213
  const kind = action.kind;
12214
12214
  if (typeof kind === "string" && !kinds.includes(kind)) {
12215
- issues.push({ path: [...path46, "kind"], message: monitorActionKindMessage(kind, trigger) });
12215
+ issues.push({ path: [...path48, "kind"], message: monitorActionKindMessage(kind, trigger) });
12216
12216
  }
12217
12217
  const toolName = action.tool_name;
12218
12218
  if (kind === "call_tool" && typeof toolName === "string" && isRefusedNativeToolName(toolName, trigger)) {
12219
- issues.push({ path: [...path46, "tool_name"], message: monitorRuleToolNotAllowedMessage(toolName, trigger) });
12219
+ issues.push({ path: [...path48, "tool_name"], message: monitorRuleToolNotAllowedMessage(toolName, trigger) });
12220
12220
  continue;
12221
12221
  }
12222
12222
  if (kind === "call_tool" && toolName === INSERT_NOTE_TOOL_NAME) {
12223
- issues.push(...insertNoteArgumentIssues(action, path46));
12223
+ issues.push(...insertNoteArgumentIssues(action, path48));
12224
12224
  }
12225
12225
  if (kind === "call_tool" && toolName === RUN_MONITOR_TOOL_NAME) {
12226
12226
  const callee = readRunMonitorCallee(action);
12227
12227
  if (!callee.ok) {
12228
12228
  issues.push({
12229
- path: [...path46, "args", "monitor_name"],
12229
+ path: [...path48, "args", "monitor_name"],
12230
12230
  message: runMonitorCalleeMessage(callee.reason)
12231
12231
  });
12232
12232
  }
@@ -12286,11 +12286,11 @@ function insertNoteTemplateMessage(reason3) {
12286
12286
  return `insert_note's template is longer than the ${MONITOR_NOTE_TEMPLATE_MAX}-character limit.`;
12287
12287
  }
12288
12288
  }
12289
- function insertNoteArgumentIssues(action, path46) {
12289
+ function insertNoteArgumentIssues(action, path48) {
12290
12290
  const result = readInsertNoteTemplate(action);
12291
12291
  if (result.ok) return [];
12292
12292
  return [{
12293
- path: [...path46, "args", "template"],
12293
+ path: [...path48, "args", "template"],
12294
12294
  message: insertNoteTemplateMessage(result.reason)
12295
12295
  }];
12296
12296
  }
@@ -13264,8 +13264,8 @@ function evalInitialStateError(input) {
13264
13264
  const parsed = evalInitialStateEntry.safeParse(entries[i]);
13265
13265
  if (!parsed.success) {
13266
13266
  const issue = parsed.error.issues[0];
13267
- const path46 = issue?.path.join(".") || "?";
13268
- return `initial_state[${i}].${path46} is invalid: ${issue?.message ?? "malformed"}`;
13267
+ const path48 = issue?.path.join(".") || "?";
13268
+ return `initial_state[${i}].${path48} is invalid: ${issue?.message ?? "malformed"}`;
13269
13269
  }
13270
13270
  if (seenSlugs.has(parsed.data.slug)) {
13271
13271
  return `initial_state[${i}].slug "${parsed.data.slug}" is declared more than once`;
@@ -13791,12 +13791,12 @@ function validateFollowupLinks(followups, label3, ctx) {
13791
13791
  const linkTargets = /* @__PURE__ */ new Set();
13792
13792
  followups.forEach((followup, i) => {
13793
13793
  const ref = followup?.after_followup_id;
13794
- const path46 = ["followups", i, "after_followup_id"];
13794
+ const path48 = ["followups", i, "after_followup_id"];
13795
13795
  if (followup?.type !== "inactivity_after_before_event") {
13796
13796
  if (ref !== void 0) {
13797
13797
  ctx.addIssue({
13798
13798
  code: external_exports.ZodIssueCode.custom,
13799
- path: path46,
13799
+ path: path48,
13800
13800
  message: `kanban status ${label3}: after_followup_id is only valid on inactivity_after_before_event followups (this one is ${followup?.type})`
13801
13801
  });
13802
13802
  }
@@ -13805,7 +13805,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13805
13805
  if (ref === void 0) {
13806
13806
  ctx.addIssue({
13807
13807
  code: external_exports.ZodIssueCode.custom,
13808
- path: path46,
13808
+ path: path48,
13809
13809
  message: `kanban status ${label3}: inactivity_after_before_event requires after_followup_id naming the id of a before_event followup in the same status`
13810
13810
  });
13811
13811
  return;
@@ -13815,7 +13815,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13815
13815
  if (matches.length > 1) {
13816
13816
  ctx.addIssue({
13817
13817
  code: external_exports.ZodIssueCode.custom,
13818
- path: path46,
13818
+ path: path48,
13819
13819
  message: `kanban status ${label3}: after_followup_id "${ref}" matches ${matches.length} followups \u2014 a link must name exactly one`
13820
13820
  });
13821
13821
  return;
@@ -13827,7 +13827,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13827
13827
  );
13828
13828
  ctx.addIssue({
13829
13829
  code: external_exports.ZodIssueCode.custom,
13830
- path: path46,
13830
+ path: path48,
13831
13831
  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`
13832
13832
  });
13833
13833
  return;
@@ -13835,7 +13835,7 @@ function validateFollowupLinks(followups, label3, ctx) {
13835
13835
  if (target.type !== "before_event") {
13836
13836
  ctx.addIssue({
13837
13837
  code: external_exports.ZodIssueCode.custom,
13838
- path: path46,
13838
+ path: path48,
13839
13839
  message: `kanban status ${label3}: after_followup_id "${ref}" points at a ${target.type} followup \u2014 only before_event followups can anchor a chain`
13840
13840
  });
13841
13841
  }
@@ -14628,10 +14628,10 @@ function refineHubAsCodePersons(config, ctx) {
14628
14628
  function refineHubAsCodeEvalAttachments(config, ctx) {
14629
14629
  const cfg = config;
14630
14630
  const referencedHashes = /* @__PURE__ */ new Set();
14631
- const addTurnIssue = (path46, turn, name) => {
14631
+ const addTurnIssue = (path48, turn, name) => {
14632
14632
  const error = evalTurnAttachmentsError(turn);
14633
14633
  if (error) {
14634
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path46, message: `${name}: ${error}` });
14634
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path48, message: `${name}: ${error}` });
14635
14635
  return;
14636
14636
  }
14637
14637
  for (const hash of collectTurnAttachmentHashes(turn)) referencedHashes.add(hash);
@@ -14732,17 +14732,17 @@ function refineHubAsCodeCallOpenings(config, ctx) {
14732
14732
  const agent = entry;
14733
14733
  const openings = agent?.call_openings;
14734
14734
  if (openings === void 0 || openings === null) return;
14735
- const path46 = ["agents", a, "call_openings"];
14735
+ const path48 = ["agents", a, "call_openings"];
14736
14736
  const name = `agent "${typeof agent?.name === "string" ? agent.name : "<unnamed>"}"`;
14737
14737
  if (typeof openings !== "object" || Array.isArray(openings)) {
14738
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path46, message: `${name}: call_openings must map a language to an opening` });
14738
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path48, message: `${name}: call_openings must map a language to an opening` });
14739
14739
  return;
14740
14740
  }
14741
14741
  if (agent?.role !== "pilot_voice" && Object.keys(openings).length > 0) {
14742
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path46, message: `${name}: only a pilot_voice agent has call_openings` });
14742
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path48, message: `${name}: only a pilot_voice agent has call_openings` });
14743
14743
  }
14744
14744
  for (const [language, raw] of Object.entries(openings)) {
14745
- const at = [...path46, language];
14745
+ const at = [...path48, language];
14746
14746
  if (!callOpeningLanguage.safeParse(language).success) {
14747
14747
  ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: at, message: `${name}: call_openings language must be one of ${CALL_OPENING_LANGUAGES.join(", ")}` });
14748
14748
  continue;
@@ -14878,11 +14878,11 @@ function refineHubAsCodeDelegation(config, ctx) {
14878
14878
  }
14879
14879
  }
14880
14880
  if (del.context_boundary === void 0) return;
14881
- const path46 = ["agents", agentIndex, "tools", "delegation", delIndex, "context_boundary"];
14881
+ const path48 = ["agents", agentIndex, "tools", "delegation", delIndex, "context_boundary"];
14882
14882
  if (del.type !== "hub") {
14883
14883
  ctx.addIssue({
14884
14884
  code: external_exports.ZodIssueCode.custom,
14885
- path: path46,
14885
+ path: path48,
14886
14886
  message: `context_boundary applies only to \`type: hub\` delegations (got type "${got(del.type)}")`
14887
14887
  });
14888
14888
  return;
@@ -14890,18 +14890,18 @@ function refineHubAsCodeDelegation(config, ctx) {
14890
14890
  if (!CONTEXT_BOUNDARIES.includes(del.context_boundary)) {
14891
14891
  ctx.addIssue({
14892
14892
  code: external_exports.ZodIssueCode.custom,
14893
- path: path46,
14893
+ path: path48,
14894
14894
  message: `context_boundary must be one of: ${CONTEXT_BOUNDARIES.join(", ")}`
14895
14895
  });
14896
14896
  }
14897
14897
  });
14898
14898
  });
14899
14899
  }
14900
- function refuseNonBooleanFlag(ctx, subject, entry, key, path46) {
14900
+ function refuseNonBooleanFlag(ctx, subject, entry, key, path48) {
14901
14901
  const value = entry[key];
14902
14902
  if (value === void 0 || typeof value === "boolean") return;
14903
14903
  const shown3 = value === null || typeof value !== "object" ? JSON.stringify(value).slice(0, 40) : Array.isArray(value) ? "a list" : "an object";
14904
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: [...path46, key], message: `${subject}: ${key} must be true or false, got ${shown3}` });
14904
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: [...path48, key], message: `${subject}: ${key} must be true or false, got ${shown3}` });
14905
14905
  }
14906
14906
  function refineHubAsCodeFlags(config, ctx) {
14907
14907
  const { agents, connections, evals, journeys, teams } = config;
@@ -15092,11 +15092,11 @@ function pathPastDepth(root, levels) {
15092
15092
  function refusedNesting(value, at, ctx) {
15093
15093
  const past = pathPastDepth(value, MAX_HUB_AS_CODE_DEPTH - at.length);
15094
15094
  if (!past) return false;
15095
- const path46 = [...at, ...past].slice(0, NAMED_DEPTH_SEGMENTS).map((key) => typeof key === "string" ? key.slice(0, NAMED_DEPTH_KEY_CHARS) : key);
15095
+ const path48 = [...at, ...past].slice(0, NAMED_DEPTH_SEGMENTS).map((key) => typeof key === "string" ? key.slice(0, NAMED_DEPTH_KEY_CHARS) : key);
15096
15096
  ctx.addIssue({
15097
15097
  code: external_exports.ZodIssueCode.custom,
15098
- path: path46,
15099
- message: `${fieldName(path46)}\u2026 nests deeper than ${MAX_HUB_AS_CODE_DEPTH} levels of arrays and objects`,
15098
+ path: path48,
15099
+ message: `${fieldName(path48)}\u2026 nests deeper than ${MAX_HUB_AS_CODE_DEPTH} levels of arrays and objects`,
15100
15100
  fatal: true
15101
15101
  });
15102
15102
  return true;
@@ -15113,15 +15113,15 @@ function refusedStringConfigNesting(config, ctx) {
15113
15113
  }
15114
15114
  function refusedUnreadableSection(config, ctx) {
15115
15115
  if (!isPlainObject(config)) return false;
15116
- const refused = (path46, must) => {
15117
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path46, message: `${fieldName(path46)} must ${must}`, fatal: true });
15116
+ const refused = (path48, must) => {
15117
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: path48, message: `${fieldName(path48)} must ${must}`, fatal: true });
15118
15118
  return true;
15119
15119
  };
15120
- const badList = (value, path46, reads = {}) => {
15120
+ const badList = (value, path48, reads = {}) => {
15121
15121
  if (value === void 0 || value === null && reads.nullSection !== false) return false;
15122
- if (!Array.isArray(value)) return refused(path46, "be an array");
15122
+ if (!Array.isArray(value)) return refused(path48, "be an array");
15123
15123
  const nullAt = reads.nullEntries ? -1 : value.indexOf(null);
15124
- return nullAt !== -1 && refused([...path46, nullAt], "not be null");
15124
+ return nullAt !== -1 && refused([...path48, nullAt], "not be null");
15125
15125
  };
15126
15126
  const entries = (section) => Array.isArray(section) ? section : [];
15127
15127
  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) => {
@@ -15297,7 +15297,7 @@ var init_chunk_EO5MKW7Q = __esm({
15297
15297
  MAX_HUB_AS_CODE_DEPTH = 128;
15298
15298
  NAMED_DEPTH_SEGMENTS = 12;
15299
15299
  NAMED_DEPTH_KEY_CHARS = 64;
15300
- fieldName = (path46) => path46.reduce(
15300
+ fieldName = (path48) => path48.reduce(
15301
15301
  (name, key) => typeof key === "number" ? `${name}[${key}]` : name ? `${name}.${key}` : key,
15302
15302
  ""
15303
15303
  );
@@ -15852,8 +15852,8 @@ var init_chunk_VROZDNLV = __esm({
15852
15852
  CASE_UPLOAD_REVISION_FIELD = "revision";
15853
15853
  isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob;
15854
15854
  caseUploadForm = external_exports.record(external_exports.string(), external_exports.unknown()).transform((form2, ctx) => {
15855
- const refuse2 = (message, path46) => {
15856
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path46] });
15855
+ const refuse2 = (message, path48) => {
15856
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path48] });
15857
15857
  return external_exports.NEVER;
15858
15858
  };
15859
15859
  const text5 = form2[CASE_UPLOAD_REVISION_FIELD];
@@ -16145,8 +16145,8 @@ var init_chunk_3LMWOJQX = __esm({
16145
16145
  // ../../packages/core/dist/chunk-PMBOHJKA.js
16146
16146
  function collectionUploadForm(field, shape) {
16147
16147
  return external_exports.record(external_exports.string(), external_exports.unknown()).transform((form2, ctx) => {
16148
- const refuse2 = (message, path46) => {
16149
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path46] });
16148
+ const refuse2 = (message, path48) => {
16149
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path48] });
16150
16150
  return external_exports.NEVER;
16151
16151
  };
16152
16152
  const text5 = form2[field];
@@ -16172,7 +16172,16 @@ function collectionUploadForm(field, shape) {
16172
16172
  return { body, fields: parsed.data, parts };
16173
16173
  });
16174
16174
  }
16175
- var CASE_COLLECTION_FOLDERS, CASE_COLLECTION_PARTS, isCaseCollectionPart, CASE_COLLECTION_TITLE_MAX_LENGTH, CASE_COLLECTION_TYPE_MAX_LENGTH, CASE_COLLECTION_REASON_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;
16175
+ function caseCollectionFileName(sent) {
16176
+ const base = (sent.split(/[\\/]/).pop() ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim();
16177
+ let name = "";
16178
+ for (const character of base) {
16179
+ if (name.length + character.length > CASE_COLLECTION_FILE_NAME_MAX_LENGTH) break;
16180
+ name += character;
16181
+ }
16182
+ return name || "document";
16183
+ }
16184
+ 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;
16176
16185
  var init_chunk_PMBOHJKA = __esm({
16177
16186
  "../../packages/core/dist/chunk-PMBOHJKA.js"() {
16178
16187
  "use strict";
@@ -16189,6 +16198,7 @@ var init_chunk_PMBOHJKA = __esm({
16189
16198
  CASE_COLLECTION_TITLE_MAX_LENGTH = 300;
16190
16199
  CASE_COLLECTION_TYPE_MAX_LENGTH = 100;
16191
16200
  CASE_COLLECTION_REASON_MAX_LENGTH = 2e3;
16201
+ CASE_COLLECTION_FILE_NAME_MAX_LENGTH = 255;
16192
16202
  caseCollectionDocumentParam = caseSpaceParam.extend({ document_id: uuidSchema });
16193
16203
  dateOnly = caseDateSchema;
16194
16204
  title = external_exports.string().trim().min(1).max(CASE_COLLECTION_TITLE_MAX_LENGTH);
@@ -16317,17 +16327,17 @@ function fixedTextProblem(text5) {
16317
16327
  }
16318
16328
  return null;
16319
16329
  }
16320
- function casePieceSidecar(path46) {
16321
- if (/\.yaml$/i.test(path46)) return null;
16322
- const sidecar = path46.replace(/\.[^./]+$/, ".yaml");
16323
- return sidecar === path46 ? null : sidecar;
16330
+ function casePieceSidecar(path48) {
16331
+ if (/\.yaml$/i.test(path48)) return null;
16332
+ const sidecar = path48.replace(/\.[^./]+$/, ".yaml");
16333
+ return sidecar === path48 ? null : sidecar;
16324
16334
  }
16325
16335
  function pathsOverlap(a, b) {
16326
16336
  return a === b || a.endsWith("/") && b.startsWith(a) || b.endsWith("/") && a.startsWith(b);
16327
16337
  }
16328
- function boundPathKey(path46, folders) {
16329
- const folder = path46.endsWith("/");
16330
- const checked = checkCaseFilePath({ path: folder ? `${path46}${CHAPTER_PROBE}` : path46, type: "file" }, folders);
16338
+ function boundPathKey(path48, folders) {
16339
+ const folder = path48.endsWith("/");
16340
+ const checked = checkCaseFilePath({ path: folder ? `${path48}${CHAPTER_PROBE}` : path48, type: "file" }, folders);
16331
16341
  if (!checked.ok || checked.received) return null;
16332
16342
  return folder ? checked.fold_key.slice(0, -CHAPTER_PROBE.length) : checked.fold_key;
16333
16343
  }
@@ -16380,11 +16390,11 @@ function caseTypeDefinitionProblem(definition) {
16380
16390
  if (output.format === "file" && output.output_items.length > 0) return problem("file_output_with_items", outputAt);
16381
16391
  if (output.format === "file" && output.case_items_allowed) return problem("file_output_with_case_items", outputAt);
16382
16392
  if (caseValuesRepeated(output.approving_team_ids)) return problem("approving_team_repeated", outputAt);
16383
- for (const path46 of output.file_paths) {
16384
- if (!path46.startsWith(`${phase.folder}/`)) return problem("file_path_outside_phase", outputAt);
16385
- const key = boundPathKey(path46, folders);
16393
+ for (const path48 of output.file_paths) {
16394
+ if (!path48.startsWith(`${phase.folder}/`)) return problem("file_path_outside_phase", outputAt);
16395
+ const key = boundPathKey(path48, folders);
16386
16396
  if (key === null) return problem("file_path_not_writable", outputAt);
16387
- if (output.format === "file" && path46.endsWith("/")) return problem("file_path_folder_for_file", outputAt);
16397
+ if (output.format === "file" && path48.endsWith("/")) return problem("file_path_folder_for_file", outputAt);
16388
16398
  if (paths.some((held) => pathsOverlap(held, key))) return problem("file_path_overlaps", outputAt);
16389
16399
  paths.push(key);
16390
16400
  }
@@ -16505,8 +16515,8 @@ var init_chunk_PFPADFUC = __esm({
16505
16515
  const { folder, code: targetCode } = resolveItemLink("", target);
16506
16516
  return (!target.includes("/") || CASE_PHASE_FOLDER_PATTERN.test(folder)) && CASE_CODE_PATTERN.test(targetCode);
16507
16517
  }, "An item is named by its code, or by its phase folder and code");
16508
- filePath = external_exports.string().min(1).max(CASE_FILE_PATH_MAX_LENGTH).refine((path46) => {
16509
- const segments = (path46.endsWith("/") ? path46.slice(0, -1) : path46).split("/");
16518
+ filePath = external_exports.string().min(1).max(CASE_FILE_PATH_MAX_LENGTH).refine((path48) => {
16519
+ const segments = (path48.endsWith("/") ? path48.slice(0, -1) : path48).split("/");
16510
16520
  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));
16511
16521
  }, "A file path is the phase folder, then letters, digits, dots, dashes and underscores");
16512
16522
  caseTypePartyRoleSchema = external_exports.object({
@@ -16749,7 +16759,13 @@ var init_chunk_733K4J4G = __esm({
16749
16759
  });
16750
16760
 
16751
16761
  // ../../packages/core/dist/chunk-ZB7W3DKK.js
16752
- var 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, ZIP_DIRECTORY_MAX_BYTES, CONTENT_TYPES_MAX_BYTES, CONTENT_TYPES_INFLATED_MAX_BYTES, CASE_RECEIVED_PAGE_MAX, caseReceivedQuery, caseReceivedContentQuery;
16762
+ function caseReceivedFormat(fileName) {
16763
+ const dot = fileName.lastIndexOf(".");
16764
+ if (dot < 0) return null;
16765
+ const extension = fileName.slice(dot + 1).toLowerCase();
16766
+ return isCaseReceivedFormat(extension) ? extension : null;
16767
+ }
16768
+ 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;
16753
16769
  var init_chunk_ZB7W3DKK = __esm({
16754
16770
  "../../packages/core/dist/chunk-ZB7W3DKK.js"() {
16755
16771
  "use strict";
@@ -16760,6 +16776,22 @@ var init_chunk_ZB7W3DKK = __esm({
16760
16776
  init_chunk_3T3D7LTE();
16761
16777
  init_chunk_HZ6CADSY();
16762
16778
  init_zod();
16779
+ ZIP_SIGNATURE = [80, 75, 3, 4];
16780
+ CASE_RECEIVED_FORMATS = {
16781
+ pdf: { signature: [37, 80, 68, 70] },
16782
+ docx: { signature: ZIP_SIGNATURE, zip: "office" },
16783
+ xlsx: { signature: ZIP_SIGNATURE, zip: "office" },
16784
+ pptx: { signature: ZIP_SIGNATURE, zip: "office" },
16785
+ odt: { signature: ZIP_SIGNATURE, zip: "open_document" },
16786
+ ods: { signature: ZIP_SIGNATURE, zip: "open_document" },
16787
+ csv: {},
16788
+ txt: {},
16789
+ md: {},
16790
+ png: { signature: [137, 80, 78, 71] },
16791
+ jpg: { signature: [255, 216, 255] },
16792
+ jpeg: { signature: [255, 216, 255] }
16793
+ };
16794
+ isCaseReceivedFormat = (format) => typeof format === "string" && Object.hasOwn(CASE_RECEIVED_FORMATS, format);
16763
16795
  CASE_RECEIVED_PARTS = ["file", "text"];
16764
16796
  CASE_RECEIVED_TITLE_MAX_LENGTH = 300;
16765
16797
  CASE_RECEIVED_TYPE_MAX_LENGTH = 100;
@@ -16775,8 +16807,8 @@ var init_chunk_ZB7W3DKK = __esm({
16775
16807
  confidential: external_exports.boolean().default(false)
16776
16808
  }).strict();
16777
16809
  caseReceivedUploadForm = external_exports.record(external_exports.string(), external_exports.unknown()).transform((form2, ctx) => {
16778
- const refuse2 = (message, path46) => {
16779
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path46] });
16810
+ const refuse2 = (message, path48) => {
16811
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message, path: [path48] });
16780
16812
  return external_exports.NEVER;
16781
16813
  };
16782
16814
  const text5 = form2[CASE_RECEIVED_DOCUMENT_FIELD];
@@ -16800,6 +16832,7 @@ var init_chunk_ZB7W3DKK = __esm({
16800
16832
  const sentName = file.name;
16801
16833
  return { body, file: { bytes: file, name: typeof sentName === "string" ? sentName : "" }, text: markdown };
16802
16834
  });
16835
+ caseReceivedFileName = caseCollectionFileName;
16803
16836
  ZIP_DIRECTORY_MAX_BYTES = 5 * 1024 * 1024;
16804
16837
  CONTENT_TYPES_MAX_BYTES = 2 * 1024 * 1024;
16805
16838
  CONTENT_TYPES_INFLATED_MAX_BYTES = 8 * 1024 * 1024;
@@ -16847,7 +16880,7 @@ var init_chunk_BT77VXJU = __esm({
16847
16880
  });
16848
16881
 
16849
16882
  // ../../packages/core/dist/chunk-RHXF6X2Y.js
16850
- var CASE_CHECK_CSV_MAX_BYTES, caseChecksQuery;
16883
+ var CASE_CHECK_CSV_MAX_BYTES, CASE_DECISIONS_CSV_PATH, CASE_CONFIDENTIAL_DECISIONS_CSV_PATH, caseChecksQuery;
16851
16884
  var init_chunk_RHXF6X2Y = __esm({
16852
16885
  "../../packages/core/dist/chunk-RHXF6X2Y.js"() {
16853
16886
  "use strict";
@@ -16855,6 +16888,8 @@ var init_chunk_RHXF6X2Y = __esm({
16855
16888
  init_chunk_HZ6CADSY();
16856
16889
  init_zod();
16857
16890
  CASE_CHECK_CSV_MAX_BYTES = 4 * 1024 * 1024;
16891
+ CASE_DECISIONS_CSV_PATH = "analysis/decisions.csv";
16892
+ CASE_CONFIDENTIAL_DECISIONS_CSV_PATH = "conf/analysis/decisions.csv";
16858
16893
  caseChecksQuery = external_exports.object({
16859
16894
  output_id: uuidSchema.optional()
16860
16895
  }).strict();
@@ -19429,24 +19464,24 @@ import * as path7 from "path";
19429
19464
  import * as readline from "readline";
19430
19465
  function prompt(question) {
19431
19466
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
19432
- return new Promise((resolve13) => {
19467
+ return new Promise((resolve14) => {
19433
19468
  rl.question(question, (answer) => {
19434
19469
  rl.close();
19435
- resolve13(answer.trim());
19470
+ resolve14(answer.trim());
19436
19471
  });
19437
19472
  });
19438
19473
  }
19439
19474
  function confirm(question) {
19440
19475
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
19441
- return new Promise((resolve13) => {
19476
+ return new Promise((resolve14) => {
19442
19477
  rl.question(`${question} [y/N]: `, (answer) => {
19443
19478
  rl.close();
19444
- resolve13(answer.trim().toLowerCase() === "y");
19479
+ resolve14(answer.trim().toLowerCase() === "y");
19445
19480
  });
19446
19481
  });
19447
19482
  }
19448
19483
  function promptSecret(question) {
19449
- return new Promise((resolve13) => {
19484
+ return new Promise((resolve14) => {
19450
19485
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
19451
19486
  const originalWrite = rl._writeToOutput;
19452
19487
  let firstWrite = true;
@@ -19462,18 +19497,18 @@ function promptSecret(question) {
19462
19497
  rl._writeToOutput = originalWrite;
19463
19498
  process.stdout.write("\n");
19464
19499
  rl.close();
19465
- resolve13(answer);
19500
+ resolve14(answer);
19466
19501
  });
19467
19502
  });
19468
19503
  }
19469
19504
  function readStdin() {
19470
- return new Promise((resolve13, reject) => {
19505
+ return new Promise((resolve14, reject) => {
19471
19506
  let data = "";
19472
19507
  process.stdin.setEncoding("utf-8");
19473
19508
  process.stdin.on("data", (chunk) => {
19474
19509
  data += chunk;
19475
19510
  });
19476
- process.stdin.on("end", () => resolve13(data.trim()));
19511
+ process.stdin.on("end", () => resolve14(data.trim()));
19477
19512
  process.stdin.on("error", reject);
19478
19513
  });
19479
19514
  }
@@ -19993,9 +20028,9 @@ function oldLayoutEntries(root, skills, oldLayout) {
19993
20028
  function assertOldLayoutConvertible(root, skills, oldLayout, pullCommand3) {
19994
20029
  const { leftover } = oldLayoutEntries(root, skills, oldLayout);
19995
20030
  if (leftover.length === 0) return;
19996
- const one = leftover.length === 1;
20031
+ const one2 = leftover.length === 1;
19997
20032
  throw expected(
19998
- `${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 ${one ? "it" : "them"} out of ${path8.basename(root)}/ (a knowledge backup belongs outside the workspace), then run \`${pullCommand3}\` again. Nothing was written.`
20033
+ `${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 ${one2 ? "it" : "them"} out of ${path8.basename(root)}/ (a knowledge backup belongs outside the workspace), then run \`${pullCommand3}\` again. Nothing was written.`
19999
20034
  );
20000
20035
  }
20001
20036
  function removeConvertedOldResources(root, skills, log, opts = {}) {
@@ -20247,6 +20282,31 @@ var init_resource_files = __esm({
20247
20282
  }
20248
20283
  });
20249
20284
 
20285
+ // ../../packages/core/dist/contracts/case-received-documents.js
20286
+ var init_case_received_documents = __esm({
20287
+ "../../packages/core/dist/contracts/case-received-documents.js"() {
20288
+ "use strict";
20289
+ init_chunk_ZB7W3DKK();
20290
+ init_chunk_PMBOHJKA();
20291
+ init_chunk_U3X3BIQH();
20292
+ init_chunk_3LMWOJQX();
20293
+ init_chunk_VROZDNLV();
20294
+ init_chunk_733K4J4G();
20295
+ init_chunk_PFPADFUC();
20296
+ init_chunk_KWRHZBGU();
20297
+ init_chunk_3T3D7LTE();
20298
+ init_chunk_M2T55BV6();
20299
+ init_chunk_VYINA6YP();
20300
+ init_chunk_ZVXO3XL6();
20301
+ init_chunk_FBV7NLKO();
20302
+ init_chunk_WEXVYJ5H();
20303
+ init_chunk_HZ6CADSY();
20304
+ init_chunk_ICYO56QW();
20305
+ init_chunk_WFQDSQJK();
20306
+ init_chunk_ZTNFLGW5();
20307
+ }
20308
+ });
20309
+
20250
20310
  // src/lib/api-client.ts
20251
20311
  var api_client_exports = {};
20252
20312
  __export(api_client_exports, {
@@ -20270,10 +20330,10 @@ function toDataProxyPath(v1Path) {
20270
20330
  }
20271
20331
  return `${DATA_PROXY_PREFIX}${v1Path.slice(REKOR_V1_PREFIX.length)}`;
20272
20332
  }
20273
- function withOrgSelector(path46, orgId) {
20274
- if (!orgId) return path46;
20275
- const separator = path46.includes("?") ? "&" : "?";
20276
- return `${path46}${separator}${DATA_PROXY_ORG_QUERY_PARAM}=${encodeURIComponent(orgId)}`;
20333
+ function withOrgSelector(path48, orgId) {
20334
+ if (!orgId) return path48;
20335
+ const separator = path48.includes("?") ? "&" : "?";
20336
+ return `${path48}${separator}${DATA_PROXY_ORG_QUERY_PARAM}=${encodeURIComponent(orgId)}`;
20277
20337
  }
20278
20338
  function dataErrorMessage(err) {
20279
20339
  if (!(err instanceof ApiError)) return null;
@@ -20294,11 +20354,12 @@ var init_api_client = __esm({
20294
20354
  "src/lib/api-client.ts"() {
20295
20355
  "use strict";
20296
20356
  init_resource_files();
20357
+ init_case_received_documents();
20297
20358
  init_contracts();
20298
20359
  init_sentry();
20299
20360
  init_mask_secrets();
20300
20361
  RETRYABLE_BACKOFF_MS = [500, 1e3, 2e3];
20301
- delay = (ms) => new Promise((resolve13) => setTimeout(resolve13, ms));
20362
+ delay = (ms) => new Promise((resolve14) => setTimeout(resolve14, ms));
20302
20363
  accessDimensions = (orgId, dimensionId) => `/api/setup/organizations/${encodeURIComponent(orgId)}/access-dimensions${dimensionId === void 0 ? "" : `/${encodeURIComponent(dimensionId)}`}`;
20303
20364
  courseAuthoring = (communityId, courseId) => `/api/communities/${encodeURIComponent(communityId)}/authoring/courses${courseId === void 0 ? "" : `/${encodeURIComponent(courseId)}`}`;
20304
20365
  casePath = (ref) => `/api/cases/${encodeURIComponent(ref.org_id)}/${encodeURIComponent(ref.space_id)}/cases/${encodeURIComponent(ref.code)}`;
@@ -20311,13 +20372,13 @@ var init_api_client = __esm({
20311
20372
  * telling them apart by body shape misreads one for the other.
20312
20373
  */
20313
20374
  path;
20314
- constructor(method, path46, status, body) {
20375
+ constructor(method, path48, status, body) {
20315
20376
  const safeBody = maskSecretsInMessage(body);
20316
- super(`API request failed: ${method} ${path46} (${status}): ${safeBody}`);
20377
+ super(`API request failed: ${method} ${path48} (${status}): ${safeBody}`);
20317
20378
  this.name = "ApiError";
20318
20379
  this.status = status;
20319
20380
  this.body = safeBody;
20320
- this.path = path46;
20381
+ this.path = path48;
20321
20382
  }
20322
20383
  /** True when the status code is a 4xx client error (expected user-facing condition, not a bug). */
20323
20384
  get isExpected() {
@@ -20452,6 +20513,54 @@ var init_api_client = __esm({
20452
20513
  async revokeCaseAgentAuthorization(ref, authorizationId) {
20453
20514
  return this.request("DELETE", `${casePath(ref)}/agents/${encodeURIComponent(authorizationId)}`);
20454
20515
  }
20516
+ // A case's work, with the case token (wayai#5921 Stage 8, `wayai cases`): each route on the token's list in
20517
+ // `apps/backend/src/cases/channel-gate.ts`, and no other.
20518
+ async getCase(ref) {
20519
+ return this.request("GET", casePath(ref));
20520
+ }
20521
+ async getCaseState(ref) {
20522
+ return this.request("GET", `${casePath(ref)}/state`);
20523
+ }
20524
+ /** A page of the case's notes, newest first. */
20525
+ async listCaseNotes(ref, query = {}) {
20526
+ const params = new URLSearchParams();
20527
+ if (query.cursor) params.set("cursor", query.cursor);
20528
+ if (query.limit !== void 0) params.set("limit", String(query.limit));
20529
+ const qs = params.toString();
20530
+ return this.request("GET", `${casePath(ref)}/notes${qs ? `?${qs}` : ""}`);
20531
+ }
20532
+ async addCaseNote(ref, body) {
20533
+ return this.request("POST", `${casePath(ref)}/notes`, body);
20534
+ }
20535
+ async completeCaseNote(ref, noteId) {
20536
+ return this.request("POST", `${casePath(ref)}/notes/${encodeURIComponent(noteId)}/complete`);
20537
+ }
20538
+ async getCasePhaseWork(ref, phaseId) {
20539
+ return this.request("GET", `${casePath(ref)}/phases/${encodeURIComponent(phaseId)}/work`);
20540
+ }
20541
+ /** A page of one phase's agenda groups. */
20542
+ async getCaseAgenda(ref, phaseId, cursor) {
20543
+ const params = new URLSearchParams({ phase_id: phaseId });
20544
+ if (cursor) params.set("cursor", cursor);
20545
+ return this.request("GET", `${casePath(ref)}/agenda?${params}`);
20546
+ }
20547
+ /** The approved decisions; a confidential group's only when `confidential` is asked, which only its caller decides. */
20548
+ async listCaseApprovedDecisions(ref, confidential) {
20549
+ return this.request("GET", `${casePath(ref)}/agenda/approved${confidential ? "?confidential=true" : ""}`);
20550
+ }
20551
+ /** The drafting checks of a phase's delivery (a joint phase's), or of one output's. */
20552
+ async getCasePhaseChecks(ref, phaseId, outputId) {
20553
+ const qs = outputId ? `?${new URLSearchParams({ output_id: outputId })}` : "";
20554
+ return this.request("GET", `${casePath(ref)}/phases/${encodeURIComponent(phaseId)}/checks${qs}`);
20555
+ }
20556
+ /** Register a received document: its fields, its file under the name it is kept by, and its Markdown text, in one multipart request. */
20557
+ async registerCaseReceivedDocument(ref, document, file, text5) {
20558
+ const form2 = new FormData();
20559
+ form2.set(CASE_RECEIVED_DOCUMENT_FIELD, JSON.stringify(document));
20560
+ form2.set("file", new Blob([file.bytes]), file.name);
20561
+ form2.set("text", new Blob([text5], { type: "text/markdown" }), "text.md");
20562
+ return this.request("POST", `${casePath(ref)}/received/uploads`, form2);
20563
+ }
20455
20564
  // Destroy an org-owned community (platform-admin gated, gh #4872). Used by
20456
20565
  // `wayai admin communities destroy`.
20457
20566
  async adminDestroyCommunity(communityId) {
@@ -20640,8 +20749,8 @@ var init_api_client = __esm({
20640
20749
  ...opts?.check && { check: true }
20641
20750
  });
20642
20751
  }
20643
- async lookup(path46, opts) {
20644
- const params = new URLSearchParams({ path: path46 });
20752
+ async lookup(path48, opts) {
20753
+ const params = new URLSearchParams({ path: path48 });
20645
20754
  if (opts?.organizationId) params.set("organization_id", opts.organizationId);
20646
20755
  return this.request("GET", `/api/ci/lookup?${params.toString()}`);
20647
20756
  }
@@ -21181,9 +21290,9 @@ var init_api_client = __esm({
21181
21290
  `/api/admin/data-explorer/debug/observability/${encodeURIComponent(hubId)}/conversations/${encodeURIComponent(conversationId)}${qs}`
21182
21291
  );
21183
21292
  }
21184
- async request(method, path46, body, extraHeaders, contentType) {
21185
- addApiBreadcrumb(method, path46);
21186
- const url = `${this.apiUrl}${path46}`;
21293
+ async request(method, path48, body, extraHeaders, contentType) {
21294
+ addApiBreadcrumb(method, path48);
21295
+ const url = `${this.apiUrl}${path48}`;
21187
21296
  let refreshedOn401 = false;
21188
21297
  for (let retry = 0; ; retry++) {
21189
21298
  let response = await this.send(url, method, body, extraHeaders, contentType);
@@ -21208,7 +21317,7 @@ var init_api_client = __esm({
21208
21317
  await delay(RETRYABLE_BACKOFF_MS[retry]);
21209
21318
  continue;
21210
21319
  }
21211
- throw new ApiError(method, path46, response.status, errorBody);
21320
+ throw new ApiError(method, path48, response.status, errorBody);
21212
21321
  }
21213
21322
  }
21214
21323
  /**
@@ -21275,9 +21384,9 @@ var init_api_client = __esm({
21275
21384
  * transient-retry loop — re-streaming a blob is not worth a cold-start probe.
21276
21385
  */
21277
21386
  async dataDownload(v1Path, orgId) {
21278
- const path46 = withOrgSelector(toDataProxyPath(v1Path), orgId);
21279
- addApiBreadcrumb("GET", path46);
21280
- const url = `${this.apiUrl}${path46}`;
21387
+ const path48 = withOrgSelector(toDataProxyPath(v1Path), orgId);
21388
+ addApiBreadcrumb("GET", path48);
21389
+ const url = `${this.apiUrl}${path48}`;
21281
21390
  let response = await this.send(url, "GET");
21282
21391
  if (response.status === 401 && this.onUnauthorized) {
21283
21392
  let refreshed;
@@ -21291,7 +21400,7 @@ var init_api_client = __esm({
21291
21400
  }
21292
21401
  }
21293
21402
  if (!response.ok) {
21294
- throw new ApiError("GET", path46, response.status, await response.text());
21403
+ throw new ApiError("GET", path48, response.status, await response.text());
21295
21404
  }
21296
21405
  return {
21297
21406
  bytes: new Uint8Array(await response.arrayBuffer()),
@@ -21313,15 +21422,19 @@ var init_api_client = __esm({
21313
21422
  headers: {
21314
21423
  // Caller-supplied FIRST, so everything pinned below is out of their
21315
21424
  // reach: a metadata header cannot restate the credential or mislabel
21316
- // the body.
21317
- ...extraHeaders,
21425
+ // the body. With a multipart body, which takes the content type `fetch`
21426
+ // writes, a caller's is dropped.
21427
+ ...body instanceof FormData && extraHeaders ? Object.fromEntries(Object.entries(extraHeaders).filter(([name]) => name.toLowerCase() !== "content-type")) : extraHeaders,
21318
21428
  Authorization: `Bearer ${this.accessToken}`,
21319
21429
  // The content type describes THIS body, so it is derived from the body
21320
21430
  // rather than accepted from `extraHeaders` — which is pinned out above,
21321
21431
  // and would otherwise be the one way to mislabel a JSON request.
21322
21432
  // `||`, not `??`: an empty content type is not a content type, and an
21323
21433
  // unlabelled body should fall back rather than announce nothing.
21324
- "Content-Type": body instanceof Uint8Array ? contentType || "application/octet-stream" : "application/json",
21434
+ // A multipart body carries none: `fetch` writes it, with the boundary it chose.
21435
+ ...body instanceof FormData ? {} : {
21436
+ "Content-Type": body instanceof Uint8Array ? contentType || "application/octet-stream" : "application/json"
21437
+ },
21325
21438
  // Names the calling surface for the Data Worker's audit rows, which
21326
21439
  // record `cli` vs `api` vs `mcp`. A HINT, not an
21327
21440
  // authorization input: any client can send it, so the backend must
@@ -21330,10 +21443,10 @@ var init_api_client = __esm({
21330
21443
  // audit rows are its consumer.
21331
21444
  "X-WayAI-Client": "cli"
21332
21445
  },
21333
- // Bytes go on the wire verbatim (file content, attachments); everything
21334
- // else is JSON. Encoding a Uint8Array through JSON.stringify would send
21446
+ // Bytes and a multipart form go on the wire verbatim (file content,
21447
+ // attachments, a case's received document); everything else is JSON. Encoding a Uint8Array through JSON.stringify would send
21335
21448
  // `{"0":137,…}` — a corrupt upload rather than a failed one.
21336
- body: !body ? void 0 : body instanceof Uint8Array ? body : JSON.stringify(body)
21449
+ body: !body ? void 0 : body instanceof Uint8Array || body instanceof FormData ? body : JSON.stringify(body)
21337
21450
  });
21338
21451
  }
21339
21452
  };
@@ -21730,9 +21843,9 @@ function getVersionCachePath(filename = CLI_CACHE_FILE) {
21730
21843
  }
21731
21844
  function readVersionCache(filename = CLI_CACHE_FILE) {
21732
21845
  try {
21733
- const path46 = getVersionCachePath(filename);
21734
- if (!existsSync4(path46)) return null;
21735
- const parsed = JSON.parse(readFileSync6(path46, "utf-8"));
21846
+ const path48 = getVersionCachePath(filename);
21847
+ if (!existsSync4(path48)) return null;
21848
+ const parsed = JSON.parse(readFileSync6(path48, "utf-8"));
21736
21849
  if (typeof parsed.lastCheck !== "number") return null;
21737
21850
  if (parsed.latest !== null && typeof parsed.latest !== "string") return null;
21738
21851
  return parsed;
@@ -21752,10 +21865,10 @@ function isVersionCacheStale(filename = CLI_CACHE_FILE, maxAgeMs = MAX_AGE_24H_M
21752
21865
  return Date.now() - cache.lastCheck > maxAgeMs;
21753
21866
  }
21754
21867
  function writeVersionCache(filename, cache) {
21755
- const path46 = getVersionCachePath(filename);
21756
- const dir = dirname6(path46);
21868
+ const path48 = getVersionCachePath(filename);
21869
+ const dir = dirname6(path48);
21757
21870
  if (!existsSync4(dir)) mkdirSync2(dir, { recursive: true });
21758
- writeFileSync2(path46, JSON.stringify(cache));
21871
+ writeFileSync2(path48, JSON.stringify(cache));
21759
21872
  }
21760
21873
  function touchVersionCache(filename) {
21761
21874
  writeVersionCache(filename, { lastCheck: Date.now(), latest: readVersionCache(filename)?.latest ?? null });
@@ -21794,14 +21907,14 @@ function parseFrontmatterVersion(content) {
21794
21907
  function findInstalledSkills(projectRoot, paths = SKILL_INSTALL_PATHS) {
21795
21908
  const found = [];
21796
21909
  for (const rel of paths) {
21797
- const path46 = join9(projectRoot, rel);
21798
- if (!existsSync5(path46)) continue;
21910
+ const path48 = join9(projectRoot, rel);
21911
+ if (!existsSync5(path48)) continue;
21799
21912
  let version = null;
21800
21913
  try {
21801
- version = parseFrontmatterVersion(readFileSync7(path46, "utf-8"));
21914
+ version = parseFrontmatterVersion(readFileSync7(path48, "utf-8"));
21802
21915
  } catch {
21803
21916
  }
21804
- found.push({ path: path46, version });
21917
+ found.push({ path: path48, version });
21805
21918
  }
21806
21919
  return found;
21807
21920
  }
@@ -22277,7 +22390,7 @@ async function validateToken(apiUrl, token) {
22277
22390
  }
22278
22391
  }
22279
22392
  function startCallbackServer(port, expectedState, timeoutMs = 12e4) {
22280
- return new Promise((resolve13, reject) => {
22393
+ return new Promise((resolve14, reject) => {
22281
22394
  const server = http.createServer((req, res) => {
22282
22395
  const url = new URL(req.url || "/", `http://127.0.0.1:${port}`);
22283
22396
  if (url.pathname === "/callback") {
@@ -22303,7 +22416,7 @@ function startCallbackServer(port, expectedState, timeoutMs = 12e4) {
22303
22416
  res.writeHead(200, { "Content-Type": "text/html" });
22304
22417
  res.end("<html><body><h2>Login successful!</h2><p>You can close this tab and return to your terminal.</p></body></html>");
22305
22418
  server.close();
22306
- resolve13({ code: code2, port });
22419
+ resolve14({ code: code2, port });
22307
22420
  } else {
22308
22421
  res.writeHead(400, { "Content-Type": "text/html" });
22309
22422
  res.end("<html><body><h2>Login failed</h2><p>No authorization code received</p></body></html>");
@@ -22552,10 +22665,10 @@ import * as readline2 from "readline";
22552
22665
  function prompt2(question, defaultValue) {
22553
22666
  const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
22554
22667
  const display = defaultValue ? `${question} [${defaultValue}]: ` : `${question}: `;
22555
- return new Promise((resolve13) => {
22668
+ return new Promise((resolve14) => {
22556
22669
  rl.question(display, (answer) => {
22557
22670
  rl.close();
22558
- resolve13(answer.trim() || defaultValue || "");
22671
+ resolve14(answer.trim() || defaultValue || "");
22559
22672
  });
22560
22673
  });
22561
22674
  }
@@ -22683,8 +22796,8 @@ async function tryOpenBrowser(url) {
22683
22796
  cmd = "xdg-open";
22684
22797
  args2 = [url];
22685
22798
  }
22686
- return new Promise((resolve13) => {
22687
- execFile(cmd, args2, (err) => resolve13(!err));
22799
+ return new Promise((resolve14) => {
22800
+ execFile(cmd, args2, (err) => resolve14(!err));
22688
22801
  });
22689
22802
  } catch {
22690
22803
  return false;
@@ -25461,8 +25574,8 @@ function extraTargetRefusal(verb, tokens2) {
25461
25574
  ...(tokens2.extraPositionals ?? []).map(shownArgument)
25462
25575
  ];
25463
25576
  if (named.length < 2) return null;
25464
- const listed2 = `${named.slice(0, -1).map((t) => `\`${t}\``).join(", ")} and \`${named[named.length - 1]}\``;
25465
- return `\`wayai ${verb}\` acts on one target, and was given ${named.length}: ${listed2}. It is refused rather than run on one of them alone: name one target per run.`;
25577
+ const listed3 = `${named.slice(0, -1).map((t) => `\`${t}\``).join(", ")} and \`${named[named.length - 1]}\``;
25578
+ return `\`wayai ${verb}\` acts on one target, and was given ${named.length}: ${listed3}. It is refused rather than run on one of them alone: name one target per run.`;
25466
25579
  }
25467
25580
  function firstSegment(p) {
25468
25581
  const normalized = p.split(path22.sep).join("/");
@@ -25734,12 +25847,12 @@ async function createDataClient(orgId, opts = {}) {
25734
25847
  return orgId2;
25735
25848
  }
25736
25849
  return {
25737
- async request(method, path46, body, headers) {
25738
- const envelope = await api.dataRequest(method, path46, body, org, headers);
25850
+ async request(method, path48, body, headers) {
25851
+ const envelope = await api.dataRequest(method, path48, body, org, headers);
25739
25852
  return envelope.data;
25740
25853
  },
25741
- async requestRaw(method, path46, body) {
25742
- const body_ = await api.dataRequest(method, path46, body, org);
25854
+ async requestRaw(method, path48, body) {
25855
+ const body_ = await api.dataRequest(method, path48, body, org);
25743
25856
  return body_;
25744
25857
  },
25745
25858
  async collectPages(makePath) {
@@ -26844,8 +26957,8 @@ function installEvalSignalHandlers(input) {
26844
26957
  let signalCount = 0;
26845
26958
  let disposed = false;
26846
26959
  let settle;
26847
- const settled = new Promise((resolve13) => {
26848
- settle = resolve13;
26960
+ const settled = new Promise((resolve14) => {
26961
+ settle = resolve14;
26849
26962
  });
26850
26963
  const listeners = /* @__PURE__ */ new Map();
26851
26964
  const dispose = () => {
@@ -26975,7 +27088,7 @@ var init_pacer = __esm({
26975
27088
  WINDOW_MS = 6e4;
26976
27089
  DEFAULT_RETRY_AFTER_SECONDS = 60;
26977
27090
  MAX_RATE_LIMITED_RETRIES = 5;
26978
- realSleep = (ms) => new Promise((resolve13) => setTimeout(resolve13, ms));
27091
+ realSleep = (ms) => new Promise((resolve14) => setTimeout(resolve14, ms));
26979
27092
  Pacer = class {
26980
27093
  perMinute;
26981
27094
  now;
@@ -27270,8 +27383,8 @@ function readCourseFolder(communityFolder, folder, slug, problems2) {
27270
27383
  const lessonsDir = path26.join(folder, LESSONS_DIR);
27271
27384
  requireRealSubdirNoSymlink(communityFolder, lessonsDir, false);
27272
27385
  const modules = readModules(communityFolder, lessonsDir, doc.modules, slug, where, problems2);
27273
- const listed2 = new Set(modules.flatMap((module) => module.lessons.map((lesson) => lesson.slug)));
27274
- const unlisted = folderEntries(lessonsDir).filter((name) => name.endsWith(LESSON_FILE_EXT) && !listed2.has(path26.basename(name, LESSON_FILE_EXT))).map((name) => ({ name, id: uuidField(lessonFrontmatter(readFileNoFollow(communityFolder, path26.join(lessonsDir, name))), "id") }));
27386
+ const listed3 = new Set(modules.flatMap((module) => module.lessons.map((lesson) => lesson.slug)));
27387
+ const unlisted = folderEntries(lessonsDir).filter((name) => name.endsWith(LESSON_FILE_EXT) && !listed3.has(path26.basename(name, LESSON_FILE_EXT))).map((name) => ({ name, id: uuidField(lessonFrontmatter(readFileNoFollow(communityFolder, path26.join(lessonsDir, name))), "id") }));
27275
27388
  if (!parsed.success) return null;
27276
27389
  return {
27277
27390
  slug,
@@ -27789,8 +27902,8 @@ function restrict(order, ids) {
27789
27902
  const keep = new Set(ids);
27790
27903
  return order.filter((id) => keep.has(id));
27791
27904
  }
27792
- function mergeOrder(listed2, server, named) {
27793
- const listedIds2 = idsOf(listed2);
27905
+ function mergeOrder(listed3, server, named) {
27906
+ const listedIds2 = idsOf(listed3);
27794
27907
  const first = [];
27795
27908
  const after = /* @__PURE__ */ new Map();
27796
27909
  let anchor = null;
@@ -27803,15 +27916,15 @@ function mergeOrder(listed2, server, named) {
27803
27916
  }
27804
27917
  }
27805
27918
  const slots = first.map((id) => ({ untracked: id }));
27806
- for (const child of listed2) {
27919
+ for (const child of listed3) {
27807
27920
  slots.push({ entry: child.entry });
27808
27921
  if (child.id !== void 0) for (const id of after.get(child.id) ?? []) slots.push({ untracked: id });
27809
27922
  }
27810
27923
  return slots;
27811
27924
  }
27812
- function filesOrder(listed2, server, named) {
27813
- const byEntry = new Map(listed2.map((child) => [child.entry, child.id]));
27814
- return mergeOrder(listed2, server, named).flatMap((slot) => {
27925
+ function filesOrder(listed3, server, named) {
27926
+ const byEntry = new Map(listed3.map((child) => [child.entry, child.id]));
27927
+ return mergeOrder(listed3, server, named).flatMap((slot) => {
27815
27928
  const id = "untracked" in slot ? slot.untracked : byEntry.get(slot.entry);
27816
27929
  return id === void 0 ? [] : [id];
27817
27930
  });
@@ -33724,7 +33837,7 @@ Timeout after ${timeoutSeconds}s${queuedSeconds > 0 ? ` (${queuedSeconds}s of it
33724
33837
  process.exit(1);
33725
33838
  }
33726
33839
  function sleep(ms) {
33727
- return new Promise((resolve13) => setTimeout(resolve13, ms));
33840
+ return new Promise((resolve14) => setTimeout(resolve14, ms));
33728
33841
  }
33729
33842
  function parseRunNumbers(raw) {
33730
33843
  if (!raw || raw.startsWith("--")) {
@@ -34081,15 +34194,15 @@ var init_caller_audio = __esm({
34081
34194
  }
34082
34195
  describe;
34083
34196
  async clipFor(line) {
34084
- const path46 = line.clip ? isAbsolute2(line.clip) ? line.clip : resolve10(this.planDir, line.clip) : this.dir ? join33(this.dir, `${line.n}.wav`) : null;
34085
- if (!path46) throw new Error(`Line ${line.n} has no clip: give --clips <dir>, or a "clip" for it in the plan.`);
34197
+ const path48 = line.clip ? isAbsolute2(line.clip) ? line.clip : resolve10(this.planDir, line.clip) : this.dir ? join33(this.dir, `${line.n}.wav`) : null;
34198
+ if (!path48) throw new Error(`Line ${line.n} has no clip: give --clips <dir>, or a "clip" for it in the plan.`);
34086
34199
  let buf;
34087
34200
  try {
34088
- buf = readFileSync17(path46);
34201
+ buf = readFileSync17(path48);
34089
34202
  } catch {
34090
- throw new Error(`Line ${line.n}'s clip ${path46} cannot be read.`);
34203
+ throw new Error(`Line ${line.n}'s clip ${path48} cannot be read.`);
34091
34204
  }
34092
- return parseWav(buf, path46);
34205
+ return parseWav(buf, path48);
34093
34206
  }
34094
34207
  };
34095
34208
  OPENAI_PCM_SAMPLE_RATE = 24e3;
@@ -34119,17 +34232,17 @@ ${text5}`).digest("hex");
34119
34232
  return join33(this.cacheDir, `${key}.pcm`);
34120
34233
  }
34121
34234
  clipFor(line) {
34122
- const path46 = this.cachePath(line.say);
34123
- let pending = this.inFlight.get(path46);
34235
+ const path48 = this.cachePath(line.say);
34236
+ let pending = this.inFlight.get(path48);
34124
34237
  if (!pending) {
34125
- pending = this.readOrSynthesize(line, path46);
34126
- this.inFlight.set(path46, pending);
34238
+ pending = this.readOrSynthesize(line, path48);
34239
+ this.inFlight.set(path48, pending);
34127
34240
  }
34128
34241
  return pending;
34129
34242
  }
34130
- async readOrSynthesize(line, path46) {
34243
+ async readOrSynthesize(line, path48) {
34131
34244
  try {
34132
- return pcmClip(readFileSync17(path46));
34245
+ return pcmClip(readFileSync17(path48));
34133
34246
  } catch {
34134
34247
  }
34135
34248
  const res = await this.doFetch("https://api.openai.com/v1/audio/speech", {
@@ -34143,10 +34256,10 @@ ${text5}`).digest("hex");
34143
34256
  }
34144
34257
  const buf = Buffer.from(await res.arrayBuffer());
34145
34258
  if (buf.length < 2) throw new Error(`OpenAI speech synthesis returned no audio for line ${line.n}.`);
34146
- mkdirSync12(dirname12(path46), { recursive: true });
34147
- const tmp = `${path46}.${process.pid}.tmp`;
34259
+ mkdirSync12(dirname12(path48), { recursive: true });
34260
+ const tmp = `${path48}.${process.pid}.tmp`;
34148
34261
  writeFileSync7(tmp, buf);
34149
- renameSync5(tmp, path46);
34262
+ renameSync5(tmp, path48);
34150
34263
  return pcmClip(buf);
34151
34264
  }
34152
34265
  };
@@ -34173,14 +34286,14 @@ async function loadWrtcRuntime(importPackage = () => import(WRTC_PACKAGE)) {
34173
34286
  function waitFor(ready, timeoutMs, clock = systemClock) {
34174
34287
  if (ready()) return Promise.resolve(true);
34175
34288
  const deadline = clock.now() + timeoutMs;
34176
- return new Promise((resolve13) => {
34289
+ return new Promise((resolve14) => {
34177
34290
  const timer = setInterval(() => {
34178
34291
  if (ready()) {
34179
34292
  clearInterval(timer);
34180
- resolve13(true);
34293
+ resolve14(true);
34181
34294
  } else if (clock.now() >= deadline) {
34182
34295
  clearInterval(timer);
34183
- resolve13(false);
34296
+ resolve14(false);
34184
34297
  }
34185
34298
  }, WAIT_POLL_MS);
34186
34299
  });
@@ -34295,8 +34408,8 @@ var init_call_media = __esm({
34295
34408
  * asked before every frame, answers true — the rest of the clip is then dropped.
34296
34409
  */
34297
34410
  play(clip, abort = () => false) {
34298
- return new Promise((resolve13) => {
34299
- this.queue.push({ samples: resample(clip, PUMP_SAMPLE_RATE), offset: 0, startedAtMs: null, abort, resolve: resolve13 });
34411
+ return new Promise((resolve14) => {
34412
+ this.queue.push({ samples: resample(clip, PUMP_SAMPLE_RATE), offset: 0, startedAtMs: null, abort, resolve: resolve14 });
34300
34413
  });
34301
34414
  }
34302
34415
  /** Send every frame the wall clock says is due. */
@@ -35508,7 +35621,7 @@ var init_runner = __esm({
35508
35621
  init_score();
35509
35622
  systemRunnerClock = {
35510
35623
  now: () => Date.now(),
35511
- sleep: (ms) => new Promise((resolve13) => setTimeout(resolve13, ms))
35624
+ sleep: (ms) => new Promise((resolve14) => setTimeout(resolve14, ms))
35512
35625
  };
35513
35626
  LONGEST_SPOKEN_LINE_MS = Math.ceil(EVAL_CALL_SPOKEN_LINE_MAX_CHARS / 15) * 1e3;
35514
35627
  DEFAULT_RUNNER_TIMINGS = {
@@ -35711,15 +35824,15 @@ function parseEvalCallArgs(args2) {
35711
35824
  if (parsed.jsonPath) checkReportPath(parsed.jsonPath);
35712
35825
  return parsed;
35713
35826
  }
35714
- function checkReportPath(path46) {
35715
- const target = resolve11(path46);
35827
+ function checkReportPath(path48) {
35828
+ const target = resolve11(path48);
35716
35829
  const dir = dirname13(target);
35717
- if (!existsSync17(dir) || !statSync8(dir).isDirectory()) fail(`--json ${path46}: the folder ${dir} does not exist.`);
35718
- if (existsSync17(target) && statSync8(target).isDirectory()) fail(`--json ${path46} is a folder; name a file.`);
35830
+ if (!existsSync17(dir) || !statSync8(dir).isDirectory()) fail(`--json ${path48}: the folder ${dir} does not exist.`);
35831
+ if (existsSync17(target) && statSync8(target).isDirectory()) fail(`--json ${path48} is a folder; name a file.`);
35719
35832
  try {
35720
35833
  accessSync(existsSync17(target) ? target : dir, fsConstants.W_OK);
35721
35834
  } catch {
35722
- fail(`--json ${path46} cannot be written here.`);
35835
+ fail(`--json ${path48} cannot be written here.`);
35723
35836
  }
35724
35837
  }
35725
35838
  function suiteExitCode(report2, runs, reportWritten) {
@@ -38180,8 +38293,8 @@ async function runAccessAdd(target, emails, json) {
38180
38293
  return;
38181
38294
  }
38182
38295
  const { added, already_listed: already } = data;
38183
- const listed2 = already === 0 ? "" : `; ${already} ${already === 1 ? "was" : "were"} already on it`;
38184
- console.log(`Added ${added.length} email(s) to the access list of ${label3}${listed2}.`);
38296
+ const listed3 = already === 0 ? "" : `; ${already} ${already === 1 ? "was" : "were"} already on it`;
38297
+ console.log(`Added ${added.length} email(s) to the access list of ${label3}${listed3}.`);
38185
38298
  }
38186
38299
  async function runAccessRemove(target, email, { json, yes }) {
38187
38300
  const api = await communitiesClient();
@@ -38627,6 +38740,578 @@ var init_case_tokens = __esm({
38627
38740
  }
38628
38741
  });
38629
38742
 
38743
+ // src/cases/case-session.ts
38744
+ function selectCaseConnection(selector) {
38745
+ const all = listCaseConnections();
38746
+ const matches = all.filter((c) => (selector.case === void 0 || c.code === selector.case) && (selector.org === void 0 || c.org_id === selector.org) && (selector.space === void 0 || c.space_id === selector.space));
38747
+ if (matches.length === 1) return matches[0];
38748
+ if (matches.length === 0) {
38749
+ if (all.length === 0) {
38750
+ throw expected("This machine is not connected to any case. Run `wayai cases connect <org_id> <space_id> <code>` first.");
38751
+ }
38752
+ throw expected(`This machine is not connected to that case. Its connected cases:
38753
+ ${listed2(all)}`);
38754
+ }
38755
+ throw expected(`This machine is connected to ${matches.length} cases; pick one with --case (and --org and --space when codes repeat):
38756
+ ${listed2(matches)}`);
38757
+ }
38758
+ function listed2(connections) {
38759
+ return connections.map((c) => ` --case ${c.code} --org ${c.org_id} --space ${c.space_id}`).join("\n");
38760
+ }
38761
+ async function openCaseSession(selector, now = Date.now()) {
38762
+ const connection = selectCaseConnection(selector);
38763
+ const expiresAt = Date.parse(connection.expires_at);
38764
+ if (Number.isFinite(expiresAt) && expiresAt <= now) {
38765
+ throw expected(`This machine's authorization on case ${connection.code} expired at ${connection.expires_at}. Connect again: ${connectCommand(connection)}`);
38766
+ }
38767
+ let token;
38768
+ try {
38769
+ token = await readCaseToken(connection);
38770
+ } catch (err) {
38771
+ throw expected(`This machine's keyring could not read the token for case ${connection.code} (${err instanceof Error ? err.message : String(err)}).`);
38772
+ }
38773
+ if (!token) throw expected(`This machine's keyring holds no token for case ${connection.code}. Connect again: ${connectCommand(connection)}`);
38774
+ return { connection, api: new ApiClient({ apiUrl: connection.api_url, accessToken: token }) };
38775
+ }
38776
+ function caseCallFailure(err, connection, notFound = `Case ${connection.code} was not found`) {
38777
+ if (!(err instanceof ApiError)) return err;
38778
+ if (err.status === 401) {
38779
+ return expected(`The case token was refused: its authorization was revoked, expired or replaced. Connect again: ${connectCommand(connection)}`);
38780
+ }
38781
+ if (err.status === 404) {
38782
+ return expected(`${notFound}, or this machine's authorization on case ${connection.code} is no longer live.`);
38783
+ }
38784
+ if (err.status === 429) {
38785
+ const seconds2 = retryAfterSeconds(err);
38786
+ return expected(`Too many requests to the case for now. Try again in ${seconds2 ?? 60} s.`);
38787
+ }
38788
+ if (err.status >= 400 && err.status < 500) {
38789
+ const reason3 = extractApiErrorReason(err);
38790
+ return expected(sanitizeTerminalText(`${extractApiMessage(err)}${reason3 ? ` (${reason3})` : ""}`));
38791
+ }
38792
+ return err;
38793
+ }
38794
+ var connectCommand;
38795
+ var init_case_session = __esm({
38796
+ "src/cases/case-session.ts"() {
38797
+ "use strict";
38798
+ init_api_client();
38799
+ init_errors3();
38800
+ init_expected();
38801
+ init_terminal_output();
38802
+ init_case_tokens();
38803
+ connectCommand = (c) => `wayai cases connect ${c.org_id} ${c.space_id} ${c.code}`;
38804
+ }
38805
+ });
38806
+
38807
+ // src/cases/case-local-files.ts
38808
+ import * as fs31 from "fs";
38809
+ import * as path43 from "path";
38810
+ function caseLocalPathProblem(rel) {
38811
+ if (rel === "") return "it is empty";
38812
+ if (rel.includes("\0")) return "it holds a NUL";
38813
+ if (rel.includes("\\")) return "it holds a backslash";
38814
+ if (rel.startsWith("/") || /^[A-Za-z]:/.test(rel)) return "it is absolute";
38815
+ for (const segment of rel.split("/")) {
38816
+ if (segment === "") return "it has an empty segment";
38817
+ if (segment === "." || segment === "..") return `it has a "${segment}" segment`;
38818
+ }
38819
+ return null;
38820
+ }
38821
+ function caseLocalRoot(dir) {
38822
+ let root;
38823
+ try {
38824
+ root = fs31.realpathSync(path43.resolve(dir));
38825
+ } catch {
38826
+ throw expected(`${sanitizeTerminalText(dir)} does not exist.`);
38827
+ }
38828
+ if (!fs31.statSync(root).isDirectory()) throw expected(`${sanitizeTerminalText(dir)} is not a folder.`);
38829
+ return root;
38830
+ }
38831
+ function writeCaseLocalFile(root, rel, data) {
38832
+ const problem = caseLocalPathProblem(rel);
38833
+ const shown3 = sanitizeTerminalText(rel);
38834
+ if (problem) throw expected(`Refused to write ${JSON.stringify(shown3)}: ${problem}.`);
38835
+ const target = path43.join(root, ...rel.split("/"));
38836
+ if (!ensureRealSubdirNoSymlink(root, path43.dirname(target), true)) {
38837
+ throw expected(`Refused to write ${shown3}: a folder on its way is a symlink or a file. The CLI never writes through a symlink.`);
38838
+ }
38839
+ let existing;
38840
+ try {
38841
+ existing = fs31.lstatSync(target);
38842
+ } catch {
38843
+ existing = void 0;
38844
+ }
38845
+ if (existing && !existing.isFile()) throw expected(`Refused to write ${shown3}: it is a symlink or not a file. The CLI never writes through a symlink.`);
38846
+ if (existing && fileHasBytes(target, data)) return "unchanged";
38847
+ const flags = fs31.constants.O_WRONLY | fs31.constants.O_CREAT | fs31.constants.O_TRUNC | (fs31.constants.O_NOFOLLOW ?? 0);
38848
+ let fd;
38849
+ try {
38850
+ fd = fs31.openSync(target, flags, 420);
38851
+ } catch (err) {
38852
+ if (err.code === "ELOOP") throw expected(`Refused to write ${shown3}: it is a symlink. The CLI never writes through a symlink.`);
38853
+ throw err;
38854
+ }
38855
+ try {
38856
+ fs31.writeFileSync(fd, data);
38857
+ } finally {
38858
+ fs31.closeSync(fd);
38859
+ }
38860
+ return "written";
38861
+ }
38862
+ var init_case_local_files = __esm({
38863
+ "src/cases/case-local-files.ts"() {
38864
+ "use strict";
38865
+ init_fs_safety();
38866
+ init_expected();
38867
+ init_terminal_output();
38868
+ }
38869
+ });
38870
+
38871
+ // ../../packages/core/dist/contracts/case-notes.js
38872
+ var init_case_notes = __esm({
38873
+ "../../packages/core/dist/contracts/case-notes.js"() {
38874
+ "use strict";
38875
+ init_chunk_7TQYAKCB();
38876
+ init_chunk_733K4J4G();
38877
+ init_chunk_PFPADFUC();
38878
+ init_chunk_KWRHZBGU();
38879
+ init_chunk_3T3D7LTE();
38880
+ init_chunk_M2T55BV6();
38881
+ init_chunk_VYINA6YP();
38882
+ init_chunk_ZVXO3XL6();
38883
+ init_chunk_FBV7NLKO();
38884
+ init_chunk_WEXVYJ5H();
38885
+ init_chunk_HZ6CADSY();
38886
+ init_chunk_ICYO56QW();
38887
+ init_chunk_WFQDSQJK();
38888
+ init_chunk_ZTNFLGW5();
38889
+ }
38890
+ });
38891
+
38892
+ // ../../packages/core/dist/contracts/case-checks.js
38893
+ var init_case_checks = __esm({
38894
+ "../../packages/core/dist/contracts/case-checks.js"() {
38895
+ "use strict";
38896
+ init_chunk_RHXF6X2Y();
38897
+ init_chunk_5Y2NNQHX();
38898
+ init_chunk_HZ6CADSY();
38899
+ }
38900
+ });
38901
+
38902
+ // src/cases/case-work.ts
38903
+ import * as fs32 from "fs";
38904
+ import * as path44 from "path";
38905
+ async function call(session, run, notFound) {
38906
+ try {
38907
+ return await run();
38908
+ } catch (err) {
38909
+ throw caseCallFailure(err, session.connection, notFound);
38910
+ }
38911
+ }
38912
+ function findPhase(detail, name) {
38913
+ const phase = detail.phases.find((p) => p.folder === name) ?? detail.phases.find((p) => p.code === name);
38914
+ if (phase) return phase;
38915
+ throw expected(`Case ${detail.code} has no phase ${JSON.stringify(sanitizeTerminalText(name))}. Its phases: ${detail.phases.map((p) => p.folder).join(", ")}.`);
38916
+ }
38917
+ function blockerLine(b, names) {
38918
+ switch (b.reason) {
38919
+ case "phase_not_activated":
38920
+ return "on demand and not activated: a person at Conduct level activates it, in the web app";
38921
+ case "phase_dependency_pending":
38922
+ return `waits for ${names.phase(b.phase_id)}`;
38923
+ case "output_pending":
38924
+ return b.submission ? `${names.output(b.output_id)}: its submission awaits ${AWAITING[b.submission.awaiting]} (${b.actor})` : `${names.output(b.output_id)} has no official version: write it; a person submits it, in the web app`;
38925
+ case "publication_pending":
38926
+ return "one official version of an output delivers this phase";
38927
+ case "task_pending":
38928
+ return `${names.task(b.case_task_id)} is open`;
38929
+ case "input_pending":
38930
+ return `${names.input(b.input_id)} is neither linked nor dispensed`;
38931
+ case "agenda_group_pending":
38932
+ return b.actor === "approver" ? `${names.group(b.agenda_group_id)} awaits approval by its teams` : `${names.group(b.agenda_group_id)} is ${statusWords(b.group_status)}: propose its values; a person at Conduct level sends it`;
38933
+ case "task_dependency_pending":
38934
+ return `waits for ${names.task(b.case_task_id)}`;
38935
+ case "confidential_pending":
38936
+ return `something confidential is pending (${b.actor})`;
38937
+ }
38938
+ }
38939
+ async function namesFor(session, detail, phaseIds) {
38940
+ const names = new CaseNames(session, detail);
38941
+ if (readsWork(detail)) for (const id of phaseIds) await names.readPhase(id);
38942
+ return names;
38943
+ }
38944
+ function printPhasesView(detail, state) {
38945
+ const byId = new Map(detail.phases.map((p) => [p.phase_id, p]));
38946
+ console.log(`${detail.code}: ${state.status}`);
38947
+ for (const p of state.phases) {
38948
+ const row = byId.get(p.phase_id);
38949
+ console.log(` ${row ? phaseLabel(row) : p.code}: ${statusWords(p.status)}${p.late ? ", late" : ""}`);
38950
+ }
38951
+ console.log(PHASES_VIEW_NOTE);
38952
+ }
38953
+ async function openNotes(session) {
38954
+ const open = [];
38955
+ let cursor;
38956
+ for (let page = 0; page < NOTE_PAGES_READ; page++) {
38957
+ const { notes, next_cursor } = (await call(session, () => session.api.listCaseNotes(session.connection, { cursor, limit: NOTES_PAGE }))).data;
38958
+ open.push(...notes.filter((n) => (n.kind === "pending" || n.kind === "next_step") && n.completed_at === null));
38959
+ if (!next_cursor) break;
38960
+ cursor = next_cursor;
38961
+ }
38962
+ return open;
38963
+ }
38964
+ async function caseBrief(session, opts) {
38965
+ const [detail, state] = await Promise.all([loadCase(session), loadState(session)]);
38966
+ const notes = state.view === "work" && readsWork(detail) ? await openNotes(session) : [];
38967
+ if (opts.json) {
38968
+ console.log(JSON.stringify({ case: detail, state, open_notes: notes }, null, 2));
38969
+ return;
38970
+ }
38971
+ const head = `${detail.code}, ${one(detail.type_name)} (version ${detail.version})${detail.confidential ? ", confidential" : ""}`;
38972
+ console.log(head);
38973
+ if (detail.closure) {
38974
+ console.log(`Closed on ${detail.closure.closed_at}${detail.closure.outcome_name ? `: ${one(detail.closure.outcome_name)}` : ""}.`);
38975
+ }
38976
+ if (detail.owner?.display_name) console.log(`Owner: ${one(detail.owner.display_name)}.`);
38977
+ if (detail.parties?.length) console.log(`Parties: ${detail.parties.map((p) => `${one(p.role)}: ${one(p.name)}`).join("; ")}.`);
38978
+ if (state.view === "phases") {
38979
+ printPhasesView(detail, state);
38980
+ return;
38981
+ }
38982
+ const byId = new Map(detail.phases.map((p) => [p.phase_id, p]));
38983
+ const underWay = state.state.phases.filter((p) => p.status === "in_progress");
38984
+ console.log(`Under way: ${underWay.length ? underWay.map((p) => byId.get(p.phase_id) ? phaseLabel(byId.get(p.phase_id)) : p.code).join("; ") : "no phase"}.`);
38985
+ const deadlines = state.state.phases.filter((p) => p.due_on && (p.status === "in_progress" || p.status === "waiting"));
38986
+ if (deadlines.length) {
38987
+ console.log("Deadlines:");
38988
+ for (const p of deadlines) console.log(` ${byId.get(p.phase_id)?.folder ?? p.code}: ${p.due_on}${p.late ? ", late" : ""}`);
38989
+ }
38990
+ const active = new Set(underWay.map((p) => p.phase_id));
38991
+ const taskState = new Map(state.state.tasks.map((t) => [t.case_task_id, t]));
38992
+ const open = (detail.tasks ?? []).filter((t) => active.has(t.phase_id) && taskState.get(t.case_task_id)?.status !== "completed");
38993
+ if (open.length) {
38994
+ console.log(`Open tasks (${open.length}):`);
38995
+ for (const t of open) {
38996
+ const st = taskState.get(t.case_task_id);
38997
+ console.log(` ${byId.get(t.phase_id)?.folder ?? ""}: ${one(t.name)}${t.required ? " (required)" : ""}${st?.status === "waiting" ? ", waits for another task" : ""}${st?.late ? ", late" : ""} [${t.case_task_id}]`);
38998
+ }
38999
+ }
39000
+ if (notes.length) {
39001
+ console.log(`Open pending items and next steps (${notes.length}):`);
39002
+ for (const n of notes) console.log(` ${noteLine(n)}`);
39003
+ }
39004
+ }
39005
+ async function caseExplain(session, opts) {
39006
+ const [detail, state] = await Promise.all([loadCase(session), loadState(session)]);
39007
+ const asked = opts.phase === void 0 ? void 0 : findPhase(detail, opts.phase);
39008
+ if (state.view === "phases") {
39009
+ if (opts.json) console.log(JSON.stringify({ case: detail, state }, null, 2));
39010
+ else printPhasesView(detail, state);
39011
+ return;
39012
+ }
39013
+ if (opts.json) {
39014
+ console.log(JSON.stringify({ case: detail, state }, null, 2));
39015
+ return;
39016
+ }
39017
+ const phases = asked ? state.phases.filter((p) => p.phase_id === asked.phase_id) : state.phases;
39018
+ const named = asked ? [asked.phase_id] : phases.filter((p) => p.status === "in_progress").map((p) => p.phase_id);
39019
+ if (state.state.status === "closed") {
39020
+ console.log(`${detail.code} is closed: nothing is pending.`);
39021
+ return;
39022
+ }
39023
+ if (asked && phases.length === 0) {
39024
+ const st = state.state.phases.find((p) => p.phase_id === asked.phase_id);
39025
+ console.log(`Phase ${phaseLabel(asked)}: ${st ? statusWords(st.status) : "not shown"}. Nothing holds it.`);
39026
+ return;
39027
+ }
39028
+ const names = await namesFor(session, detail, named);
39029
+ if (phases.length === 0) console.log(`Every phase of ${detail.code} is delivered or dispensed.`);
39030
+ const fullyNamed = new Set(named);
39031
+ for (const p of phases) {
39032
+ const row = names.phaseRow(p.phase_id);
39033
+ console.log(`Phase ${row ? phaseLabel(row) : p.phase_id}: ${statusWords(p.status)}`);
39034
+ const shown3 = fullyNamed.has(p.phase_id) ? p.blockers : p.blockers.filter((b) => b.reason === "phase_dependency_pending" || b.reason === "phase_not_activated");
39035
+ for (const b of shown3) console.log(` - ${blockerLine(b, names)}`);
39036
+ const rest = p.blockers.length - shown3.length;
39037
+ if (rest > 0) console.log(` - and ${rest} requirement${rest === 1 ? "" : "s"} of its own (\`wayai cases explain --phase ${one(names.phaseRow(p.phase_id)?.folder ?? "")}\`)`);
39038
+ }
39039
+ const taskPhase = new Map((detail.tasks ?? []).map((t) => [t.case_task_id, t.phase_id]));
39040
+ const tasks = state.tasks.filter((t) => fullyNamed.has(taskPhase.get(t.case_task_id) ?? ""));
39041
+ if (tasks.length) {
39042
+ console.log("Open tasks:");
39043
+ for (const t of tasks) console.log(` ${names.taskName(t.case_task_id)} [${t.case_task_id}]: ${t.blockers.map((b) => blockerLine(b, names)).join("; ")}`);
39044
+ }
39045
+ }
39046
+ function agentWork(b) {
39047
+ switch (b.reason) {
39048
+ case "output_pending":
39049
+ return b.submission === null;
39050
+ case "input_pending":
39051
+ case "task_pending":
39052
+ case "publication_pending":
39053
+ return true;
39054
+ case "agenda_group_pending":
39055
+ return b.actor === "edit";
39056
+ default:
39057
+ return false;
39058
+ }
39059
+ }
39060
+ async function caseNext(session, opts) {
39061
+ const [detail, state] = await Promise.all([loadCase(session), loadState(session)]);
39062
+ if (state.view === "phases") {
39063
+ if (opts.json) console.log(JSON.stringify({ case: detail, state }, null, 2));
39064
+ else printPhasesView(detail, state);
39065
+ return;
39066
+ }
39067
+ if (state.state.status === "closed" && !opts.json) {
39068
+ console.log(`${detail.code} is closed: it takes no new work.`);
39069
+ return;
39070
+ }
39071
+ const underWay = state.phases.filter((p) => p.status === "in_progress");
39072
+ const notes = readsWork(detail) ? await openNotes(session) : [];
39073
+ const yours = [];
39074
+ const others = [];
39075
+ const seen = /* @__PURE__ */ new Set();
39076
+ for (const p of underWay) {
39077
+ for (const b of p.blockers) {
39078
+ const key = blockerKey(b);
39079
+ if (key && seen.has(key)) continue;
39080
+ if (key) seen.add(key);
39081
+ (agentWork(b) ? yours : others).push({ phase_id: p.phase_id, blocker: b });
39082
+ }
39083
+ }
39084
+ if (opts.json) {
39085
+ console.log(JSON.stringify({ to_do: yours, waiting_on_others: others, open_notes: notes }, null, 2));
39086
+ return;
39087
+ }
39088
+ const names = await namesFor(session, detail, underWay.map((p) => p.phase_id));
39089
+ if (underWay.length === 0) console.log(`No phase of ${detail.code} is under way.`);
39090
+ if (yours.length) {
39091
+ console.log("To do:");
39092
+ for (const { phase_id, blocker } of yours) console.log(` ${names.phaseRow(phase_id)?.folder ?? ""}: ${blockerLine(blocker, names)}`);
39093
+ }
39094
+ if (notes.length) {
39095
+ console.log("Open pending items and next steps:");
39096
+ for (const n of notes) console.log(` ${noteLine(n)}`);
39097
+ }
39098
+ if (others.length) {
39099
+ console.log("Waiting on someone else:");
39100
+ for (const { phase_id, blocker } of others) console.log(` ${names.phaseRow(phase_id)?.folder ?? ""}: ${blockerLine(blocker, names)}`);
39101
+ }
39102
+ if (underWay.length && !yours.length && !notes.length && !others.length) console.log("Nothing is pending on the phases under way.");
39103
+ }
39104
+ async function caseCheck(session, opts) {
39105
+ const detail = await loadCase(session);
39106
+ const phase = findPhase(detail, opts.phase);
39107
+ let outputId;
39108
+ if (opts.output !== void 0) {
39109
+ const work = (await call(session, () => session.api.getCasePhaseWork(session.connection, phase.phase_id))).data;
39110
+ const output = work.outputs.find((o) => o.code === opts.output);
39111
+ if (!output) {
39112
+ throw expected(`Phase ${phase.folder} has no output ${JSON.stringify(sanitizeTerminalText(opts.output))}. Its outputs: ${work.outputs.map((o) => one(o.code)).join(", ") || "none"}.`);
39113
+ }
39114
+ outputId = output.id;
39115
+ }
39116
+ const checks = (await call(session, () => session.api.getCasePhaseChecks(session.connection, phase.phase_id, outputId))).data;
39117
+ if (checks.refused) process.exitCode = 1;
39118
+ if (opts.json) {
39119
+ console.log(JSON.stringify(checks, null, 2));
39120
+ return;
39121
+ }
39122
+ const errors = checks.problems.filter((p) => p.severity === "error").length;
39123
+ const warnings = checks.problems.length - errors;
39124
+ console.log(`Checks of ${phase.folder}${opts.output ? `, output ${opts.output}` : ""}, over the case's files as WayAI holds them: ${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"}. A submit now would be ${checks.refused ? "refused" : "accepted by the checks"}.`);
39125
+ for (const p of checks.problems) {
39126
+ const where = [p.output_code && one(p.output_code), p.path && `${one(p.path)}${p.line ? `:${p.line}` : ""}`].filter(Boolean).join(" ");
39127
+ const what = p.confidential ? "about something confidential" : [p.subject && one(p.subject), p.expected !== null && `expected ${one(p.expected)}`, p.found !== null && `found ${one(p.found)}`, p.count !== null && `${p.count}\xD7`].filter(Boolean).join(", ");
39128
+ console.log(` ${p.severity} ${p.code}${where ? ` [${where}]` : ""}${what ? `: ${what}` : ""}`);
39129
+ }
39130
+ if (checks.truncated) console.log(" (more problems were found than one answer carries)");
39131
+ for (const c of checks.coverage) {
39132
+ console.log(`Coverage of ${one(c.output_code)}: ${c.ready} of ${c.total} items ready${c.dispensed ? `, ${c.dispensed} dispensed` : ""}.`);
39133
+ }
39134
+ }
39135
+ function decisionCsvValue(d) {
39136
+ const value = d.type === "percent" && typeof d.value === "number" ? Number((d.value / 100).toPrecision(15)) : d.value;
39137
+ const text5 = String(value);
39138
+ if (/[,;"\r\n]/.test(text5)) throw expected(`The approved value of ${d.code} cannot be written in a CSV row as the checks read it.`);
39139
+ return text5;
39140
+ }
39141
+ function decisionsCsv(rows) {
39142
+ return `name,value
39143
+ ${rows.map((d) => `${d.code},${decisionCsvValue(d)}
39144
+ `).join("")}`;
39145
+ }
39146
+ async function caseDecisions(session, opts) {
39147
+ const root = caseLocalRoot(opts.dir);
39148
+ const decisions = (await call(session, () => session.api.listCaseApprovedDecisions(session.connection, opts.confidential))).data;
39149
+ const open = decisions.filter((d) => !d.confidential);
39150
+ const results = [{ rel: CASE_DECISIONS_CSV_PATH, rows: open, outcome: writeCaseLocalFile(root, CASE_DECISIONS_CSV_PATH, Buffer.from(decisionsCsv(open))) }];
39151
+ if (opts.confidential) {
39152
+ const sealed = decisions.filter((d) => d.confidential);
39153
+ const exists = fs32.existsSync(path44.join(root, ...CASE_CONFIDENTIAL_DECISIONS_CSV_PATH.split("/")));
39154
+ if (sealed.length || exists) {
39155
+ results.push({
39156
+ rel: CASE_CONFIDENTIAL_DECISIONS_CSV_PATH,
39157
+ rows: sealed,
39158
+ outcome: writeCaseLocalFile(root, CASE_CONFIDENTIAL_DECISIONS_CSV_PATH, Buffer.from(decisionsCsv(sealed)))
39159
+ });
39160
+ }
39161
+ }
39162
+ for (const r of results) {
39163
+ const listed3 = r.rows.length ? `: ${r.rows.map((d) => one(d.code)).join(", ")}` : ", with its header alone: no decision is approved yet";
39164
+ console.log(`${r.rel} ${r.outcome === "written" ? "written" : "already up to date"}${listed3}.`);
39165
+ }
39166
+ }
39167
+ async function caseNote(session, text5, opts) {
39168
+ const kind = opts.kind ?? "observation";
39169
+ if (!CASE_NOTE_KINDS.includes(kind)) throw expected(`--kind takes ${CASE_NOTE_KINDS.join(", ")}.`);
39170
+ if (opts.origin !== void 0 && kind !== "contribution") throw expected("--origin applies only to --kind contribution.");
39171
+ if (kind === "contribution" && opts.origin === void 0) throw expected("A contribution names who sent it: --origin <who>.");
39172
+ if (opts.task !== void 0 && !UUID_RE3.test(opts.task)) throw expected("--task takes a task's id, as `wayai cases brief` shows it.");
39173
+ const phaseId = opts.phase === void 0 ? null : findPhase(await loadCase(session), opts.phase).phase_id;
39174
+ const parsed = addCaseNoteBody.safeParse({ kind, text: text5, origin: opts.origin ?? null, phase_id: phaseId, case_task_id: opts.task ?? null });
39175
+ if (!parsed.success) throw expected(`The note is refused: ${parsed.error.issues[0]?.message ?? "not of its shape"}.`);
39176
+ const note = (await call(session, () => session.api.addCaseNote(session.connection, parsed.data), "A task or phase it names was not found")).data;
39177
+ console.log(`Note added to ${session.connection.code}: ${note.note_id}`);
39178
+ }
39179
+ async function caseNoteDone(session, noteId) {
39180
+ if (!UUID_RE3.test(noteId)) throw expected("note done takes a note's id, as `wayai cases next` shows it.");
39181
+ const note = (await call(session, () => session.api.completeCaseNote(session.connection, noteId), `Note ${noteId} was not found`)).data;
39182
+ console.log(`Done: ${one(note.text)}`);
39183
+ }
39184
+ function sizeOf(file) {
39185
+ try {
39186
+ return fs32.statSync(file).size;
39187
+ } catch {
39188
+ throw expected(`Cannot read ${sanitizeTerminalText(file)}.`);
39189
+ }
39190
+ }
39191
+ function readLocal(file) {
39192
+ try {
39193
+ return fs32.readFileSync(file);
39194
+ } catch {
39195
+ throw expected(`Cannot read ${sanitizeTerminalText(file)}.`);
39196
+ }
39197
+ }
39198
+ async function caseReceivedAdd(session, file, opts) {
39199
+ const name = caseReceivedFileName(path44.basename(file));
39200
+ const format = caseReceivedFormat(name);
39201
+ if (!format) throw expected(`${sanitizeTerminalText(name)} is in no format a received document takes: ${Object.keys(CASE_RECEIVED_FORMATS).join(", ")}.`);
39202
+ const tooLarge = () => expected(`The file and its text together pass ${CASE_RECEIVED_UPLOAD_BODY_MAX_BYTES / (1024 * 1024)} MiB, the most one registration takes.`);
39203
+ if (sizeOf(file) + sizeOf(opts.text) > CASE_RECEIVED_UPLOAD_BODY_MAX_BYTES) throw tooLarge();
39204
+ const bytes = readLocal(file);
39205
+ const text5 = readLocal(opts.text);
39206
+ if (bytes.byteLength + text5.byteLength > CASE_RECEIVED_UPLOAD_BODY_MAX_BYTES) throw tooLarge();
39207
+ const phase = findPhase(await loadCase(session), opts.phase);
39208
+ const title2 = opts.title ?? path44.parse(name).name;
39209
+ const document = registerCaseReceivedDocumentShape.safeParse({ phase_id: phase.phase_id, title: title2, type: opts.type, confidential: opts.confidential });
39210
+ if (!document.success) throw expected(`The document is refused: ${document.error.issues[0]?.message ?? "not of its shape"}.`);
39211
+ const received = (await call(session, () => session.api.registerCaseReceivedDocument(
39212
+ session.connection,
39213
+ document.data,
39214
+ { name, bytes },
39215
+ text5
39216
+ ))).data;
39217
+ console.log(`${one(received.title)} registered in ${phase.folder}/received/ of ${session.connection.code}: ${received.received_id}`);
39218
+ if (received.text_origin === "agent") console.log("Its text is marked as converted by an agent, for whoever reviews it.");
39219
+ }
39220
+ var NOTE_PAGES_READ, NOTES_PAGE, AGENDA_PAGES_READ, one, loadCase, loadState, phaseLabel, statusWords, CaseNames, AWAITING, readsWork, PHASES_VIEW_NOTE, noteLine, blockerKey;
39221
+ var init_case_work = __esm({
39222
+ "src/cases/case-work.ts"() {
39223
+ "use strict";
39224
+ init_utils();
39225
+ init_expected();
39226
+ init_terminal_output();
39227
+ init_case_session();
39228
+ init_case_local_files();
39229
+ init_case_notes();
39230
+ init_case_checks();
39231
+ init_case_received_documents();
39232
+ NOTE_PAGES_READ = 3;
39233
+ NOTES_PAGE = CASE_NOTES_PAGE_MAX;
39234
+ AGENDA_PAGES_READ = 5;
39235
+ one = (value) => sanitizeTerminalText(value).replace(/\s*\n\s*/g, " ");
39236
+ loadCase = async (s) => (await call(s, () => s.api.getCase(s.connection))).data;
39237
+ loadState = async (s) => (await call(s, () => s.api.getCaseState(s.connection))).data;
39238
+ phaseLabel = (p) => `${one(p.folder)} (${one(p.name)})`;
39239
+ statusWords = (status) => status.replaceAll("_", " ");
39240
+ CaseNames = class {
39241
+ constructor(session, detail) {
39242
+ this.session = session;
39243
+ this.phases = new Map(detail.phases.map((p) => [p.phase_id, p]));
39244
+ this.tasks = new Map((detail.tasks ?? []).map((t) => [t.case_task_id, one(t.name)]));
39245
+ }
39246
+ phases;
39247
+ tasks;
39248
+ outputs = /* @__PURE__ */ new Map();
39249
+ inputs = /* @__PURE__ */ new Map();
39250
+ groups = /* @__PURE__ */ new Map();
39251
+ /** Read one phase's outputs, inputs and agenda groups, to name them. */
39252
+ async readPhase(phaseId) {
39253
+ const s = this.session;
39254
+ const work = (await call(s, () => s.api.getCasePhaseWork(s.connection, phaseId))).data;
39255
+ for (const o of work.outputs) this.outputs.set(o.id, `${one(o.code)} (${one(o.document_type)})`);
39256
+ for (const i of work.inputs) this.inputs.set(i.id, `${one(i.key)} (${one(i.name)})`);
39257
+ let cursor;
39258
+ for (let page = 0; page < AGENDA_PAGES_READ; page++) {
39259
+ const { groups, next_cursor } = (await call(s, () => s.api.getCaseAgenda(s.connection, phaseId, cursor))).data;
39260
+ for (const g of groups) this.groups.set(g.agenda_group_id, `${one(g.code)} (${one(g.name)})`);
39261
+ if (!next_cursor) break;
39262
+ cursor = next_cursor;
39263
+ }
39264
+ }
39265
+ // Each name with its noun: `output memo (Technical memo)`, or `an output` for one not read.
39266
+ phase(id) {
39267
+ const p = this.phases.get(id);
39268
+ return p ? `phase ${phaseLabel(p)}` : "a phase";
39269
+ }
39270
+ phaseRow(id) {
39271
+ return this.phases.get(id);
39272
+ }
39273
+ task(id) {
39274
+ return this.tasks.has(id) ? `task ${this.tasks.get(id)}` : "a task";
39275
+ }
39276
+ taskName(id) {
39277
+ return this.tasks.get(id) ?? "";
39278
+ }
39279
+ output(id) {
39280
+ return this.outputs.has(id) ? `output ${this.outputs.get(id)}` : "an output";
39281
+ }
39282
+ input(id) {
39283
+ return this.inputs.has(id) ? `input ${this.inputs.get(id)}` : "an input";
39284
+ }
39285
+ group(id) {
39286
+ return this.groups.has(id) ? `agenda group ${this.groups.get(id)}` : "an agenda group";
39287
+ }
39288
+ };
39289
+ AWAITING = {
39290
+ rendering: "its rendering",
39291
+ sign_off: "review sign-off",
39292
+ approval: "approval",
39293
+ publication: "publication"
39294
+ };
39295
+ readsWork = (detail) => detail.access.capabilities.includes("view_work");
39296
+ PHASES_VIEW_NOTE = "You see only the phases' status of this case: its work is not yours to read here.";
39297
+ noteLine = (n) => `${n.kind === "pending" ? "pending" : "next step"}: ${one(n.text)} [${n.note_id}]`;
39298
+ blockerKey = (b) => {
39299
+ switch (b.reason) {
39300
+ case "output_pending":
39301
+ return `output:${b.output_id}`;
39302
+ case "input_pending":
39303
+ return `input:${b.input_id}`;
39304
+ case "agenda_group_pending":
39305
+ return `group:${b.agenda_group_id}`;
39306
+ case "task_pending":
39307
+ return `task:${b.case_task_id}`;
39308
+ default:
39309
+ return "";
39310
+ }
39311
+ };
39312
+ }
39313
+ });
39314
+
38630
39315
  // src/commands/cases.ts
38631
39316
  var cases_exports = {};
38632
39317
  __export(cases_exports, {
@@ -38651,29 +39336,73 @@ async function casesCommand(args2) {
38651
39336
  }
38652
39337
  let parsed;
38653
39338
  try {
38654
- parsed = parseArgs26({
38655
- args: args2,
38656
- options: { label: { type: "string" }, org: { type: "string" }, space: { type: "string" } },
38657
- allowPositionals: true,
38658
- strict: true
38659
- });
39339
+ parsed = parseArgs26({ args: args2, options: OPTIONS2, allowPositionals: true, strict: true });
38660
39340
  } catch (err) {
38661
39341
  throw usageError4(err instanceof Error ? err.message : String(err));
38662
39342
  }
38663
39343
  const { values, positionals } = parsed;
38664
39344
  const [sub, ...rest] = positionals;
38665
- if (sub === "connect") {
38666
- if (values.org !== void 0 || values.space !== void 0) throw usageError4("connect takes the org and space as arguments, not --org or --space.");
38667
- if (rest.length !== 3) throw usageError4("connect takes <org_id> <space_id> <code>.");
38668
- const [orgId, spaceId, code2] = rest;
39345
+ if (sub === void 0) throw usageError4("No subcommand given.");
39346
+ const twoWords = sub === "note" && rest[0] === "done" || sub === "received" && rest[0] === "add";
39347
+ const name = twoWords ? `${sub} ${rest[0]}` : sub;
39348
+ const operands = twoWords ? rest.slice(1) : rest;
39349
+ const admitted = ADMITS[name];
39350
+ if (!admitted) throw usageError4(`Unknown subcommand ${JSON.stringify(sanitizeTerminalText(name))}.`);
39351
+ const extra = Object.keys(values).filter((key) => values[key] !== void 0 && !admitted.includes(key));
39352
+ if (extra.length) throw usageError4(`${name} does not take ${extra.map((key) => `--${key}`).join(", ")}.`);
39353
+ if (name === "connect") {
39354
+ if (operands.length !== 3) throw usageError4("connect takes <org_id> <space_id> <code>.");
39355
+ const [orgId, spaceId, code2] = operands;
38669
39356
  return connect(caseRef(orgId, spaceId, code2), machineLabel2(values.label));
38670
39357
  }
38671
- if (sub === "disconnect") {
38672
- if (values.label !== void 0) throw usageError4("--label applies only to connect.");
38673
- if (rest.length !== 1) throw usageError4("disconnect takes one <code>.");
38674
- return disconnect(rest[0], { org: values.org, space: values.space });
39358
+ if (name === "disconnect") {
39359
+ if (operands.length !== 1) throw usageError4("disconnect takes one <code>.");
39360
+ return disconnect(operands[0], { org: values.org, space: values.space });
39361
+ }
39362
+ const selector = { case: values.case, org: values.org, space: values.space };
39363
+ const json = values.json === true;
39364
+ const takesNone = () => {
39365
+ if (operands.length) throw usageError4(`${name} takes no argument.`);
39366
+ };
39367
+ switch (name) {
39368
+ case "brief":
39369
+ takesNone();
39370
+ return caseBrief(await openCaseSession(selector), { json });
39371
+ case "next":
39372
+ takesNone();
39373
+ return caseNext(await openCaseSession(selector), { json });
39374
+ case "explain":
39375
+ takesNone();
39376
+ return caseExplain(await openCaseSession(selector), { json, phase: values.phase });
39377
+ case "check":
39378
+ takesNone();
39379
+ if (values.phase === void 0) throw usageError4("check takes --phase <folder>.");
39380
+ return caseCheck(await openCaseSession(selector), { json, phase: values.phase, output: values.output });
39381
+ case "decisions":
39382
+ takesNone();
39383
+ return caseDecisions(await openCaseSession(selector), { dir: values.dir ?? process.cwd(), confidential: values.confidential === true });
39384
+ case "note":
39385
+ if (operands.length !== 1) throw usageError4("note takes its text as one argument: quote it.");
39386
+ return caseNote(await openCaseSession(selector), operands[0], { kind: values.kind, phase: values.phase, task: values.task, origin: values.origin });
39387
+ case "note done":
39388
+ if (operands.length !== 1) throw usageError4("note done takes one <note_id>.");
39389
+ return caseNoteDone(await openCaseSession(selector), operands[0]);
39390
+ case "received add": {
39391
+ if (operands.length !== 1) throw usageError4("received add takes one <file>.");
39392
+ if (values.text === void 0 || values.phase === void 0 || values.type === void 0) {
39393
+ throw usageError4("received add takes --text <markdown file>, --phase <folder> and --type <type>.");
39394
+ }
39395
+ return caseReceivedAdd(await openCaseSession(selector), operands[0], {
39396
+ text: values.text,
39397
+ phase: values.phase,
39398
+ type: values.type,
39399
+ title: values.title,
39400
+ confidential: values.confidential === true
39401
+ });
39402
+ }
39403
+ default:
39404
+ throw usageError4(`Unknown subcommand ${JSON.stringify(sanitizeTerminalText(name))}.`);
38675
39405
  }
38676
- throw usageError4(sub === void 0 ? "No subcommand given." : `Unknown subcommand ${JSON.stringify(sanitizeTerminalText(sub))}.`);
38677
39406
  }
38678
39407
  function caseRef(orgId, spaceId, code2) {
38679
39408
  const parsed = caseRecordParam.safeParse({ org_id: orgId, space_id: spaceId, code: code2 });
@@ -38701,9 +39430,9 @@ function webOrigin(apiUrl) {
38701
39430
  else return null;
38702
39431
  return `${url.protocol}//${host}${url.port ? `:${url.port}` : ""}`;
38703
39432
  }
38704
- function webLocation(apiUrl, path46) {
39433
+ function webLocation(apiUrl, path48) {
38705
39434
  const origin = webOrigin(apiUrl);
38706
- return origin ? `${origin}${path46}` : `${path46} (in the WayAI web app)`;
39435
+ return origin ? `${origin}${path48}` : `${path48} (in the WayAI web app)`;
38707
39436
  }
38708
39437
  function pickupSecret() {
38709
39438
  const bytes = crypto4.randomBytes(32);
@@ -38853,7 +39582,7 @@ async function disconnect(code2, filter) {
38853
39582
  ${manualCaseTokenCleanup(connection)}`
38854
39583
  );
38855
39584
  }
38856
- var PICKUP_POLL_INTERVAL_MS, USAGE5, casePagePath, delay2;
39585
+ var PICKUP_POLL_INTERVAL_MS, USAGE5, OPTIONS2, SELECT, ADMITS, casePagePath, delay2;
38857
39586
  var init_cases = __esm({
38858
39587
  "src/commands/cases.ts"() {
38859
39588
  "use strict";
@@ -38867,15 +39596,28 @@ var init_cases = __esm({
38867
39596
  init_terminal_output();
38868
39597
  init_token_store();
38869
39598
  init_utils();
39599
+ init_case_session();
39600
+ init_case_work();
38870
39601
  init_case_tokens();
38871
39602
  PICKUP_POLL_INTERVAL_MS = 5e3;
38872
39603
  USAGE5 = `
38873
- wayai cases \u2014 connect this machine's code agents to one case
39604
+ wayai cases \u2014 connect this machine's code agents to one case, and work on it
38874
39605
 
38875
39606
  Usage:
38876
39607
  wayai cases connect <org_id> <space_id> <code> [--label <machine>]
38877
39608
  wayai cases disconnect <code> [--org <org_id>] [--space <space_id>]
38878
39609
 
39610
+ wayai cases brief [--json]
39611
+ wayai cases next [--json]
39612
+ wayai cases explain [--phase <folder>] [--json]
39613
+ wayai cases check --phase <folder> [--output <code>] [--json]
39614
+ wayai cases decisions [--dir <folder>] [--confidential]
39615
+ wayai cases note "<text>" [--kind observation|next_step|pending|contribution]
39616
+ [--phase <folder>] [--task <task_id>] [--origin <who sent it>]
39617
+ wayai cases note done <note_id>
39618
+ wayai cases received add <file> --text <markdown file> --phase <folder> --type <type>
39619
+ [--title <title>] [--confidential]
39620
+
38879
39621
  connect Ask to connect this machine to the case, wait while you approve it
38880
39622
  in the WayAI web app, then keep the case's token in this machine's
38881
39623
  keyring. The token reaches that one case alone, with your rights.
@@ -38885,13 +39627,66 @@ connect Ask to connect this machine to the case, wait while you approve it
38885
39627
  disconnect Revoke the case's token and remove it from this machine. --org and
38886
39628
  --space pick the case when two connected cases share its code.
38887
39629
 
39630
+ The work commands use the case's token, never your sign-in, and reach the
39631
+ case this machine is connected to; with several connected, pick one with
39632
+ --case <code> (and --org and --space when codes repeat).
39633
+ brief The case at a glance: status, phases under way, deadlines, open
39634
+ tasks, open pending items and next steps.
39635
+ next What to do next on the phases under way, then what waits on
39636
+ someone else.
39637
+ explain Why each phase and task is not done, and who can move it. --phase
39638
+ names everything holding one phase.
39639
+ check A delivery's checks over the case's files as WayAI holds them:
39640
+ a joint phase's, or one output's (--output). Exits 1 when a submit
39641
+ now would be refused.
39642
+ decisions Write the approved decisions to analysis/decisions.csv under --dir
39643
+ (default: this folder). With --confidential, a confidential group's
39644
+ go to conf/analysis/decisions.csv, if the case lets you read them.
39645
+ note Add a note (an observation unless --kind says otherwise). A
39646
+ contribution names who sent it (--origin).
39647
+ note done Mark a pending item or next step done.
39648
+ received add Register a document a party sent, in one phase, with its
39649
+ Markdown text, read from the file --text names. --confidential registers it as
39650
+ confidential, if the case lets you write one.
39651
+
39652
+ Confidential content is never asked for unless you pass --confidential.
38888
39653
  The case's agents page in the web app shows the exact connect command.
38889
39654
  After connecting, this machine still holds your \`wayai login\`:
38890
39655
  \`wayai logout\` is the recommended next step, and the case token does not
38891
39656
  need it.
38892
39657
  `.trim();
39658
+ OPTIONS2 = {
39659
+ label: { type: "string" },
39660
+ org: { type: "string" },
39661
+ space: { type: "string" },
39662
+ case: { type: "string" },
39663
+ json: { type: "boolean" },
39664
+ phase: { type: "string" },
39665
+ output: { type: "string" },
39666
+ dir: { type: "string" },
39667
+ confidential: { type: "boolean" },
39668
+ kind: { type: "string" },
39669
+ task: { type: "string" },
39670
+ origin: { type: "string" },
39671
+ text: { type: "string" },
39672
+ type: { type: "string" },
39673
+ title: { type: "string" }
39674
+ };
39675
+ SELECT = ["case", "org", "space"];
39676
+ ADMITS = {
39677
+ connect: ["label"],
39678
+ disconnect: ["org", "space"],
39679
+ brief: [...SELECT, "json"],
39680
+ next: [...SELECT, "json"],
39681
+ explain: [...SELECT, "json", "phase"],
39682
+ check: [...SELECT, "json", "phase", "output"],
39683
+ decisions: [...SELECT, "dir", "confidential"],
39684
+ note: [...SELECT, "kind", "phase", "task", "origin"],
39685
+ "note done": SELECT,
39686
+ "received add": [...SELECT, "text", "phase", "type", "title", "confidential"]
39687
+ };
38893
39688
  casePagePath = (ref) => `/cases/${ref.org_id}/${ref.space_id}/${ref.code}`;
38894
- delay2 = (ms) => new Promise((resolve13) => setTimeout(resolve13, ms));
39689
+ delay2 = (ms) => new Promise((resolve14) => setTimeout(resolve14, ms));
38895
39690
  }
38896
39691
  });
38897
39692
 
@@ -38906,7 +39701,7 @@ function usageError5(message) {
38906
39701
 
38907
39702
  ${USAGE6}`);
38908
39703
  }
38909
- function parse3(args2) {
39704
+ function parse4(args2) {
38910
39705
  try {
38911
39706
  return parseArgs27({
38912
39707
  args: args2,
@@ -38940,7 +39735,7 @@ async function dimensionsCommand(args2) {
38940
39735
  console.log(USAGE6);
38941
39736
  return;
38942
39737
  }
38943
- const { values, positionals } = parse3(args2);
39738
+ const { values, positionals } = parse4(args2);
38944
39739
  const [sub, ...ids] = positionals;
38945
39740
  if (!SUBCOMMANDS3.includes(sub)) throw usageError5(`Unknown subcommand ${JSON.stringify(sub)}.`);
38946
39741
  const shape = SHAPE[sub];
@@ -39068,7 +39863,7 @@ function usageError6(message) {
39068
39863
 
39069
39864
  ${USAGE7}`);
39070
39865
  }
39071
- function parse4(args2) {
39866
+ function parse5(args2) {
39072
39867
  try {
39073
39868
  return parseArgs28({
39074
39869
  args: args2,
@@ -39157,7 +39952,7 @@ async function accessCommand(args2) {
39157
39952
  console.log(USAGE7);
39158
39953
  return;
39159
39954
  }
39160
- const { values, positionals } = parse4(args2);
39955
+ const { values, positionals } = parse5(args2);
39161
39956
  const [sub, ...rest] = positionals;
39162
39957
  if (sub !== "explain") throw usageError6(`Unknown subcommand ${JSON.stringify(sub)}.`);
39163
39958
  if (rest.length > 0) throw usageError6("explain takes no arguments.");
@@ -39293,8 +40088,8 @@ var init_headers = __esm({
39293
40088
  });
39294
40089
 
39295
40090
  // src/data/files-sync/local.ts
39296
- import * as fs31 from "fs";
39297
- import * as path43 from "path";
40091
+ import * as fs33 from "fs";
40092
+ import * as path45 from "path";
39298
40093
  function foldSegment(segment) {
39299
40094
  return segment.normalize("NFC").toLowerCase().replace(/[. ]+$/, "");
39300
40095
  }
@@ -39322,7 +40117,7 @@ function remotePath(folder, rel) {
39322
40117
  return folder ? `${folder}/${rel}` : rel;
39323
40118
  }
39324
40119
  function defaultDir(fileType, folder) {
39325
- return path43.join(fileType, ...folder ? folder.split("/") : []);
40120
+ return path45.join(fileType, ...folder ? folder.split("/") : []);
39326
40121
  }
39327
40122
  function describeSync(r) {
39328
40123
  const where = r.folder ? `folder "${r.folder}"` : "the whole file type";
@@ -39385,7 +40180,7 @@ function assertPushable(folder, rels, platform2 = process.platform) {
39385
40180
  }
39386
40181
  function syncDirExists(dir) {
39387
40182
  try {
39388
- fs31.lstatSync(dir);
40183
+ fs33.lstatSync(dir);
39389
40184
  return true;
39390
40185
  } catch {
39391
40186
  return false;
@@ -39393,13 +40188,13 @@ function syncDirExists(dir) {
39393
40188
  }
39394
40189
  function ensureSyncDir(dir) {
39395
40190
  if (!syncDirExists(dir)) {
39396
- fs31.mkdirSync(dir, { recursive: true });
40191
+ fs33.mkdirSync(dir, { recursive: true });
39397
40192
  return;
39398
40193
  }
39399
- if (!fs31.lstatSync(dir).isDirectory()) throw symlinkRefusal(dir, "directory");
40194
+ if (!fs33.lstatSync(dir).isDirectory()) throw symlinkRefusal(dir, "directory");
39400
40195
  }
39401
40196
  function readRecord(dir) {
39402
- const text5 = readRealFileOrThrow(dir, path43.join(dir, RECORD_FILE));
40197
+ const text5 = readRealFileOrThrow(dir, path45.join(dir, RECORD_FILE));
39403
40198
  if (text5 === null) return null;
39404
40199
  let parsed;
39405
40200
  try {
@@ -39409,7 +40204,7 @@ function readRecord(dir) {
39409
40204
  }
39410
40205
  if (!isRecord3(parsed)) {
39411
40206
  throw expected(
39412
- `${path43.join(dir, RECORD_FILE)} is not a record \`wayai files pull\` wrote. Restore it from version control, or move the folder aside and pull again.`
40207
+ `${path45.join(dir, RECORD_FILE)} is not a record \`wayai files pull\` wrote. Restore it from version control, or move the folder aside and pull again.`
39413
40208
  );
39414
40209
  }
39415
40210
  return parsed;
@@ -39429,16 +40224,16 @@ function writeRecord(dir, record) {
39429
40224
  for (const rel of Object.keys(record.files).sort()) files[rel] = syncedFile(record.files[rel]);
39430
40225
  const body = `${JSON.stringify({ base: record.base, file_type: record.file_type, folder: record.folder, files }, null, 2)}
39431
40226
  `;
39432
- const tmp = path43.join(dir, `${RECORD_FILE}.tmp`);
40227
+ const tmp = path45.join(dir, `${RECORD_FILE}.tmp`);
39433
40228
  if (!writeFileNoFollow(dir, tmp, Buffer.from(body, "utf-8"))) throw symlinkRefusal(tmp, "file");
39434
- fs31.renameSync(tmp, path43.join(dir, RECORD_FILE));
40229
+ fs33.renameSync(tmp, path45.join(dir, RECORD_FILE));
39435
40230
  }
39436
40231
  function syncedFile(f) {
39437
40232
  return { version: f.version, content_sha256: f.content_sha256 };
39438
40233
  }
39439
- function readLocal(dir, rel) {
39440
- const bytes = readFileNoFollow(dir, path43.join(dir, ...rel.split("/")));
39441
- if (!bytes) throw symlinkRefusal(path43.join(dir, rel), "file");
40234
+ function readLocal2(dir, rel) {
40235
+ const bytes = readFileNoFollow(dir, path45.join(dir, ...rel.split("/")));
40236
+ if (!bytes) throw symlinkRefusal(path45.join(dir, rel), "file");
39442
40237
  return bytes;
39443
40238
  }
39444
40239
  function scanLocal(dir) {
@@ -39446,22 +40241,22 @@ function scanLocal(dir) {
39446
40241
  if (!syncDirExists(dir)) return out;
39447
40242
  ensureSyncDir(dir);
39448
40243
  const walk = (absDir, relDir) => {
39449
- for (const name of fs31.readdirSync(absDir).sort()) {
40244
+ for (const name of fs33.readdirSync(absDir).sort()) {
39450
40245
  const rel = relDir ? `${relDir}/${name}` : name;
39451
40246
  if (foldSegment(name) === ".git") {
39452
40247
  throw expected(
39453
- `${sanitizeTerminalText(path43.join(dir, rel))} is a git repository inside the synced folder, which files pull and push do not sync into. Sync into a folder of its own \u2014 a folder inside a repository is fine; a repository's root, or a folder holding one, is not.`
40248
+ `${sanitizeTerminalText(path45.join(dir, rel))} is a git repository inside the synced folder, which files pull and push do not sync into. Sync into a folder of its own \u2014 a folder inside a repository is fine; a repository's root, or a folder holding one, is not.`
39454
40249
  );
39455
40250
  }
39456
40251
  if (isOutsideSync(rel)) continue;
39457
- const st = fs31.lstatSync(path43.join(absDir, name));
40252
+ const st = fs33.lstatSync(path45.join(absDir, name));
39458
40253
  if (st.isDirectory()) {
39459
- walk(path43.join(absDir, name), rel);
40254
+ walk(path45.join(absDir, name), rel);
39460
40255
  } else if (st.isFile()) {
39461
- const bytes = readLocal(dir, rel);
40256
+ const bytes = readLocal2(dir, rel);
39462
40257
  out.set(rel, { rel, content_sha256: computeHash(bytes), size: bytes.length });
39463
40258
  } else {
39464
- throw symlinkRefusal(path43.join(dir, rel), "file or folder");
40259
+ throw symlinkRefusal(path45.join(dir, rel), "file or folder");
39465
40260
  }
39466
40261
  }
39467
40262
  };
@@ -39469,7 +40264,7 @@ function scanLocal(dir) {
39469
40264
  return out;
39470
40265
  }
39471
40266
  function matchesScan(dir, rel, scanned) {
39472
- const abs = path43.join(dir, ...rel.split("/"));
40267
+ const abs = path45.join(dir, ...rel.split("/"));
39473
40268
  if (!syncDirExists(abs)) return scanned === void 0;
39474
40269
  if (scanned === void 0) return false;
39475
40270
  const bytes = readFileNoFollow(dir, abs);
@@ -39477,27 +40272,27 @@ function matchesScan(dir, rel, scanned) {
39477
40272
  }
39478
40273
  function writeLocal(dir, rel, bytes) {
39479
40274
  const data = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
39480
- if (!writeFileNoFollow(dir, path43.join(dir, ...rel.split("/")), data)) {
39481
- throw symlinkRefusal(path43.join(dir, rel), "file");
40275
+ if (!writeFileNoFollow(dir, path45.join(dir, ...rel.split("/")), data)) {
40276
+ throw symlinkRefusal(path45.join(dir, rel), "file");
39482
40277
  }
39483
40278
  }
39484
40279
  function removeLocal(dir, rel) {
39485
- const abs = path43.join(dir, ...rel.split("/"));
39486
- requireRealSubdirNoSymlink(dir, path43.dirname(abs), false);
40280
+ const abs = path45.join(dir, ...rel.split("/"));
40281
+ requireRealSubdirNoSymlink(dir, path45.dirname(abs), false);
39487
40282
  let st;
39488
40283
  try {
39489
- st = fs31.lstatSync(abs);
40284
+ st = fs33.lstatSync(abs);
39490
40285
  } catch {
39491
40286
  return;
39492
40287
  }
39493
- if (!st.isFile()) throw symlinkRefusal(path43.join(dir, rel), "file");
39494
- fs31.rmSync(abs);
39495
- const root = path43.resolve(dir);
39496
- for (let parent = path43.dirname(path43.resolve(abs)); parent !== root && isUnder(root, parent); parent = path43.dirname(parent)) {
39497
- const names = fs31.readdirSync(parent);
40288
+ if (!st.isFile()) throw symlinkRefusal(path45.join(dir, rel), "file");
40289
+ fs33.rmSync(abs);
40290
+ const root = path45.resolve(dir);
40291
+ for (let parent = path45.dirname(path45.resolve(abs)); parent !== root && isUnder(root, parent); parent = path45.dirname(parent)) {
40292
+ const names = fs33.readdirSync(parent);
39498
40293
  if (names.some((n) => n !== ".DS_Store")) break;
39499
- for (const n of names) fs31.rmSync(path43.join(parent, n));
39500
- fs31.rmdirSync(parent);
40294
+ for (const n of names) fs33.rmSync(path45.join(parent, n));
40295
+ fs33.rmdirSync(parent);
39501
40296
  }
39502
40297
  }
39503
40298
  function diskClash(dir, rel) {
@@ -39506,7 +40301,7 @@ function diskClash(dir, rel) {
39506
40301
  for (let i = 0; i < segments.length; i++) {
39507
40302
  let names;
39508
40303
  try {
39509
- names = fs31.readdirSync(abs);
40304
+ names = fs33.readdirSync(abs);
39510
40305
  } catch {
39511
40306
  return void 0;
39512
40307
  }
@@ -39514,8 +40309,8 @@ function diskClash(dir, rel) {
39514
40309
  const twin = names.find((n) => n !== segments[i] && foldSegment(n) === want);
39515
40310
  if (twin !== void 0) return { reason: "case_twin", other: [...segments.slice(0, i), twin].join("/") };
39516
40311
  if (!names.includes(segments[i])) return void 0;
39517
- abs = path43.join(abs, segments[i]);
39518
- const isDir = fs31.lstatSync(abs).isDirectory();
40312
+ abs = path45.join(abs, segments[i]);
40313
+ const isDir = fs33.lstatSync(abs).isDirectory();
39519
40314
  const here = segments.slice(0, i + 1).join("/");
39520
40315
  if (i < segments.length - 1 && !isDir) return { reason: "file_folder", other: here };
39521
40316
  if (i === segments.length - 1 && isDir) return { reason: "file_folder", other: `${here}/` };
@@ -39704,25 +40499,25 @@ var init_plan = __esm({
39704
40499
  constructor(paths = []) {
39705
40500
  for (const p of paths) this.add(p);
39706
40501
  }
39707
- add(path46) {
39708
- this.cases.add(path46);
39709
- this.files.add(path46);
39710
- const segments = path46.split("/");
40502
+ add(path48) {
40503
+ this.cases.add(path48);
40504
+ this.files.add(path48);
40505
+ const segments = path48.split("/");
39711
40506
  for (let i = 1; i < segments.length; i++) {
39712
40507
  const folder = segments.slice(0, i).join("/");
39713
- if (!this.folders.has(folder)) this.folders.set(folder, path46);
40508
+ if (!this.folders.has(folder)) this.folders.set(folder, path48);
39714
40509
  }
39715
40510
  }
39716
40511
  /** The path `path` would collide with, and how; undefined when it collides with none. */
39717
- clash(path46) {
39718
- const twin = this.cases.twinOf(path46);
40512
+ clash(path48) {
40513
+ const twin = this.cases.twinOf(path48);
39719
40514
  if (twin !== void 0) return { reason: "case_twin", other: twin };
39720
- const segments = path46.split("/");
40515
+ const segments = path48.split("/");
39721
40516
  for (let i = 1; i < segments.length; i++) {
39722
40517
  const folder = segments.slice(0, i).join("/");
39723
40518
  if (this.files.has(folder)) return { reason: "file_folder", other: folder };
39724
40519
  }
39725
- const inside = this.folders.get(path46);
40520
+ const inside = this.folders.get(path48);
39726
40521
  return inside === void 0 ? void 0 : { reason: "file_folder", other: inside };
39727
40522
  }
39728
40523
  };
@@ -39744,9 +40539,9 @@ async function openRemote2() {
39744
40539
  )
39745
40540
  });
39746
40541
  return {
39747
- request: (method, path46, body, headers) => pacer.run(() => client.request(method, path46, body, headers)),
39748
- upload: (path46, bytes, contentType, headers) => pacer.run(() => client.upload(path46, bytes, contentType, headers)),
39749
- download: (path46) => pacer.run(() => client.download(path46))
40542
+ request: (method, path48, body, headers) => pacer.run(() => client.request(method, path48, body, headers)),
40543
+ upload: (path48, bytes, contentType, headers) => pacer.run(() => client.upload(path48, bytes, contentType, headers)),
40544
+ download: (path48) => pacer.run(() => client.download(path48))
39750
40545
  };
39751
40546
  }
39752
40547
  function filesRoot(t) {
@@ -39879,13 +40674,13 @@ async function pullFiles(opts) {
39879
40674
  conflicts.push({ rel: w.rel, ...clash });
39880
40675
  continue;
39881
40676
  }
39882
- const path46 = filePath2(target, w.rel);
40677
+ const path48 = filePath2(target, w.rel);
39883
40678
  let bytes;
39884
40679
  let version = w.remote.version;
39885
40680
  try {
39886
- bytes = (await client.download(path46)).bytes;
40681
+ bytes = (await client.download(path48)).bytes;
39887
40682
  if (computeHash(bytes) !== w.remote.content_sha256) {
39888
- const meta = await client.request("GET", `${path46}?meta=1`);
40683
+ const meta = await client.request("GET", `${path48}?meta=1`);
39889
40684
  if (meta?.content_sha256 !== computeHash(bytes)) {
39890
40685
  changedWhilePulling.push(w.rel);
39891
40686
  continue;
@@ -39956,7 +40751,7 @@ async function describeSteps(client, t, dir, steps) {
39956
40751
  continue;
39957
40752
  }
39958
40753
  const before = Buffer.from(bytes).toString("utf-8");
39959
- const after = readLocal(dir, step.rel).toString("utf-8");
40754
+ const after = readLocal2(dir, step.rel).toString("utf-8");
39960
40755
  for (const line of changedLines(before, after)) lines.push(` ${line}`);
39961
40756
  }
39962
40757
  }
@@ -40014,7 +40809,7 @@ Push ${n} change${n === 1 ? "" : "s"} to ${describeSync(target)}?`, opts.yes)) {
40014
40809
  let pushed = 0;
40015
40810
  const refusedDeletes = /* @__PURE__ */ new Set();
40016
40811
  for (const step of plan.steps) {
40017
- const path46 = filePath2(target, step.rel);
40812
+ const path48 = filePath2(target, step.rel);
40018
40813
  const blockedBy = step.op === "create" ? step.after?.find((d) => refusedDeletes.has(d.rel)) : void 0;
40019
40814
  if (blockedBy !== void 0) {
40020
40815
  const conflict = { rel: step.rel, reason: blockedBy.reason, other: blockedBy.rel };
@@ -40024,16 +40819,16 @@ Push ${n} change${n === 1 ? "" : "s"} to ${describeSync(target)}?`, opts.yes)) {
40024
40819
  }
40025
40820
  try {
40026
40821
  if (step.op === "delete") {
40027
- await client.request("DELETE", path46, void 0, fileWriteHeaders({ ifMatch: step.ifMatch }));
40822
+ await client.request("DELETE", path48, void 0, fileWriteHeaders({ ifMatch: step.ifMatch }));
40028
40823
  delete record.files[step.rel];
40029
40824
  } else {
40030
- const bytes = readLocal(dir, step.rel);
40825
+ const bytes = readLocal2(dir, step.rel);
40031
40826
  if (computeHash(bytes) !== step.local.content_sha256) {
40032
40827
  throw expected(`${safe(step.rel)} changed while the push ran. Nothing more was pushed; run the push again.`);
40033
40828
  }
40034
40829
  const contentType = step.op === "update" ? step.remote.content_type : guessMimeType(step.rel) ?? "application/octet-stream";
40035
40830
  const row = await client.upload(
40036
- path46,
40831
+ path48,
40037
40832
  bytes,
40038
40833
  contentType,
40039
40834
  fileWriteHeaders({ ...step.op === "update" ? { ifMatch: step.ifMatch } : { createOnly: true }, label: label3 })
@@ -40232,13 +41027,13 @@ ${USAGE8}`);
40232
41027
  }
40233
41028
  function readArgs(args2) {
40234
41029
  try {
40235
- return parseArgs29({ args: args2, options: OPTIONS2, allowPositionals: true, strict: true });
41030
+ return parseArgs29({ args: args2, options: OPTIONS3, allowPositionals: true, strict: true });
40236
41031
  } catch (err) {
40237
41032
  throw usageError7(err instanceof Error ? err.message : String(err));
40238
41033
  }
40239
41034
  }
40240
41035
  function parseKnowledgeArgs(args2) {
40241
- const [retired] = parseArgs29({ args: args2, options: OPTIONS2, allowPositionals: true, strict: false }).positionals;
41036
+ const [retired] = parseArgs29({ args: args2, options: OPTIONS3, allowPositionals: true, strict: false }).positionals;
40242
41037
  if (retired !== void 0 && RETIRED_VERBS.has(retired)) {
40243
41038
  throw expected(
40244
41039
  `\`wayai knowledge ${retired}\` is retired: knowledge resources are gone, and an organization's documents live in its knowledge base as files (\`wayai files pull\` and \`push\`).`
@@ -40265,7 +41060,7 @@ async function knowledgeCommand(args2) {
40265
41060
  const data = await createDataClient(options.orgId, { refreshLogin: true });
40266
41061
  await refreshPreviewKnowledge(knowledgeBase(data), options, { log: (line) => console.log(line), confirm });
40267
41062
  }
40268
- var USAGE8, OPTIONS2, RETIRED_VERBS;
41063
+ var USAGE8, OPTIONS3, RETIRED_VERBS;
40269
41064
  var init_knowledge = __esm({
40270
41065
  "src/commands/knowledge.ts"() {
40271
41066
  "use strict";
@@ -40290,7 +41085,7 @@ refresh-preview: make the knowledge base's preview hold its production base's fi
40290
41085
  --base The production knowledge base, or its preview.
40291
41086
  -y, --yes Skip the question before copying.
40292
41087
  `;
40293
- OPTIONS2 = {
41088
+ OPTIONS3 = {
40294
41089
  org: { type: "string" },
40295
41090
  base: { type: "string" },
40296
41091
  yes: { type: "boolean", short: "y" }
@@ -40300,8 +41095,8 @@ refresh-preview: make the knowledge base's preview hold its production base's fi
40300
41095
  });
40301
41096
 
40302
41097
  // src/lib/file-map.ts
40303
- import * as fs32 from "fs";
40304
- import * as path44 from "path";
41098
+ import * as fs34 from "fs";
41099
+ import * as path46 from "path";
40305
41100
  function isSafeRelPath(rel) {
40306
41101
  if (rel.length === 0 || rel.length > 300) return false;
40307
41102
  if (rel.startsWith("/") || rel.includes("\\")) return false;
@@ -40316,9 +41111,9 @@ function writeFileMap(targetDir, files) {
40316
41111
  if (!isSafeRelPath(rel)) {
40317
41112
  throw new Error(`Refusing to write unsafe path: ${rel}`);
40318
41113
  }
40319
- const abs = path44.join(targetDir, rel);
40320
- fs32.mkdirSync(path44.dirname(abs), { recursive: true });
40321
- fs32.writeFileSync(abs, body, "utf-8");
41114
+ const abs = path46.join(targetDir, rel);
41115
+ fs34.mkdirSync(path46.dirname(abs), { recursive: true });
41116
+ fs34.writeFileSync(abs, body, "utf-8");
40322
41117
  written.push(rel);
40323
41118
  }
40324
41119
  return written;
@@ -40408,8 +41203,8 @@ var admin_exports = {};
40408
41203
  __export(admin_exports, {
40409
41204
  adminCommand: () => adminCommand
40410
41205
  });
40411
- import * as fs33 from "fs";
40412
- import * as path45 from "path";
41206
+ import * as fs35 from "fs";
41207
+ import * as path47 from "path";
40413
41208
  async function adminCommand(args2) {
40414
41209
  const [group, ...afterGroup] = args2;
40415
41210
  if (!group) {
@@ -41050,13 +41845,13 @@ async function runSkillInstall(positional) {
41050
41845
  throw err;
41051
41846
  }
41052
41847
  const root = findGitRoot() ?? process.cwd();
41053
- const present = HARNESS_SKILL_DIRS.filter((dir) => fs33.existsSync(path45.join(root, dir)));
41848
+ const present = HARNESS_SKILL_DIRS.filter((dir) => fs35.existsSync(path47.join(root, dir)));
41054
41849
  const targets = present.length > 0 ? present : HARNESS_SKILL_DIRS;
41055
41850
  const fileCount = Object.keys(res.files).length;
41056
41851
  const relDirs = targets.map((harness) => {
41057
- const targetDir = path45.join(root, harness, "skills", name);
41852
+ const targetDir = path47.join(root, harness, "skills", name);
41058
41853
  writeFileMap(targetDir, res.files);
41059
- return `${path45.relative(root, targetDir)}/`;
41854
+ return `${path47.relative(root, targetDir)}/`;
41060
41855
  });
41061
41856
  console.log(`Installed skill "${name}" (${fileCount} file${fileCount === 1 ? "" : "s"}) \u2192 ${relDirs.join(", ")}`);
41062
41857
  console.log("Reload your agent (e.g. restart Claude Code) to pick up the skill.");
@@ -43539,7 +44334,7 @@ var init_actions = __esm({
43539
44334
 
43540
44335
  // src/data/commands/attachments.ts
43541
44336
  import { Command as Command3 } from "commander";
43542
- import { readFileSync as readFileSync20 } from "fs";
44337
+ import { readFileSync as readFileSync21 } from "fs";
43543
44338
  function findAttachmentByFilename(attachments, filename) {
43544
44339
  return attachments.find((a) => a.key.endsWith(`/${filename}`)) ?? null;
43545
44340
  }
@@ -43580,7 +44375,7 @@ function buildAttachmentsCommand() {
43580
44375
  printOutput(data, outputFormat(this));
43581
44376
  return;
43582
44377
  }
43583
- const body = readFileSync20(opts.file);
44378
+ const body = readFileSync21(opts.file);
43584
44379
  await client.upload(uploadPathFrom(data?.upload_url), body, opts.contentType);
43585
44380
  printOutput({ ...data, uploaded: true }, outputFormat(this));
43586
44381
  });
@@ -43673,7 +44468,7 @@ var init_batch = __esm({
43673
44468
 
43674
44469
  // src/data/commands/import.ts
43675
44470
  import { createReadStream } from "fs";
43676
- import { access, constants, stat } from "fs/promises";
44471
+ import { access, constants as constants2, stat } from "fs/promises";
43677
44472
  import { createInterface as createInterface3 } from "readline";
43678
44473
  import { randomUUID as randomUUID2 } from "crypto";
43679
44474
  import { Command as Command5 } from "commander";
@@ -43786,7 +44581,7 @@ function buildBasesImportCommand() {
43786
44581
  }
43787
44582
  try {
43788
44583
  if ((await stat(opts.file)).isDirectory()) throw new Error("is a directory");
43789
- await access(opts.file, constants.R_OK);
44584
+ await access(opts.file, constants2.R_OK);
43790
44585
  } catch {
43791
44586
  throw expected(`--file ${opts.file}: not a readable file.`);
43792
44587
  }
@@ -43997,7 +44792,7 @@ var init_import = __esm({
43997
44792
 
43998
44793
  // src/data/commands/providers.ts
43999
44794
  import { Command as Command6 } from "commander";
44000
- import { writeFileSync as writeFileSync11 } from "fs";
44795
+ import { writeFileSync as writeFileSync12 } from "fs";
44001
44796
  function providerSegment(provider) {
44002
44797
  if (!VALID_PROVIDERS.includes(provider)) {
44003
44798
  throw expected(`Unknown provider ${JSON.stringify(provider)}. Expected one of: ${VALID_PROVIDERS_HELP}.`);
@@ -44030,7 +44825,7 @@ function buildBasesProvidersCommand() {
44030
44825
  );
44031
44826
  if (opts.to) {
44032
44827
  try {
44033
- writeFileSync11(opts.to, JSON.stringify(data, null, 2));
44828
+ writeFileSync12(opts.to, JSON.stringify(data, null, 2));
44034
44829
  } catch (e) {
44035
44830
  throw expected(`--to ${opts.to}: ${e instanceof Error ? e.message : "could not be written"}`);
44036
44831
  }
@@ -44151,7 +44946,7 @@ var init_credentials = __esm({
44151
44946
 
44152
44947
  // src/data/commands/sql.ts
44153
44948
  import { Command as Command8 } from "commander";
44154
- import { readFileSync as readFileSync21 } from "fs";
44949
+ import { readFileSync as readFileSync22 } from "fs";
44155
44950
  function buildBasesSqlCommand() {
44156
44951
  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(
44157
44952
  "--param <kv...>",
@@ -44161,7 +44956,7 @@ function buildBasesSqlCommand() {
44161
44956
  let query;
44162
44957
  if (opts.file) {
44163
44958
  try {
44164
- query = readFileSync21(opts.file, "utf-8").trim();
44959
+ query = readFileSync22(opts.file, "utf-8").trim();
44165
44960
  } catch (e) {
44166
44961
  throw expected(`--file ${opts.file}: ${e instanceof Error ? e.message : "could not be read"}`);
44167
44962
  }
@@ -44321,16 +45116,16 @@ MCP URL: ${toolsetMcpUrl(slug)}`);
44321
45116
  ).option("--force", "Revoke even if the token appears to be in live use").action(async function(tokenId, opts) {
44322
45117
  const client = await createDataClient();
44323
45118
  const id = pathSegment(tokenId, "token id");
44324
- const path46 = (force) => `/v1/tokens/${id}${force ? "?force=true" : ""}`;
45119
+ const path48 = (force) => `/v1/tokens/${id}${force ? "?force=true" : ""}`;
44325
45120
  const format = outputFormat(this);
44326
45121
  const revoked = (forced) => printOutput({ token_id: tokenId, revoked: true, forced }, format);
44327
45122
  if (opts.force) {
44328
- await client.request("DELETE", path46(true));
45123
+ await client.request("DELETE", path48(true));
44329
45124
  revoked(true);
44330
45125
  return;
44331
45126
  }
44332
45127
  try {
44333
- await client.request("DELETE", path46(false));
45128
+ await client.request("DELETE", path48(false));
44334
45129
  revoked(false);
44335
45130
  } catch (err) {
44336
45131
  if (!(err instanceof ApiError) || err.status !== 409 || dataErrorDetails(err)?.requires_force !== true) {
@@ -44345,7 +45140,7 @@ MCP URL: ${toolsetMcpUrl(slug)}`);
44345
45140
  console.error("Aborted.");
44346
45141
  return process.exit(1);
44347
45142
  }
44348
- await client.request("DELETE", path46(true));
45143
+ await client.request("DELETE", path48(true));
44349
45144
  revoked(true);
44350
45145
  }
44351
45146
  });
@@ -44497,9 +45292,9 @@ var init_base_tags = __esm({
44497
45292
 
44498
45293
  // src/data/commands/bases.ts
44499
45294
  import { Command as Command10 } from "commander";
44500
- function pageOf(path46, cursor) {
44501
- if (!cursor) return path46;
44502
- return `${path46}${path46.includes("?") ? "&" : "?"}cursor=${encodeURIComponent(cursor)}`;
45295
+ function pageOf(path48, cursor) {
45296
+ if (!cursor) return path48;
45297
+ return `${path48}${path48.includes("?") ? "&" : "?"}cursor=${encodeURIComponent(cursor)}`;
44503
45298
  }
44504
45299
  function parseEnum(flag, value, allowed) {
44505
45300
  if (value === void 0) return void 0;
@@ -44656,9 +45451,9 @@ function buildBasesCommand() {
44656
45451
  });
44657
45452
  bases.command("list-previews <origin-id>").description("List preview bases cloned from a base (production or preview)").action(async function(originId) {
44658
45453
  const client = await createDataClient();
44659
- const path46 = `/v1/${pathSegment(originId, "origin base id")}/previews`;
45454
+ const path48 = `/v1/${pathSegment(originId, "origin base id")}/previews`;
44660
45455
  printOutput(
44661
- await client.collectPages((cursor) => pageOf(path46, cursor)),
45456
+ await client.collectPages((cursor) => pageOf(path48, cursor)),
44662
45457
  outputFormat(this)
44663
45458
  );
44664
45459
  });
@@ -44697,9 +45492,9 @@ function buildBasesCommand() {
44697
45492
  });
44698
45493
  bases.command("promotions <production-id>").description("List promotion history for a production base").action(async function(productionId) {
44699
45494
  const client = await createDataClient();
44700
- const path46 = `/v1/${pathSegment(productionId, "production base id")}/promotions`;
45495
+ const path48 = `/v1/${pathSegment(productionId, "production base id")}/promotions`;
44701
45496
  printOutput(
44702
- await client.collectPages((cursor) => pageOf(path46, cursor)),
45497
+ await client.collectPages((cursor) => pageOf(path48, cursor)),
44703
45498
  outputFormat(this)
44704
45499
  );
44705
45500
  });
@@ -44840,8 +45635,8 @@ var init_file_types = __esm({
44840
45635
 
44841
45636
  // src/data/commands/files.ts
44842
45637
  import { Command as Command12 } from "commander";
44843
- import { readFileSync as readFileSync22, writeFileSync as writeFileSync12 } from "fs";
44844
- import { basename as basename29 } from "path";
45638
+ import { readFileSync as readFileSync23, writeFileSync as writeFileSync13 } from "fs";
45639
+ import { basename as basename30 } from "path";
44845
45640
  function renderFileDiff(fileType, filePath3, from, to, d) {
44846
45641
  console.log(sanitizeTerminalText(`${fileType}/${filePath3}: v${from} \u2192 v${to}`));
44847
45642
  const md = d.metadata_delta;
@@ -44873,7 +45668,7 @@ function renderFileDiff(fileType, filePath3, from, to, d) {
44873
45668
  }
44874
45669
  function downloadTarget(remotePath2, to) {
44875
45670
  if (to) return to;
44876
- const derived = basename29(remotePath2);
45671
+ const derived = basename30(remotePath2);
44877
45672
  if (derived === "" || derived === "." || derived === "..") {
44878
45673
  throw expected(
44879
45674
  `Cannot derive a local filename from "${remotePath2}" \u2014 pass --to <local> to name it.`
@@ -44897,7 +45692,7 @@ function buildFilesCommand() {
44897
45692
  label: opts.label,
44898
45693
  metadata: opts.metadata === void 0 ? void 0 : parseData(opts.metadata, "--metadata")
44899
45694
  });
44900
- const body = readFileSync22(opts.file);
45695
+ const body = readFileSync23(opts.file);
44901
45696
  const client = await createDataClient();
44902
45697
  printOutput(
44903
45698
  await client.upload(
@@ -44929,7 +45724,7 @@ function buildFilesCommand() {
44929
45724
  const { bytes } = await client.download(
44930
45725
  `/v1/${base}/files/${pathSegment(fileType, "file_type")}/${encoded}${versionQs ? `?${versionQs}` : ""}`
44931
45726
  );
44932
- writeFileSync12(out, bytes);
45727
+ writeFileSync13(out, bytes);
44933
45728
  console.log(`Downloaded to ${out}`);
44934
45729
  });
44935
45730
  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) {
@@ -45269,8 +46064,8 @@ function buildRecordsCommand() {
45269
46064
  const body = { data: parseData(opts.data) };
45270
46065
  if (opts.externalId) body.external_id = opts.externalId;
45271
46066
  if (opts.externalSource) body.external_source = opts.externalSource;
45272
- const path46 = opts.id ? `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${pathSegment(opts.id, "--id")}` : `/v1/${base}/records/${pathSegment(recordType2, "record_type")}`;
45273
- printOutput(await client.request("PUT", path46, body), outputFormat(this));
46067
+ const path48 = opts.id ? `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${pathSegment(opts.id, "--id")}` : `/v1/${base}/records/${pathSegment(recordType2, "record_type")}`;
46068
+ printOutput(await client.request("PUT", path48, body), outputFormat(this));
45274
46069
  });
45275
46070
  records.command("query <record_type>").description("List/search records: exact filters + fuzzy `search`, sorting, pagination").option(
45276
46071
  "--external-source <source>",
@@ -45305,9 +46100,9 @@ function buildRecordsCommand() {
45305
46100
  ).action(async function(recordType2, id, opts) {
45306
46101
  const base = pathSegment(requireBase(this), "--base");
45307
46102
  const client = await createDataClient();
45308
- let path46 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
45309
- if (opts.externalSource) path46 += `?external_source=${encodeURIComponent(opts.externalSource)}`;
45310
- printOutput(await client.request("GET", path46), outputFormat(this));
46103
+ let path48 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
46104
+ if (opts.externalSource) path48 += `?external_source=${encodeURIComponent(opts.externalSource)}`;
46105
+ printOutput(await client.request("GET", path48), outputFormat(this));
45311
46106
  });
45312
46107
  records.command("delete <record_type> <id>").description(
45313
46108
  "Delete a record by internal ID, or by external_id (pass --external-source to scope it)"
@@ -45321,11 +46116,11 @@ function buildRecordsCommand() {
45321
46116
  }
45322
46117
  const base = pathSegment(requireBase(this), "--base");
45323
46118
  const client = await createDataClient();
45324
- let path46 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
46119
+ let path48 = `/v1/${base}/records/${pathSegment(recordType2, "record_type")}/${recordKey(id, opts.externalSource)}`;
45325
46120
  if (opts.externalSource) {
45326
- path46 += `?external_source=${encodeURIComponent(opts.externalSource)}&external_id=${encodeURIComponent(id)}`;
46121
+ path48 += `?external_source=${encodeURIComponent(opts.externalSource)}&external_id=${encodeURIComponent(id)}`;
45327
46122
  }
45328
- await client.request("DELETE", path46);
46123
+ await client.request("DELETE", path48);
45329
46124
  console.log("Deleted");
45330
46125
  });
45331
46126
  records.command("history <id>").description(
@@ -45490,8 +46285,8 @@ function buildRelationshipsCommand() {
45490
46285
  if (opts.data) body.data = parseData(opts.data);
45491
46286
  const base = pathSegment(requireBase(this), "--base");
45492
46287
  const client = await createDataClient();
45493
- const path46 = opts.id ? `/v1/${base}/relationships/${pathSegment(opts.id, "--id")}` : `/v1/${base}/relationships`;
45494
- printOutput(await client.request("PUT", path46, body), outputFormat(this));
46288
+ const path48 = opts.id ? `/v1/${base}/relationships/${pathSegment(opts.id, "--id")}` : `/v1/${base}/relationships`;
46289
+ printOutput(await client.request("PUT", path48, body), outputFormat(this));
45495
46290
  });
45496
46291
  relationships.command("get <id>").description(
45497
46292
  "Get a relationship by ID (or by its external key: pass the external_id with --rel-type)"
@@ -45724,8 +46519,8 @@ function buildToolsetsCommand() {
45724
46519
  toolsets.command("get <slug>").description("Get a toolset").option("--resolved", "Include resolved record_type schemas").action(async function(slug, opts) {
45725
46520
  const base = pathSegment(requireBase(this), "--base");
45726
46521
  const client = await createDataClient();
45727
- const path46 = opts.resolved ? `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}/resolved` : `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}`;
45728
- printOutput(await client.request("GET", path46), outputFormat(this));
46522
+ const path48 = opts.resolved ? `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}/resolved` : `/v1/${base}/toolsets/${pathSegment(slug, "toolset slug")}`;
46523
+ printOutput(await client.request("GET", path48), outputFormat(this));
45729
46524
  });
45730
46525
  toolsets.command("list").description("List all toolsets").action(async function() {
45731
46526
  const base = pathSegment(requireBase(this), "--base");
@@ -45860,9 +46655,9 @@ init_errors3();
45860
46655
  init_mask_secrets();
45861
46656
  init_utils();
45862
46657
  init_registry();
45863
- import { readFileSync as readFileSync23 } from "fs";
46658
+ import { readFileSync as readFileSync24 } from "fs";
45864
46659
  import { fileURLToPath as fileURLToPath2 } from "url";
45865
- import { dirname as dirname17, join as join40 } from "path";
46660
+ import { dirname as dirname18, join as join42 } from "path";
45866
46661
 
45867
46662
  // src/lib/version-refresh.ts
45868
46663
  init_version_cache();
@@ -45870,7 +46665,7 @@ init_skill_version();
45870
46665
  import { exec } from "child_process";
45871
46666
  var REFRESH_TIMEOUT_MS = 1e4;
45872
46667
  function refreshCliCache() {
45873
- return new Promise((resolve13) => {
46668
+ return new Promise((resolve14) => {
45874
46669
  exec("npm view @wayai/cli version", { timeout: REFRESH_TIMEOUT_MS }, (err, stdout) => {
45875
46670
  if (!err) {
45876
46671
  const latest = stdout.trim();
@@ -45881,7 +46676,7 @@ function refreshCliCache() {
45881
46676
  }
45882
46677
  }
45883
46678
  }
45884
- resolve13();
46679
+ resolve14();
45885
46680
  });
45886
46681
  });
45887
46682
  }
@@ -45907,8 +46702,8 @@ async function refreshSkillCache() {
45907
46702
  }
45908
46703
  async function refreshAdminSkillCache() {
45909
46704
  let timer;
45910
- const deadline = new Promise((resolve13) => {
45911
- timer = setTimeout(resolve13, REFRESH_TIMEOUT_MS);
46705
+ const deadline = new Promise((resolve14) => {
46706
+ timer = setTimeout(resolve14, REFRESH_TIMEOUT_MS);
45912
46707
  });
45913
46708
  await Promise.race([deadline, fetchAndCacheAdminSkillVersion().catch(() => {
45914
46709
  })]);
@@ -46017,8 +46812,8 @@ Run \`wayai admin skill install\` to update.`);
46017
46812
  }
46018
46813
 
46019
46814
  // src/index.ts
46020
- var __dirname = dirname17(fileURLToPath2(import.meta.url));
46021
- var pkg = JSON.parse(readFileSync23(join40(__dirname, "..", "package.json"), "utf-8"));
46815
+ var __dirname = dirname18(fileURLToPath2(import.meta.url));
46816
+ var pkg = JSON.parse(readFileSync24(join42(__dirname, "..", "package.json"), "utf-8"));
46022
46817
  var [, , command, ...args] = process.argv;
46023
46818
  var isBackgroundRefresh = command === REFRESH_COMMAND;
46024
46819
  if (!isBackgroundRefresh) initSentry(command, pkg.version);
@@ -46341,7 +47136,7 @@ Commands:
46341
47136
  list List organizations and hubs
46342
47137
  communities An organization's communities: list, join link (get/rotate/off), stats, access list (list/add/remove) \u2014 \`wayai communities --help\`
46343
47138
  contacts Person links, the deny list, person lookup (browser sign-in only) \u2014 \`wayai contacts --help\`
46344
- cases Connect this machine's code agents to one case (connect), or disconnect them \u2014 \`wayai cases --help\`
47139
+ cases Connect this machine's code agents to one case (connect), work on it (brief, next, note, \u2026), or disconnect \u2014 \`wayai cases --help\`
46345
47140
  dimensions An organization's access dimensions and their values: list, create, relabel, add/retire values \u2014 \`wayai dimensions --help\`
46346
47141
  access explain The access set a hub agent's toolset calls send for a person, and which layer removed each value \u2014 \`wayai access --help\`
46347
47142
  knowledge refresh-preview Make the knowledge base's preview hold its production base's files \u2014 \`wayai knowledge --help\`