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