@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/index.cjs CHANGED
@@ -3503,9 +3503,16 @@ var ArbiSessionExpiredError = class extends ArbiError {
3503
3503
  }
3504
3504
  };
3505
3505
  function detailText(detail) {
3506
- if (!Array.isArray(detail)) return detail || void 0;
3507
- const messages = detail.map((d2) => d2?.msg).filter((m2) => Boolean(m2));
3508
- return messages.length ? messages.join("; ") : void 0;
3506
+ if (typeof detail === "string") return detail || void 0;
3507
+ if (Array.isArray(detail)) {
3508
+ const messages = detail.map((d2) => d2?.msg).filter((m2) => Boolean(m2));
3509
+ return messages.length ? messages.join("; ") : void 0;
3510
+ }
3511
+ if (!detail || typeof detail !== "object") return void 0;
3512
+ const message = typeof detail.message === "string" ? detail.message : void 0;
3513
+ const fields = detail.fields && typeof detail.fields === "object" && !Array.isArray(detail.fields) ? Object.entries(detail.fields).map(([name, problem]) => `${name}: ${String(problem)}`).join("; ") : "";
3514
+ if (message) return fields ? `${message} (${fields})` : message;
3515
+ return fields || void 0;
3509
3516
  }
3510
3517
  function apiErrorDetail(apiError) {
3511
3518
  if (typeof apiError === "string") return apiError || void 0;
@@ -4470,6 +4477,12 @@ async function streamSSE(response, callbacks = {}) {
4470
4477
  const { events, remaining } = parseSSEEvents(decoder.decode(value, { stream: true }), sseBuffer);
4471
4478
  sseBuffer = remaining;
4472
4479
  processEvents(events);
4480
+ if (completed) {
4481
+ sseBuffer = "";
4482
+ void reader.cancel().catch(() => {
4483
+ });
4484
+ break;
4485
+ }
4473
4486
  }
4474
4487
  if (sseBuffer.trim()) {
4475
4488
  const { events } = parseSSEEvents(sseBuffer + "\n\n", "");
@@ -5701,11 +5714,25 @@ function extractResponseText(response) {
5701
5714
  // src/operations/tags.ts
5702
5715
  var tags_exports = {};
5703
5716
  __export(tags_exports, {
5717
+ TAG_FIELD_TYPES: () => TAG_FIELD_TYPES,
5704
5718
  createTag: () => createTag,
5705
5719
  deleteTag: () => deleteTag,
5720
+ getTagMatrix: () => getTagMatrix,
5706
5721
  listTags: () => listTags,
5707
- updateTag: () => updateTag
5722
+ mergeTagFieldDefinitions: () => mergeTagFieldDefinitions,
5723
+ ownTagFields: () => ownTagFields,
5724
+ tagMatrixColumns: () => tagMatrixColumns,
5725
+ updateTag: () => updateTag,
5726
+ updateTagFields: () => updateTagFields
5708
5727
  });
5728
+ var TAG_FIELD_TYPES = [
5729
+ "text",
5730
+ "number",
5731
+ "date",
5732
+ "checkbox",
5733
+ "select",
5734
+ "person"
5735
+ ];
5709
5736
  async function listTags(arbi) {
5710
5737
  return requireData(await arbi.fetch.GET("/v1/tag/list"), "Failed to fetch tags");
5711
5738
  }
@@ -5716,7 +5743,10 @@ async function createTag(arbi, options) {
5716
5743
  name: options.name,
5717
5744
  tag_type: options.tagType ?? { type: "checkbox", options: [] },
5718
5745
  instruction: options.instruction ?? null,
5719
- shared: options.shared ?? false
5746
+ shared: options.shared ?? false,
5747
+ ...options.parentId ? { parent_ext_id: options.parentId } : {},
5748
+ ...options.fields ? { fields: options.fields } : {},
5749
+ ...options.fieldValues ? { field_values: options.fieldValues } : {}
5720
5750
  }
5721
5751
  }),
5722
5752
  "Failed to create tag"
@@ -5739,6 +5769,46 @@ async function updateTag(arbi, tagId, body) {
5739
5769
  "Failed to update tag"
5740
5770
  );
5741
5771
  }
5772
+ async function updateTagFields(arbi, tagId, change) {
5773
+ const body = {};
5774
+ if (change.fields) body.fields = change.fields;
5775
+ if (change.values) body.field_values = change.values;
5776
+ return updateTag(arbi, tagId, body);
5777
+ }
5778
+ async function getTagMatrix(arbi, selection, linksLimit) {
5779
+ const query = "parentId" in selection ? { parent_ext_id: selection.parentId } : { tag_ext_id: selection.tagIds };
5780
+ if (linksLimit !== void 0) query.links_limit = linksLimit;
5781
+ return requireData(
5782
+ await arbi.fetch.GET("/v1/tag/matrix", { params: { query } }),
5783
+ "Failed to fetch the tag matrix"
5784
+ );
5785
+ }
5786
+ function tagMatrixColumns(matrix) {
5787
+ const columns = [];
5788
+ const add = (f2) => {
5789
+ if (!columns.some((c2) => c2.id === f2.id)) columns.push(f2);
5790
+ };
5791
+ for (const f2 of matrix.parent?.fields ?? []) add(f2);
5792
+ for (const row of matrix.rows ?? []) for (const f2 of row.tag.fields ?? []) add(f2);
5793
+ return columns;
5794
+ }
5795
+ function ownTagFields(tag) {
5796
+ return (tag.fields ?? []).filter((f2) => f2.tag_ext_id === tag.external_id);
5797
+ }
5798
+ function mergeTagFieldDefinitions(tag, wanted, { keepOthers = false } = {}) {
5799
+ const own = ownTagFields(tag);
5800
+ const byName = new Map(own.map((f2) => [f2.name.toLowerCase(), f2]));
5801
+ const out = wanted.map((w2) => {
5802
+ const old = w2.id ? void 0 : byName.get(w2.name.trim().toLowerCase());
5803
+ return old ? { ...w2, id: old.id } : w2;
5804
+ });
5805
+ if (keepOthers) {
5806
+ for (const f2 of own)
5807
+ if (!out.some((w2) => w2.id === f2.id))
5808
+ out.push({ id: f2.id, name: f2.name, type: f2.type, options: f2.options ?? null });
5809
+ }
5810
+ return out;
5811
+ }
5742
5812
 
5743
5813
  // src/operations/contacts.ts
5744
5814
  var contacts_exports = {};
@@ -6554,25 +6624,88 @@ var projects_exports = {};
6554
6624
  __export(projects_exports, {
6555
6625
  createProject: () => createProject,
6556
6626
  deleteProject: () => deleteProject,
6627
+ formatBudget: () => formatBudget,
6628
+ getProjectConversationUsage: () => getProjectConversationUsage,
6557
6629
  getProjectInvoices: () => getProjectInvoices,
6558
6630
  getProjectUsage: () => getProjectUsage,
6559
6631
  getUserUsageToday: () => getUserUsageToday,
6632
+ listProjectEvents: () => listProjectEvents,
6560
6633
  listProjects: () => listProjects,
6634
+ parseBudget: () => parseBudget,
6561
6635
  refreshProject: () => refreshProject,
6562
6636
  renameProject: () => renameProject,
6563
6637
  updateProject: () => updateProject
6564
6638
  });
6565
- async function listProjects(arbi) {
6566
- return requireData(await arbi.fetch.GET("/v1/user/projects/"), "Failed to fetch projects");
6639
+ async function listProjects(arbi, filters = {}) {
6640
+ const query = {};
6641
+ if (filters.stage) query.stage = filters.stage;
6642
+ if (filters.leadUser) query.lead_user = filters.leadUser;
6643
+ return requireData(
6644
+ await arbi.fetch.GET(
6645
+ "/v1/user/projects/",
6646
+ Object.keys(query).length ? { params: { query } } : void 0
6647
+ ),
6648
+ "Failed to fetch projects"
6649
+ );
6567
6650
  }
6568
- async function createProject(arbi, name, plan = "free") {
6651
+ async function createProject(arbi, name, plan = "free", details = {}) {
6569
6652
  return requireData(
6570
6653
  await arbi.fetch.POST("/v1/user/projects/", {
6571
- body: { name, plan }
6654
+ body: { ...details, name, plan }
6572
6655
  }),
6573
6656
  "Failed to create project"
6574
6657
  );
6575
6658
  }
6659
+ async function listProjectEvents(arbi, projectExtId, options = {}) {
6660
+ const query = {};
6661
+ if (options.kind) query.kind = options.kind;
6662
+ if (options.limit !== void 0) query.limit = options.limit;
6663
+ return requireData(
6664
+ await arbi.fetch.GET("/v1/user/projects/{project_ext_id}/events", {
6665
+ params: { path: { project_ext_id: projectExtId }, query }
6666
+ }),
6667
+ "Failed to fetch project events"
6668
+ );
6669
+ }
6670
+ async function getProjectConversationUsage(arbi, projectExtId, monthsBack) {
6671
+ return requireData(
6672
+ await arbi.fetch.GET("/v1/user/projects/{project_ext_id}/usage/conversations", {
6673
+ params: {
6674
+ path: { project_ext_id: projectExtId },
6675
+ query: monthsBack === void 0 ? void 0 : { months_back: monthsBack }
6676
+ }
6677
+ }),
6678
+ "Failed to fetch project usage by conversation"
6679
+ );
6680
+ }
6681
+ function minorDigits(currency) {
6682
+ try {
6683
+ return new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits ?? 2;
6684
+ } catch {
6685
+ throw new Error(`Unknown currency "${currency}": use an ISO 4217 code such as GBP or USD`);
6686
+ }
6687
+ }
6688
+ function parseBudget(text) {
6689
+ const t2 = text.trim();
6690
+ const after = /^([0-9][0-9,_]*(?:\.[0-9]+)?)\s*([A-Za-z]{3})$/.exec(t2);
6691
+ const before = /^([A-Za-z]{3})\s*([0-9][0-9,_]*(?:\.[0-9]+)?)$/.exec(t2);
6692
+ const [amountText, code] = after ? [after[1], after[2]] : before ? [before[2], before[1]] : [];
6693
+ if (!amountText || !code)
6694
+ throw new Error(`Invalid budget "${text}": use an amount and a currency, e.g. 6000GBP`);
6695
+ const currency = code.toUpperCase();
6696
+ const digits = minorDigits(currency);
6697
+ const major = Number(amountText.replace(/[,_]/g, ""));
6698
+ const amount = Math.round(major * 10 ** digits);
6699
+ if (!Number.isFinite(major) || Math.abs(major * 10 ** digits - amount) > 1e-6)
6700
+ throw new Error(`Invalid budget "${text}": ${currency} has ${digits} decimal places`);
6701
+ return { amount, currency };
6702
+ }
6703
+ function formatBudget(budget) {
6704
+ if (!budget) return "";
6705
+ const digits = minorDigits(budget.currency);
6706
+ const major = budget.amount / 10 ** digits;
6707
+ return `${budget.currency} ${major.toLocaleString("en", { minimumFractionDigits: digits, maximumFractionDigits: digits })}`;
6708
+ }
6576
6709
  async function updateProject(arbi, projectExtId, body) {
6577
6710
  return requireData(
6578
6711
  await arbi.fetch.PATCH("/v1/user/projects/{project_ext_id}", {
@@ -6628,15 +6761,19 @@ async function getUserUsageToday(arbi) {
6628
6761
  var work_exports = {};
6629
6762
  __export(work_exports, {
6630
6763
  actOnStep: () => actOnStep,
6764
+ completeStep: () => completeStep,
6631
6765
  createWork: () => createWork,
6632
6766
  getActivity: () => getActivity,
6633
6767
  getConversation: () => getConversation,
6768
+ getConversationUsage: () => getConversationUsage,
6634
6769
  getPendingAuth: () => getPendingAuth,
6635
6770
  getRunProgress: () => getRunProgress,
6636
6771
  getStepAnswers: () => getStepAnswers,
6637
6772
  notifyConversation: () => notifyConversation,
6638
6773
  planWork: () => planWork,
6639
6774
  runConversation: () => runConversation,
6775
+ sendBackStep: () => sendBackStep,
6776
+ skipStep: () => skipStep,
6640
6777
  updateConversation: () => updateConversation
6641
6778
  });
6642
6779
 
@@ -6645,14 +6782,23 @@ var workflow_steps_exports = {};
6645
6782
  __export(workflow_steps_exports, {
6646
6783
  PERSON_STEP_KINDS: () => PERSON_STEP_KINDS,
6647
6784
  PlanStepsError: () => PlanStepsError,
6785
+ SIGNAL_NAME_PATTERN: () => SIGNAL_NAME_PATTERN,
6786
+ STEP_FIELD_TYPES: () => STEP_FIELD_TYPES,
6648
6787
  STEP_ID_PATTERN: () => STEP_ID_PATTERN,
6649
6788
  STEP_KINDS: () => STEP_KINDS,
6789
+ checkStepInputs: () => checkStepInputs,
6790
+ describeAssignee: () => describeAssignee,
6791
+ describeInputProblems: () => describeInputProblems,
6650
6792
  isPersonStep: () => isPersonStep,
6793
+ linkedRuns: () => linkedRuns,
6794
+ messageWorkflowStep: () => messageWorkflowStep,
6651
6795
  missingRequiredFields: () => missingRequiredFields,
6652
6796
  parseInputPairs: () => parseInputPairs,
6653
6797
  parsePlanSteps: () => parsePlanSteps,
6798
+ raisedSignals: () => raisedSignals,
6654
6799
  runSteps: () => runSteps,
6655
6800
  runWaitingOn: () => runWaitingOn,
6801
+ sendBacks: () => sendBacks,
6656
6802
  stepDependencies: () => stepDependencies,
6657
6803
  stepFields: () => stepFields,
6658
6804
  stepPhase: () => stepPhase,
@@ -6668,6 +6814,15 @@ var STEP_EVENTS = {
6668
6814
  step_skipped: "skipped",
6669
6815
  step_failed: "failed"
6670
6816
  };
6817
+ var EMPTY_STATE = {
6818
+ status: "pending",
6819
+ responseId: null,
6820
+ error: null,
6821
+ sentBack: false,
6822
+ hasNote: false,
6823
+ announcedTo: null
6824
+ };
6825
+ var str = (v2) => typeof v2 === "string" ? v2 : null;
6671
6826
  var isFinished = (state) => state?.status === "done" || state?.status === "skipped";
6672
6827
  var isPersonStep = (step) => PERSON_STEP_KINDS.includes(step.kind);
6673
6828
  function stepDependencies(steps, id) {
@@ -6689,18 +6844,80 @@ function dependsOn(steps, a2, b2) {
6689
6844
  }
6690
6845
  return false;
6691
6846
  }
6847
+ function reopenedBy(detail) {
6848
+ const to = str(detail.to);
6849
+ const listed = Array.isArray(detail.reopened) ? detail.reopened : to ? [to] : [];
6850
+ return listed.filter((id) => typeof id === "string");
6851
+ }
6692
6852
  function stepStatesFromActivity(events) {
6693
6853
  const states = {};
6694
6854
  for (const e of events) {
6855
+ const detail = e.detail ?? {};
6856
+ const step = str(detail.step);
6857
+ if (!step) continue;
6858
+ if (e.kind === "step_sent_back") {
6859
+ const to = str(detail.to);
6860
+ for (const id of reopenedBy(detail))
6861
+ states[id] = {
6862
+ ...EMPTY_STATE,
6863
+ sentBack: id === to,
6864
+ hasNote: id === to && typeof detail.note_encrypted === "string"
6865
+ };
6866
+ continue;
6867
+ }
6868
+ if (e.kind === "step_ready") {
6869
+ states[step] = { ...states[step] ?? EMPTY_STATE, announcedTo: str(detail.to) };
6870
+ continue;
6871
+ }
6695
6872
  const status = STEP_EVENTS[e.kind];
6696
- const step = e.detail?.step;
6697
- if (!status || typeof step !== "string") continue;
6698
- const responseId = typeof e.detail?.response_id === "string" ? e.detail.response_id : null;
6699
- const error = typeof e.detail?.error === "string" ? e.detail.error : null;
6700
- states[step] = { status, responseId: responseId ?? states[step]?.responseId ?? null, error };
6873
+ if (!status) continue;
6874
+ states[step] = {
6875
+ ...EMPTY_STATE,
6876
+ status,
6877
+ responseId: str(detail.response_id) ?? states[step]?.responseId ?? null,
6878
+ error: str(detail.error)
6879
+ };
6701
6880
  }
6702
6881
  return states;
6703
6882
  }
6883
+ function raisedSignals(events) {
6884
+ return events.flatMap((e) => {
6885
+ const step = str(e.detail?.step);
6886
+ const signal = str(e.detail?.signal);
6887
+ return e.kind === "step_signal" && step && signal ? [{ step, signal, at: e.created_at ?? null }] : [];
6888
+ });
6889
+ }
6890
+ function linkedRuns(events) {
6891
+ return events.flatMap((e) => {
6892
+ const conversationId = str(e.detail?.conversation_ext_id);
6893
+ return e.kind === "linked_run" && conversationId ? [
6894
+ {
6895
+ step: str(e.detail?.step),
6896
+ signal: str(e.detail?.signal),
6897
+ conversationId,
6898
+ workflowId: str(e.detail?.workflow_ext_id),
6899
+ at: e.created_at ?? null
6900
+ }
6901
+ ] : [];
6902
+ });
6903
+ }
6904
+ function sendBacks(events) {
6905
+ return events.flatMap((e) => {
6906
+ const detail = e.detail ?? {};
6907
+ const step = str(detail.step);
6908
+ const to = str(detail.to);
6909
+ return e.kind === "step_sent_back" && step && to ? [
6910
+ {
6911
+ step,
6912
+ to,
6913
+ reopened: reopenedBy(detail),
6914
+ hasNote: typeof detail.note_encrypted === "string",
6915
+ by: e.actor_ext_id ?? null,
6916
+ at: e.created_at ?? null
6917
+ }
6918
+ ] : [];
6919
+ });
6920
+ }
6704
6921
  function stepPhase(steps, states, id) {
6705
6922
  const state = states[id];
6706
6923
  if (state && state.status !== "pending") return state.status;
@@ -6708,15 +6925,40 @@ function stepPhase(steps, states, id) {
6708
6925
  }
6709
6926
  function runSteps(steps, events) {
6710
6927
  const states = stepStatesFromActivity(events);
6711
- return steps.map((s2) => ({
6712
- id: s2.id,
6713
- title: s2.title,
6714
- kind: s2.kind,
6715
- phase: stepPhase(steps, states, s2.id),
6716
- after: stepDependencies(steps, s2.id),
6717
- responseId: states[s2.id]?.responseId ?? null,
6718
- error: states[s2.id]?.error ?? null
6719
- }));
6928
+ const signals = raisedSignals(events);
6929
+ const links = linkedRuns(events);
6930
+ const backs = sendBacks(events);
6931
+ return steps.map((s2) => {
6932
+ const state = states[s2.id] ?? EMPTY_STATE;
6933
+ return {
6934
+ id: s2.id,
6935
+ title: s2.title,
6936
+ kind: s2.kind,
6937
+ phase: stepPhase(steps, states, s2.id),
6938
+ after: stepDependencies(steps, s2.id),
6939
+ responseId: state.responseId,
6940
+ error: state.error,
6941
+ assignee: s2.assignee ?? null,
6942
+ announcedTo: state.announcedTo,
6943
+ sentBack: state.sentBack,
6944
+ hasNote: state.hasNote,
6945
+ timesSentBack: backs.filter((b2) => b2.to === s2.id).length,
6946
+ signals: [...new Set(signals.filter((x2) => x2.step === s2.id).map((x2) => x2.signal))],
6947
+ linkedRuns: links.filter((l2) => l2.step === s2.id)
6948
+ };
6949
+ });
6950
+ }
6951
+ function describeAssignee(assignee) {
6952
+ if (!assignee) return "";
6953
+ if (assignee.user) return assignee.user;
6954
+ if (assignee.run_owner) return "run owner";
6955
+ if (assignee.project_lead) return "project lead";
6956
+ if (assignee.input) return `input:${assignee.input}`;
6957
+ return "";
6958
+ }
6959
+ function messageWorkflowStep(message) {
6960
+ const tool = message.tools?.workflow_step;
6961
+ return str(tool?.workflow_step);
6720
6962
  }
6721
6963
  function runWaitingOn(run) {
6722
6964
  if (run.length > 0 && run.every((s2) => s2.phase === "done" || s2.phase === "skipped"))
@@ -6726,15 +6968,97 @@ function runWaitingOn(run) {
6726
6968
  if (run.some((s2) => s2.kind !== "agent" && s2.phase === "ready")) return "person";
6727
6969
  return "stuck";
6728
6970
  }
6971
+ var STEP_FIELD_TYPES = [
6972
+ "text",
6973
+ "longtext",
6974
+ "boolean",
6975
+ "select",
6976
+ "number",
6977
+ "date",
6978
+ "scope",
6979
+ "documents",
6980
+ "person"
6981
+ ];
6729
6982
  function stepFields(step) {
6983
+ if (step.kind === "agent") return [];
6984
+ if (Array.isArray(step.fields)) return step.fields;
6730
6985
  if (step.kind !== "form") return [];
6731
6986
  const fields = step.ui?.fields;
6732
6987
  return Array.isArray(fields) ? fields : [];
6733
6988
  }
6734
- var blank = (value) => value === void 0 || value === null || typeof value === "string" && value.trim() === "";
6989
+ var blank = (value) => {
6990
+ if (value === void 0 || value === null) return true;
6991
+ if (typeof value === "string") return value.trim() === "";
6992
+ if (Array.isArray(value)) return value.length === 0;
6993
+ if (isRecord(value)) return !["documents", "folders", "labels"].some((k2) => !blank(value[k2]));
6994
+ return false;
6995
+ };
6735
6996
  function missingRequiredFields(step, inputs) {
6736
6997
  return stepFields(step).filter((f2) => f2.required && blank(inputs[f2.name])).map((f2) => f2.name);
6737
6998
  }
6999
+ var PERSON_ID = /^(?:usr|agt)-[a-zA-Z0-9]{8}$/;
7000
+ function fieldProblem(field, value) {
7001
+ if (blank(value)) return field.required ? "required" : null;
7002
+ switch (field.type ?? "text") {
7003
+ case "number": {
7004
+ const n2 = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
7005
+ if (Number.isNaN(n2)) return "number";
7006
+ if (field.min !== null && field.min !== void 0 && n2 < field.min) return "min";
7007
+ if (field.max !== null && field.max !== void 0 && n2 > field.max) return "max";
7008
+ return null;
7009
+ }
7010
+ case "boolean":
7011
+ return typeof value === "boolean" ? null : "type";
7012
+ case "select": {
7013
+ if (typeof value !== "string") return "type";
7014
+ const options = (field.options ?? []).map((o2) => o2.value);
7015
+ return options.length === 0 || options.includes(value) ? null : "option";
7016
+ }
7017
+ case "date":
7018
+ return typeof value === "string" && !Number.isNaN(Date.parse(value)) ? null : "type";
7019
+ case "scope":
7020
+ case "documents":
7021
+ return typeof value === "object" ? null : "type";
7022
+ case "person":
7023
+ return typeof value === "string" && PERSON_ID.test(value) ? null : "type";
7024
+ default:
7025
+ return typeof value === "string" || typeof value === "number" ? null : "type";
7026
+ }
7027
+ }
7028
+ function checkStepInputs(step, inputs) {
7029
+ if (!Array.isArray(step.fields)) return {};
7030
+ const given = inputs ?? {};
7031
+ const byName = new Map(step.fields.map((f2) => [f2.name, f2]));
7032
+ const problems = {};
7033
+ for (const name of Object.keys(given)) if (!byName.has(name)) problems[name] = "unknown";
7034
+ for (const [name, field] of byName) {
7035
+ const problem = fieldProblem(field, given[name]);
7036
+ if (problem) problems[name] = problem;
7037
+ }
7038
+ return problems;
7039
+ }
7040
+ function describeInputProblems(step, problems) {
7041
+ const fields = new Map((step.fields ?? []).map((f2) => [f2.name, f2]));
7042
+ return Object.entries(problems).map(([name, problem]) => {
7043
+ const f2 = fields.get(name);
7044
+ switch (problem) {
7045
+ case "unknown":
7046
+ return `${name}: this step does not ask for it (it asks for ${[...fields.keys()].join(", ") || "nothing"})`;
7047
+ case "option":
7048
+ return `${name}: must be one of ${(f2?.options ?? []).map((o2) => o2.value).join(", ")}`;
7049
+ case "min":
7050
+ return `${name}: must be at least ${f2?.min}`;
7051
+ case "max":
7052
+ return `${name}: must be at most ${f2?.max}`;
7053
+ case "number":
7054
+ return `${name}: must be a number`;
7055
+ case "type":
7056
+ return `${name}: must be a ${f2?.type === "person" ? "person id (usr-\u2026 or agt-\u2026)" : f2?.type ?? "value"}`;
7057
+ default:
7058
+ return `${name}: ${problem}`;
7059
+ }
7060
+ }).join("; ");
7061
+ }
6738
7062
  function parseInputPairs(pairs, fields = []) {
6739
7063
  const types = new Map(fields.map((f2) => [f2.name, f2.type]));
6740
7064
  const out = {};
@@ -6767,8 +7091,16 @@ var STEP_KEYS = /* @__PURE__ */ new Set([
6767
7091
  "inputs",
6768
7092
  "branch",
6769
7093
  "requires_files",
6770
- "ui"
7094
+ "ui",
7095
+ "signals",
7096
+ "assignee",
7097
+ "remind_after_hours",
7098
+ "fields"
6771
7099
  ]);
7100
+ var SIGNAL_NAME_PATTERN = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
7101
+ var FIELD_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/;
7102
+ var WHEN_KEYS = ["field", "equals", "contains", "matches", "approved"];
7103
+ var ASSIGNEE_KEYS = ["user", "run_owner", "input", "project_lead"];
6772
7104
  var isRecord = (v2) => typeof v2 === "object" && v2 !== null && !Array.isArray(v2);
6773
7105
  var PlanStepsError = class extends Error {
6774
7106
  constructor(problems) {
@@ -6779,6 +7111,123 @@ ${problems.map((p2) => ` - ${p2}`).join("\n")}`);
6779
7111
  }
6780
7112
  problems;
6781
7113
  };
7114
+ var isSet = (v2) => v2 !== void 0 && v2 !== null;
7115
+ function checkSignals(value, at2, problems) {
7116
+ if (!Array.isArray(value)) {
7117
+ problems.push(
7118
+ `${at2}: must be a list of signals, e.g. [{name: risk-high, when: {contains: High}}]`
7119
+ );
7120
+ return;
7121
+ }
7122
+ if (value.length > 10) problems.push(`${at2}: at most 10 signals per step`);
7123
+ value.forEach((signal, j2) => {
7124
+ const here = `${at2}[${j2}]`;
7125
+ if (!isRecord(signal)) {
7126
+ problems.push(`${here}: must be an object with a name`);
7127
+ return;
7128
+ }
7129
+ for (const key of Object.keys(signal))
7130
+ if (key !== "name" && key !== "when")
7131
+ problems.push(`${here}.${key}: unknown field (allowed: name, when)`);
7132
+ if (typeof signal.name !== "string" || !SIGNAL_NAME_PATTERN.test(signal.name))
7133
+ problems.push(
7134
+ `${here}.name: lowercase letters, digits, ".", "_" or "-", starting with a letter or digit (got ${JSON.stringify(signal.name)})`
7135
+ );
7136
+ const when = signal.when;
7137
+ if (!isSet(when)) return;
7138
+ if (!isRecord(when)) {
7139
+ problems.push(`${here}.when: must be an object`);
7140
+ return;
7141
+ }
7142
+ for (const key of Object.keys(when))
7143
+ if (!WHEN_KEYS.includes(key))
7144
+ problems.push(`${here}.when.${key}: unknown field (allowed: ${WHEN_KEYS.join(", ")})`);
7145
+ const shapes = [
7146
+ isSet(when.field) || isSet(when.equals),
7147
+ isSet(when.contains),
7148
+ isSet(when.matches),
7149
+ isSet(when.approved)
7150
+ ].filter(Boolean).length;
7151
+ if (shapes !== 1)
7152
+ problems.push(
7153
+ `${here}.when: exactly one of field+equals (a form value), contains or matches (an agent's answer), or approved (a review)`
7154
+ );
7155
+ if (isSet(when.field) !== isSet(when.equals))
7156
+ problems.push(`${here}.when: a field condition needs both field and equals`);
7157
+ if (isSet(when.field) && typeof when.field !== "string")
7158
+ problems.push(`${here}.when.field: must be a field name`);
7159
+ if (isSet(when.equals) && !["string", "number", "boolean"].includes(typeof when.equals))
7160
+ problems.push(`${here}.when.equals: must be text, a number or true/false`);
7161
+ for (const key of ["contains", "matches"])
7162
+ if (isSet(when[key]) && (typeof when[key] !== "string" || !when[key].trim()))
7163
+ problems.push(`${here}.when.${key}: must be text`);
7164
+ if (typeof when.matches === "string")
7165
+ try {
7166
+ new RegExp(when.matches);
7167
+ } catch (err) {
7168
+ problems.push(
7169
+ `${here}.when.matches: not a valid regular expression (${err.message})`
7170
+ );
7171
+ }
7172
+ if (isSet(when.approved) && typeof when.approved !== "boolean")
7173
+ problems.push(`${here}.when.approved: true or false`);
7174
+ });
7175
+ }
7176
+ function checkAssignee(value, at2, problems) {
7177
+ const hint = `one of {user: usr-\u2026}, {run_owner: true}, {input: <person field>} or {project_lead: true}`;
7178
+ if (!isRecord(value)) {
7179
+ problems.push(`${at2}: must be ${hint}`);
7180
+ return;
7181
+ }
7182
+ for (const key of Object.keys(value))
7183
+ if (!ASSIGNEE_KEYS.includes(key)) problems.push(`${at2}.${key}: unknown field (${hint})`);
7184
+ const set = ASSIGNEE_KEYS.filter((k2) => isSet(value[k2]));
7185
+ if (set.length !== 1) problems.push(`${at2}: exactly ${hint}`);
7186
+ if (isSet(value.user) && (typeof value.user !== "string" || !PERSON_ID.test(value.user)))
7187
+ problems.push(`${at2}.user: a person or agent id (usr-\u2026 or agt-\u2026)`);
7188
+ for (const key of ["run_owner", "project_lead"])
7189
+ if (isSet(value[key]) && value[key] !== true) problems.push(`${at2}.${key}: must be true`);
7190
+ if (isSet(value.input) && (typeof value.input !== "string" || !FIELD_NAME_PATTERN.test(value.input)))
7191
+ problems.push(`${at2}.input: the name of a person field, e.g. "reviewer"`);
7192
+ }
7193
+ function checkFields(value, at2, problems) {
7194
+ if (!Array.isArray(value)) {
7195
+ problems.push(`${at2}: must be a list of fields, e.g. [{name: rating, type: select}]`);
7196
+ return;
7197
+ }
7198
+ if (value.length > 50) problems.push(`${at2}: at most 50 fields`);
7199
+ const names = /* @__PURE__ */ new Set();
7200
+ value.forEach((f2, j2) => {
7201
+ const here = `${at2}[${j2}]`;
7202
+ if (!isRecord(f2)) {
7203
+ problems.push(`${here}: must be an object with a name`);
7204
+ return;
7205
+ }
7206
+ if (typeof f2.name !== "string" || !FIELD_NAME_PATTERN.test(f2.name))
7207
+ problems.push(`${here}.name: a field needs a name like "rating" (letters, digits, "_")`);
7208
+ else if (names.has(f2.name)) problems.push(`${here}.name: "${f2.name}" is used twice`);
7209
+ else names.add(f2.name);
7210
+ if (isSet(f2.type) && !STEP_FIELD_TYPES.includes(f2.type))
7211
+ problems.push(
7212
+ `${here}.type: must be one of ${STEP_FIELD_TYPES.join(", ")} (got ${JSON.stringify(f2.type)})`
7213
+ );
7214
+ if (isSet(f2.label) && typeof f2.label !== "string") problems.push(`${here}.label: must be text`);
7215
+ if (isSet(f2.required) && typeof f2.required !== "boolean")
7216
+ problems.push(`${here}.required: true or false`);
7217
+ for (const key of ["min", "max"])
7218
+ if (isSet(f2[key]) && typeof f2[key] !== "number") problems.push(`${here}.${key}: a number`);
7219
+ if (isSet(f2.options)) {
7220
+ if (!Array.isArray(f2.options) || f2.options.some((o2) => !isRecord(o2) || typeof o2.value !== "string"))
7221
+ problems.push(`${here}.options: a list of {value, label}, e.g. [{value: high}]`);
7222
+ }
7223
+ });
7224
+ }
7225
+ var normalFields = (fields) => fields.map((f2) => ({
7226
+ ...f2,
7227
+ name: f2.name,
7228
+ type: f2.type ?? "text",
7229
+ required: !!f2.required
7230
+ }));
6782
7231
  function checkStep(raw, at2, problems) {
6783
7232
  if (!isRecord(raw)) {
6784
7233
  problems.push(`${at2}: must be an object with id, title and kind`);
@@ -6833,6 +7282,20 @@ function checkStep(raw, at2, problems) {
6833
7282
  problems.push(`${at2}.${key}: only agent steps have a ${key} (this is a ${kind} step)`);
6834
7283
  if (branch) problems.push(`${at2}.branch: only agent steps can branch`);
6835
7284
  }
7285
+ const { signals, assignee, remind_after_hours: remind, fields: stepFieldsRaw } = raw;
7286
+ if (isSet(signals)) checkSignals(signals, `${at2}.signals`, problems);
7287
+ if (isSet(assignee)) checkAssignee(assignee, `${at2}.assignee`, problems);
7288
+ if (isSet(remind)) {
7289
+ if (typeof remind !== "number" || !(remind > 0) || remind > 24 * 365)
7290
+ problems.push(`${at2}.remind_after_hours: a number of hours above 0 (at most a year: 8760)`);
7291
+ else if (kind === "agent")
7292
+ problems.push(`${at2}.remind_after_hours: only a step that waits for a person can remind them`);
7293
+ }
7294
+ if (isSet(stepFieldsRaw)) {
7295
+ if (kind === "agent")
7296
+ problems.push(`${at2}.fields: an agent step has no fields: a person step asks for them`);
7297
+ else checkFields(stepFieldsRaw, `${at2}.fields`, problems);
7298
+ }
6836
7299
  if (kind === "form" && isRecord(ui) && ui.fields !== void 0) {
6837
7300
  if (!Array.isArray(ui.fields)) problems.push(`${at2}.ui.fields: must be a list of fields`);
6838
7301
  else
@@ -6857,7 +7320,11 @@ function checkStep(raw, at2, problems) {
6857
7320
  inputs: inputs ?? null,
6858
7321
  branch: !!branch,
6859
7322
  requires_files: !!raw.requires_files,
6860
- ui: isRecord(ui) ? { ...ui, ...fields ? { fields } : {} } : null
7323
+ ui: isRecord(ui) ? { ...ui, ...fields ? { fields } : {} } : null,
7324
+ ...isSet(signals) ? { signals } : {},
7325
+ ...isSet(assignee) ? { assignee } : {},
7326
+ ...isSet(remind) ? { remind_after_hours: remind } : {},
7327
+ ...isSet(stepFieldsRaw) ? { fields: normalFields(stepFieldsRaw) } : {}
6861
7328
  };
6862
7329
  }
6863
7330
  function parsePlanSteps(value) {
@@ -6933,6 +7400,30 @@ async function actOnStep(arbi, conversationId, body) {
6933
7400
  "Failed to update the workflow step"
6934
7401
  );
6935
7402
  }
7403
+ async function completeStep(arbi, conversationId, step, inputs) {
7404
+ return actOnStep(arbi, conversationId, {
7405
+ step,
7406
+ action: "complete",
7407
+ ...inputs && Object.keys(inputs).length ? { inputs } : {}
7408
+ });
7409
+ }
7410
+ async function skipStep(arbi, conversationId, step) {
7411
+ return actOnStep(arbi, conversationId, { step, action: "skip" });
7412
+ }
7413
+ async function sendBackStep(arbi, conversationId, step, options = {}) {
7414
+ return actOnStep(arbi, conversationId, {
7415
+ step,
7416
+ action: "send_back",
7417
+ ...options.to ? { to: options.to } : {},
7418
+ ...options.note?.trim() ? { note: options.note.trim() } : {}
7419
+ });
7420
+ }
7421
+ async function getConversationUsage(arbi, conversationId) {
7422
+ return requireData(
7423
+ await arbi.fetch.GET("/v1/conversation/{conversation_ext_id}/usage", byId(conversationId)),
7424
+ "Failed to fetch the conversation usage"
7425
+ );
7426
+ }
6936
7427
  async function notifyConversation(arbi, conversationId, userIds) {
6937
7428
  return requireData(
6938
7429
  await arbi.fetch.POST("/v1/conversation/{conversation_ext_id}/notify", {
@@ -6972,7 +7463,14 @@ async function getRunProgress(arbi, conversationId) {
6972
7463
  if (!plan.length)
6973
7464
  throw new Error(`${conversationId} is not a stepped workflow run (its plan has no steps)`);
6974
7465
  const steps = runSteps(plan, activity);
6975
- return { conversation, steps, waitingOn: runWaitingOn(steps) };
7466
+ return {
7467
+ conversation,
7468
+ steps,
7469
+ waitingOn: runWaitingOn(steps),
7470
+ signals: raisedSignals(activity),
7471
+ linkedRuns: linkedRuns(activity),
7472
+ sendBacks: sendBacks(activity)
7473
+ };
6976
7474
  }
6977
7475
  async function getStepAnswers(arbi, conversationId, responseIds) {
6978
7476
  if (!responseIds.length) return {};
@@ -7351,8 +7849,15 @@ var Arbi = class {
7351
7849
  }
7352
7850
  // ── Projects ──────────────────────────────────────────────────────────
7353
7851
  projects = {
7354
- list: () => listProjects(this.requireClient()),
7355
- create: (name) => createProject(this.requireClient(), name),
7852
+ /** The caller's projects; only those at `stage` and/or led by `leadUser` when given. */
7853
+ list: (filters) => listProjects(this.requireClient(), filters),
7854
+ create: (name, plan, details) => createProject(this.requireClient(), name, plan, details),
7855
+ /** Patch a project: name, daily cap, budget, client, stage, lead, fields (merged key by key). */
7856
+ update: (projectExtId, body) => updateProject(this.requireClient(), projectExtId, body),
7857
+ /** The project's stage and budget changes, newest first. */
7858
+ events: (projectExtId, options) => listProjectEvents(this.requireClient(), projectExtId, options),
7859
+ /** The project's spend by conversation in a billing period (credits). */
7860
+ usageByConversation: (projectExtId, monthsBack) => getProjectConversationUsage(this.requireClient(), projectExtId, monthsBack),
7356
7861
  refresh: (projectExtId) => refreshProject(this.requireClient(), projectExtId),
7357
7862
  /** AI usage + spend breakdown for a project's billing period. */
7358
7863
  usage: (projectExtId, monthsBack) => getProjectUsage(this.requireClient(), projectExtId, monthsBack),
@@ -7629,6 +8134,16 @@ var Arbi = class {
7629
8134
  activity: (conversationId) => getActivity(this.requireClient(), conversationId),
7630
8135
  /** Complete or skip a step of a workflow run; the run goes on to its next agent step. */
7631
8136
  actOnStep: (conversationId, body) => actOnStep(this.requireClient(), conversationId, body),
8137
+ /** Complete a person step (with its inputs, checked against the step's `fields`). */
8138
+ completeStep: (conversationId, step, inputs) => completeStep(this.requireClient(), conversationId, step, inputs),
8139
+ /** Skip a step so what waits for it can go on. */
8140
+ skipStep: (conversationId, step) => skipStep(this.requireClient(), conversationId, step),
8141
+ /** Send the work back from a person step to an earlier one (`to`), with an optional note. */
8142
+ sendBackStep: (conversationId, step, options) => sendBackStep(this.requireClient(), conversationId, step, options),
8143
+ /** A stepped run's steps, signals, linked runs and send-backs, and what it waits for. */
8144
+ runProgress: (conversationId) => getRunProgress(this.requireClient(), conversationId),
8145
+ /** What the conversation's AI work cost: by step, run, model, agent and feature (credits). */
8146
+ usage: (conversationId) => getConversationUsage(this.requireClient(), conversationId),
7632
8147
  /** Notify people about a conversation (each gets a notification); resolves with who was. */
7633
8148
  notify: (conversationId, userIds) => notifyConversation(this.requireClient(), conversationId, userIds),
7634
8149
  /** Draft an editable plan from an objective. */
@@ -7772,7 +8287,11 @@ var Arbi = class {
7772
8287
  workspaceId: options.workspaceId ?? this.requireWorkspace()
7773
8288
  }),
7774
8289
  delete: (tagId) => deleteTag(this.requireClient(), tagId),
7775
- update: (tagId, body) => updateTag(this.requireClient(), tagId, body)
8290
+ update: (tagId, body) => updateTag(this.requireClient(), tagId, body),
8291
+ /** Replace a tag's own field definitions and/or merge-patch its values (`null` clears one). */
8292
+ updateFields: (tagId, change) => updateTagFields(this.requireClient(), tagId, change),
8293
+ /** Tags as rows (a parent's children, or the given tags) with field values, docs and facts. */
8294
+ matrix: (selection, linksLimit) => getTagMatrix(this.requireClient(), selection, linksLimit)
7776
8295
  };
7777
8296
  // ── Document Tags ─────────────────────────────────────────────────────
7778
8297
  doctags = {