@arbidocs/sdk 0.4.76 → 0.4.77

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/browser.cjs CHANGED
@@ -3491,9 +3491,16 @@ var ArbiSessionExpiredError = class extends ArbiError {
3491
3491
  }
3492
3492
  };
3493
3493
  function detailText(detail) {
3494
- if (!Array.isArray(detail)) return detail || void 0;
3495
- const messages = detail.map((d2) => d2?.msg).filter((m2) => Boolean(m2));
3496
- return messages.length ? messages.join("; ") : void 0;
3494
+ if (typeof detail === "string") return detail || void 0;
3495
+ if (Array.isArray(detail)) {
3496
+ const messages = detail.map((d2) => d2?.msg).filter((m2) => Boolean(m2));
3497
+ return messages.length ? messages.join("; ") : void 0;
3498
+ }
3499
+ if (!detail || typeof detail !== "object") return void 0;
3500
+ const message = typeof detail.message === "string" ? detail.message : void 0;
3501
+ const fields = detail.fields && typeof detail.fields === "object" && !Array.isArray(detail.fields) ? Object.entries(detail.fields).map(([name, problem]) => `${name}: ${String(problem)}`).join("; ") : "";
3502
+ if (message) return fields ? `${message} (${fields})` : message;
3503
+ return fields || void 0;
3497
3504
  }
3498
3505
  function apiErrorDetail(apiError) {
3499
3506
  if (typeof apiError === "string") return apiError || void 0;
@@ -4068,6 +4075,12 @@ async function streamSSE(response, callbacks = {}) {
4068
4075
  const { events, remaining } = parseSSEEvents(decoder.decode(value, { stream: true }), sseBuffer);
4069
4076
  sseBuffer = remaining;
4070
4077
  processEvents(events);
4078
+ if (completed) {
4079
+ sseBuffer = "";
4080
+ void reader.cancel().catch(() => {
4081
+ });
4082
+ break;
4083
+ }
4071
4084
  }
4072
4085
  if (sseBuffer.trim()) {
4073
4086
  const { events } = parseSSEEvents(sseBuffer + "\n\n", "");
@@ -5152,11 +5165,25 @@ function extractResponseText(response) {
5152
5165
  // src/operations/tags.ts
5153
5166
  var tags_exports = {};
5154
5167
  __export(tags_exports, {
5168
+ TAG_FIELD_TYPES: () => TAG_FIELD_TYPES,
5155
5169
  createTag: () => createTag,
5156
5170
  deleteTag: () => deleteTag,
5171
+ getTagMatrix: () => getTagMatrix,
5157
5172
  listTags: () => listTags,
5158
- updateTag: () => updateTag
5173
+ mergeTagFieldDefinitions: () => mergeTagFieldDefinitions,
5174
+ ownTagFields: () => ownTagFields,
5175
+ tagMatrixColumns: () => tagMatrixColumns,
5176
+ updateTag: () => updateTag,
5177
+ updateTagFields: () => updateTagFields
5159
5178
  });
5179
+ var TAG_FIELD_TYPES = [
5180
+ "text",
5181
+ "number",
5182
+ "date",
5183
+ "checkbox",
5184
+ "select",
5185
+ "person"
5186
+ ];
5160
5187
  async function listTags(arbi) {
5161
5188
  return requireData(await arbi.fetch.GET("/v1/tag/list"), "Failed to fetch tags");
5162
5189
  }
@@ -5167,7 +5194,10 @@ async function createTag(arbi, options) {
5167
5194
  name: options.name,
5168
5195
  tag_type: options.tagType ?? { type: "checkbox", options: [] },
5169
5196
  instruction: options.instruction ?? null,
5170
- shared: options.shared ?? false
5197
+ shared: options.shared ?? false,
5198
+ ...options.parentId ? { parent_ext_id: options.parentId } : {},
5199
+ ...options.fields ? { fields: options.fields } : {},
5200
+ ...options.fieldValues ? { field_values: options.fieldValues } : {}
5171
5201
  }
5172
5202
  }),
5173
5203
  "Failed to create tag"
@@ -5190,6 +5220,46 @@ async function updateTag(arbi, tagId, body) {
5190
5220
  "Failed to update tag"
5191
5221
  );
5192
5222
  }
5223
+ async function updateTagFields(arbi, tagId, change) {
5224
+ const body = {};
5225
+ if (change.fields) body.fields = change.fields;
5226
+ if (change.values) body.field_values = change.values;
5227
+ return updateTag(arbi, tagId, body);
5228
+ }
5229
+ async function getTagMatrix(arbi, selection, linksLimit) {
5230
+ const query = "parentId" in selection ? { parent_ext_id: selection.parentId } : { tag_ext_id: selection.tagIds };
5231
+ if (linksLimit !== void 0) query.links_limit = linksLimit;
5232
+ return requireData(
5233
+ await arbi.fetch.GET("/v1/tag/matrix", { params: { query } }),
5234
+ "Failed to fetch the tag matrix"
5235
+ );
5236
+ }
5237
+ function tagMatrixColumns(matrix) {
5238
+ const columns = [];
5239
+ const add = (f2) => {
5240
+ if (!columns.some((c2) => c2.id === f2.id)) columns.push(f2);
5241
+ };
5242
+ for (const f2 of matrix.parent?.fields ?? []) add(f2);
5243
+ for (const row of matrix.rows ?? []) for (const f2 of row.tag.fields ?? []) add(f2);
5244
+ return columns;
5245
+ }
5246
+ function ownTagFields(tag) {
5247
+ return (tag.fields ?? []).filter((f2) => f2.tag_ext_id === tag.external_id);
5248
+ }
5249
+ function mergeTagFieldDefinitions(tag, wanted, { keepOthers = false } = {}) {
5250
+ const own = ownTagFields(tag);
5251
+ const byName = new Map(own.map((f2) => [f2.name.toLowerCase(), f2]));
5252
+ const out = wanted.map((w2) => {
5253
+ const old = w2.id ? void 0 : byName.get(w2.name.trim().toLowerCase());
5254
+ return old ? { ...w2, id: old.id } : w2;
5255
+ });
5256
+ if (keepOthers) {
5257
+ for (const f2 of own)
5258
+ if (!out.some((w2) => w2.id === f2.id))
5259
+ out.push({ id: f2.id, name: f2.name, type: f2.type, options: f2.options ?? null });
5260
+ }
5261
+ return out;
5262
+ }
5193
5263
 
5194
5264
  // src/operations/contacts.ts
5195
5265
  var contacts_exports = {};
@@ -5990,25 +6060,88 @@ var projects_exports = {};
5990
6060
  __export(projects_exports, {
5991
6061
  createProject: () => createProject,
5992
6062
  deleteProject: () => deleteProject,
6063
+ formatBudget: () => formatBudget,
6064
+ getProjectConversationUsage: () => getProjectConversationUsage,
5993
6065
  getProjectInvoices: () => getProjectInvoices,
5994
6066
  getProjectUsage: () => getProjectUsage,
5995
6067
  getUserUsageToday: () => getUserUsageToday,
6068
+ listProjectEvents: () => listProjectEvents,
5996
6069
  listProjects: () => listProjects,
6070
+ parseBudget: () => parseBudget,
5997
6071
  refreshProject: () => refreshProject,
5998
6072
  renameProject: () => renameProject,
5999
6073
  updateProject: () => updateProject
6000
6074
  });
6001
- async function listProjects(arbi) {
6002
- return requireData(await arbi.fetch.GET("/v1/user/projects/"), "Failed to fetch projects");
6075
+ async function listProjects(arbi, filters = {}) {
6076
+ const query = {};
6077
+ if (filters.stage) query.stage = filters.stage;
6078
+ if (filters.leadUser) query.lead_user = filters.leadUser;
6079
+ return requireData(
6080
+ await arbi.fetch.GET(
6081
+ "/v1/user/projects/",
6082
+ Object.keys(query).length ? { params: { query } } : void 0
6083
+ ),
6084
+ "Failed to fetch projects"
6085
+ );
6003
6086
  }
6004
- async function createProject(arbi, name, plan = "free") {
6087
+ async function createProject(arbi, name, plan = "free", details = {}) {
6005
6088
  return requireData(
6006
6089
  await arbi.fetch.POST("/v1/user/projects/", {
6007
- body: { name, plan }
6090
+ body: { ...details, name, plan }
6008
6091
  }),
6009
6092
  "Failed to create project"
6010
6093
  );
6011
6094
  }
6095
+ async function listProjectEvents(arbi, projectExtId, options = {}) {
6096
+ const query = {};
6097
+ if (options.kind) query.kind = options.kind;
6098
+ if (options.limit !== void 0) query.limit = options.limit;
6099
+ return requireData(
6100
+ await arbi.fetch.GET("/v1/user/projects/{project_ext_id}/events", {
6101
+ params: { path: { project_ext_id: projectExtId }, query }
6102
+ }),
6103
+ "Failed to fetch project events"
6104
+ );
6105
+ }
6106
+ async function getProjectConversationUsage(arbi, projectExtId, monthsBack) {
6107
+ return requireData(
6108
+ await arbi.fetch.GET("/v1/user/projects/{project_ext_id}/usage/conversations", {
6109
+ params: {
6110
+ path: { project_ext_id: projectExtId },
6111
+ query: monthsBack === void 0 ? void 0 : { months_back: monthsBack }
6112
+ }
6113
+ }),
6114
+ "Failed to fetch project usage by conversation"
6115
+ );
6116
+ }
6117
+ function minorDigits(currency) {
6118
+ try {
6119
+ return new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits ?? 2;
6120
+ } catch {
6121
+ throw new Error(`Unknown currency "${currency}": use an ISO 4217 code such as GBP or USD`);
6122
+ }
6123
+ }
6124
+ function parseBudget(text) {
6125
+ const t2 = text.trim();
6126
+ const after = /^([0-9][0-9,_]*(?:\.[0-9]+)?)\s*([A-Za-z]{3})$/.exec(t2);
6127
+ const before = /^([A-Za-z]{3})\s*([0-9][0-9,_]*(?:\.[0-9]+)?)$/.exec(t2);
6128
+ const [amountText, code] = after ? [after[1], after[2]] : before ? [before[2], before[1]] : [];
6129
+ if (!amountText || !code)
6130
+ throw new Error(`Invalid budget "${text}": use an amount and a currency, e.g. 6000GBP`);
6131
+ const currency = code.toUpperCase();
6132
+ const digits = minorDigits(currency);
6133
+ const major = Number(amountText.replace(/[,_]/g, ""));
6134
+ const amount = Math.round(major * 10 ** digits);
6135
+ if (!Number.isFinite(major) || Math.abs(major * 10 ** digits - amount) > 1e-6)
6136
+ throw new Error(`Invalid budget "${text}": ${currency} has ${digits} decimal places`);
6137
+ return { amount, currency };
6138
+ }
6139
+ function formatBudget(budget) {
6140
+ if (!budget) return "";
6141
+ const digits = minorDigits(budget.currency);
6142
+ const major = budget.amount / 10 ** digits;
6143
+ return `${budget.currency} ${major.toLocaleString("en", { minimumFractionDigits: digits, maximumFractionDigits: digits })}`;
6144
+ }
6012
6145
  async function updateProject(arbi, projectExtId, body) {
6013
6146
  return requireData(
6014
6147
  await arbi.fetch.PATCH("/v1/user/projects/{project_ext_id}", {
@@ -6064,15 +6197,19 @@ async function getUserUsageToday(arbi) {
6064
6197
  var work_exports = {};
6065
6198
  __export(work_exports, {
6066
6199
  actOnStep: () => actOnStep,
6200
+ completeStep: () => completeStep,
6067
6201
  createWork: () => createWork,
6068
6202
  getActivity: () => getActivity,
6069
6203
  getConversation: () => getConversation,
6204
+ getConversationUsage: () => getConversationUsage,
6070
6205
  getPendingAuth: () => getPendingAuth,
6071
6206
  getRunProgress: () => getRunProgress,
6072
6207
  getStepAnswers: () => getStepAnswers,
6073
6208
  notifyConversation: () => notifyConversation,
6074
6209
  planWork: () => planWork,
6075
6210
  runConversation: () => runConversation,
6211
+ sendBackStep: () => sendBackStep,
6212
+ skipStep: () => skipStep,
6076
6213
  updateConversation: () => updateConversation
6077
6214
  });
6078
6215
 
@@ -6081,14 +6218,23 @@ var workflow_steps_exports = {};
6081
6218
  __export(workflow_steps_exports, {
6082
6219
  PERSON_STEP_KINDS: () => PERSON_STEP_KINDS,
6083
6220
  PlanStepsError: () => PlanStepsError,
6221
+ SIGNAL_NAME_PATTERN: () => SIGNAL_NAME_PATTERN,
6222
+ STEP_FIELD_TYPES: () => STEP_FIELD_TYPES,
6084
6223
  STEP_ID_PATTERN: () => STEP_ID_PATTERN,
6085
6224
  STEP_KINDS: () => STEP_KINDS,
6225
+ checkStepInputs: () => checkStepInputs,
6226
+ describeAssignee: () => describeAssignee,
6227
+ describeInputProblems: () => describeInputProblems,
6086
6228
  isPersonStep: () => isPersonStep,
6229
+ linkedRuns: () => linkedRuns,
6230
+ messageWorkflowStep: () => messageWorkflowStep,
6087
6231
  missingRequiredFields: () => missingRequiredFields,
6088
6232
  parseInputPairs: () => parseInputPairs,
6089
6233
  parsePlanSteps: () => parsePlanSteps,
6234
+ raisedSignals: () => raisedSignals,
6090
6235
  runSteps: () => runSteps,
6091
6236
  runWaitingOn: () => runWaitingOn,
6237
+ sendBacks: () => sendBacks,
6092
6238
  stepDependencies: () => stepDependencies,
6093
6239
  stepFields: () => stepFields,
6094
6240
  stepPhase: () => stepPhase,
@@ -6104,6 +6250,15 @@ var STEP_EVENTS = {
6104
6250
  step_skipped: "skipped",
6105
6251
  step_failed: "failed"
6106
6252
  };
6253
+ var EMPTY_STATE = {
6254
+ status: "pending",
6255
+ responseId: null,
6256
+ error: null,
6257
+ sentBack: false,
6258
+ hasNote: false,
6259
+ announcedTo: null
6260
+ };
6261
+ var str = (v2) => typeof v2 === "string" ? v2 : null;
6107
6262
  var isFinished = (state) => state?.status === "done" || state?.status === "skipped";
6108
6263
  var isPersonStep = (step) => PERSON_STEP_KINDS.includes(step.kind);
6109
6264
  function stepDependencies(steps, id) {
@@ -6125,18 +6280,80 @@ function dependsOn(steps, a2, b2) {
6125
6280
  }
6126
6281
  return false;
6127
6282
  }
6283
+ function reopenedBy(detail) {
6284
+ const to = str(detail.to);
6285
+ const listed = Array.isArray(detail.reopened) ? detail.reopened : to ? [to] : [];
6286
+ return listed.filter((id) => typeof id === "string");
6287
+ }
6128
6288
  function stepStatesFromActivity(events) {
6129
6289
  const states = {};
6130
6290
  for (const e of events) {
6291
+ const detail = e.detail ?? {};
6292
+ const step = str(detail.step);
6293
+ if (!step) continue;
6294
+ if (e.kind === "step_sent_back") {
6295
+ const to = str(detail.to);
6296
+ for (const id of reopenedBy(detail))
6297
+ states[id] = {
6298
+ ...EMPTY_STATE,
6299
+ sentBack: id === to,
6300
+ hasNote: id === to && typeof detail.note_encrypted === "string"
6301
+ };
6302
+ continue;
6303
+ }
6304
+ if (e.kind === "step_ready") {
6305
+ states[step] = { ...states[step] ?? EMPTY_STATE, announcedTo: str(detail.to) };
6306
+ continue;
6307
+ }
6131
6308
  const status = STEP_EVENTS[e.kind];
6132
- const step = e.detail?.step;
6133
- if (!status || typeof step !== "string") continue;
6134
- const responseId = typeof e.detail?.response_id === "string" ? e.detail.response_id : null;
6135
- const error = typeof e.detail?.error === "string" ? e.detail.error : null;
6136
- states[step] = { status, responseId: responseId ?? states[step]?.responseId ?? null, error };
6309
+ if (!status) continue;
6310
+ states[step] = {
6311
+ ...EMPTY_STATE,
6312
+ status,
6313
+ responseId: str(detail.response_id) ?? states[step]?.responseId ?? null,
6314
+ error: str(detail.error)
6315
+ };
6137
6316
  }
6138
6317
  return states;
6139
6318
  }
6319
+ function raisedSignals(events) {
6320
+ return events.flatMap((e) => {
6321
+ const step = str(e.detail?.step);
6322
+ const signal = str(e.detail?.signal);
6323
+ return e.kind === "step_signal" && step && signal ? [{ step, signal, at: e.created_at ?? null }] : [];
6324
+ });
6325
+ }
6326
+ function linkedRuns(events) {
6327
+ return events.flatMap((e) => {
6328
+ const conversationId = str(e.detail?.conversation_ext_id);
6329
+ return e.kind === "linked_run" && conversationId ? [
6330
+ {
6331
+ step: str(e.detail?.step),
6332
+ signal: str(e.detail?.signal),
6333
+ conversationId,
6334
+ workflowId: str(e.detail?.workflow_ext_id),
6335
+ at: e.created_at ?? null
6336
+ }
6337
+ ] : [];
6338
+ });
6339
+ }
6340
+ function sendBacks(events) {
6341
+ return events.flatMap((e) => {
6342
+ const detail = e.detail ?? {};
6343
+ const step = str(detail.step);
6344
+ const to = str(detail.to);
6345
+ return e.kind === "step_sent_back" && step && to ? [
6346
+ {
6347
+ step,
6348
+ to,
6349
+ reopened: reopenedBy(detail),
6350
+ hasNote: typeof detail.note_encrypted === "string",
6351
+ by: e.actor_ext_id ?? null,
6352
+ at: e.created_at ?? null
6353
+ }
6354
+ ] : [];
6355
+ });
6356
+ }
6140
6357
  function stepPhase(steps, states, id) {
6141
6358
  const state = states[id];
6142
6359
  if (state && state.status !== "pending") return state.status;
@@ -6144,15 +6361,40 @@ function stepPhase(steps, states, id) {
6144
6361
  }
6145
6362
  function runSteps(steps, events) {
6146
6363
  const states = stepStatesFromActivity(events);
6147
- return steps.map((s2) => ({
6148
- id: s2.id,
6149
- title: s2.title,
6150
- kind: s2.kind,
6151
- phase: stepPhase(steps, states, s2.id),
6152
- after: stepDependencies(steps, s2.id),
6153
- responseId: states[s2.id]?.responseId ?? null,
6154
- error: states[s2.id]?.error ?? null
6155
- }));
6364
+ const signals = raisedSignals(events);
6365
+ const links = linkedRuns(events);
6366
+ const backs = sendBacks(events);
6367
+ return steps.map((s2) => {
6368
+ const state = states[s2.id] ?? EMPTY_STATE;
6369
+ return {
6370
+ id: s2.id,
6371
+ title: s2.title,
6372
+ kind: s2.kind,
6373
+ phase: stepPhase(steps, states, s2.id),
6374
+ after: stepDependencies(steps, s2.id),
6375
+ responseId: state.responseId,
6376
+ error: state.error,
6377
+ assignee: s2.assignee ?? null,
6378
+ announcedTo: state.announcedTo,
6379
+ sentBack: state.sentBack,
6380
+ hasNote: state.hasNote,
6381
+ timesSentBack: backs.filter((b2) => b2.to === s2.id).length,
6382
+ signals: [...new Set(signals.filter((x2) => x2.step === s2.id).map((x2) => x2.signal))],
6383
+ linkedRuns: links.filter((l2) => l2.step === s2.id)
6384
+ };
6385
+ });
6386
+ }
6387
+ function describeAssignee(assignee) {
6388
+ if (!assignee) return "";
6389
+ if (assignee.user) return assignee.user;
6390
+ if (assignee.run_owner) return "run owner";
6391
+ if (assignee.project_lead) return "project lead";
6392
+ if (assignee.input) return `input:${assignee.input}`;
6393
+ return "";
6394
+ }
6395
+ function messageWorkflowStep(message) {
6396
+ const tool = message.tools?.workflow_step;
6397
+ return str(tool?.workflow_step);
6156
6398
  }
6157
6399
  function runWaitingOn(run) {
6158
6400
  if (run.length > 0 && run.every((s2) => s2.phase === "done" || s2.phase === "skipped"))
@@ -6162,15 +6404,97 @@ function runWaitingOn(run) {
6162
6404
  if (run.some((s2) => s2.kind !== "agent" && s2.phase === "ready")) return "person";
6163
6405
  return "stuck";
6164
6406
  }
6407
+ var STEP_FIELD_TYPES = [
6408
+ "text",
6409
+ "longtext",
6410
+ "boolean",
6411
+ "select",
6412
+ "number",
6413
+ "date",
6414
+ "scope",
6415
+ "documents",
6416
+ "person"
6417
+ ];
6165
6418
  function stepFields(step) {
6419
+ if (step.kind === "agent") return [];
6420
+ if (Array.isArray(step.fields)) return step.fields;
6166
6421
  if (step.kind !== "form") return [];
6167
6422
  const fields = step.ui?.fields;
6168
6423
  return Array.isArray(fields) ? fields : [];
6169
6424
  }
6170
- var blank = (value) => value === void 0 || value === null || typeof value === "string" && value.trim() === "";
6425
+ var blank = (value) => {
6426
+ if (value === void 0 || value === null) return true;
6427
+ if (typeof value === "string") return value.trim() === "";
6428
+ if (Array.isArray(value)) return value.length === 0;
6429
+ if (isRecord(value)) return !["documents", "folders", "labels"].some((k2) => !blank(value[k2]));
6430
+ return false;
6431
+ };
6171
6432
  function missingRequiredFields(step, inputs) {
6172
6433
  return stepFields(step).filter((f2) => f2.required && blank(inputs[f2.name])).map((f2) => f2.name);
6173
6434
  }
6435
+ var PERSON_ID = /^(?:usr|agt)-[a-zA-Z0-9]{8}$/;
6436
+ function fieldProblem(field, value) {
6437
+ if (blank(value)) return field.required ? "required" : null;
6438
+ switch (field.type ?? "text") {
6439
+ case "number": {
6440
+ const n2 = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
6441
+ if (Number.isNaN(n2)) return "number";
6442
+ if (field.min !== null && field.min !== void 0 && n2 < field.min) return "min";
6443
+ if (field.max !== null && field.max !== void 0 && n2 > field.max) return "max";
6444
+ return null;
6445
+ }
6446
+ case "boolean":
6447
+ return typeof value === "boolean" ? null : "type";
6448
+ case "select": {
6449
+ if (typeof value !== "string") return "type";
6450
+ const options = (field.options ?? []).map((o2) => o2.value);
6451
+ return options.length === 0 || options.includes(value) ? null : "option";
6452
+ }
6453
+ case "date":
6454
+ return typeof value === "string" && !Number.isNaN(Date.parse(value)) ? null : "type";
6455
+ case "scope":
6456
+ case "documents":
6457
+ return typeof value === "object" ? null : "type";
6458
+ case "person":
6459
+ return typeof value === "string" && PERSON_ID.test(value) ? null : "type";
6460
+ default:
6461
+ return typeof value === "string" || typeof value === "number" ? null : "type";
6462
+ }
6463
+ }
6464
+ function checkStepInputs(step, inputs) {
6465
+ if (!Array.isArray(step.fields)) return {};
6466
+ const given = inputs ?? {};
6467
+ const byName = new Map(step.fields.map((f2) => [f2.name, f2]));
6468
+ const problems = {};
6469
+ for (const name of Object.keys(given)) if (!byName.has(name)) problems[name] = "unknown";
6470
+ for (const [name, field] of byName) {
6471
+ const problem = fieldProblem(field, given[name]);
6472
+ if (problem) problems[name] = problem;
6473
+ }
6474
+ return problems;
6475
+ }
6476
+ function describeInputProblems(step, problems) {
6477
+ const fields = new Map((step.fields ?? []).map((f2) => [f2.name, f2]));
6478
+ return Object.entries(problems).map(([name, problem]) => {
6479
+ const f2 = fields.get(name);
6480
+ switch (problem) {
6481
+ case "unknown":
6482
+ return `${name}: this step does not ask for it (it asks for ${[...fields.keys()].join(", ") || "nothing"})`;
6483
+ case "option":
6484
+ return `${name}: must be one of ${(f2?.options ?? []).map((o2) => o2.value).join(", ")}`;
6485
+ case "min":
6486
+ return `${name}: must be at least ${f2?.min}`;
6487
+ case "max":
6488
+ return `${name}: must be at most ${f2?.max}`;
6489
+ case "number":
6490
+ return `${name}: must be a number`;
6491
+ case "type":
6492
+ return `${name}: must be a ${f2?.type === "person" ? "person id (usr-\u2026 or agt-\u2026)" : f2?.type ?? "value"}`;
6493
+ default:
6494
+ return `${name}: ${problem}`;
6495
+ }
6496
+ }).join("; ");
6497
+ }
6174
6498
  function parseInputPairs(pairs, fields = []) {
6175
6499
  const types = new Map(fields.map((f2) => [f2.name, f2.type]));
6176
6500
  const out = {};
@@ -6203,8 +6527,16 @@ var STEP_KEYS = /* @__PURE__ */ new Set([
6203
6527
  "inputs",
6204
6528
  "branch",
6205
6529
  "requires_files",
6206
- "ui"
6530
+ "ui",
6531
+ "signals",
6532
+ "assignee",
6533
+ "remind_after_hours",
6534
+ "fields"
6207
6535
  ]);
6536
+ var SIGNAL_NAME_PATTERN = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
6537
+ var FIELD_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;
6538
+ var WHEN_KEYS = ["field", "equals", "contains", "matches", "approved"];
6539
+ var ASSIGNEE_KEYS = ["user", "run_owner", "input", "project_lead"];
6208
6540
  var isRecord = (v2) => typeof v2 === "object" && v2 !== null && !Array.isArray(v2);
6209
6541
  var PlanStepsError = class extends Error {
6210
6542
  constructor(problems) {
@@ -6215,6 +6547,123 @@ ${problems.map((p2) => ` - ${p2}`).join("\n")}`);
6215
6547
  }
6216
6548
  problems;
6217
6549
  };
6550
+ var isSet = (v2) => v2 !== void 0 && v2 !== null;
6551
+ function checkSignals(value, at2, problems) {
6552
+ if (!Array.isArray(value)) {
6553
+ problems.push(
6554
+ `${at2}: must be a list of signals, e.g. [{name: risk-high, when: {contains: High}}]`
6555
+ );
6556
+ return;
6557
+ }
6558
+ if (value.length > 10) problems.push(`${at2}: at most 10 signals per step`);
6559
+ value.forEach((signal, j2) => {
6560
+ const here = `${at2}[${j2}]`;
6561
+ if (!isRecord(signal)) {
6562
+ problems.push(`${here}: must be an object with a name`);
6563
+ return;
6564
+ }
6565
+ for (const key of Object.keys(signal))
6566
+ if (key !== "name" && key !== "when")
6567
+ problems.push(`${here}.${key}: unknown field (allowed: name, when)`);
6568
+ if (typeof signal.name !== "string" || !SIGNAL_NAME_PATTERN.test(signal.name))
6569
+ problems.push(
6570
+ `${here}.name: lowercase letters, digits, ".", "_" or "-", starting with a letter or digit (got ${JSON.stringify(signal.name)})`
6571
+ );
6572
+ const when = signal.when;
6573
+ if (!isSet(when)) return;
6574
+ if (!isRecord(when)) {
6575
+ problems.push(`${here}.when: must be an object`);
6576
+ return;
6577
+ }
6578
+ for (const key of Object.keys(when))
6579
+ if (!WHEN_KEYS.includes(key))
6580
+ problems.push(`${here}.when.${key}: unknown field (allowed: ${WHEN_KEYS.join(", ")})`);
6581
+ const shapes = [
6582
+ isSet(when.field) || isSet(when.equals),
6583
+ isSet(when.contains),
6584
+ isSet(when.matches),
6585
+ isSet(when.approved)
6586
+ ].filter(Boolean).length;
6587
+ if (shapes !== 1)
6588
+ problems.push(
6589
+ `${here}.when: exactly one of field+equals (a form value), contains or matches (an agent's answer), or approved (a review)`
6590
+ );
6591
+ if (isSet(when.field) !== isSet(when.equals))
6592
+ problems.push(`${here}.when: a field condition needs both field and equals`);
6593
+ if (isSet(when.field) && typeof when.field !== "string")
6594
+ problems.push(`${here}.when.field: must be a field name`);
6595
+ if (isSet(when.equals) && !["string", "number", "boolean"].includes(typeof when.equals))
6596
+ problems.push(`${here}.when.equals: must be text, a number or true/false`);
6597
+ for (const key of ["contains", "matches"])
6598
+ if (isSet(when[key]) && (typeof when[key] !== "string" || !when[key].trim()))
6599
+ problems.push(`${here}.when.${key}: must be text`);
6600
+ if (typeof when.matches === "string")
6601
+ try {
6602
+ new RegExp(when.matches);
6603
+ } catch (err) {
6604
+ problems.push(
6605
+ `${here}.when.matches: not a valid regular expression (${err.message})`
6606
+ );
6607
+ }
6608
+ if (isSet(when.approved) && typeof when.approved !== "boolean")
6609
+ problems.push(`${here}.when.approved: true or false`);
6610
+ });
6611
+ }
6612
+ function checkAssignee(value, at2, problems) {
6613
+ const hint = `one of {user: usr-\u2026}, {run_owner: true}, {input: <person field>} or {project_lead: true}`;
6614
+ if (!isRecord(value)) {
6615
+ problems.push(`${at2}: must be ${hint}`);
6616
+ return;
6617
+ }
6618
+ for (const key of Object.keys(value))
6619
+ if (!ASSIGNEE_KEYS.includes(key)) problems.push(`${at2}.${key}: unknown field (${hint})`);
6620
+ const set = ASSIGNEE_KEYS.filter((k2) => isSet(value[k2]));
6621
+ if (set.length !== 1) problems.push(`${at2}: exactly ${hint}`);
6622
+ if (isSet(value.user) && (typeof value.user !== "string" || !PERSON_ID.test(value.user)))
6623
+ problems.push(`${at2}.user: a person or agent id (usr-\u2026 or agt-\u2026)`);
6624
+ for (const key of ["run_owner", "project_lead"])
6625
+ if (isSet(value[key]) && value[key] !== true) problems.push(`${at2}.${key}: must be true`);
6626
+ if (isSet(value.input) && (typeof value.input !== "string" || !FIELD_NAME_PATTERN.test(value.input)))
6627
+ problems.push(`${at2}.input: the name of a person field, e.g. "reviewer"`);
6628
+ }
6629
+ function checkFields(value, at2, problems) {
6630
+ if (!Array.isArray(value)) {
6631
+ problems.push(`${at2}: must be a list of fields, e.g. [{name: rating, type: select}]`);
6632
+ return;
6633
+ }
6634
+ if (value.length > 50) problems.push(`${at2}: at most 50 fields`);
6635
+ const names = /* @__PURE__ */ new Set();
6636
+ value.forEach((f2, j2) => {
6637
+ const here = `${at2}[${j2}]`;
6638
+ if (!isRecord(f2)) {
6639
+ problems.push(`${here}: must be an object with a name`);
6640
+ return;
6641
+ }
6642
+ if (typeof f2.name !== "string" || !FIELD_NAME_PATTERN.test(f2.name))
6643
+ problems.push(`${here}.name: a field needs a name like "rating" (letters, digits, "_")`);
6644
+ else if (names.has(f2.name)) problems.push(`${here}.name: "${f2.name}" is used twice`);
6645
+ else names.add(f2.name);
6646
+ if (isSet(f2.type) && !STEP_FIELD_TYPES.includes(f2.type))
6647
+ problems.push(
6648
+ `${here}.type: must be one of ${STEP_FIELD_TYPES.join(", ")} (got ${JSON.stringify(f2.type)})`
6649
+ );
6650
+ if (isSet(f2.label) && typeof f2.label !== "string") problems.push(`${here}.label: must be text`);
6651
+ if (isSet(f2.required) && typeof f2.required !== "boolean")
6652
+ problems.push(`${here}.required: true or false`);
6653
+ for (const key of ["min", "max"])
6654
+ if (isSet(f2[key]) && typeof f2[key] !== "number") problems.push(`${here}.${key}: a number`);
6655
+ if (isSet(f2.options)) {
6656
+ if (!Array.isArray(f2.options) || f2.options.some((o2) => !isRecord(o2) || typeof o2.value !== "string"))
6657
+ problems.push(`${here}.options: a list of {value, label}, e.g. [{value: high}]`);
6658
+ }
6659
+ });
6660
+ }
6661
+ var normalFields = (fields) => fields.map((f2) => ({
6662
+ ...f2,
6663
+ name: f2.name,
6664
+ type: f2.type ?? "text",
6665
+ required: !!f2.required
6666
+ }));
6218
6667
  function checkStep(raw, at2, problems) {
6219
6668
  if (!isRecord(raw)) {
6220
6669
  problems.push(`${at2}: must be an object with id, title and kind`);
@@ -6269,6 +6718,20 @@ function checkStep(raw, at2, problems) {
6269
6718
  problems.push(`${at2}.${key}: only agent steps have a ${key} (this is a ${kind} step)`);
6270
6719
  if (branch) problems.push(`${at2}.branch: only agent steps can branch`);
6271
6720
  }
6721
+ const { signals, assignee, remind_after_hours: remind, fields: stepFieldsRaw } = raw;
6722
+ if (isSet(signals)) checkSignals(signals, `${at2}.signals`, problems);
6723
+ if (isSet(assignee)) checkAssignee(assignee, `${at2}.assignee`, problems);
6724
+ if (isSet(remind)) {
6725
+ if (typeof remind !== "number" || !(remind > 0) || remind > 24 * 365)
6726
+ problems.push(`${at2}.remind_after_hours: a number of hours above 0 (at most a year: 8760)`);
6727
+ else if (kind === "agent")
6728
+ problems.push(`${at2}.remind_after_hours: only a step that waits for a person can remind them`);
6729
+ }
6730
+ if (isSet(stepFieldsRaw)) {
6731
+ if (kind === "agent")
6732
+ problems.push(`${at2}.fields: an agent step has no fields: a person step asks for them`);
6733
+ else checkFields(stepFieldsRaw, `${at2}.fields`, problems);
6734
+ }
6272
6735
  if (kind === "form" && isRecord(ui) && ui.fields !== void 0) {
6273
6736
  if (!Array.isArray(ui.fields)) problems.push(`${at2}.ui.fields: must be a list of fields`);
6274
6737
  else
@@ -6293,7 +6756,11 @@ function checkStep(raw, at2, problems) {
6293
6756
  inputs: inputs ?? null,
6294
6757
  branch: !!branch,
6295
6758
  requires_files: !!raw.requires_files,
6296
- ui: isRecord(ui) ? { ...ui, ...fields ? { fields } : {} } : null
6759
+ ui: isRecord(ui) ? { ...ui, ...fields ? { fields } : {} } : null,
6760
+ ...isSet(signals) ? { signals } : {},
6761
+ ...isSet(assignee) ? { assignee } : {},
6762
+ ...isSet(remind) ? { remind_after_hours: remind } : {},
6763
+ ...isSet(stepFieldsRaw) ? { fields: normalFields(stepFieldsRaw) } : {}
6297
6764
  };
6298
6765
  }
6299
6766
  function parsePlanSteps(value) {
@@ -6369,6 +6836,30 @@ async function actOnStep(arbi, conversationId, body) {
6369
6836
  "Failed to update the workflow step"
6370
6837
  );
6371
6838
  }
6839
+ async function completeStep(arbi, conversationId, step, inputs) {
6840
+ return actOnStep(arbi, conversationId, {
6841
+ step,
6842
+ action: "complete",
6843
+ ...inputs && Object.keys(inputs).length ? { inputs } : {}
6844
+ });
6845
+ }
6846
+ async function skipStep(arbi, conversationId, step) {
6847
+ return actOnStep(arbi, conversationId, { step, action: "skip" });
6848
+ }
6849
+ async function sendBackStep(arbi, conversationId, step, options = {}) {
6850
+ return actOnStep(arbi, conversationId, {
6851
+ step,
6852
+ action: "send_back",
6853
+ ...options.to ? { to: options.to } : {},
6854
+ ...options.note?.trim() ? { note: options.note.trim() } : {}
6855
+ });
6856
+ }
6857
+ async function getConversationUsage(arbi, conversationId) {
6858
+ return requireData(
6859
+ await arbi.fetch.GET("/v1/conversation/{conversation_ext_id}/usage", byId(conversationId)),
6860
+ "Failed to fetch the conversation usage"
6861
+ );
6862
+ }
6372
6863
  async function notifyConversation(arbi, conversationId, userIds) {
6373
6864
  return requireData(
6374
6865
  await arbi.fetch.POST("/v1/conversation/{conversation_ext_id}/notify", {
@@ -6408,7 +6899,14 @@ async function getRunProgress(arbi, conversationId) {
6408
6899
  if (!plan.length)
6409
6900
  throw new Error(`${conversationId} is not a stepped workflow run (its plan has no steps)`);
6410
6901
  const steps = runSteps(plan, activity);
6411
- return { conversation, steps, waitingOn: runWaitingOn(steps) };
6902
+ return {
6903
+ conversation,
6904
+ steps,
6905
+ waitingOn: runWaitingOn(steps),
6906
+ signals: raisedSignals(activity),
6907
+ linkedRuns: linkedRuns(activity),
6908
+ sendBacks: sendBacks(activity)
6909
+ };
6412
6910
  }
6413
6911
  async function getStepAnswers(arbi, conversationId, responseIds) {
6414
6912
  if (!responseIds.length) return {};
@@ -6787,8 +7285,15 @@ var Arbi = class {
6787
7285
  }
6788
7286
  // ── Projects ──────────────────────────────────────────────────────────
6789
7287
  projects = {
6790
- list: () => listProjects(this.requireClient()),
6791
- create: (name) => createProject(this.requireClient(), name),
7288
+ /** The caller's projects; only those at `stage` and/or led by `leadUser` when given. */
7289
+ list: (filters) => listProjects(this.requireClient(), filters),
7290
+ create: (name, plan, details) => createProject(this.requireClient(), name, plan, details),
7291
+ /** Patch a project: name, daily cap, budget, client, stage, lead, fields (merged key by key). */
7292
+ update: (projectExtId, body) => updateProject(this.requireClient(), projectExtId, body),
7293
+ /** The project's stage and budget changes, newest first. */
7294
+ events: (projectExtId, options) => listProjectEvents(this.requireClient(), projectExtId, options),
7295
+ /** The project's spend by conversation in a billing period (credits). */
7296
+ usageByConversation: (projectExtId, monthsBack) => getProjectConversationUsage(this.requireClient(), projectExtId, monthsBack),
6792
7297
  refresh: (projectExtId) => refreshProject(this.requireClient(), projectExtId),
6793
7298
  /** AI usage + spend breakdown for a project's billing period. */
6794
7299
  usage: (projectExtId, monthsBack) => getProjectUsage(this.requireClient(), projectExtId, monthsBack),
@@ -7065,6 +7570,16 @@ var Arbi = class {
7065
7570
  activity: (conversationId) => getActivity(this.requireClient(), conversationId),
7066
7571
  /** Complete or skip a step of a workflow run; the run goes on to its next agent step. */
7067
7572
  actOnStep: (conversationId, body) => actOnStep(this.requireClient(), conversationId, body),
7573
+ /** Complete a person step (with its inputs, checked against the step's `fields`). */
7574
+ completeStep: (conversationId, step, inputs) => completeStep(this.requireClient(), conversationId, step, inputs),
7575
+ /** Skip a step so what waits for it can go on. */
7576
+ skipStep: (conversationId, step) => skipStep(this.requireClient(), conversationId, step),
7577
+ /** Send the work back from a person step to an earlier one (`to`), with an optional note. */
7578
+ sendBackStep: (conversationId, step, options) => sendBackStep(this.requireClient(), conversationId, step, options),
7579
+ /** A stepped run's steps, signals, linked runs and send-backs, and what it waits for. */
7580
+ runProgress: (conversationId) => getRunProgress(this.requireClient(), conversationId),
7581
+ /** What the conversation's AI work cost: by step, run, model, agent and feature (credits). */
7582
+ usage: (conversationId) => getConversationUsage(this.requireClient(), conversationId),
7068
7583
  /** Notify people about a conversation (each gets a notification); resolves with who was. */
7069
7584
  notify: (conversationId, userIds) => notifyConversation(this.requireClient(), conversationId, userIds),
7070
7585
  /** Draft an editable plan from an objective. */
@@ -7208,7 +7723,11 @@ var Arbi = class {
7208
7723
  workspaceId: options.workspaceId ?? this.requireWorkspace()
7209
7724
  }),
7210
7725
  delete: (tagId) => deleteTag(this.requireClient(), tagId),
7211
- update: (tagId, body) => updateTag(this.requireClient(), tagId, body)
7726
+ update: (tagId, body) => updateTag(this.requireClient(), tagId, body),
7727
+ /** Replace a tag's own field definitions and/or merge-patch its values (`null` clears one). */
7728
+ updateFields: (tagId, change) => updateTagFields(this.requireClient(), tagId, change),
7729
+ /** Tags as rows (a parent's children, or the given tags) with field values, docs and facts. */
7730
+ matrix: (selection, linksLimit) => getTagMatrix(this.requireClient(), selection, linksLimit)
7212
7731
  };
7213
7732
  // ── Document Tags ─────────────────────────────────────────────────────
7214
7733
  doctags = {