@arbidocs/sdk 0.5.101 → 0.5.103

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
@@ -4741,1899 +4741,1915 @@ function withSupportNotificationReference(notification, domain) {
4741
4741
  }
4742
4742
  }
4743
4743
 
4744
- // src/diagnostics.ts
4745
- async function diagnoseSetup(options) {
4746
- const checks = [];
4747
- const add = (check, status, message, hint) => checks.push({ check, status, message, ...hint ? { hint } : {} });
4748
- let base;
4749
- try {
4750
- base = new URL(options.url);
4751
- if (!["http:", "https:"].includes(base.protocol) || base.username || base.password || base.search || base.hash)
4752
- throw new Error("Invalid API URL");
4753
- } catch {
4754
- add(
4755
- "connection",
4756
- "error",
4757
- "Invalid API URL.",
4758
- "Use an absolute HTTP(S) API URL without credentials, query or fragment."
4759
- );
4760
- return { ok: false, checks };
4761
- }
4762
- const request = (path2, authenticated = false) => (options.fetch ?? globalThis.fetch)(`${base.href.replace(/\/$/, "")}${path2}`, {
4763
- method: "GET",
4764
- credentials: "omit",
4765
- redirect: "error",
4766
- cache: "no-store",
4767
- headers: authenticated && options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {},
4768
- signal: AbortSignal.timeout(options.timeoutMs ?? 1e4)
4769
- });
4770
- try {
4771
- const config = await request("/config.json");
4772
- if (!config.ok) {
4773
- add(
4774
- "connection",
4775
- "error",
4776
- `Deployment configuration returned HTTP ${config.status}.`,
4777
- "Check the API base URL and proxy routing."
4778
- );
4779
- } else {
4780
- const body = await config.json();
4781
- add("connection", "ok", "Deployment configuration is reachable.");
4782
- const domain = body?.deployment?.domain;
4783
- if (typeof domain !== "string" || !domain) {
4784
- add(
4785
- "deployment",
4786
- "warning",
4787
- "The deployment did not advertise its key-derivation domain.",
4788
- "Confirm deploymentDomain with the deployment owner, especially when using a proxy."
4789
- );
4790
- } else if (domain !== (options.deploymentDomain ?? base.hostname)) {
4791
- add(
4792
- "deployment",
4793
- "error",
4794
- "The configured key-derivation domain differs from the deployment.",
4795
- "Set deploymentDomain to the deployment\u2019s domain; a proxy hostname is not the key-derivation domain."
4796
- );
4797
- } else add("deployment", "ok", "The key-derivation domain matches the deployment.");
4798
- }
4799
- } catch {
4800
- add(
4801
- "connection",
4802
- "error",
4803
- "Could not read deployment configuration.",
4804
- "Check DNS, TLS, proxy routing and connectivity. In a browser, inspect DevTools for CORS, mixed-content or private-network denial; fetch alone cannot distinguish them."
4805
- );
4806
- }
4807
- if (!options.accessToken) {
4808
- add(
4809
- "authentication",
4810
- "warning",
4811
- "No live session token is available.",
4812
- "Sign in explicitly when online. An offline-unlocked identity is not a verified server session."
4813
- );
4814
- add("workspace", "skipped", "Workspace access was not checked.");
4815
- add("permissions", "skipped", "Permissions were not checked.");
4816
- } else {
4817
- let authenticated = false;
4818
- try {
4819
- const user = await request("/v1/user/me", true);
4820
- if (!user.ok) {
4821
- add(
4822
- "authentication",
4823
- "error",
4824
- `Session check returned HTTP ${user.status}.`,
4825
- user.status === 401 ? "Sign in explicitly to renew the session." : "Check deployment access and account permissions."
4826
- );
4827
- add("workspace", "skipped", "Workspace access was not checked.");
4828
- add("permissions", "skipped", "Permissions were not checked.");
4829
- } else {
4830
- const profile = await user.json();
4831
- authenticated = true;
4832
- add("authentication", "ok", "The server accepts the current session.");
4833
- if (!options.workspaceId) {
4834
- add(
4835
- "workspace",
4836
- "warning",
4837
- "No current workspace is selected.",
4838
- "Choose a workspace explicitly before reading documents or starting work."
4839
- );
4840
- add("permissions", "skipped", "Select a workspace to check membership.");
4841
- } else {
4842
- const response = await request("/v1/user/workspaces", true);
4843
- if (!response.ok) {
4844
- add(
4845
- "workspace",
4846
- "error",
4847
- `Workspace membership check returned HTTP ${response.status}.`,
4848
- "Check current account access; diagnosis does not switch workspaces or grant access."
4849
- );
4850
- add("permissions", "skipped", "Membership could not be verified.");
4851
- } else {
4852
- const workspaces = await response.json();
4853
- const workspace = Array.isArray(workspaces) ? workspaces.find((w2) => w2.external_id === options.workspaceId) : void 0;
4854
- if (!workspace) {
4855
- add(
4856
- "workspace",
4857
- "error",
4858
- "The selected workspace is not in this account\u2019s workspace list.",
4859
- "Choose an accessible workspace explicitly. Project visibility does not imply workspace access."
4860
- );
4861
- add("permissions", "skipped", "Workspace permissions could not be verified.");
4862
- } else {
4863
- add(
4864
- "workspace",
4865
- "ok",
4866
- "The selected workspace appears in the account\u2019s workspace list."
4867
- );
4868
- const member = workspace.users?.find(
4869
- (entry) => entry.user?.external_id === profile.external_id
4870
- );
4871
- const role = ["owner", "collaborator", "guest"].includes(member?.role) ? member.role : null;
4872
- add(
4873
- "permissions",
4874
- role ? "ok" : "warning",
4875
- role ? `Workspace membership role: ${role}.` : "No direct membership role was reported.",
4876
- "This is a membership check, not proof of a live workspace key or authorization for an agent task. Temporary grants, expiry and execution permissions remain enforced by the API."
4877
- );
4878
- }
4879
- }
4880
- }
4881
- }
4882
- } catch {
4883
- add(
4884
- authenticated ? "workspace" : "authentication",
4885
- "error",
4886
- authenticated ? "The workspace membership check could not finish." : "The session check could not finish.",
4887
- "Check connectivity and browser network policy. No login, workspace switch or grant was attempted."
4888
- );
4889
- if (authenticated)
4890
- add("permissions", "skipped", "Workspace membership could not be verified.");
4891
- }
4892
- }
4893
- return { ok: checks.every((c2) => c2.status === "ok"), checks };
4894
- }
4895
-
4896
- // src/operations/responses.ts
4897
- var responses_exports = {};
4898
- __export(responses_exports, {
4899
- extractResponseText: () => extractResponseText,
4900
- getResponse: () => getResponse,
4901
- submitBackgroundQuery: () => submitBackgroundQuery
4744
+ // src/operations/workspaces.ts
4745
+ var workspaces_exports = {};
4746
+ __export(workspaces_exports, {
4747
+ EXTERNAL_ACCESS_SECONDS: () => EXTERNAL_ACCESS_SECONDS,
4748
+ WORKSPACE_ROLE_LABELS: () => WORKSPACE_ROLE_LABELS,
4749
+ addWorkspaceMembers: () => addWorkspaceMembers,
4750
+ addWorkspaceMembersBody: () => addWorkspaceMembersBody,
4751
+ addWorkspaceUsers: () => addWorkspaceUsers,
4752
+ archiveWorkspace: () => archiveWorkspace,
4753
+ cancelWorkspaceTransfer: () => cancelWorkspaceTransfer,
4754
+ copyDocuments: () => copyDocuments,
4755
+ createWorkspace: () => createWorkspace,
4756
+ deleteWorkspaces: () => deleteWorkspaces,
4757
+ exportWorkspaceData: () => exportWorkspaceData,
4758
+ getWorkspaceAccessStatus: () => getWorkspaceAccessStatus,
4759
+ getWorkspaceActivity: () => getWorkspaceActivity,
4760
+ getWorkspaceArchive: () => getWorkspaceArchive,
4761
+ getWorkspaceTransfer: () => getWorkspaceTransfer,
4762
+ grantTemporaryWorkspaceAccess: () => grantTemporaryWorkspaceAccess,
4763
+ listWorkspaceTransfers: () => listWorkspaceTransfers,
4764
+ listWorkspaceUsers: () => listWorkspaceUsers,
4765
+ listWorkspaces: () => listWorkspaces,
4766
+ moveWorkspaceToProject: () => moveWorkspaceToProject,
4767
+ parseWorkspaceRole: () => parseWorkspaceRole,
4768
+ planWorkspaceTransfer: () => planWorkspaceTransfer,
4769
+ primeWorkspaceKey: () => primeWorkspaceKey,
4770
+ removeWorkspaceUsers: () => removeWorkspaceUsers,
4771
+ resumeWorkspaceTransfer: () => resumeWorkspaceTransfer,
4772
+ setUserRole: () => setUserRole,
4773
+ startWorkspaceTransfer: () => startWorkspaceTransfer,
4774
+ unarchiveWorkspace: () => unarchiveWorkspace,
4775
+ updateWorkspace: () => updateWorkspace,
4776
+ workspaceRoleLabel: () => workspaceRoleLabel
4902
4777
  });
4903
- async function submitBackgroundQuery(options) {
4904
- const {
4905
- workspaceId,
4906
- question,
4907
- docIds,
4908
- previousResponseId,
4909
- model,
4910
- text: text2,
4911
- task,
4912
- conversationId,
4913
- mentions,
4914
- activeArtifactExtId,
4915
- fullContext = true,
4916
- ...auth
4917
- } = options;
4918
- const tools = {};
4919
- if (docIds.length > 0) {
4920
- tools.retrieval_chunk = {
4921
- name: "retrieval_chunk",
4922
- description: "retrieval chunk",
4923
- tool_args: { doc_ext_ids: docIds },
4924
- tool_responses: {}
4925
- };
4926
- if (fullContext)
4927
- tools.retrieval_full_context = {
4928
- name: "retrieval_full_context",
4929
- description: "retrieval full context",
4930
- tool_args: { doc_ext_ids: docIds },
4931
- tool_responses: {}
4932
- };
4933
- }
4934
- const body = {
4935
- input: question,
4936
- workspace_ext_id: workspaceId,
4937
- stream: false,
4938
- background: true,
4939
- store: true,
4940
- tools,
4941
- ...task !== void 0 ? { task } : {},
4942
- ...conversationId ? { conversation_ext_id: conversationId } : {},
4943
- ...mentions !== void 0 ? { mentions } : {},
4944
- ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
4945
- ...previousResponseId ? { previous_response_id: previousResponseId } : {},
4946
- ...model ? { model } : {},
4947
- ...text2 ? { text: text2 } : {}
4948
- };
4949
- const res = await authenticatedFetch({
4950
- ...auth,
4951
- path: "/v1/responses",
4952
- method: "POST",
4953
- body: JSON.stringify(body),
4954
- headers: { "Content-Type": "application/json" }
4955
- });
4956
- return await res.json();
4778
+ var WORKSPACE_ROLE_LABELS = {
4779
+ owner: "Owner",
4780
+ collaborator: "Collaborator",
4781
+ guest: "Read only"
4782
+ };
4783
+ function workspaceRoleLabel(role) {
4784
+ return WORKSPACE_ROLE_LABELS[role] ?? role.charAt(0).toUpperCase() + role.slice(1);
4957
4785
  }
4958
- async function getResponse(auth, responseId) {
4959
- const res = await authenticatedFetch({
4960
- ...auth,
4961
- path: `/v1/responses/${responseId}`,
4962
- method: "GET"
4963
- });
4964
- return await res.json();
4786
+ function parseWorkspaceRole(input) {
4787
+ const value = input.trim().toLowerCase();
4788
+ if (value === "owner" || value === "collaborator" || value === "guest") return value;
4789
+ return /^read[-_ ]?only$/.test(value) ? "guest" : null;
4965
4790
  }
4966
- function extractResponseText(response) {
4967
- const parts = [];
4968
- for (const msg of Array.isArray(response.output) ? response.output : []) {
4969
- if (msg.type !== "message" || !Array.isArray(msg.content)) continue;
4970
- for (const item of msg.content) {
4971
- if (item?.type === "output_text" && typeof item.text === "string") parts.push(item.text);
4972
- }
4973
- }
4974
- return parts.join("");
4975
- }
4976
-
4977
- // src/responses-resource.ts
4978
- function withOutputText(response, requestId) {
4979
- return {
4980
- ...response,
4981
- output_text: extractResponseText(response),
4982
- ...requestId ? { _request_id: requestId } : {}
4983
- };
4984
- }
4985
- var ResponseStream = class {
4986
- constructor(handle) {
4987
- this.handle = handle;
4988
- }
4989
- handle;
4990
- async *[Symbol.asyncIterator]() {
4991
- try {
4992
- for await (const frame of this.handle.events()) {
4993
- const data = frame.data && typeof frame.data === "object" && !Array.isArray(frame.data) ? frame.data : { data: frame.data };
4994
- yield {
4995
- ...data,
4996
- type: typeof data.type === "string" ? data.type : frame.event
4997
- };
4998
- }
4999
- const outcome = await this.handle.outcome;
5000
- if (outcome.status === "disconnected")
5001
- throw outcome.error ?? new ArbiTransportError(new Error("The response stream disconnected."), this.handle.id);
5002
- } finally {
5003
- this.handle.detach();
5004
- }
5005
- }
5006
- };
5007
-
5008
- // src/structured-output.ts
5009
- var ArbiStructuredOutputError = class extends ArbiError {
5010
- constructor(message, response, options) {
5011
- const id = response && typeof response === "object" && "id" in response && typeof response.id === "string" ? response.id : void 0;
5012
- super(message, { responseId: id, ...options });
5013
- this.response = response;
5014
- this.name = "ArbiStructuredOutputError";
5015
- }
5016
- response;
5017
- };
5018
- function localReferences(value) {
5019
- if (Array.isArray(value)) {
5020
- value.forEach(localReferences);
5021
- return;
5022
- }
5023
- if (!value || typeof value !== "object") return;
5024
- for (const [key, child] of Object.entries(value)) {
5025
- if ((key === "$ref" || key === "$dynamicRef") && (typeof child !== "string" || !child.startsWith("#")))
5026
- throw new Error("Only local schema references are supported.");
5027
- if (!["enum", "const", "default", "examples"].includes(key)) localReferences(child);
5028
- }
5029
- }
5030
- async function createStructuredParser(format) {
5031
- let validate;
5032
- let Constructor;
5033
- try {
5034
- Constructor = (await import('ajv/dist/2020.js')).default;
5035
- } catch (cause) {
5036
- throw new ArbiStructuredOutputError(
5037
- "The JSON Schema validator could not be loaded.",
5038
- void 0,
5039
- { code: "STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE", cause }
5040
- );
5041
- }
5042
- try {
5043
- if (format.type !== "json_schema" || typeof format.name !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(format.name) || !format.schema || typeof format.schema !== "object" || Array.isArray(format.schema))
5044
- throw new Error("Invalid structured output format.");
5045
- if (format.schema.$schema !== void 0 && format.schema.$schema !== "https://json-schema.org/draft/2020-12/schema")
5046
- throw new Error("Expected JSON Schema draft 2020-12.");
5047
- localReferences(format.schema);
5048
- validate = new Constructor({
5049
- strict: false,
5050
- logger: false,
5051
- validateFormats: false,
5052
- strictNumbers: true,
5053
- addUsedSchema: false
5054
- }).compile(format.schema);
5055
- } catch (cause) {
5056
- const unavailable = cause instanceof EvalError;
5057
- throw new ArbiStructuredOutputError(
5058
- unavailable ? "This runtime cannot compile JSON Schema validators." : "Invalid or unsupported output schema.",
5059
- void 0,
5060
- {
5061
- code: unavailable ? "STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE" : "STRUCTURED_OUTPUT_SCHEMA_INVALID",
5062
- cause
5063
- }
5064
- );
5065
- }
5066
- return (response, options = {}) => {
5067
- const fail = (code, message, cause) => {
5068
- throw new ArbiStructuredOutputError(message, response, { ...options, code, cause });
5069
- };
5070
- if (!response || typeof response !== "object")
5071
- fail("RESPONSE_INVALID_ENVELOPE", "Expected a Responses JSON object.");
5072
- if (response.status === "incomplete")
5073
- fail("RESPONSE_INCOMPLETE", "The response is incomplete; no validated data is available.");
5074
- if (response.status === "cancelled")
5075
- fail("RESPONSE_CANCELLED", "The response was cancelled; no validated data is available.");
5076
- if (response.status === "failed")
5077
- fail(
5078
- typeof response.error?.code === "string" ? response.error.code : "RESPONSE_FAILED",
5079
- typeof response.error?.message === "string" ? response.error.message : "The response failed."
5080
- );
5081
- if (response.status !== "completed")
5082
- fail(
5083
- "RESPONSE_NOT_COMPLETED",
5084
- "Wait for a completed response before parsing structured output."
5085
- );
5086
- const messages = Array.isArray(response.output) ? response.output.filter(
5087
- (item) => item && typeof item === "object" && item.type === "message" && item.role === "assistant"
5088
- ) : [];
5089
- if (messages.some(
5090
- (message) => !Array.isArray(message.content) || message.content.some((part) => !part || typeof part !== "object")
5091
- ))
5092
- fail("RESPONSE_INVALID_ENVELOPE", "Invalid assistant output content.");
5093
- if (messages.some((message) => message.content.some((part) => part.type === "refusal")))
5094
- fail("RESPONSE_REFUSED", "The model refused this response.");
5095
- const answers = messages.map(
5096
- (message) => message.content.filter((part) => part.type === "output_text" && typeof part.text === "string").map((part) => part.text).join("")
5097
- ).filter((answer) => answer.length > 0);
5098
- if (answers.length !== 1)
5099
- fail(
5100
- "STRUCTURED_OUTPUT_AMBIGUOUS",
5101
- "Expected one final assistant output message; narrative and answer text are not joined."
5102
- );
5103
- let data;
5104
- try {
5105
- data = JSON.parse(answers[0]);
5106
- } catch (cause) {
5107
- fail("STRUCTURED_OUTPUT_INVALID_JSON", "The response is not valid JSON.", cause);
5108
- }
5109
- if (!validate(data))
5110
- fail("STRUCTURED_OUTPUT_INVALID", "The response did not match the requested JSON schema.");
5111
- return { data, response };
5112
- };
5113
- }
5114
- async function parseStructuredResponse(response, format) {
5115
- return (await createStructuredParser(format))(response);
5116
- }
5117
-
5118
- // src/response-handle.ts
5119
- var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5120
- var text = (value) => typeof value === "string" ? value : void 0;
5121
- var messageId = (value) => typeof value === "string" && /^msg-[\w-]+$/.test(value);
5122
- function immutable(value) {
5123
- if (value && typeof value === "object" && !(value instanceof Error) && !Object.isFrozen(value)) {
5124
- Object.freeze(value);
5125
- for (const child of Object.values(value)) immutable(child);
5126
- }
5127
- return value;
5128
- }
5129
- function reportObserverError(error) {
5130
- queueMicrotask(() => {
5131
- throw error;
5132
- });
5133
- }
5134
- var ResponseEventDecoder = class {
5135
- buffer = "";
5136
- event = "";
5137
- data = [];
5138
- id;
5139
- push(chunk, final = false) {
5140
- this.buffer += chunk;
5141
- const frames = [];
5142
- const dispatch = () => {
5143
- if (this.data.length)
5144
- frames.push({
5145
- event: this.event || "message",
5146
- data: this.data.join("\n"),
5147
- ...this.id !== void 0 ? { id: this.id } : {}
5148
- });
5149
- this.event = "";
5150
- this.data = [];
5151
- this.id = void 0;
5152
- };
5153
- const line = (value) => {
5154
- if (!value) {
5155
- dispatch();
5156
- return;
5157
- }
5158
- if (value.startsWith(":")) return;
5159
- const colon = value.indexOf(":");
5160
- const field = colon < 0 ? value : value.slice(0, colon);
5161
- let content = colon < 0 ? "" : value.slice(colon + 1);
5162
- if (content.startsWith(" ")) content = content.slice(1);
5163
- if (field === "event") this.event = content;
5164
- if (field === "data") this.data.push(content);
5165
- if (field === "id" && !content.includes("\0")) this.id = content;
5166
- };
5167
- while (true) {
5168
- const index = this.buffer.search(/[\r\n]/);
5169
- if (index < 0 || !final && index === this.buffer.length - 1 && this.buffer[index] === "\r")
5170
- break;
5171
- const width = this.buffer[index] === "\r" && this.buffer[index + 1] === "\n" ? 2 : 1;
5172
- line(this.buffer.slice(0, index));
5173
- this.buffer = this.buffer.slice(index + width);
5174
- }
5175
- if (final) {
5176
- if (this.buffer) line(this.buffer);
5177
- this.buffer = "";
5178
- dispatch();
5179
- }
5180
- return frames;
5181
- }
5182
- };
5183
- function consumeResponse(response, controller, cancel, options = {}) {
5184
- if (!response.body)
5185
- return Promise.reject(
5186
- new ArbiApiError("Response has no stream body.", void 0, response.status, {
5187
- code: "MISSING_RESPONSE_BODY"
5188
- })
5189
- );
5190
- const reader = response.body.getReader();
5191
- let resolveStart;
5192
- let rejectStart;
5193
- const start = new Promise((resolve, reject) => {
5194
- resolveStart = resolve;
5195
- rejectStart = reject;
5196
- });
5197
- let resolveOutcome;
5198
- const outcome = new Promise((resolve) => {
5199
- resolveOutcome = resolve;
5200
- });
5201
- let state = immutable({
5202
- id: options.id ?? "",
5203
- conversationId: null,
5204
- connection: "connecting",
5205
- responseStatus: null,
5206
- output: [],
5207
- displayText: ""
5208
- });
5209
- let bound = false;
5210
- let finished = false;
5211
- let acknowledgement;
5212
- const listeners = /* @__PURE__ */ new Set();
5213
- const queue = [];
5214
- let capacityAvailable;
5215
- const releaseCapacity = () => {
5216
- capacityAvailable?.();
5217
- capacityAvailable = void 0;
5218
- };
5219
- let claimed = false;
5220
- let iteratorClosed = false;
5221
- let iteratorError;
5222
- let pending;
5223
- const emit = (event) => {
5224
- if (!claimed && !options.bufferEvents || iteratorClosed) return;
5225
- if (pending) {
5226
- pending.resolve({ value: immutable(event), done: false });
5227
- pending = void 0;
5228
- } else if (queue.length < 256) queue.push(immutable(event));
5229
- else {
5230
- iteratorError = new ArbiError("Raw response event consumer fell behind.", {
5231
- code: "RESPONSE_EVENT_OVERFLOW"
5232
- });
5233
- queue.length = 0;
5234
- iteratorClosed = true;
5235
- }
5236
- };
5237
- const notify = () => {
5238
- for (const listener of [...listeners]) {
5239
- try {
5240
- listener(state);
5241
- } catch (error) {
5242
- reportObserverError(error);
5243
- }
5244
- }
5245
- };
5246
- const update = (patch) => {
5247
- state = immutable({ ...state, ...patch });
5248
- notify();
5249
- };
5250
- const finish = (value, detached = false) => {
5251
- if (finished) return;
5252
- finished = true;
5253
- releaseCapacity();
5254
- controller.signal.removeEventListener("abort", abort);
5255
- options.cleanup?.();
5256
- update({ connection: detached ? "detached" : "closed", outcome: immutable(value) });
5257
- listeners.clear();
5258
- resolveOutcome(state.outcome);
5259
- if (pending) {
5260
- pending.resolve({ value: void 0, done: true });
5261
- pending = void 0;
5262
- }
5263
- void reader.cancel().catch(() => {
5264
- });
5265
- };
5266
- const abort = () => {
5267
- if (!bound) rejectStart(new DOMException("The operation was aborted.", "AbortError"));
5268
- finish({ status: "disconnected", responseId: bound ? state.id : null, reason: "aborted" }, true);
5269
- queue.length = 0;
5270
- };
5271
- const handle = {
5272
- get id() {
5273
- return state.id;
5274
- },
5275
- snapshot: () => state,
5276
- subscribe(listener) {
5277
- if (!finished) listeners.add(listener);
5278
- try {
5279
- listener(state);
5280
- } catch (error) {
5281
- reportObserverError(error);
5282
- }
5283
- return () => {
5284
- listeners.delete(listener);
5285
- };
5286
- },
5287
- outcome,
5288
- detach: () => {
5289
- if (!finished) controller.abort();
5290
- },
5291
- cancel: () => cancel(state.id),
5292
- events() {
5293
- if (claimed)
5294
- throw new ArbiError("A response handle supports one raw event iterator.", {
5295
- code: "RESPONSE_EVENTS_ALREADY_CLAIMED"
5296
- });
5297
- claimed = true;
5298
- const close = () => {
5299
- iteratorClosed = true;
5300
- queue.length = 0;
5301
- releaseCapacity();
5302
- if (pending) {
5303
- pending.resolve({ value: void 0, done: true });
5304
- pending = void 0;
5305
- }
5306
- };
5307
- return {
5308
- [Symbol.asyncIterator]() {
5309
- return this;
5310
- },
5311
- next() {
5312
- if (iteratorError) return Promise.reject(iteratorError);
5313
- if (queue.length) {
5314
- const value = queue.shift();
5315
- releaseCapacity();
5316
- return Promise.resolve({ value, done: false });
5317
- }
5318
- if (finished || iteratorClosed)
5319
- return Promise.resolve({ value: void 0, done: true });
5320
- if (pending)
5321
- return Promise.reject(
5322
- new ArbiError("Concurrent iterator reads are unsupported.", {
5323
- code: "RESPONSE_EVENTS_CONCURRENT_READ"
5324
- })
5325
- );
5326
- return new Promise((resolve, reject) => {
5327
- pending = { resolve, reject };
5328
- });
5329
- },
5330
- async return() {
5331
- close();
5332
- return { value: void 0, done: true };
5333
- },
5334
- async throw(error) {
5335
- close();
5336
- throw error;
5337
- }
5338
- };
5339
- }
5340
- };
5341
- const bind = (id) => {
5342
- if (bound) return;
5343
- bound = true;
5344
- state = immutable({ ...state, id, connection: "streaming" });
5345
- resolveStart({ kind: "response", handle });
5346
- };
5347
- const diagnostic = (code, frame) => emit({ event: "arbi.sdk.protocol_error", data: { code, frame } });
5348
- const process = (frame) => {
5349
- if (finished) return;
5350
- let data;
5351
- if (frame.event === "reasoning") {
5352
- emit({
5353
- event: frame.event,
5354
- data: frame.data,
5355
- ...frame.id !== void 0 ? { id: frame.id } : {}
5356
- });
5357
- return;
5358
- }
5359
- try {
5360
- data = JSON.parse(frame.data);
5361
- } catch {
5362
- diagnostic("MALFORMED_JSON", frame);
5363
- return;
5364
- }
5365
- const payload = object(data);
5366
- const raw = object(payload?.response);
5367
- const id = raw?.id;
5368
- if (bound && typeof id === "string" && id !== state.id) {
5369
- diagnostic("CONFLICTING_RESPONSE_ID", frame);
5370
- return;
5371
- }
5372
- if (messageId(id)) bind(id);
5373
- emit({ event: frame.event, data, ...frame.id !== void 0 ? { id: frame.id } : {} });
5374
- if (frame.event === "arbi.message_queued") acknowledgement = payload;
5375
- const patch = {};
5376
- if (frame.event === "arbi.user_message" && !state.conversationId && typeof payload?.conversation_ext_id === "string")
5377
- patch.conversationId = payload.conversation_ext_id;
5378
- if (raw) {
5379
- patch.rawResponse = raw;
5380
- if (typeof raw.status === "string") patch.responseStatus = raw.status;
5381
- if (Array.isArray(raw.output))
5382
- patch.output = raw.output.filter((item2) => !!object(item2));
5383
- const metadata = object(raw.metadata);
5384
- const conversation = text(metadata?.conversation_ext_id) ?? text(metadata?.conversation_id) ?? text(raw.conversation_id);
5385
- if (conversation && (!state.conversationId || state.conversationId === conversation))
5386
- patch.conversationId = conversation;
5387
- if (typeof metadata?.content === "string") patch.displayText = metadata.content;
5388
- }
5389
- const item = object(payload?.item);
5390
- if ((frame.event === "response.output_item.added" || frame.event === "response.output_item.done") && item) {
5391
- const output = [...state.output];
5392
- const index = output.findIndex((existing) => existing.id === item.id);
5393
- if (index >= 0 && item.id) output[index] = item;
5394
- else
5395
- output.splice(
5396
- typeof payload?.output_index === "number" ? payload.output_index : output.length,
5397
- 0,
5398
- item
5399
- );
5400
- patch.output = output;
5401
- }
5402
- const itemId = text(payload?.item_id);
5403
- const delta = text(payload?.delta);
5404
- if (itemId && [
5405
- "response.content_part.added",
5406
- "response.output_text.delta",
5407
- "response.output_text.done",
5408
- "response.function_call_arguments.delta",
5409
- "response.reasoning_summary_text.delta"
5410
- ].includes(frame.event)) {
5411
- const output = [...patch.output ?? state.output];
5412
- let index = output.findIndex((existing) => existing.id === itemId);
5413
- if (index < 0) {
5414
- index = output.length;
5415
- output.push({
5416
- id: itemId,
5417
- type: frame.event.includes("function_call") ? "function_call" : frame.event.includes("reasoning") ? "reasoning" : "message"
5418
- });
5419
- }
5420
- const current = { ...output[index] };
5421
- if (frame.event === "response.function_call_arguments.delta")
5422
- current.arguments = (text(current.arguments) ?? "") + (delta ?? "");
5423
- else {
5424
- const key = frame.event.includes("reasoning") ? "summary" : "content";
5425
- const content = Array.isArray(current[key]) ? [...current[key]] : [];
5426
- const partIndex = typeof payload?.content_index === "number" ? payload.content_index : typeof payload?.summary_index === "number" ? payload.summary_index : 0;
5427
- const part = {
5428
- ...object(content[partIndex]) ?? {
5429
- type: key === "summary" ? "summary_text" : "output_text",
5430
- text: ""
5431
- }
5432
- };
5433
- if (frame.event === "response.content_part.added")
5434
- content[partIndex] = object(payload?.part) ?? part;
5435
- else {
5436
- part.text = frame.event === "response.output_text.done" ? text(payload?.text) ?? "" : (text(part.text) ?? "") + (delta ?? "");
5437
- content[partIndex] = part;
5438
- }
5439
- current[key] = content;
5440
- }
5441
- output[index] = current;
5442
- patch.output = output;
5443
- }
5444
- if (frame.event === "response.output_text.delta" && delta)
5445
- patch.displayText = state.displayText + delta;
5446
- if (frame.event === "response.output_text.done" && typeof payload?.text === "string")
5447
- patch.displayText = payload.text;
5448
- update(patch);
5449
- const terminal = /^response\.(completed|failed|cancelled|incomplete)$/.exec(
5450
- frame.event
5451
- )?.[1];
5452
- if (terminal && bound) {
5453
- const status = raw?.status;
5454
- const resolved = status === "completed" || status === "failed" || status === "cancelled" || status === "incomplete" ? status : terminal;
5455
- const error = resolved === "failed" || raw?.error ? new ArbiApiError(
5456
- text(object(raw?.error)?.message) ?? "Response failed.",
5457
- { response: raw },
5458
- void 0,
5459
- { ...apiErrorMetadata({ response: raw }), responseId: state.id }
5460
- ) : void 0;
5461
- finish({
5462
- status: resolved,
5463
- responseId: state.id,
5464
- ...raw ? { response: raw } : {},
5465
- ...error ? { error } : {}
5466
- });
5467
- }
5468
- };
5469
- controller.signal.addEventListener("abort", abort, { once: true });
5470
- if (controller.signal.aborted) abort();
5471
- else if (options.id) bind(options.id);
5472
- void (async () => {
5473
- const decoder = new TextDecoder();
5474
- const frames = new ResponseEventDecoder();
5475
- try {
5476
- while (!finished) {
5477
- const { value, done } = await reader.read();
5478
- for (const frame of frames.push(decoder.decode(value, { stream: !done }), done)) {
5479
- process(frame);
5480
- if (options.bufferEvents && bound && !finished && !iteratorClosed && queue.length >= 256)
5481
- await new Promise((resolve) => {
5482
- capacityAvailable = resolve;
5483
- });
5484
- }
5485
- if (done) break;
4791
+ async function listWorkspaces(arbi) {
4792
+ return requireData(await arbi.fetch.GET("/v1/user/workspaces"), "Failed to fetch workspaces");
4793
+ }
4794
+ async function createWorkspace(arbi, name, encryptedWorkspaceKey, projectExtId, description, isPublic = false) {
4795
+ return requireData(
4796
+ await arbi.fetch.POST("/v1/workspace/create_protected", {
4797
+ body: {
4798
+ name,
4799
+ description: description ?? null,
4800
+ is_public: isPublic,
4801
+ workspace_key: encryptedWorkspaceKey,
4802
+ project_ext_id: projectExtId
5486
4803
  }
5487
- if (!finished) {
5488
- if (!bound && acknowledgement) {
5489
- const value = { status: "acknowledged", responseId: null };
5490
- resolveStart({
5491
- kind: "acknowledged",
5492
- acknowledgement: immutable(acknowledgement),
5493
- outcome: immutable(value)
5494
- });
5495
- finish(value);
5496
- } else {
5497
- if (!bound)
5498
- rejectStart(
5499
- new ArbiApiError(
5500
- "Stream ended before response identity was established.",
5501
- void 0,
5502
- void 0,
5503
- { code: "MISSING_RESPONSE_ID" }
5504
- )
5505
- );
5506
- finish({
5507
- status: "disconnected",
5508
- responseId: bound ? state.id : null,
5509
- reason: "connection_closed"
5510
- });
5511
- }
4804
+ }),
4805
+ "Failed to create workspace"
4806
+ );
4807
+ }
4808
+ async function moveWorkspaceToProject(arbi, workspaceExtId, projectExtId) {
4809
+ return requireData(
4810
+ await arbi.fetch.PUT("/v1/workspace/{workspace_ext_id}/project", {
4811
+ params: { path: { workspace_ext_id: workspaceExtId } },
4812
+ body: { project_ext_id: projectExtId }
4813
+ }),
4814
+ "Failed to move workspace"
4815
+ );
4816
+ }
4817
+ async function getWorkspaceArchive(arbi, workspaceExtId) {
4818
+ return requireData(
4819
+ await arbi.fetch.GET("/v1/workspace/{workspace_ext_id}/archive", {
4820
+ params: { path: { workspace_ext_id: workspaceExtId } }
4821
+ }),
4822
+ "Could not read the archive state"
4823
+ );
4824
+ }
4825
+ async function archiveWorkspace(arbi, workspaceExtId) {
4826
+ return requireData(
4827
+ await arbi.fetch.POST("/v1/workspace/{workspace_ext_id}/archive", {
4828
+ params: { path: { workspace_ext_id: workspaceExtId } }
4829
+ }),
4830
+ "Could not archive the workspace"
4831
+ );
4832
+ }
4833
+ async function unarchiveWorkspace(arbi, workspaceExtId) {
4834
+ return requireData(
4835
+ await arbi.fetch.POST("/v1/workspace/{workspace_ext_id}/unarchive", {
4836
+ params: { path: { workspace_ext_id: workspaceExtId } }
4837
+ }),
4838
+ "Could not unarchive the workspace"
4839
+ );
4840
+ }
4841
+ async function deleteWorkspaces(arbi, workspaceIds) {
4842
+ requireOk(
4843
+ await arbi.fetch.DELETE("/v1/workspace/", {
4844
+ body: { external_ids: workspaceIds }
4845
+ }),
4846
+ "Failed to delete workspace(s)"
4847
+ );
4848
+ }
4849
+ async function updateWorkspace(arbi, body) {
4850
+ return requireData(
4851
+ await arbi.fetch.PATCH("/v1/workspace/", { body }),
4852
+ "Failed to update workspace"
4853
+ );
4854
+ }
4855
+ async function listWorkspaceUsers(arbi) {
4856
+ return requireData(await arbi.fetch.GET("/v1/workspace/users"), "Failed to fetch workspace users");
4857
+ }
4858
+ var EXTERNAL_ACCESS_SECONDS = 86400;
4859
+ function addWorkspaceMembersBody(request) {
4860
+ return {
4861
+ ...request,
4862
+ access_duration_seconds: request.access_duration_seconds ?? EXTERNAL_ACCESS_SECONDS
4863
+ };
4864
+ }
4865
+ async function addWorkspaceMembers(arbi, request) {
4866
+ return requireData(
4867
+ await arbi.fetch.POST("/v1/workspace/users", { body: addWorkspaceMembersBody(request) }),
4868
+ "Failed to add users"
4869
+ );
4870
+ }
4871
+ async function addWorkspaceUsers(arbi, emails, role = "collaborator", target, confirmInvite = false) {
4872
+ const invite = confirmInvite ? { confirm_invite: true } : {};
4873
+ return requireData(
4874
+ await arbi.fetch.POST("/v1/workspace/users", {
4875
+ body: addWorkspaceMembersBody(
4876
+ target ? {
4877
+ emails,
4878
+ role,
4879
+ workspace_ext_id: target.workspaceExtId,
4880
+ workspace_key: target.workspaceKey,
4881
+ ...invite
4882
+ } : { emails, role, ...invite }
4883
+ )
4884
+ }),
4885
+ "Failed to add users"
4886
+ );
4887
+ }
4888
+ async function grantTemporaryWorkspaceAccess(arbi, params) {
4889
+ return requireData(
4890
+ await arbi.fetch.POST("/v1/workspace/users", {
4891
+ body: addWorkspaceMembersBody({
4892
+ emails: params.emails,
4893
+ role: params.role ?? "collaborator",
4894
+ workspace_ext_id: params.workspaceExtId,
4895
+ workspace_key: params.workspaceKey,
4896
+ session_pubkey_b64: params.sessionPubkeyB64
4897
+ })
4898
+ }),
4899
+ "Failed to grant temporary access"
4900
+ );
4901
+ }
4902
+ async function removeWorkspaceUsers(arbi, userIds, workspaceExtId) {
4903
+ requireOk(
4904
+ await arbi.fetch.DELETE("/v1/workspace/users", {
4905
+ body: {
4906
+ users: userIds.map((id) => ({ user_ext_id: id })),
4907
+ ...workspaceExtId ? { workspace_ext_id: workspaceExtId } : {}
5512
4908
  }
5513
- } catch (cause) {
5514
- if (!finished) {
5515
- const error = transportError(cause, bound ? state.id : void 0);
5516
- if (!bound) rejectStart(error);
5517
- finish({
5518
- status: "disconnected",
5519
- responseId: bound ? state.id : null,
5520
- reason: error.name === "AbortError" ? "aborted" : "connection_error",
5521
- ...error instanceof ArbiError ? { error } : {}
5522
- });
4909
+ }),
4910
+ "Failed to remove users"
4911
+ );
4912
+ }
4913
+ async function setUserRole(arbi, userIds, role) {
4914
+ return requireData(
4915
+ await arbi.fetch.PATCH("/v1/workspace/users", {
4916
+ body: { user_ext_ids: userIds, role }
4917
+ }),
4918
+ "Failed to update roles"
4919
+ );
4920
+ }
4921
+ async function copyDocuments(arbi, targetWorkspaceId, docIds, targetWorkspaceKey) {
4922
+ return requireData(
4923
+ await arbi.fetch.POST("/v1/workspace/copy", {
4924
+ body: {
4925
+ target_workspace_ext_id: targetWorkspaceId,
4926
+ target_workspace_key: targetWorkspaceKey,
4927
+ items: docIds
5523
4928
  }
5524
- } finally {
5525
- reader.releaseLock();
5526
- }
5527
- })();
5528
- return start;
4929
+ }),
4930
+ "Failed to copy documents"
4931
+ );
5529
4932
  }
5530
-
5531
- // src/operations/documents.ts
5532
- var documents_exports = {};
5533
- __export(documents_exports, {
5534
- MAX_PAGES: () => MAX_PAGES,
5535
- SUPPORTED_EXTENSIONS: () => SUPPORTED_EXTENSIONS,
5536
- deleteDocuments: () => deleteDocuments,
5537
- downloadDocument: () => downloadDocument,
5538
- finaliseTranslation: () => finaliseTranslation,
5539
- getDocuments: () => getDocuments,
5540
- getParsedContent: () => getParsedContent,
5541
- getThumbnails: () => getThumbnails,
5542
- listAll: () => listAll,
5543
- listDocuments: () => listDocuments,
5544
- listPaginated: () => listPaginated,
5545
- listVersions: () => listVersions,
5546
- mimeFromName: () => mimeFromName,
5547
- presignedPut: () => presignedPut,
5548
- sanitizeFolderPath: () => sanitizeFolderPath,
5549
- similarDocuments: () => similarDocuments,
5550
- updateDocuments: () => updateDocuments,
5551
- uploadDocuments: () => uploadDocuments,
5552
- uploadDocumentsDirect: () => uploadDocumentsDirect,
5553
- uploadFile: () => uploadFile,
5554
- uploadFiles: () => uploadFiles,
5555
- uploadUrl: () => uploadUrl
5556
- });
5557
- var MAX_PAGES = 400;
5558
- var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
5559
- ".pdf",
5560
- ".txt",
5561
- ".md",
5562
- ".html",
5563
- ".htm",
5564
- ".doc",
5565
- ".docx",
5566
- ".rtf",
5567
- ".ppt",
5568
- ".pptx",
5569
- ".xls",
5570
- ".xlsx",
5571
- ".jpg",
5572
- ".jpeg",
5573
- ".png",
5574
- ".gif",
5575
- ".bmp",
5576
- ".tiff",
5577
- ".tif",
5578
- ".webp",
5579
- // Video (store only, no parsing)
5580
- ".mp4",
5581
- ".mpeg",
5582
- ".mpg",
5583
- ".webm",
5584
- ".mov",
5585
- ".avi",
5586
- ".mkv",
5587
- // Audio (store only, no parsing)
5588
- ".mp3",
5589
- ".wav",
5590
- ".m4a",
5591
- ".aac",
5592
- ".ogg",
5593
- ".flac",
5594
- // Email formats (parsed for content)
5595
- ".eml",
5596
- ".msg",
5597
- ".mbox",
5598
- ".pst",
5599
- ".ost"
5600
- ]);
5601
- function sanitizeFolderPath(folderPath) {
5602
- return folderPath.replace(/[\x00-\x1f\x7f]/g, "").replace(/\\/g, "/").replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "").trim();
4933
+ async function getWorkspaceActivity(arbi, workspaceExtId, options = {}) {
4934
+ return requireData(
4935
+ await arbi.fetch.GET("/v1/workspace/{workspace_ext_id}/activity", {
4936
+ params: {
4937
+ path: { workspace_ext_id: workspaceExtId },
4938
+ query: { cursor: options.cursor ?? void 0, limit: options.limit }
4939
+ }
4940
+ }),
4941
+ "Failed to fetch workspace activity"
4942
+ );
5603
4943
  }
5604
- async function listDocuments(arbi, workspaceExtId) {
5605
- if (!workspaceExtId) {
5606
- return requireData(await arbi.fetch.GET("/v1/document/list"), "Failed to fetch documents");
5607
- }
5608
- const docs = requireData(
5609
- await arbi.fetch.GET("/v1/document/list", {
5610
- params: { query: { workspace_ext_id: workspaceExtId } }
4944
+ async function primeWorkspaceKey(arbi, workspaceExtId, sessionSealedKey) {
4945
+ requireOk(
4946
+ await arbi.fetch.POST("/v1/workspace/{workspace_ext_id}/prime-key", {
4947
+ params: { path: { workspace_ext_id: workspaceExtId } },
4948
+ body: { workspace_key: sessionSealedKey }
5611
4949
  }),
5612
- "Failed to fetch documents"
4950
+ "Failed to prime the workspace key"
5613
4951
  );
5614
- if (docs.some((doc) => doc.workspace_ext_id !== workspaceExtId)) {
5615
- throw new ArbiError(`This server cannot list workspace ${workspaceExtId} without opening it`);
5616
- }
5617
- return docs;
5618
4952
  }
5619
- async function* listPaginated(arbi, options = {}) {
5620
- const {
5621
- pageSize = 5e3,
5622
- firstPageSize,
5623
- order = "id_asc",
5624
- fields,
5625
- signal,
5626
- lookahead = 1,
5627
- workspaceExtId
5628
- } = options;
5629
- const fetchPage = async (pageOffset, limit) => {
5630
- const query2 = {
5631
- limit,
5632
- offset: pageOffset,
5633
- order
5634
- };
5635
- if (fields) query2.fields = fields;
5636
- if (workspaceExtId) query2.workspace_ext_id = workspaceExtId;
5637
- const { data, error } = await arbi.fetch.GET("/v1/document/list", {
5638
- params: { query: query2 },
5639
- signal
5640
- });
5641
- if (error) {
5642
- throw new Error(typeof error === "string" ? error : JSON.stringify(error));
5643
- }
5644
- const page = data ?? [];
5645
- if (workspaceExtId && page.some((doc) => doc.workspace_ext_id !== workspaceExtId)) {
5646
- throw new ArbiError(`The server returned another workspace's documents for ${workspaceExtId}`);
5647
- }
5648
- return page;
5649
- };
5650
- if (signal?.aborted) return;
5651
- const depth = Math.max(1, Math.min(lookahead, MAX_PAGES));
5652
- let issued = 0;
5653
- let pagesYielded = 0;
5654
- let nextOffsetToIssue = 0;
5655
- let done = false;
5656
- const queue = [];
5657
- const tryEnqueue = () => {
5658
- while (!done && queue.length < depth && issued < MAX_PAGES) {
5659
- const limit = issued === 0 && firstPageSize !== void 0 ? firstPageSize : pageSize;
5660
- const promise = fetchPage(nextOffsetToIssue, limit);
5661
- promise.catch(() => {
5662
- });
5663
- queue.push({ limit, promise });
5664
- nextOffsetToIssue += limit;
5665
- issued++;
5666
- }
5667
- };
5668
- tryEnqueue();
5669
- while (queue.length > 0 && !signal?.aborted) {
5670
- const { limit, promise } = queue.shift();
5671
- const page = await promise;
5672
- if (signal?.aborted) return;
5673
- const isShort = page.length < limit;
5674
- if (isShort) done = true;
5675
- tryEnqueue();
5676
- if (page.length > 0) {
5677
- yield page;
5678
- pagesYielded++;
5679
- }
5680
- if (isShort) return;
5681
- if (pagesYielded >= MAX_PAGES) break;
4953
+ async function planWorkspaceTransfer(arbi, scope, mode) {
4954
+ return requireData(
4955
+ await arbi.fetch.POST("/v1/workspace/transfer/plan", { body: { scope, mode } }),
4956
+ "Failed to plan the transfer"
4957
+ );
4958
+ }
4959
+ async function startWorkspaceTransfer(arbi, params) {
4960
+ return requireData(
4961
+ await arbi.fetch.POST("/v1/workspace/transfer", {
4962
+ body: {
4963
+ scope: params.scope,
4964
+ mode: params.mode,
4965
+ target_workspace_ext_id: params.targetWorkspaceId,
4966
+ target_workspace_key: params.targetWorkspaceKey,
4967
+ on_conflict: params.onConflict ?? "skip"
4968
+ }
4969
+ }),
4970
+ "Failed to start the transfer"
4971
+ );
4972
+ }
4973
+ async function resumeWorkspaceTransfer(arbi, transferId, targetWorkspaceKey) {
4974
+ return requireData(
4975
+ await arbi.fetch.POST("/v1/workspace/transfer/{transfer_ext_id}/resume", {
4976
+ params: { path: { transfer_ext_id: transferId } },
4977
+ body: { target_workspace_key: targetWorkspaceKey }
4978
+ }),
4979
+ "Failed to resume the transfer"
4980
+ );
4981
+ }
4982
+ async function cancelWorkspaceTransfer(arbi, transferId) {
4983
+ return requireData(
4984
+ await arbi.fetch.POST("/v1/workspace/transfer/{transfer_ext_id}/cancel", {
4985
+ params: { path: { transfer_ext_id: transferId } }
4986
+ }),
4987
+ "Failed to cancel the transfer"
4988
+ );
4989
+ }
4990
+ async function getWorkspaceTransfer(arbi, transferId) {
4991
+ return requireData(
4992
+ await arbi.fetch.GET("/v1/workspace/transfer/{transfer_ext_id}", {
4993
+ params: { path: { transfer_ext_id: transferId } }
4994
+ }),
4995
+ "Failed to fetch the transfer"
4996
+ );
4997
+ }
4998
+ async function listWorkspaceTransfers(arbi) {
4999
+ return requireData(
5000
+ await arbi.fetch.GET("/v1/workspace/transfer", {}),
5001
+ "Failed to list transfers"
5002
+ );
5003
+ }
5004
+ async function exportWorkspaceData(arbi, scope) {
5005
+ return requireData(
5006
+ await arbi.fetch.POST("/v1/workspace/export", { body: { scope } }),
5007
+ "Failed to export the workspace"
5008
+ );
5009
+ }
5010
+ async function getWorkspaceAccessStatus(arbi, workspaceId) {
5011
+ return requireData(
5012
+ await arbi.fetch.GET("/v1/workspace/{workspace_ext_id}/access-status", {
5013
+ params: { path: { workspace_ext_id: workspaceId } }
5014
+ }),
5015
+ "Could not read workspace access"
5016
+ );
5017
+ }
5018
+
5019
+ // src/diagnostics.ts
5020
+ async function diagnoseSetup(options) {
5021
+ const checks = [];
5022
+ const add = (check, status, message, hint) => checks.push({ check, status, message, ...hint ? { hint } : {} });
5023
+ let base;
5024
+ try {
5025
+ base = new URL(options.url);
5026
+ if (!["http:", "https:"].includes(base.protocol) || base.username || base.password || base.search || base.hash)
5027
+ throw new Error("Invalid API URL");
5028
+ } catch {
5029
+ add(
5030
+ "connection",
5031
+ "error",
5032
+ "Invalid API URL.",
5033
+ "Use an absolute HTTP(S) API URL without credentials, query or fragment."
5034
+ );
5035
+ return { ok: false, checks };
5682
5036
  }
5683
- if (!signal?.aborted && !done && pagesYielded >= MAX_PAGES) {
5684
- console.warn(
5685
- `[arbi-sdk] listPaginated hit MAX_PAGES (${MAX_PAGES}) \u2014 stopped. Workspace may have more than ${MAX_PAGES * pageSize} documents.`
5037
+ const request = (path2, authenticated = false) => (options.fetch ?? globalThis.fetch)(`${base.href.replace(/\/$/, "")}${path2}`, {
5038
+ method: "GET",
5039
+ credentials: "omit",
5040
+ redirect: "error",
5041
+ cache: "no-store",
5042
+ headers: authenticated && options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {},
5043
+ signal: AbortSignal.timeout(options.timeoutMs ?? 1e4)
5044
+ });
5045
+ try {
5046
+ const config = await request("/config.json");
5047
+ if (!config.ok) {
5048
+ add(
5049
+ "connection",
5050
+ "error",
5051
+ `Deployment configuration returned HTTP ${config.status}.`,
5052
+ "Check the API base URL and proxy routing."
5053
+ );
5054
+ } else {
5055
+ const body = await config.json();
5056
+ add("connection", "ok", "Deployment configuration is reachable.");
5057
+ const domain = body?.deployment?.domain;
5058
+ if (typeof domain !== "string" || !domain) {
5059
+ add(
5060
+ "deployment",
5061
+ "warning",
5062
+ "The deployment did not advertise its key-derivation domain.",
5063
+ "Confirm deploymentDomain with the deployment owner, especially when using a proxy."
5064
+ );
5065
+ } else if (domain !== (options.deploymentDomain ?? base.hostname)) {
5066
+ add(
5067
+ "deployment",
5068
+ "error",
5069
+ "The configured key-derivation domain differs from the deployment.",
5070
+ "Set deploymentDomain to the deployment\u2019s domain; a proxy hostname is not the key-derivation domain."
5071
+ );
5072
+ } else add("deployment", "ok", "The key-derivation domain matches the deployment.");
5073
+ }
5074
+ } catch {
5075
+ add(
5076
+ "connection",
5077
+ "error",
5078
+ "Could not read deployment configuration.",
5079
+ "Check DNS, TLS, proxy routing and connectivity. In a browser, inspect DevTools for CORS, mixed-content or private-network denial; fetch alone cannot distinguish them."
5686
5080
  );
5687
5081
  }
5688
- }
5689
- async function listAll(arbi, options = {}) {
5690
- const all = [];
5691
- const seen = /* @__PURE__ */ new Set();
5692
- for await (const page of listPaginated(arbi, options)) {
5693
- for (const doc of page) {
5694
- const id = doc.external_id;
5695
- if (id && !seen.has(id)) {
5696
- seen.add(id);
5697
- all.push(doc);
5082
+ if (!options.accessToken) {
5083
+ add(
5084
+ "authentication",
5085
+ "warning",
5086
+ "No live session token is available.",
5087
+ "Sign in explicitly when online. An offline-unlocked identity is not a verified server session."
5088
+ );
5089
+ add("workspace", "skipped", "Workspace access was not checked.");
5090
+ add("permissions", "skipped", "Permissions were not checked.");
5091
+ } else {
5092
+ let authenticated = false;
5093
+ try {
5094
+ const user = await request("/v1/user/me", true);
5095
+ if (!user.ok) {
5096
+ add(
5097
+ "authentication",
5098
+ "error",
5099
+ `Session check returned HTTP ${user.status}.`,
5100
+ user.status === 401 ? "Sign in explicitly to renew the session." : "Check deployment access and account permissions."
5101
+ );
5102
+ add("workspace", "skipped", "Workspace access was not checked.");
5103
+ add("permissions", "skipped", "Permissions were not checked.");
5104
+ } else {
5105
+ const profile = await user.json();
5106
+ authenticated = true;
5107
+ add("authentication", "ok", "The server accepts the current session.");
5108
+ if (!options.workspaceId) {
5109
+ add(
5110
+ "workspace",
5111
+ "warning",
5112
+ "No current workspace is selected.",
5113
+ "Choose a workspace explicitly before reading documents or starting work."
5114
+ );
5115
+ add("permissions", "skipped", "Select a workspace to check membership.");
5116
+ } else {
5117
+ const response = await request("/v1/user/workspaces", true);
5118
+ if (!response.ok) {
5119
+ add(
5120
+ "workspace",
5121
+ "error",
5122
+ `Workspace membership check returned HTTP ${response.status}.`,
5123
+ "Check current account access; diagnosis does not switch workspaces or grant access."
5124
+ );
5125
+ add("permissions", "skipped", "Membership could not be verified.");
5126
+ } else {
5127
+ const workspaces = await response.json();
5128
+ const workspace = Array.isArray(workspaces) ? workspaces.find((w2) => w2.external_id === options.workspaceId) : void 0;
5129
+ if (!workspace) {
5130
+ add(
5131
+ "workspace",
5132
+ "error",
5133
+ "The selected workspace is not in this account\u2019s workspace list.",
5134
+ "Choose an accessible workspace explicitly. Project visibility does not imply workspace access."
5135
+ );
5136
+ add("permissions", "skipped", "Workspace permissions could not be verified.");
5137
+ } else {
5138
+ add(
5139
+ "workspace",
5140
+ "ok",
5141
+ "The selected workspace appears in the account\u2019s workspace list."
5142
+ );
5143
+ const member = workspace.users?.find(
5144
+ (entry) => entry.user?.external_id === profile.external_id
5145
+ );
5146
+ const role = ["owner", "collaborator", "guest"].includes(member?.role) ? member.role : null;
5147
+ add(
5148
+ "permissions",
5149
+ role ? "ok" : "warning",
5150
+ role ? `Workspace membership role: ${workspaceRoleLabel(role)} (${role}).` : "No direct membership role was reported.",
5151
+ "This is a membership check, not proof of a live workspace key or authorization for an agent task. Temporary grants, expiry and execution permissions remain enforced by the API."
5152
+ );
5153
+ }
5154
+ }
5155
+ }
5698
5156
  }
5157
+ } catch {
5158
+ add(
5159
+ authenticated ? "workspace" : "authentication",
5160
+ "error",
5161
+ authenticated ? "The workspace membership check could not finish." : "The session check could not finish.",
5162
+ "Check connectivity and browser network policy. No login, workspace switch or grant was attempted."
5163
+ );
5164
+ if (authenticated)
5165
+ add("permissions", "skipped", "Workspace membership could not be verified.");
5699
5166
  }
5700
5167
  }
5701
- return all;
5702
- }
5703
- async function getDocuments(arbi, externalIds) {
5704
- return requireData(
5705
- await arbi.fetch.GET("/v1/document/", { params: { query: { external_ids: externalIds } } }),
5706
- "Failed to fetch documents"
5707
- );
5168
+ return { ok: checks.every((c2) => c2.status === "ok"), checks };
5708
5169
  }
5709
- async function listVersions(arbi, docId) {
5710
- return requireData(
5711
- await arbi.fetch.GET("/v1/document/{document_ext_id}/versions", {
5712
- params: { path: { document_ext_id: docId } }
5713
- }),
5714
- "Failed to fetch document versions"
5715
- );
5170
+
5171
+ // src/operations/responses.ts
5172
+ var responses_exports = {};
5173
+ __export(responses_exports, {
5174
+ extractResponseText: () => extractResponseText,
5175
+ getResponse: () => getResponse,
5176
+ submitBackgroundQuery: () => submitBackgroundQuery
5177
+ });
5178
+ async function submitBackgroundQuery(options) {
5179
+ const {
5180
+ workspaceId,
5181
+ question,
5182
+ docIds,
5183
+ previousResponseId,
5184
+ model,
5185
+ text: text2,
5186
+ task,
5187
+ conversationId,
5188
+ mentions,
5189
+ activeArtifactExtId,
5190
+ fullContext = true,
5191
+ ...auth
5192
+ } = options;
5193
+ const tools = {};
5194
+ if (docIds.length > 0) {
5195
+ tools.retrieval_chunk = {
5196
+ name: "retrieval_chunk",
5197
+ description: "retrieval chunk",
5198
+ tool_args: { doc_ext_ids: docIds },
5199
+ tool_responses: {}
5200
+ };
5201
+ if (fullContext)
5202
+ tools.retrieval_full_context = {
5203
+ name: "retrieval_full_context",
5204
+ description: "retrieval full context",
5205
+ tool_args: { doc_ext_ids: docIds },
5206
+ tool_responses: {}
5207
+ };
5208
+ }
5209
+ const body = {
5210
+ input: question,
5211
+ workspace_ext_id: workspaceId,
5212
+ stream: false,
5213
+ background: true,
5214
+ store: true,
5215
+ tools,
5216
+ ...task !== void 0 ? { task } : {},
5217
+ ...conversationId ? { conversation_ext_id: conversationId } : {},
5218
+ ...mentions !== void 0 ? { mentions } : {},
5219
+ ...activeArtifactExtId ? { active_artifact_ext_id: activeArtifactExtId } : {},
5220
+ ...previousResponseId ? { previous_response_id: previousResponseId } : {},
5221
+ ...model ? { model } : {},
5222
+ ...text2 ? { text: text2 } : {}
5223
+ };
5224
+ const res = await authenticatedFetch({
5225
+ ...auth,
5226
+ path: "/v1/responses",
5227
+ method: "POST",
5228
+ body: JSON.stringify(body),
5229
+ headers: { "Content-Type": "application/json" }
5230
+ });
5231
+ return await res.json();
5716
5232
  }
5717
- async function finaliseTranslation(arbi, docId) {
5718
- return requireData(
5719
- await arbi.fetch.POST("/v1/document/{document_ext_id}/finalise-translation", {
5720
- params: { path: { document_ext_id: docId } }
5721
- }),
5722
- "Failed to finalise the translation"
5723
- );
5233
+ async function getResponse(auth, responseId) {
5234
+ const res = await authenticatedFetch({
5235
+ ...auth,
5236
+ path: `/v1/responses/${responseId}`,
5237
+ method: "GET"
5238
+ });
5239
+ return await res.json();
5724
5240
  }
5725
- async function deleteDocuments(arbi, externalIds) {
5726
- requireOk(
5727
- await arbi.fetch.DELETE("/v1/document/", { body: { external_ids: externalIds } }),
5728
- "Failed to delete documents"
5729
- );
5241
+ function extractResponseText(response) {
5242
+ const parts = [];
5243
+ for (const msg of Array.isArray(response.output) ? response.output : []) {
5244
+ if (msg.type !== "message" || !Array.isArray(msg.content)) continue;
5245
+ for (const item of msg.content) {
5246
+ if (item?.type === "output_text" && typeof item.text === "string") parts.push(item.text);
5247
+ }
5248
+ }
5249
+ return parts.join("");
5730
5250
  }
5731
- async function updateDocuments(arbi, documents) {
5732
- return requireData(
5733
- await arbi.fetch.PATCH("/v1/document/", { body: { documents } }),
5734
- "Failed to update documents"
5735
- );
5251
+
5252
+ // src/responses-resource.ts
5253
+ function withOutputText(response, requestId) {
5254
+ return {
5255
+ ...response,
5256
+ output_text: extractResponseText(response),
5257
+ ...requestId ? { _request_id: requestId } : {}
5258
+ };
5736
5259
  }
5737
- async function uploadUrl(arbi, urls, options) {
5738
- return requireUploadData(
5739
- await arbi.fetch.POST("/v1/document/upload-url", {
5740
- params: {
5741
- query: {
5742
- urls,
5743
- shared: options.shared ?? false,
5744
- workspace_ext_id: options.workspaceExtId,
5745
- ...options.configExtId ? { config_ext_id: options.configExtId } : {}
5746
- }
5260
+ var ResponseStream = class {
5261
+ constructor(handle) {
5262
+ this.handle = handle;
5263
+ }
5264
+ handle;
5265
+ async *[Symbol.asyncIterator]() {
5266
+ try {
5267
+ for await (const frame of this.handle.events()) {
5268
+ const data = frame.data && typeof frame.data === "object" && !Array.isArray(frame.data) ? frame.data : { data: frame.data };
5269
+ yield {
5270
+ ...data,
5271
+ type: typeof data.type === "string" ? data.type : frame.event
5272
+ };
5747
5273
  }
5748
- }),
5749
- "Failed to upload from URLs"
5750
- );
5751
- }
5752
- var UPLOAD_WORKSPACE_CONFLICT_MESSAGES = {
5753
- workspace_mismatch: "These files were prepared for another workspace, so they were not saved. Upload them again.",
5754
- workspace_key_required: "The workspace couldn't be unlocked for this upload, so the files were not saved."
5274
+ const outcome = await this.handle.outcome;
5275
+ if (outcome.status === "disconnected")
5276
+ throw outcome.error ?? new ArbiTransportError(new Error("The response stream disconnected."), this.handle.id);
5277
+ } finally {
5278
+ this.handle.detach();
5279
+ }
5280
+ }
5755
5281
  };
5756
- function requireUploadData(result, message) {
5757
- return requireWorkspaceData(result, message, UPLOAD_WORKSPACE_CONFLICT_MESSAGES);
5282
+
5283
+ // src/structured-output.ts
5284
+ var ArbiStructuredOutputError = class extends ArbiError {
5285
+ constructor(message, response, options) {
5286
+ const id = response && typeof response === "object" && "id" in response && typeof response.id === "string" ? response.id : void 0;
5287
+ super(message, { responseId: id, ...options });
5288
+ this.response = response;
5289
+ this.name = "ArbiStructuredOutputError";
5290
+ }
5291
+ response;
5292
+ };
5293
+ function localReferences(value) {
5294
+ if (Array.isArray(value)) {
5295
+ value.forEach(localReferences);
5296
+ return;
5297
+ }
5298
+ if (!value || typeof value !== "object") return;
5299
+ for (const [key, child] of Object.entries(value)) {
5300
+ if ((key === "$ref" || key === "$dynamicRef") && (typeof child !== "string" || !child.startsWith("#")))
5301
+ throw new Error("Only local schema references are supported.");
5302
+ if (!["enum", "const", "default", "examples"].includes(key)) localReferences(child);
5303
+ }
5758
5304
  }
5759
- async function uploadDocuments(arbi, files, options = {}) {
5760
- const query2 = {};
5761
- if (options.shared !== void 0) query2.shared = options.shared;
5762
- if (options.folder) query2.folder = sanitizeFolderPath(options.folder);
5763
- if (options.configExtId) query2.config_ext_id = options.configExtId;
5764
- if (options.wpType) query2.wp_type = options.wpType;
5765
- if (options.versionOf) query2.version_of = options.versionOf;
5766
- if (options.tagExtId) query2.tag_ext_id = options.tagExtId;
5767
- if (options.workspaceExtId) query2.workspace_ext_id = options.workspaceExtId;
5768
- if (options.derivedFrom) {
5769
- query2.derived_from = options.derivedFrom.docId;
5770
- query2.derived_role = options.derivedFrom.role;
5305
+ async function createStructuredParser(format) {
5306
+ let validate;
5307
+ let Constructor;
5308
+ try {
5309
+ Constructor = (await import('ajv/dist/2020.js')).default;
5310
+ } catch (cause) {
5311
+ throw new ArbiStructuredOutputError(
5312
+ "The JSON Schema validator could not be loaded.",
5313
+ void 0,
5314
+ { code: "STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE", cause }
5315
+ );
5316
+ }
5317
+ try {
5318
+ if (format.type !== "json_schema" || typeof format.name !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(format.name) || !format.schema || typeof format.schema !== "object" || Array.isArray(format.schema))
5319
+ throw new Error("Invalid structured output format.");
5320
+ if (format.schema.$schema !== void 0 && format.schema.$schema !== "https://json-schema.org/draft/2020-12/schema")
5321
+ throw new Error("Expected JSON Schema draft 2020-12.");
5322
+ localReferences(format.schema);
5323
+ validate = new Constructor({
5324
+ strict: false,
5325
+ logger: false,
5326
+ validateFormats: false,
5327
+ strictNumbers: true,
5328
+ addUsedSchema: false
5329
+ }).compile(format.schema);
5330
+ } catch (cause) {
5331
+ const unavailable = cause instanceof EvalError;
5332
+ throw new ArbiStructuredOutputError(
5333
+ unavailable ? "This runtime cannot compile JSON Schema validators." : "Invalid or unsupported output schema.",
5334
+ void 0,
5335
+ {
5336
+ code: unavailable ? "STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE" : "STRUCTURED_OUTPUT_SCHEMA_INVALID",
5337
+ cause
5338
+ }
5339
+ );
5771
5340
  }
5772
- const result = await arbi.fetch.POST("/v1/document/upload", {
5773
- params: { query: query2 },
5774
- ...options.onProgress ? { fetch: progressFetch(options.onProgress, arbi.http) } : {},
5775
- // The schema types the files as strings; they go as multipart parts.
5776
- body: { files },
5777
- bodySerializer: () => {
5778
- const form = new FormData();
5779
- for (const file of files) form.append("files", file);
5780
- return form;
5341
+ return (response, options = {}) => {
5342
+ const fail = (code, message, cause) => {
5343
+ throw new ArbiStructuredOutputError(message, response, { ...options, code, cause });
5344
+ };
5345
+ if (!response || typeof response !== "object")
5346
+ fail("RESPONSE_INVALID_ENVELOPE", "Expected a Responses JSON object.");
5347
+ if (response.status === "incomplete")
5348
+ fail("RESPONSE_INCOMPLETE", "The response is incomplete; no validated data is available.");
5349
+ if (response.status === "cancelled")
5350
+ fail("RESPONSE_CANCELLED", "The response was cancelled; no validated data is available.");
5351
+ if (response.status === "failed")
5352
+ fail(
5353
+ typeof response.error?.code === "string" ? response.error.code : "RESPONSE_FAILED",
5354
+ typeof response.error?.message === "string" ? response.error.message : "The response failed."
5355
+ );
5356
+ if (response.status !== "completed")
5357
+ fail(
5358
+ "RESPONSE_NOT_COMPLETED",
5359
+ "Wait for a completed response before parsing structured output."
5360
+ );
5361
+ const messages = Array.isArray(response.output) ? response.output.filter(
5362
+ (item) => item && typeof item === "object" && item.type === "message" && item.role === "assistant"
5363
+ ) : [];
5364
+ if (messages.some(
5365
+ (message) => !Array.isArray(message.content) || message.content.some((part) => !part || typeof part !== "object")
5366
+ ))
5367
+ fail("RESPONSE_INVALID_ENVELOPE", "Invalid assistant output content.");
5368
+ if (messages.some((message) => message.content.some((part) => part.type === "refusal")))
5369
+ fail("RESPONSE_REFUSED", "The model refused this response.");
5370
+ const answers = messages.map(
5371
+ (message) => message.content.filter((part) => part.type === "output_text" && typeof part.text === "string").map((part) => part.text).join("")
5372
+ ).filter((answer) => answer.length > 0);
5373
+ if (answers.length !== 1)
5374
+ fail(
5375
+ "STRUCTURED_OUTPUT_AMBIGUOUS",
5376
+ "Expected one final assistant output message; narrative and answer text are not joined."
5377
+ );
5378
+ let data;
5379
+ try {
5380
+ data = JSON.parse(answers[0]);
5381
+ } catch (cause) {
5382
+ fail("STRUCTURED_OUTPUT_INVALID_JSON", "The response is not valid JSON.", cause);
5781
5383
  }
5782
- });
5783
- return requireUploadData(result, "Failed to upload documents");
5784
- }
5785
- async function similarDocuments(arbi, options = {}) {
5786
- return requireData(
5787
- await arbi.fetch.GET("/v1/document/similar", {
5788
- params: {
5789
- query: {
5790
- ...options.threshold !== void 0 ? { threshold: options.threshold } : {},
5791
- ...options.docId ? { doc_ext_id: options.docId } : {}
5792
- }
5793
- }
5794
- }),
5795
- "Failed to fetch similar documents"
5796
- );
5797
- }
5798
- async function getParsedContent(auth, docId, stage, version) {
5799
- const res = await authenticatedFetch({
5800
- ...auth,
5801
- path: `/v1/document/${docId}/parsed-${stage}${version ? `?version=${version}` : ""}`
5802
- });
5803
- return res.json();
5804
- }
5805
- async function getThumbnails(auth, docIds) {
5806
- if (docIds.length === 0) return {};
5807
- const res = await authenticatedFetch({
5808
- ...auth,
5809
- path: `/v1/document/thumbnails`,
5810
- method: "POST",
5811
- headers: { "Content-Type": "application/json" },
5812
- body: JSON.stringify({ document_ext_ids: docIds })
5813
- });
5814
- const json2 = await res.json();
5815
- return json2.thumbnails ?? {};
5384
+ if (!validate(data))
5385
+ fail("STRUCTURED_OUTPUT_INVALID", "The response did not match the requested JSON schema.");
5386
+ return { data, response };
5387
+ };
5816
5388
  }
5817
- async function uploadFile(auth, fileData, fileName, options) {
5818
- const formData = new FormData();
5819
- formData.append("files", fileData, fileName);
5820
- const params = new URLSearchParams();
5821
- if (options?.shared !== void 0) params.set("shared", String(options.shared));
5822
- if (options?.folder) params.set("folder", sanitizeFolderPath(options.folder));
5823
- if (options?.configExtId) params.set("config_ext_id", options.configExtId);
5824
- if (options?.wpType) params.set("wp_type", options.wpType);
5825
- if (options?.versionOf) params.set("version_of", options.versionOf);
5826
- if (options?.workspaceExtId) params.set("workspace_ext_id", options.workspaceExtId);
5827
- if (options?.derivedFrom) {
5828
- params.set("derived_from", options.derivedFrom.docId);
5829
- params.set("derived_role", options.derivedFrom.role);
5830
- }
5831
- const qs = params.toString();
5832
- const res = await authenticatedFetch({
5833
- ...auth,
5834
- path: qs ? `/v1/document/upload?${qs}` : `/v1/document/upload`,
5835
- method: "POST",
5836
- body: formData
5837
- });
5838
- return res.json();
5389
+ async function parseStructuredResponse(response, format) {
5390
+ return (await createStructuredParser(format))(response);
5839
5391
  }
5840
- async function uploadFiles(auth, files, options) {
5841
- const formData = new FormData();
5842
- for (const f2 of files) formData.append("files", f2.data, f2.name);
5843
- const params = new URLSearchParams();
5844
- if (options?.folder) params.set("folder", sanitizeFolderPath(options.folder));
5845
- if (options?.configExtId) params.set("config_ext_id", options.configExtId);
5846
- if (options?.wpType) params.set("wp_type", options.wpType);
5847
- if (options?.versionOf) params.set("version_of", options.versionOf);
5848
- if (options?.derivedFrom) {
5849
- params.set("derived_from", options.derivedFrom.docId);
5850
- params.set("derived_role", options.derivedFrom.role);
5392
+
5393
+ // src/response-handle.ts
5394
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5395
+ var text = (value) => typeof value === "string" ? value : void 0;
5396
+ var messageId = (value) => typeof value === "string" && /^msg-[\w-]+$/.test(value);
5397
+ function immutable(value) {
5398
+ if (value && typeof value === "object" && !(value instanceof Error) && !Object.isFrozen(value)) {
5399
+ Object.freeze(value);
5400
+ for (const child of Object.values(value)) immutable(child);
5851
5401
  }
5852
- const qs = params.toString();
5853
- const res = await authenticatedFetch({
5854
- ...auth,
5855
- path: qs ? `/v1/document/upload?${qs}` : `/v1/document/upload`,
5856
- method: "POST",
5857
- body: formData
5858
- });
5859
- return res.json();
5402
+ return value;
5860
5403
  }
5861
- async function downloadDocument(auth, docId, version) {
5862
- return authenticatedFetch({
5863
- ...auth,
5864
- path: `/v1/document/${docId}/download${version ? `?version=${version}` : ""}`
5404
+ function reportObserverError(error) {
5405
+ queueMicrotask(() => {
5406
+ throw error;
5865
5407
  });
5866
5408
  }
5867
- function mimeFromName(name) {
5868
- const dot = name.lastIndexOf(".");
5869
- const ext = dot === -1 ? "" : name.slice(dot).toLowerCase();
5870
- switch (ext) {
5871
- case ".pdf":
5872
- return "application/pdf";
5873
- case ".txt":
5874
- return "text/plain";
5875
- case ".md":
5876
- return "text/markdown";
5877
- case ".html":
5878
- case ".htm":
5879
- return "text/html";
5880
- case ".doc":
5881
- return "application/msword";
5882
- case ".docx":
5883
- return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
5884
- case ".xls":
5885
- return "application/vnd.ms-excel";
5886
- case ".xlsx":
5887
- return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
5888
- case ".ppt":
5889
- return "application/vnd.ms-powerpoint";
5890
- case ".pptx":
5891
- return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
5892
- case ".eml":
5893
- return "message/rfc822";
5894
- case ".pst":
5895
- case ".ost":
5896
- return "application/vnd.ms-outlook";
5897
- default:
5898
- return void 0;
5899
- }
5900
- }
5901
- async function presignedPut(url, body, onProgress, headers) {
5902
- const XhrGlobal = globalThis.XMLHttpRequest;
5903
- if (XhrGlobal) {
5904
- await new Promise((resolve, reject) => {
5905
- const xhr = new XhrGlobal();
5906
- xhr.open("PUT", url);
5907
- for (const [name, value] of Object.entries(headers ?? {})) {
5908
- xhr.setRequestHeader(name, value);
5409
+ var ResponseEventDecoder = class {
5410
+ buffer = "";
5411
+ event = "";
5412
+ data = [];
5413
+ id;
5414
+ push(chunk, final = false) {
5415
+ this.buffer += chunk;
5416
+ const frames = [];
5417
+ const dispatch = () => {
5418
+ if (this.data.length)
5419
+ frames.push({
5420
+ event: this.event || "message",
5421
+ data: this.data.join("\n"),
5422
+ ...this.id !== void 0 ? { id: this.id } : {}
5423
+ });
5424
+ this.event = "";
5425
+ this.data = [];
5426
+ this.id = void 0;
5427
+ };
5428
+ const line = (value) => {
5429
+ if (!value) {
5430
+ dispatch();
5431
+ return;
5432
+ }
5433
+ if (value.startsWith(":")) return;
5434
+ const colon = value.indexOf(":");
5435
+ const field = colon < 0 ? value : value.slice(0, colon);
5436
+ let content = colon < 0 ? "" : value.slice(colon + 1);
5437
+ if (content.startsWith(" ")) content = content.slice(1);
5438
+ if (field === "event") this.event = content;
5439
+ if (field === "data") this.data.push(content);
5440
+ if (field === "id" && !content.includes("\0")) this.id = content;
5441
+ };
5442
+ while (true) {
5443
+ const index = this.buffer.search(/[\r\n]/);
5444
+ if (index < 0 || !final && index === this.buffer.length - 1 && this.buffer[index] === "\r")
5445
+ break;
5446
+ const width = this.buffer[index] === "\r" && this.buffer[index + 1] === "\n" ? 2 : 1;
5447
+ line(this.buffer.slice(0, index));
5448
+ this.buffer = this.buffer.slice(index + width);
5449
+ }
5450
+ if (final) {
5451
+ if (this.buffer) line(this.buffer);
5452
+ this.buffer = "";
5453
+ dispatch();
5454
+ }
5455
+ return frames;
5456
+ }
5457
+ };
5458
+ function consumeResponse(response, controller, cancel, options = {}) {
5459
+ if (!response.body)
5460
+ return Promise.reject(
5461
+ new ArbiApiError("Response has no stream body.", void 0, response.status, {
5462
+ code: "MISSING_RESPONSE_BODY"
5463
+ })
5464
+ );
5465
+ const reader = response.body.getReader();
5466
+ let resolveStart;
5467
+ let rejectStart;
5468
+ const start = new Promise((resolve, reject) => {
5469
+ resolveStart = resolve;
5470
+ rejectStart = reject;
5471
+ });
5472
+ let resolveOutcome;
5473
+ const outcome = new Promise((resolve) => {
5474
+ resolveOutcome = resolve;
5475
+ });
5476
+ let state = immutable({
5477
+ id: options.id ?? "",
5478
+ conversationId: null,
5479
+ connection: "connecting",
5480
+ responseStatus: null,
5481
+ output: [],
5482
+ displayText: ""
5483
+ });
5484
+ let bound = false;
5485
+ let finished = false;
5486
+ let acknowledgement;
5487
+ const listeners = /* @__PURE__ */ new Set();
5488
+ const queue = [];
5489
+ let capacityAvailable;
5490
+ const releaseCapacity = () => {
5491
+ capacityAvailable?.();
5492
+ capacityAvailable = void 0;
5493
+ };
5494
+ let claimed = false;
5495
+ let iteratorClosed = false;
5496
+ let iteratorError;
5497
+ let pending;
5498
+ const emit = (event) => {
5499
+ if (!claimed && !options.bufferEvents || iteratorClosed) return;
5500
+ if (pending) {
5501
+ pending.resolve({ value: immutable(event), done: false });
5502
+ pending = void 0;
5503
+ } else if (queue.length < 256) queue.push(immutable(event));
5504
+ else {
5505
+ iteratorError = new ArbiError("Raw response event consumer fell behind.", {
5506
+ code: "RESPONSE_EVENT_OVERFLOW"
5507
+ });
5508
+ queue.length = 0;
5509
+ iteratorClosed = true;
5510
+ }
5511
+ };
5512
+ const notify = () => {
5513
+ for (const listener of [...listeners]) {
5514
+ try {
5515
+ listener(state);
5516
+ } catch (error) {
5517
+ reportObserverError(error);
5909
5518
  }
5910
- if (onProgress) {
5911
- xhr.upload.addEventListener("progress", (e) => {
5912
- if (e.lengthComputable) onProgress(e.loaded, e.total);
5913
- });
5519
+ }
5520
+ };
5521
+ const update = (patch) => {
5522
+ state = immutable({ ...state, ...patch });
5523
+ notify();
5524
+ };
5525
+ const finish = (value, detached = false) => {
5526
+ if (finished) return;
5527
+ finished = true;
5528
+ releaseCapacity();
5529
+ controller.signal.removeEventListener("abort", abort);
5530
+ options.cleanup?.();
5531
+ update({ connection: detached ? "detached" : "closed", outcome: immutable(value) });
5532
+ listeners.clear();
5533
+ resolveOutcome(state.outcome);
5534
+ if (pending) {
5535
+ pending.resolve({ value: void 0, done: true });
5536
+ pending = void 0;
5537
+ }
5538
+ void reader.cancel().catch(() => {
5539
+ });
5540
+ };
5541
+ const abort = () => {
5542
+ if (!bound) rejectStart(new DOMException("The operation was aborted.", "AbortError"));
5543
+ finish({ status: "disconnected", responseId: bound ? state.id : null, reason: "aborted" }, true);
5544
+ queue.length = 0;
5545
+ };
5546
+ const handle = {
5547
+ get id() {
5548
+ return state.id;
5549
+ },
5550
+ snapshot: () => state,
5551
+ subscribe(listener) {
5552
+ if (!finished) listeners.add(listener);
5553
+ try {
5554
+ listener(state);
5555
+ } catch (error) {
5556
+ reportObserverError(error);
5914
5557
  }
5915
- xhr.addEventListener("load", () => {
5916
- if (xhr.status >= 200 && xhr.status < 300) {
5917
- resolve();
5918
- } else {
5919
- const snippet = (xhr.responseText || "").slice(0, 200);
5920
- reject(new Error(`Presigned PUT failed: ${xhr.status} ${snippet}`));
5558
+ return () => {
5559
+ listeners.delete(listener);
5560
+ };
5561
+ },
5562
+ outcome,
5563
+ detach: () => {
5564
+ if (!finished) controller.abort();
5565
+ },
5566
+ cancel: () => cancel(state.id),
5567
+ events() {
5568
+ if (claimed)
5569
+ throw new ArbiError("A response handle supports one raw event iterator.", {
5570
+ code: "RESPONSE_EVENTS_ALREADY_CLAIMED"
5571
+ });
5572
+ claimed = true;
5573
+ const close = () => {
5574
+ iteratorClosed = true;
5575
+ queue.length = 0;
5576
+ releaseCapacity();
5577
+ if (pending) {
5578
+ pending.resolve({ value: void 0, done: true });
5579
+ pending = void 0;
5921
5580
  }
5922
- });
5923
- xhr.addEventListener("error", () => reject(new Error("Presigned PUT network error")));
5924
- xhr.addEventListener("abort", () => reject(new Error("Presigned PUT aborted")));
5925
- xhr.send(body);
5926
- });
5927
- return;
5928
- }
5929
- const putRes = await fetch(url, {
5930
- method: "PUT",
5931
- body,
5932
- ...headers ? { headers } : {}
5933
- });
5934
- if (!putRes.ok) {
5935
- const snippet = await putRes.text().catch(() => "");
5936
- throw new Error(`Presigned PUT failed: ${putRes.status} ${snippet.slice(0, 200)}`);
5937
- }
5938
- }
5939
- async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
5940
- if (!options?.workspaceExtId) {
5941
- throw new ArbiError("uploadDocumentsDirect needs options.workspaceExtId (the key's workspace)");
5942
- }
5943
- if (files.length === 0) return { doc_ext_ids: [], skipped: [] };
5944
- const SECRETBOX_ENVELOPE_OVERHEAD = 40;
5945
- const declared = files.map((f2) => ({
5946
- file_name: f2.name,
5947
- file_size: f2.data.length,
5948
- encrypted_file_size: f2.data.length + SECRETBOX_ENVELOPE_OVERHEAD,
5949
- content_hash: client.createContentHash(f2.data, workspaceKey),
5950
- content_type: f2.contentType ?? null
5951
- }));
5952
- const initBody = {
5953
- files: declared,
5954
- shared: options.shared !== false,
5955
- config_ext_id: options.configExtId ?? null,
5956
- // Only sent when set, so a plain upload is accepted by any server version.
5957
- ...options.versionOf ? { version_of: options.versionOf } : {},
5958
- wp_type: options.wpType ?? null,
5959
- tag_ext_id: options.tagExtId ?? null,
5960
- folder: options.folder ? sanitizeFolderPath(options.folder) : null,
5961
- presign_expires_in: options.presignExpiresIn ?? 3600
5581
+ };
5582
+ return {
5583
+ [Symbol.asyncIterator]() {
5584
+ return this;
5585
+ },
5586
+ next() {
5587
+ if (iteratorError) return Promise.reject(iteratorError);
5588
+ if (queue.length) {
5589
+ const value = queue.shift();
5590
+ releaseCapacity();
5591
+ return Promise.resolve({ value, done: false });
5592
+ }
5593
+ if (finished || iteratorClosed)
5594
+ return Promise.resolve({ value: void 0, done: true });
5595
+ if (pending)
5596
+ return Promise.reject(
5597
+ new ArbiError("Concurrent iterator reads are unsupported.", {
5598
+ code: "RESPONSE_EVENTS_CONCURRENT_READ"
5599
+ })
5600
+ );
5601
+ return new Promise((resolve, reject) => {
5602
+ pending = { resolve, reject };
5603
+ });
5604
+ },
5605
+ async return() {
5606
+ close();
5607
+ return { value: void 0, done: true };
5608
+ },
5609
+ async throw(error) {
5610
+ close();
5611
+ throw error;
5612
+ }
5613
+ };
5614
+ }
5962
5615
  };
5963
- const query2 = { workspace_ext_id: options.workspaceExtId };
5964
- const initResult = requireUploadData(
5965
- await arbi.fetch.POST("/v1/document/upload-init", { params: { query: query2 }, body: initBody }),
5966
- "Failed to initialize direct upload"
5967
- );
5968
- const items = initResult.items ?? [];
5969
- const bytesByName = /* @__PURE__ */ new Map();
5970
- for (const f2 of files) {
5971
- if (!bytesByName.has(f2.name)) bytesByName.set(f2.name, []);
5972
- bytesByName.get(f2.name).push(f2.data);
5973
- }
5974
- const skipped = [];
5975
- const toCommit = [];
5976
- const indexByName = /* @__PURE__ */ new Map();
5977
- files.forEach((f2, i2) => {
5978
- if (!indexByName.has(f2.name)) indexByName.set(f2.name, []);
5979
- indexByName.get(f2.name).push(i2);
5980
- });
5981
- for (const item of items) {
5982
- if (item.status !== "uploading" || !item.upload_url || !item.doc_ext_id) {
5983
- skipped.push({
5984
- file_name: item.file_name,
5985
- reason: item.reason || item.status
5616
+ const bind = (id) => {
5617
+ if (bound) return;
5618
+ bound = true;
5619
+ state = immutable({ ...state, id, connection: "streaming" });
5620
+ resolveStart({ kind: "response", handle });
5621
+ };
5622
+ const diagnostic = (code, frame) => emit({ event: "arbi.sdk.protocol_error", data: { code, frame } });
5623
+ const process = (frame) => {
5624
+ if (finished) return;
5625
+ let data;
5626
+ if (frame.event === "reasoning") {
5627
+ emit({
5628
+ event: frame.event,
5629
+ data: frame.data,
5630
+ ...frame.id !== void 0 ? { id: frame.id } : {}
5986
5631
  });
5987
- continue;
5632
+ return;
5633
+ }
5634
+ try {
5635
+ data = JSON.parse(frame.data);
5636
+ } catch {
5637
+ diagnostic("MALFORMED_JSON", frame);
5638
+ return;
5639
+ }
5640
+ const payload = object(data);
5641
+ const raw = object(payload?.response);
5642
+ const id = raw?.id;
5643
+ if (bound && typeof id === "string" && id !== state.id) {
5644
+ diagnostic("CONFLICTING_RESPONSE_ID", frame);
5645
+ return;
5988
5646
  }
5989
- const queue = bytesByName.get(item.file_name);
5990
- const idxQueue = indexByName.get(item.file_name);
5991
- if (!queue || queue.length === 0 || !idxQueue || idxQueue.length === 0) {
5992
- throw new Error(`upload-init returned slot for unknown file: ${item.file_name}`);
5647
+ if (messageId(id)) bind(id);
5648
+ emit({ event: frame.event, data, ...frame.id !== void 0 ? { id: frame.id } : {} });
5649
+ if (frame.event === "arbi.message_queued") acknowledgement = payload;
5650
+ const patch = {};
5651
+ if (frame.event === "arbi.user_message" && !state.conversationId && typeof payload?.conversation_ext_id === "string")
5652
+ patch.conversationId = payload.conversation_ext_id;
5653
+ if (raw) {
5654
+ patch.rawResponse = raw;
5655
+ if (typeof raw.status === "string") patch.responseStatus = raw.status;
5656
+ if (Array.isArray(raw.output))
5657
+ patch.output = raw.output.filter((item2) => !!object(item2));
5658
+ const metadata = object(raw.metadata);
5659
+ const conversation = text(metadata?.conversation_ext_id) ?? text(metadata?.conversation_id) ?? text(raw.conversation_id);
5660
+ if (conversation && (!state.conversationId || state.conversationId === conversation))
5661
+ patch.conversationId = conversation;
5662
+ if (typeof metadata?.content === "string") patch.displayText = metadata.content;
5993
5663
  }
5994
- const raw = queue.shift();
5995
- const fileIndex = idxQueue.shift();
5996
- const ciphertext = client.encryptFile(raw, workspaceKey);
5997
- const total = ciphertext.length;
5998
- try {
5999
- await presignedPut(item.upload_url, ciphertext, (loaded, putTotal) => {
6000
- options.onBytesProgress?.({
6001
- fileIndex,
6002
- fileName: item.file_name,
6003
- loaded,
6004
- total: putTotal
5664
+ const item = object(payload?.item);
5665
+ if ((frame.event === "response.output_item.added" || frame.event === "response.output_item.done") && item) {
5666
+ const output = [...state.output];
5667
+ const index = output.findIndex((existing) => existing.id === item.id);
5668
+ if (index >= 0 && item.id) output[index] = item;
5669
+ else
5670
+ output.splice(
5671
+ typeof payload?.output_index === "number" ? payload.output_index : output.length,
5672
+ 0,
5673
+ item
5674
+ );
5675
+ patch.output = output;
5676
+ }
5677
+ const itemId = text(payload?.item_id);
5678
+ const delta = text(payload?.delta);
5679
+ if (itemId && [
5680
+ "response.content_part.added",
5681
+ "response.output_text.delta",
5682
+ "response.output_text.done",
5683
+ "response.function_call_arguments.delta",
5684
+ "response.reasoning_summary_text.delta"
5685
+ ].includes(frame.event)) {
5686
+ const output = [...patch.output ?? state.output];
5687
+ let index = output.findIndex((existing) => existing.id === itemId);
5688
+ if (index < 0) {
5689
+ index = output.length;
5690
+ output.push({
5691
+ id: itemId,
5692
+ type: frame.event.includes("function_call") ? "function_call" : frame.event.includes("reasoning") ? "reasoning" : "message"
6005
5693
  });
5694
+ }
5695
+ const current = { ...output[index] };
5696
+ if (frame.event === "response.function_call_arguments.delta")
5697
+ current.arguments = (text(current.arguments) ?? "") + (delta ?? "");
5698
+ else {
5699
+ const key = frame.event.includes("reasoning") ? "summary" : "content";
5700
+ const content = Array.isArray(current[key]) ? [...current[key]] : [];
5701
+ const partIndex = typeof payload?.content_index === "number" ? payload.content_index : typeof payload?.summary_index === "number" ? payload.summary_index : 0;
5702
+ const part = {
5703
+ ...object(content[partIndex]) ?? {
5704
+ type: key === "summary" ? "summary_text" : "output_text",
5705
+ text: ""
5706
+ }
5707
+ };
5708
+ if (frame.event === "response.content_part.added")
5709
+ content[partIndex] = object(payload?.part) ?? part;
5710
+ else {
5711
+ part.text = frame.event === "response.output_text.done" ? text(payload?.text) ?? "" : (text(part.text) ?? "") + (delta ?? "");
5712
+ content[partIndex] = part;
5713
+ }
5714
+ current[key] = content;
5715
+ }
5716
+ output[index] = current;
5717
+ patch.output = output;
5718
+ }
5719
+ if (frame.event === "response.output_text.delta" && delta)
5720
+ patch.displayText = state.displayText + delta;
5721
+ if (frame.event === "response.output_text.done" && typeof payload?.text === "string")
5722
+ patch.displayText = payload.text;
5723
+ update(patch);
5724
+ const terminal = /^response\.(completed|failed|cancelled|incomplete)$/.exec(
5725
+ frame.event
5726
+ )?.[1];
5727
+ if (terminal && bound) {
5728
+ const status = raw?.status;
5729
+ const resolved = status === "completed" || status === "failed" || status === "cancelled" || status === "incomplete" ? status : terminal;
5730
+ const error = resolved === "failed" || raw?.error ? new ArbiApiError(
5731
+ text(object(raw?.error)?.message) ?? "Response failed.",
5732
+ { response: raw },
5733
+ void 0,
5734
+ { ...apiErrorMetadata({ response: raw }), responseId: state.id }
5735
+ ) : void 0;
5736
+ finish({
5737
+ status: resolved,
5738
+ responseId: state.id,
5739
+ ...raw ? { response: raw } : {},
5740
+ ...error ? { error } : {}
6006
5741
  });
6007
- } catch (err) {
6008
- throw new Error(
6009
- `Presigned PUT for ${item.doc_ext_id} failed: ${err instanceof Error ? err.message : String(err)}`
6010
- );
6011
5742
  }
6012
- options.onBytesProgress?.({
6013
- fileIndex,
6014
- fileName: item.file_name,
6015
- loaded: total,
6016
- total
6017
- });
6018
- toCommit.push(item.doc_ext_id);
6019
- }
6020
- if (toCommit.length === 0) {
6021
- return { doc_ext_ids: [], skipped };
6022
- }
6023
- const commitResult = requireUploadData(
6024
- await arbi.fetch.POST("/v1/document/upload-commit", {
6025
- params: { query: query2 },
6026
- body: {
6027
- doc_ext_ids: toCommit,
6028
- tag_ext_id: options.tagExtId ?? null
6029
- }
6030
- }),
6031
- "Failed to commit direct upload"
6032
- );
6033
- return {
6034
- doc_ext_ids: commitResult.doc_ext_ids ?? [],
6035
- version: commitResult.version ?? null,
6036
- skipped: [...skipped, ...commitResult.skipped ?? []]
6037
5743
  };
5744
+ controller.signal.addEventListener("abort", abort, { once: true });
5745
+ if (controller.signal.aborted) abort();
5746
+ else if (options.id) bind(options.id);
5747
+ void (async () => {
5748
+ const decoder = new TextDecoder();
5749
+ const frames = new ResponseEventDecoder();
5750
+ try {
5751
+ while (!finished) {
5752
+ const { value, done } = await reader.read();
5753
+ for (const frame of frames.push(decoder.decode(value, { stream: !done }), done)) {
5754
+ process(frame);
5755
+ if (options.bufferEvents && bound && !finished && !iteratorClosed && queue.length >= 256)
5756
+ await new Promise((resolve) => {
5757
+ capacityAvailable = resolve;
5758
+ });
5759
+ }
5760
+ if (done) break;
5761
+ }
5762
+ if (!finished) {
5763
+ if (!bound && acknowledgement) {
5764
+ const value = { status: "acknowledged", responseId: null };
5765
+ resolveStart({
5766
+ kind: "acknowledged",
5767
+ acknowledgement: immutable(acknowledgement),
5768
+ outcome: immutable(value)
5769
+ });
5770
+ finish(value);
5771
+ } else {
5772
+ if (!bound)
5773
+ rejectStart(
5774
+ new ArbiApiError(
5775
+ "Stream ended before response identity was established.",
5776
+ void 0,
5777
+ void 0,
5778
+ { code: "MISSING_RESPONSE_ID" }
5779
+ )
5780
+ );
5781
+ finish({
5782
+ status: "disconnected",
5783
+ responseId: bound ? state.id : null,
5784
+ reason: "connection_closed"
5785
+ });
5786
+ }
5787
+ }
5788
+ } catch (cause) {
5789
+ if (!finished) {
5790
+ const error = transportError(cause, bound ? state.id : void 0);
5791
+ if (!bound) rejectStart(error);
5792
+ finish({
5793
+ status: "disconnected",
5794
+ responseId: bound ? state.id : null,
5795
+ reason: error.name === "AbortError" ? "aborted" : "connection_error",
5796
+ ...error instanceof ArbiError ? { error } : {}
5797
+ });
5798
+ }
5799
+ } finally {
5800
+ reader.releaseLock();
5801
+ }
5802
+ })();
5803
+ return start;
6038
5804
  }
6039
5805
 
6040
- // src/operations/signature-requests.ts
6041
- async function listSignatureRequests(arbi, awaitingMe = false) {
6042
- return requireData(
6043
- await arbi.fetch.GET("/v1/signature-requests", {
6044
- params: { query: { awaiting_me: awaitingMe } }
6045
- }),
6046
- "Failed to list signature requests"
6047
- );
6048
- }
6049
- async function listDocumentSignatureRequests(arbi, docId) {
6050
- return requireData(
6051
- await arbi.fetch.GET("/v1/document/{document_ext_id}/signature-requests", {
6052
- params: { path: { document_ext_id: docId } }
6053
- }),
6054
- "Failed to list the document\u2019s signature requests"
6055
- );
6056
- }
6057
- async function getSignatureRequest(arbi, requestId) {
6058
- return requireData(
6059
- await arbi.fetch.GET("/v1/signature-requests/{request_ext_id}", {
6060
- params: { path: { request_ext_id: requestId } }
6061
- }),
6062
- "Failed to fetch the signature request"
6063
- );
6064
- }
6065
- async function suggestSignatureFields(arbi, docId, version) {
6066
- const data = requireData(
6067
- await arbi.fetch.GET("/v1/document/{document_ext_id}/signature-fields/suggest", {
6068
- params: { path: { document_ext_id: docId }, ...version ? { query: { version } } : {} }
6069
- }),
6070
- "Failed to find signature blocks"
6071
- );
6072
- return data.fields;
6073
- }
6074
- async function createSignatureRequest(arbi, docId, { fields, version, message, send = true }) {
6075
- return requireData(
6076
- await arbi.fetch.POST("/v1/document/{document_ext_id}/signature-requests", {
6077
- params: { path: { document_ext_id: docId } },
6078
- body: { fields, send, message: message ?? null, ...version ? { version } : {} }
6079
- }),
6080
- "Failed to create the signature request"
6081
- );
6082
- }
6083
- async function sendSignatureRequest(arbi, requestId) {
6084
- return requireData(
6085
- await arbi.fetch.POST("/v1/signature-requests/{request_ext_id}/send", {
6086
- params: { path: { request_ext_id: requestId } }
6087
- }),
6088
- "Failed to send the signature request"
6089
- );
6090
- }
6091
- async function voidSignatureRequest(arbi, requestId) {
6092
- return requireData(
6093
- await arbi.fetch.POST("/v1/signature-requests/{request_ext_id}/void", {
6094
- params: { path: { request_ext_id: requestId } }
6095
- }),
6096
- "Failed to void the signature request"
6097
- );
6098
- }
6099
- async function declineSignatureRequest(arbi, requestId, reason) {
6100
- return requireData(
6101
- await arbi.fetch.POST("/v1/signature-requests/{request_ext_id}/decline", {
6102
- params: { path: { request_ext_id: requestId } },
6103
- body: { reason: reason ?? null }
6104
- }),
6105
- "Failed to decline the signature request"
6106
- );
6107
- }
6108
-
6109
- // src/operations/house-template.ts
6110
- var house_template_exports = {};
6111
- __export(house_template_exports, {
6112
- getDeploymentHouseTemplate: () => getDeploymentHouseTemplate,
6113
- isDeploymentAdmin: () => isDeploymentAdmin,
6114
- listHouseTemplateCandidates: () => listHouseTemplateCandidates,
6115
- setDeploymentHouseTemplate: () => setDeploymentHouseTemplate,
6116
- setWorkspaceHouseTemplate: () => setWorkspaceHouseTemplate,
6117
- supportsHouseTemplates: () => supportsHouseTemplates,
6118
- workspaceHouseTemplateId: () => workspaceHouseTemplateId
5806
+ // src/operations/documents.ts
5807
+ var documents_exports = {};
5808
+ __export(documents_exports, {
5809
+ MAX_PAGES: () => MAX_PAGES,
5810
+ SUPPORTED_EXTENSIONS: () => SUPPORTED_EXTENSIONS,
5811
+ deleteDocuments: () => deleteDocuments,
5812
+ downloadDocument: () => downloadDocument,
5813
+ finaliseTranslation: () => finaliseTranslation,
5814
+ getDocuments: () => getDocuments,
5815
+ getParsedContent: () => getParsedContent,
5816
+ getThumbnails: () => getThumbnails,
5817
+ listAll: () => listAll,
5818
+ listDocuments: () => listDocuments,
5819
+ listPaginated: () => listPaginated,
5820
+ listVersions: () => listVersions,
5821
+ mimeFromName: () => mimeFromName,
5822
+ presignedPut: () => presignedPut,
5823
+ sanitizeFolderPath: () => sanitizeFolderPath,
5824
+ similarDocuments: () => similarDocuments,
5825
+ updateDocuments: () => updateDocuments,
5826
+ uploadDocuments: () => uploadDocuments,
5827
+ uploadDocumentsDirect: () => uploadDocumentsDirect,
5828
+ uploadFile: () => uploadFile,
5829
+ uploadFiles: () => uploadFiles,
5830
+ uploadUrl: () => uploadUrl
6119
5831
  });
6120
- function supportsHouseTemplates(workspace) {
6121
- return !!workspace && "house_template_ext_id" in workspace;
6122
- }
6123
- function workspaceHouseTemplateId(workspace) {
6124
- return workspace?.house_template_ext_id ?? null;
6125
- }
6126
- function isDeploymentAdmin(user) {
6127
- return user?.is_deployment_admin === true;
5832
+ var MAX_PAGES = 400;
5833
+ var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
5834
+ ".pdf",
5835
+ ".txt",
5836
+ ".md",
5837
+ ".html",
5838
+ ".htm",
5839
+ ".doc",
5840
+ ".docx",
5841
+ ".rtf",
5842
+ ".ppt",
5843
+ ".pptx",
5844
+ ".xls",
5845
+ ".xlsx",
5846
+ ".jpg",
5847
+ ".jpeg",
5848
+ ".png",
5849
+ ".gif",
5850
+ ".bmp",
5851
+ ".tiff",
5852
+ ".tif",
5853
+ ".webp",
5854
+ // Video (store only, no parsing)
5855
+ ".mp4",
5856
+ ".mpeg",
5857
+ ".mpg",
5858
+ ".webm",
5859
+ ".mov",
5860
+ ".avi",
5861
+ ".mkv",
5862
+ // Audio (store only, no parsing)
5863
+ ".mp3",
5864
+ ".wav",
5865
+ ".m4a",
5866
+ ".aac",
5867
+ ".ogg",
5868
+ ".flac",
5869
+ // Email formats (parsed for content)
5870
+ ".eml",
5871
+ ".msg",
5872
+ ".mbox",
5873
+ ".pst",
5874
+ ".ost"
5875
+ ]);
5876
+ function sanitizeFolderPath(folderPath) {
5877
+ return folderPath.replace(/[\x00-\x1f\x7f]/g, "").replace(/\\/g, "/").replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "").trim();
6128
5878
  }
6129
- function filenameOf(response) {
6130
- const header = response.headers.get("Content-Disposition") ?? "";
6131
- const star = /filename\*=UTF-8''([^;]+)/i.exec(header);
6132
- if (star) return decodeURIComponent(star[1]);
6133
- return /filename="?([^";]+)"?/i.exec(header)?.[1];
5879
+ async function listDocuments(arbi, workspaceExtId) {
5880
+ if (!workspaceExtId) {
5881
+ return requireData(await arbi.fetch.GET("/v1/document/list"), "Failed to fetch documents");
5882
+ }
5883
+ const docs = requireData(
5884
+ await arbi.fetch.GET("/v1/document/list", {
5885
+ params: { query: { workspace_ext_id: workspaceExtId } }
5886
+ }),
5887
+ "Failed to fetch documents"
5888
+ );
5889
+ if (docs.some((doc) => doc.workspace_ext_id !== workspaceExtId)) {
5890
+ throw new ArbiError(`This server cannot list workspace ${workspaceExtId} without opening it`);
5891
+ }
5892
+ return docs;
6134
5893
  }
6135
- async function getDeploymentHouseTemplate(arbi) {
6136
- const { data, error, response } = await arbi.fetch.GET("/v1/deployment/house-template", {
6137
- parseAs: "arrayBuffer"
6138
- });
6139
- const status = response.status;
6140
- if (status === 204 || status === 404) return null;
6141
- if (error || !data)
6142
- throw new ArbiApiError("Could not read the deployment house template", error, status);
6143
- return {
6144
- bytes: new Uint8Array(data),
6145
- name: filenameOf(response) ?? "House template.dotx"
5894
+ async function* listPaginated(arbi, options = {}) {
5895
+ const {
5896
+ pageSize = 5e3,
5897
+ firstPageSize,
5898
+ order = "id_asc",
5899
+ fields,
5900
+ signal,
5901
+ lookahead = 1,
5902
+ workspaceExtId
5903
+ } = options;
5904
+ const fetchPage = async (pageOffset, limit) => {
5905
+ const query2 = {
5906
+ limit,
5907
+ offset: pageOffset,
5908
+ order
5909
+ };
5910
+ if (fields) query2.fields = fields;
5911
+ if (workspaceExtId) query2.workspace_ext_id = workspaceExtId;
5912
+ const { data, error } = await arbi.fetch.GET("/v1/document/list", {
5913
+ params: { query: query2 },
5914
+ signal
5915
+ });
5916
+ if (error) {
5917
+ throw new Error(typeof error === "string" ? error : JSON.stringify(error));
5918
+ }
5919
+ const page = data ?? [];
5920
+ if (workspaceExtId && page.some((doc) => doc.workspace_ext_id !== workspaceExtId)) {
5921
+ throw new ArbiError(`The server returned another workspace's documents for ${workspaceExtId}`);
5922
+ }
5923
+ return page;
6146
5924
  };
6147
- }
6148
- async function setDeploymentHouseTemplate(arbi, file) {
6149
- if (!file) {
6150
- requireOk(
6151
- await arbi.fetch.DELETE("/v1/deployment/house-template"),
6152
- "Could not clear the deployment house template"
5925
+ if (signal?.aborted) return;
5926
+ const depth = Math.max(1, Math.min(lookahead, MAX_PAGES));
5927
+ let issued = 0;
5928
+ let pagesYielded = 0;
5929
+ let nextOffsetToIssue = 0;
5930
+ let done = false;
5931
+ const queue = [];
5932
+ const tryEnqueue = () => {
5933
+ while (!done && queue.length < depth && issued < MAX_PAGES) {
5934
+ const limit = issued === 0 && firstPageSize !== void 0 ? firstPageSize : pageSize;
5935
+ const promise = fetchPage(nextOffsetToIssue, limit);
5936
+ promise.catch(() => {
5937
+ });
5938
+ queue.push({ limit, promise });
5939
+ nextOffsetToIssue += limit;
5940
+ issued++;
5941
+ }
5942
+ };
5943
+ tryEnqueue();
5944
+ while (queue.length > 0 && !signal?.aborted) {
5945
+ const { limit, promise } = queue.shift();
5946
+ const page = await promise;
5947
+ if (signal?.aborted) return;
5948
+ const isShort = page.length < limit;
5949
+ if (isShort) done = true;
5950
+ tryEnqueue();
5951
+ if (page.length > 0) {
5952
+ yield page;
5953
+ pagesYielded++;
5954
+ }
5955
+ if (isShort) return;
5956
+ if (pagesYielded >= MAX_PAGES) break;
5957
+ }
5958
+ if (!signal?.aborted && !done && pagesYielded >= MAX_PAGES) {
5959
+ console.warn(
5960
+ `[arbi-sdk] listPaginated hit MAX_PAGES (${MAX_PAGES}) \u2014 stopped. Workspace may have more than ${MAX_PAGES * pageSize} documents.`
6153
5961
  );
6154
- return;
6155
5962
  }
6156
- const form = new FormData();
6157
- form.append("file", file);
6158
- requireOk(
6159
- await arbi.fetch.PUT("/v1/deployment/house-template", {
6160
- // The schema types the multipart file as a string; the FormData is sent as is.
6161
- body: form,
6162
- bodySerializer: () => form
6163
- }),
6164
- "Could not set the deployment house template"
6165
- );
6166
5963
  }
6167
- async function setWorkspaceHouseTemplate(arbi, documentId) {
6168
- requireData(
6169
- await arbi.fetch.PATCH("/v1/workspace/", { body: { house_template_ext_id: documentId } }),
6170
- "Could not set the house template"
6171
- );
5964
+ async function listAll(arbi, options = {}) {
5965
+ const all = [];
5966
+ const seen = /* @__PURE__ */ new Set();
5967
+ for await (const page of listPaginated(arbi, options)) {
5968
+ for (const doc of page) {
5969
+ const id = doc.external_id;
5970
+ if (id && !seen.has(id)) {
5971
+ seen.add(id);
5972
+ all.push(doc);
5973
+ }
5974
+ }
5975
+ }
5976
+ return all;
6172
5977
  }
6173
- async function listHouseTemplateCandidates(arbi) {
5978
+ async function getDocuments(arbi, externalIds) {
6174
5979
  return requireData(
6175
- await arbi.fetch.GET("/v1/workspace/house-template/candidates"),
6176
- "Could not list the documents that can be the house template"
5980
+ await arbi.fetch.GET("/v1/document/", { params: { query: { external_ids: externalIds } } }),
5981
+ "Failed to fetch documents"
6177
5982
  );
6178
5983
  }
6179
-
6180
- // src/operations/model-connections.ts
6181
- var model_connections_exports = {};
6182
- __export(model_connections_exports, {
6183
- directUsage: () => directUsage,
6184
- listConnections: () => listConnections,
6185
- removeConnection: () => removeConnection,
6186
- savePersonalConnection: () => savePersonalConnection,
6187
- sealPersonalApiKey: () => sealPersonalApiKey,
6188
- unlockModelConnections: () => unlockModelConnections
6189
- });
6190
- var FAILED = "Could not update model connections";
6191
- async function listConnections(arbi) {
6192
- return requireData(await arbi.fetch.GET("/v1/model-connections"), FAILED);
6193
- }
6194
- async function directUsage(arbi) {
5984
+ async function listVersions(arbi, docId) {
6195
5985
  return requireData(
6196
- await arbi.fetch.GET("/v1/model-connections/usage"),
6197
- FAILED
5986
+ await arbi.fetch.GET("/v1/document/{document_ext_id}/versions", {
5987
+ params: { path: { document_ext_id: docId } }
5988
+ }),
5989
+ "Failed to fetch document versions"
6198
5990
  );
6199
5991
  }
6200
- async function savePersonalConnection(arbi, body, id) {
6201
- const result = id ? await arbi.fetch.PUT("/v1/model-connections/personal/{connection_id}", {
6202
- params: { path: { connection_id: id } },
6203
- body
6204
- }) : await arbi.fetch.POST("/v1/model-connections/personal", { body });
6205
- return requireData(result, FAILED);
5992
+ async function finaliseTranslation(arbi, docId) {
5993
+ return requireData(
5994
+ await arbi.fetch.POST("/v1/document/{document_ext_id}/finalise-translation", {
5995
+ params: { path: { document_ext_id: docId } }
5996
+ }),
5997
+ "Failed to finalise the translation"
5998
+ );
6206
5999
  }
6207
- async function removeConnection(arbi, id) {
6000
+ async function deleteDocuments(arbi, externalIds) {
6208
6001
  requireOk(
6209
- await arbi.fetch.DELETE("/v1/model-connections/{connection_id}", {
6210
- params: { path: { connection_id: id } }
6211
- }),
6212
- FAILED
6002
+ await arbi.fetch.DELETE("/v1/document/", { body: { external_ids: externalIds } }),
6003
+ "Failed to delete documents"
6213
6004
  );
6214
6005
  }
6215
- async function sealPersonalApiKey(apiKey, signingPrivateKey) {
6216
- await client.initSodium();
6217
- const pair = client.encryptionKeypairFromSigningKey(signingPrivateKey);
6218
- const bytes = new TextEncoder().encode(apiKey);
6219
- try {
6220
- return client.sealedBoxEncrypt(bytes, pair.publicKey);
6221
- } finally {
6222
- bytes.fill(0);
6223
- pair.secretKey.fill(0);
6224
- }
6006
+ async function updateDocuments(arbi, documents) {
6007
+ return requireData(
6008
+ await arbi.fetch.PATCH("/v1/document/", { body: { documents } }),
6009
+ "Failed to update documents"
6010
+ );
6225
6011
  }
6226
- async function unlockModelConnections(arbi, keys, onlyId) {
6227
- await client.initSodium();
6228
- const pair = client.encryptionKeypairFromSigningKey(keys.signingPrivateKey);
6229
- try {
6230
- const rows = requireData(
6231
- await arbi.fetch.GET("/v1/model-connections/sealed-keys"),
6232
- FAILED
6233
- );
6234
- for (const row of rows) {
6235
- if (onlyId && onlyId !== row.id || !row.sealed_api_key || !row.enabled) continue;
6236
- const bytes = client.sealedBoxDecrypt(row.sealed_api_key, pair.secretKey);
6237
- try {
6238
- requireOk(
6239
- await arbi.fetch.POST("/v1/model-connections/session-key", {
6240
- body: {
6241
- connection_id: row.id,
6242
- sealed_api_key: client.sealedBoxEncrypt(bytes, keys.serverSessionKey)
6243
- }
6244
- }),
6245
- FAILED
6246
- );
6247
- } finally {
6248
- bytes.fill(0);
6012
+ async function uploadUrl(arbi, urls, options) {
6013
+ return requireUploadData(
6014
+ await arbi.fetch.POST("/v1/document/upload-url", {
6015
+ params: {
6016
+ query: {
6017
+ urls,
6018
+ shared: options.shared ?? false,
6019
+ workspace_ext_id: options.workspaceExtId,
6020
+ ...options.configExtId ? { config_ext_id: options.configExtId } : {}
6021
+ }
6249
6022
  }
6250
- }
6251
- } finally {
6252
- pair.secretKey.fill(0);
6253
- }
6023
+ }),
6024
+ "Failed to upload from URLs"
6025
+ );
6254
6026
  }
6255
-
6256
- // src/operations/secure-mail.ts
6257
- var secure_mail_exports = {};
6258
- __export(secure_mail_exports, {
6259
- claimSecureMail: () => claimSecureMail,
6260
- prepareSecureMail: () => prepareSecureMail,
6261
- secureMime: () => secureMime
6262
- });
6263
- var MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
6264
- var utf8 = new TextEncoder();
6265
- var encodedWord = (value) => `=?UTF-8?B?${bytesToBase64(utf8.encode(value))}?=`;
6266
- var folded = (value) => value.match(/.{1,76}/g)?.join("\r\n") ?? "";
6267
- var safeHeader = (value) => {
6268
- if (/[\r\n\0]/.test(value)) throw new Error("Email headers cannot contain newlines");
6269
- return value;
6027
+ var UPLOAD_WORKSPACE_CONFLICT_MESSAGES = {
6028
+ workspace_mismatch: "These files were prepared for another workspace, so they were not saved. Upload them again.",
6029
+ workspace_key_required: "The workspace couldn't be unlocked for this upload, so the files were not saved."
6270
6030
  };
6271
- function secureMime(compose, sender) {
6272
- const address = (r2) => `${r2.name ? encodedWord(safeHeader(r2.name)) + " " : ""}<${safeHeader(r2.email)}>`;
6273
- const boundary = "arbi-" + crypto.randomUUID();
6274
- const headers = [
6275
- `From: ${address({ email: sender.email, name: sender.display_name })}`,
6276
- ...compose.to.length ? [`To: ${compose.to.map(address).join(", ")}`] : [],
6277
- ...compose.cc.length ? [`Cc: ${compose.cc.map(address).join(", ")}`] : [],
6278
- `Subject: ${encodedWord(safeHeader(compose.subject))}`,
6279
- `Date: ${(/* @__PURE__ */ new Date()).toUTCString()}`,
6280
- `Message-ID: <${crypto.randomUUID()}@${sender.email.split("@")[1]}>`,
6281
- ...compose.in_reply_to ? [`In-Reply-To: ${safeHeader(compose.in_reply_to)}`] : [],
6282
- ...compose.references?.length ? [`References: ${compose.references.map(safeHeader).join(" ")}`] : [],
6283
- "MIME-Version: 1.0",
6284
- "X-ARBI-Secure-Delivery: 1",
6285
- `Content-Type: multipart/mixed; boundary="${boundary}"`
6286
- ];
6287
- const alternative = "alternative-" + crypto.randomUUID();
6288
- const plainPart = `Content-Type: text/plain; charset="utf-8"\r
6289
- Content-Transfer-Encoding: base64\r
6290
- \r
6291
- ${folded(bytesToBase64(utf8.encode(compose.text)))}`;
6292
- const bodyPart = compose.html ? `Content-Type: multipart/alternative; boundary="${alternative}"\r
6293
- \r
6294
- --${alternative}\r
6295
- ${plainPart}\r
6296
- --${alternative}\r
6297
- Content-Type: text/html; charset="utf-8"\r
6298
- Content-Transfer-Encoding: base64\r
6299
- \r
6300
- ${folded(bytesToBase64(utf8.encode(compose.html)))}\r
6301
- --${alternative}--\r
6302
- ` : plainPart;
6303
- const parts = [
6304
- `--${boundary}\r
6305
- ${bodyPart}`,
6306
- ...compose.attachments.map((a2) => {
6307
- if (!a2.content_base64) throw new Error("Attachment content is missing");
6308
- const name = encodeURIComponent(safeHeader(a2.name)).replace(/'/g, "%27");
6309
- return `--${boundary}\r
6310
- Content-Type: ${safeHeader(a2.content_type || "application/octet-stream")}\r
6311
- Content-Disposition: attachment; filename*=UTF-8''${name}\r
6312
- Content-Transfer-Encoding: base64\r
6313
- \r
6314
- ${folded(a2.content_base64)}`;
6031
+ function requireUploadData(result, message) {
6032
+ return requireWorkspaceData(result, message, UPLOAD_WORKSPACE_CONFLICT_MESSAGES);
6033
+ }
6034
+ async function uploadDocuments(arbi, files, options = {}) {
6035
+ const query2 = {};
6036
+ if (options.shared !== void 0) query2.shared = options.shared;
6037
+ if (options.folder) query2.folder = sanitizeFolderPath(options.folder);
6038
+ if (options.configExtId) query2.config_ext_id = options.configExtId;
6039
+ if (options.wpType) query2.wp_type = options.wpType;
6040
+ if (options.versionOf) query2.version_of = options.versionOf;
6041
+ if (options.tagExtId) query2.tag_ext_id = options.tagExtId;
6042
+ if (options.workspaceExtId) query2.workspace_ext_id = options.workspaceExtId;
6043
+ if (options.derivedFrom) {
6044
+ query2.derived_from = options.derivedFrom.docId;
6045
+ query2.derived_role = options.derivedFrom.role;
6046
+ }
6047
+ const result = await arbi.fetch.POST("/v1/document/upload", {
6048
+ params: { query: query2 },
6049
+ ...options.onProgress ? { fetch: progressFetch(options.onProgress, arbi.http) } : {},
6050
+ // The schema types the files as strings; they go as multipart parts.
6051
+ body: { files },
6052
+ bodySerializer: () => {
6053
+ const form = new FormData();
6054
+ for (const file of files) form.append("files", file);
6055
+ return form;
6056
+ }
6057
+ });
6058
+ return requireUploadData(result, "Failed to upload documents");
6059
+ }
6060
+ async function similarDocuments(arbi, options = {}) {
6061
+ return requireData(
6062
+ await arbi.fetch.GET("/v1/document/similar", {
6063
+ params: {
6064
+ query: {
6065
+ ...options.threshold !== void 0 ? { threshold: options.threshold } : {},
6066
+ ...options.docId ? { doc_ext_id: options.docId } : {}
6067
+ }
6068
+ }
6315
6069
  }),
6316
- `--${boundary}--\r
6317
- `
6318
- ];
6319
- return utf8.encode(headers.join("\r\n") + "\r\n\r\n" + parts.join("\r\n"));
6070
+ "Failed to fetch similar documents"
6071
+ );
6320
6072
  }
6321
- async function prepareSecureMail(compose, sender, { requestId, senderPublicKey, frontendOrigin }) {
6322
- const raw = secureMime(compose, sender);
6323
- try {
6324
- if (raw.length > MAX_MESSAGE_BYTES) throw new Error("Email exceeds the message size limit");
6325
- const metadata = {
6326
- secure_delivery: true,
6327
- id: "",
6328
- subject: compose.subject,
6329
- sender: [{ email: sender.email, name: sender.display_name }],
6330
- to: compose.to,
6331
- cc: compose.cc,
6332
- bcc: [],
6333
- received_at: (/* @__PURE__ */ new Date()).toISOString(),
6334
- preview: compose.text.slice(0, 220),
6335
- unread: false,
6336
- text: "",
6337
- references: compose.references ?? [],
6338
- attachments: compose.attachments.map((a2, i2) => ({
6339
- ...a2,
6340
- id: String(i2),
6341
- content_base64: null
6342
- }))
6343
- };
6344
- const recipients = [
6345
- ...new Set([...compose.to, ...compose.cc, ...compose.bcc].map((r2) => r2.email.toLowerCase()))
6346
- ];
6347
- const sealed = await client.sealSecureMail(raw, metadata, senderPublicKey);
6348
- return {
6349
- request_id: requestId,
6350
- draft_id: compose.draft_id,
6351
- recipients: recipients.map((email) => ({
6352
- id: crypto.randomUUID(),
6353
- email,
6354
- fragment_key: sealed.fragment_key
6355
- })),
6356
- ciphertext: sealed.ciphertext,
6357
- metadata_ciphertext: sealed.metadata_ciphertext,
6358
- sender_wrapped_key: sealed.sender_wrapped_key,
6359
- frontend_origin: frontendOrigin
6360
- };
6361
- } finally {
6362
- raw.fill(0);
6073
+ async function getParsedContent(auth, docId, stage, version) {
6074
+ const res = await authenticatedFetch({
6075
+ ...auth,
6076
+ path: `/v1/document/${docId}/parsed-${stage}${version ? `?version=${version}` : ""}`
6077
+ });
6078
+ return res.json();
6079
+ }
6080
+ async function getThumbnails(auth, docIds) {
6081
+ if (docIds.length === 0) return {};
6082
+ const res = await authenticatedFetch({
6083
+ ...auth,
6084
+ path: `/v1/document/thumbnails`,
6085
+ method: "POST",
6086
+ headers: { "Content-Type": "application/json" },
6087
+ body: JSON.stringify({ document_ext_ids: docIds })
6088
+ });
6089
+ const json2 = await res.json();
6090
+ return json2.thumbnails ?? {};
6091
+ }
6092
+ async function uploadFile(auth, fileData, fileName, options) {
6093
+ const formData = new FormData();
6094
+ formData.append("files", fileData, fileName);
6095
+ const params = new URLSearchParams();
6096
+ if (options?.shared !== void 0) params.set("shared", String(options.shared));
6097
+ if (options?.folder) params.set("folder", sanitizeFolderPath(options.folder));
6098
+ if (options?.configExtId) params.set("config_ext_id", options.configExtId);
6099
+ if (options?.wpType) params.set("wp_type", options.wpType);
6100
+ if (options?.versionOf) params.set("version_of", options.versionOf);
6101
+ if (options?.workspaceExtId) params.set("workspace_ext_id", options.workspaceExtId);
6102
+ if (options?.derivedFrom) {
6103
+ params.set("derived_from", options.derivedFrom.docId);
6104
+ params.set("derived_role", options.derivedFrom.role);
6363
6105
  }
6106
+ const qs = params.toString();
6107
+ const res = await authenticatedFetch({
6108
+ ...auth,
6109
+ path: qs ? `/v1/document/upload?${qs}` : `/v1/document/upload`,
6110
+ method: "POST",
6111
+ body: formData
6112
+ });
6113
+ return res.json();
6364
6114
  }
6365
- async function claimSecureMail(mail, id, fragmentKey, recipientPublicKey) {
6366
- const key = client.decodeSecureMailKey(fragmentKey);
6367
- try {
6368
- const path2 = `/secure/${encodeURIComponent(id)}`;
6369
- const response = await mail(path2);
6370
- const { raw } = await client.openSecureMail(await response.json(), key);
6371
- raw.fill(0);
6372
- const claim = await client.secureMailClaim(key, recipientPublicKey);
6373
- const claimed = await mail(`${path2}/claim`, { method: "POST", body: JSON.stringify(claim) });
6374
- return await claimed.json();
6375
- } finally {
6376
- key.fill(0);
6115
+ async function uploadFiles(auth, files, options) {
6116
+ const formData = new FormData();
6117
+ for (const f2 of files) formData.append("files", f2.data, f2.name);
6118
+ const params = new URLSearchParams();
6119
+ if (options?.folder) params.set("folder", sanitizeFolderPath(options.folder));
6120
+ if (options?.configExtId) params.set("config_ext_id", options.configExtId);
6121
+ if (options?.wpType) params.set("wp_type", options.wpType);
6122
+ if (options?.versionOf) params.set("version_of", options.versionOf);
6123
+ if (options?.derivedFrom) {
6124
+ params.set("derived_from", options.derivedFrom.docId);
6125
+ params.set("derived_role", options.derivedFrom.role);
6377
6126
  }
6127
+ const qs = params.toString();
6128
+ const res = await authenticatedFetch({
6129
+ ...auth,
6130
+ path: qs ? `/v1/document/upload?${qs}` : `/v1/document/upload`,
6131
+ method: "POST",
6132
+ body: formData
6133
+ });
6134
+ return res.json();
6378
6135
  }
6379
-
6380
- // src/operations/workspaces.ts
6381
- var workspaces_exports = {};
6382
- __export(workspaces_exports, {
6383
- EXTERNAL_ACCESS_SECONDS: () => EXTERNAL_ACCESS_SECONDS,
6384
- addWorkspaceMembers: () => addWorkspaceMembers,
6385
- addWorkspaceMembersBody: () => addWorkspaceMembersBody,
6386
- addWorkspaceUsers: () => addWorkspaceUsers,
6387
- archiveWorkspace: () => archiveWorkspace,
6388
- cancelWorkspaceTransfer: () => cancelWorkspaceTransfer,
6389
- copyDocuments: () => copyDocuments,
6390
- createWorkspace: () => createWorkspace,
6391
- deleteWorkspaces: () => deleteWorkspaces,
6392
- exportWorkspaceData: () => exportWorkspaceData,
6393
- getWorkspaceAccessStatus: () => getWorkspaceAccessStatus,
6394
- getWorkspaceActivity: () => getWorkspaceActivity,
6395
- getWorkspaceArchive: () => getWorkspaceArchive,
6396
- getWorkspaceTransfer: () => getWorkspaceTransfer,
6397
- grantTemporaryWorkspaceAccess: () => grantTemporaryWorkspaceAccess,
6398
- listWorkspaceTransfers: () => listWorkspaceTransfers,
6399
- listWorkspaceUsers: () => listWorkspaceUsers,
6400
- listWorkspaces: () => listWorkspaces,
6401
- moveWorkspaceToProject: () => moveWorkspaceToProject,
6402
- planWorkspaceTransfer: () => planWorkspaceTransfer,
6403
- primeWorkspaceKey: () => primeWorkspaceKey,
6404
- removeWorkspaceUsers: () => removeWorkspaceUsers,
6405
- resumeWorkspaceTransfer: () => resumeWorkspaceTransfer,
6406
- setUserRole: () => setUserRole,
6407
- startWorkspaceTransfer: () => startWorkspaceTransfer,
6408
- unarchiveWorkspace: () => unarchiveWorkspace,
6409
- updateWorkspace: () => updateWorkspace
6410
- });
6411
- async function listWorkspaces(arbi) {
6412
- return requireData(await arbi.fetch.GET("/v1/user/workspaces"), "Failed to fetch workspaces");
6136
+ async function downloadDocument(auth, docId, version) {
6137
+ return authenticatedFetch({
6138
+ ...auth,
6139
+ path: `/v1/document/${docId}/download${version ? `?version=${version}` : ""}`
6140
+ });
6413
6141
  }
6414
- async function createWorkspace(arbi, name, encryptedWorkspaceKey, projectExtId, description, isPublic = false) {
6415
- return requireData(
6416
- await arbi.fetch.POST("/v1/workspace/create_protected", {
6417
- body: {
6418
- name,
6419
- description: description ?? null,
6420
- is_public: isPublic,
6421
- workspace_key: encryptedWorkspaceKey,
6422
- project_ext_id: projectExtId
6142
+ function mimeFromName(name) {
6143
+ const dot = name.lastIndexOf(".");
6144
+ const ext = dot === -1 ? "" : name.slice(dot).toLowerCase();
6145
+ switch (ext) {
6146
+ case ".pdf":
6147
+ return "application/pdf";
6148
+ case ".txt":
6149
+ return "text/plain";
6150
+ case ".md":
6151
+ return "text/markdown";
6152
+ case ".html":
6153
+ case ".htm":
6154
+ return "text/html";
6155
+ case ".doc":
6156
+ return "application/msword";
6157
+ case ".docx":
6158
+ return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
6159
+ case ".xls":
6160
+ return "application/vnd.ms-excel";
6161
+ case ".xlsx":
6162
+ return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
6163
+ case ".ppt":
6164
+ return "application/vnd.ms-powerpoint";
6165
+ case ".pptx":
6166
+ return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
6167
+ case ".eml":
6168
+ return "message/rfc822";
6169
+ case ".pst":
6170
+ case ".ost":
6171
+ return "application/vnd.ms-outlook";
6172
+ default:
6173
+ return void 0;
6174
+ }
6175
+ }
6176
+ async function presignedPut(url, body, onProgress, headers) {
6177
+ const XhrGlobal = globalThis.XMLHttpRequest;
6178
+ if (XhrGlobal) {
6179
+ await new Promise((resolve, reject) => {
6180
+ const xhr = new XhrGlobal();
6181
+ xhr.open("PUT", url);
6182
+ for (const [name, value] of Object.entries(headers ?? {})) {
6183
+ xhr.setRequestHeader(name, value);
6423
6184
  }
6424
- }),
6425
- "Failed to create workspace"
6426
- );
6185
+ if (onProgress) {
6186
+ xhr.upload.addEventListener("progress", (e) => {
6187
+ if (e.lengthComputable) onProgress(e.loaded, e.total);
6188
+ });
6189
+ }
6190
+ xhr.addEventListener("load", () => {
6191
+ if (xhr.status >= 200 && xhr.status < 300) {
6192
+ resolve();
6193
+ } else {
6194
+ const snippet = (xhr.responseText || "").slice(0, 200);
6195
+ reject(new Error(`Presigned PUT failed: ${xhr.status} ${snippet}`));
6196
+ }
6197
+ });
6198
+ xhr.addEventListener("error", () => reject(new Error("Presigned PUT network error")));
6199
+ xhr.addEventListener("abort", () => reject(new Error("Presigned PUT aborted")));
6200
+ xhr.send(body);
6201
+ });
6202
+ return;
6203
+ }
6204
+ const putRes = await fetch(url, {
6205
+ method: "PUT",
6206
+ body,
6207
+ ...headers ? { headers } : {}
6208
+ });
6209
+ if (!putRes.ok) {
6210
+ const snippet = await putRes.text().catch(() => "");
6211
+ throw new Error(`Presigned PUT failed: ${putRes.status} ${snippet.slice(0, 200)}`);
6212
+ }
6427
6213
  }
6428
- async function moveWorkspaceToProject(arbi, workspaceExtId, projectExtId) {
6429
- return requireData(
6430
- await arbi.fetch.PUT("/v1/workspace/{workspace_ext_id}/project", {
6431
- params: { path: { workspace_ext_id: workspaceExtId } },
6432
- body: { project_ext_id: projectExtId }
6214
+ async function uploadDocumentsDirect(arbi, workspaceKey, files, options) {
6215
+ if (!options?.workspaceExtId) {
6216
+ throw new ArbiError("uploadDocumentsDirect needs options.workspaceExtId (the key's workspace)");
6217
+ }
6218
+ if (files.length === 0) return { doc_ext_ids: [], skipped: [] };
6219
+ const SECRETBOX_ENVELOPE_OVERHEAD = 40;
6220
+ const declared = files.map((f2) => ({
6221
+ file_name: f2.name,
6222
+ file_size: f2.data.length,
6223
+ encrypted_file_size: f2.data.length + SECRETBOX_ENVELOPE_OVERHEAD,
6224
+ content_hash: client.createContentHash(f2.data, workspaceKey),
6225
+ content_type: f2.contentType ?? null
6226
+ }));
6227
+ const initBody = {
6228
+ files: declared,
6229
+ shared: options.shared !== false,
6230
+ config_ext_id: options.configExtId ?? null,
6231
+ // Only sent when set, so a plain upload is accepted by any server version.
6232
+ ...options.versionOf ? { version_of: options.versionOf } : {},
6233
+ wp_type: options.wpType ?? null,
6234
+ tag_ext_id: options.tagExtId ?? null,
6235
+ folder: options.folder ? sanitizeFolderPath(options.folder) : null,
6236
+ presign_expires_in: options.presignExpiresIn ?? 3600
6237
+ };
6238
+ const query2 = { workspace_ext_id: options.workspaceExtId };
6239
+ const initResult = requireUploadData(
6240
+ await arbi.fetch.POST("/v1/document/upload-init", { params: { query: query2 }, body: initBody }),
6241
+ "Failed to initialize direct upload"
6242
+ );
6243
+ const items = initResult.items ?? [];
6244
+ const bytesByName = /* @__PURE__ */ new Map();
6245
+ for (const f2 of files) {
6246
+ if (!bytesByName.has(f2.name)) bytesByName.set(f2.name, []);
6247
+ bytesByName.get(f2.name).push(f2.data);
6248
+ }
6249
+ const skipped = [];
6250
+ const toCommit = [];
6251
+ const indexByName = /* @__PURE__ */ new Map();
6252
+ files.forEach((f2, i2) => {
6253
+ if (!indexByName.has(f2.name)) indexByName.set(f2.name, []);
6254
+ indexByName.get(f2.name).push(i2);
6255
+ });
6256
+ for (const item of items) {
6257
+ if (item.status !== "uploading" || !item.upload_url || !item.doc_ext_id) {
6258
+ skipped.push({
6259
+ file_name: item.file_name,
6260
+ reason: item.reason || item.status
6261
+ });
6262
+ continue;
6263
+ }
6264
+ const queue = bytesByName.get(item.file_name);
6265
+ const idxQueue = indexByName.get(item.file_name);
6266
+ if (!queue || queue.length === 0 || !idxQueue || idxQueue.length === 0) {
6267
+ throw new Error(`upload-init returned slot for unknown file: ${item.file_name}`);
6268
+ }
6269
+ const raw = queue.shift();
6270
+ const fileIndex = idxQueue.shift();
6271
+ const ciphertext = client.encryptFile(raw, workspaceKey);
6272
+ const total = ciphertext.length;
6273
+ try {
6274
+ await presignedPut(item.upload_url, ciphertext, (loaded, putTotal) => {
6275
+ options.onBytesProgress?.({
6276
+ fileIndex,
6277
+ fileName: item.file_name,
6278
+ loaded,
6279
+ total: putTotal
6280
+ });
6281
+ });
6282
+ } catch (err) {
6283
+ throw new Error(
6284
+ `Presigned PUT for ${item.doc_ext_id} failed: ${err instanceof Error ? err.message : String(err)}`
6285
+ );
6286
+ }
6287
+ options.onBytesProgress?.({
6288
+ fileIndex,
6289
+ fileName: item.file_name,
6290
+ loaded: total,
6291
+ total
6292
+ });
6293
+ toCommit.push(item.doc_ext_id);
6294
+ }
6295
+ if (toCommit.length === 0) {
6296
+ return { doc_ext_ids: [], skipped };
6297
+ }
6298
+ const commitResult = requireUploadData(
6299
+ await arbi.fetch.POST("/v1/document/upload-commit", {
6300
+ params: { query: query2 },
6301
+ body: {
6302
+ doc_ext_ids: toCommit,
6303
+ tag_ext_id: options.tagExtId ?? null
6304
+ }
6433
6305
  }),
6434
- "Failed to move workspace"
6306
+ "Failed to commit direct upload"
6435
6307
  );
6308
+ return {
6309
+ doc_ext_ids: commitResult.doc_ext_ids ?? [],
6310
+ version: commitResult.version ?? null,
6311
+ skipped: [...skipped, ...commitResult.skipped ?? []]
6312
+ };
6436
6313
  }
6437
- async function getWorkspaceArchive(arbi, workspaceExtId) {
6314
+
6315
+ // src/operations/signature-requests.ts
6316
+ async function listSignatureRequests(arbi, awaitingMe = false) {
6438
6317
  return requireData(
6439
- await arbi.fetch.GET("/v1/workspace/{workspace_ext_id}/archive", {
6440
- params: { path: { workspace_ext_id: workspaceExtId } }
6318
+ await arbi.fetch.GET("/v1/signature-requests", {
6319
+ params: { query: { awaiting_me: awaitingMe } }
6441
6320
  }),
6442
- "Could not read the archive state"
6321
+ "Failed to list signature requests"
6443
6322
  );
6444
6323
  }
6445
- async function archiveWorkspace(arbi, workspaceExtId) {
6324
+ async function listDocumentSignatureRequests(arbi, docId) {
6446
6325
  return requireData(
6447
- await arbi.fetch.POST("/v1/workspace/{workspace_ext_id}/archive", {
6448
- params: { path: { workspace_ext_id: workspaceExtId } }
6326
+ await arbi.fetch.GET("/v1/document/{document_ext_id}/signature-requests", {
6327
+ params: { path: { document_ext_id: docId } }
6449
6328
  }),
6450
- "Could not archive the workspace"
6329
+ "Failed to list the document\u2019s signature requests"
6451
6330
  );
6452
6331
  }
6453
- async function unarchiveWorkspace(arbi, workspaceExtId) {
6332
+ async function getSignatureRequest(arbi, requestId) {
6454
6333
  return requireData(
6455
- await arbi.fetch.POST("/v1/workspace/{workspace_ext_id}/unarchive", {
6456
- params: { path: { workspace_ext_id: workspaceExtId } }
6334
+ await arbi.fetch.GET("/v1/signature-requests/{request_ext_id}", {
6335
+ params: { path: { request_ext_id: requestId } }
6457
6336
  }),
6458
- "Could not unarchive the workspace"
6337
+ "Failed to fetch the signature request"
6459
6338
  );
6460
6339
  }
6461
- async function deleteWorkspaces(arbi, workspaceIds) {
6462
- requireOk(
6463
- await arbi.fetch.DELETE("/v1/workspace/", {
6464
- body: { external_ids: workspaceIds }
6340
+ async function suggestSignatureFields(arbi, docId, version) {
6341
+ const data = requireData(
6342
+ await arbi.fetch.GET("/v1/document/{document_ext_id}/signature-fields/suggest", {
6343
+ params: { path: { document_ext_id: docId }, ...version ? { query: { version } } : {} }
6465
6344
  }),
6466
- "Failed to delete workspace(s)"
6345
+ "Failed to find signature blocks"
6467
6346
  );
6347
+ return data.fields;
6468
6348
  }
6469
- async function updateWorkspace(arbi, body) {
6349
+ async function createSignatureRequest(arbi, docId, { fields, version, message, send = true }) {
6470
6350
  return requireData(
6471
- await arbi.fetch.PATCH("/v1/workspace/", { body }),
6472
- "Failed to update workspace"
6351
+ await arbi.fetch.POST("/v1/document/{document_ext_id}/signature-requests", {
6352
+ params: { path: { document_ext_id: docId } },
6353
+ body: { fields, send, message: message ?? null, ...version ? { version } : {} }
6354
+ }),
6355
+ "Failed to create the signature request"
6473
6356
  );
6474
6357
  }
6475
- async function listWorkspaceUsers(arbi) {
6476
- return requireData(await arbi.fetch.GET("/v1/workspace/users"), "Failed to fetch workspace users");
6477
- }
6478
- var EXTERNAL_ACCESS_SECONDS = 86400;
6479
- function addWorkspaceMembersBody(request) {
6480
- return {
6481
- ...request,
6482
- access_duration_seconds: request.access_duration_seconds ?? EXTERNAL_ACCESS_SECONDS
6483
- };
6484
- }
6485
- async function addWorkspaceMembers(arbi, request) {
6358
+ async function sendSignatureRequest(arbi, requestId) {
6486
6359
  return requireData(
6487
- await arbi.fetch.POST("/v1/workspace/users", { body: addWorkspaceMembersBody(request) }),
6488
- "Failed to add users"
6360
+ await arbi.fetch.POST("/v1/signature-requests/{request_ext_id}/send", {
6361
+ params: { path: { request_ext_id: requestId } }
6362
+ }),
6363
+ "Failed to send the signature request"
6489
6364
  );
6490
6365
  }
6491
- async function addWorkspaceUsers(arbi, emails, role = "collaborator", target, confirmInvite = false) {
6492
- const invite = confirmInvite ? { confirm_invite: true } : {};
6366
+ async function voidSignatureRequest(arbi, requestId) {
6493
6367
  return requireData(
6494
- await arbi.fetch.POST("/v1/workspace/users", {
6495
- body: addWorkspaceMembersBody(
6496
- target ? {
6497
- emails,
6498
- role,
6499
- workspace_ext_id: target.workspaceExtId,
6500
- workspace_key: target.workspaceKey,
6501
- ...invite
6502
- } : { emails, role, ...invite }
6503
- )
6368
+ await arbi.fetch.POST("/v1/signature-requests/{request_ext_id}/void", {
6369
+ params: { path: { request_ext_id: requestId } }
6504
6370
  }),
6505
- "Failed to add users"
6371
+ "Failed to void the signature request"
6506
6372
  );
6507
6373
  }
6508
- async function grantTemporaryWorkspaceAccess(arbi, params) {
6374
+ async function declineSignatureRequest(arbi, requestId, reason) {
6509
6375
  return requireData(
6510
- await arbi.fetch.POST("/v1/workspace/users", {
6511
- body: addWorkspaceMembersBody({
6512
- emails: params.emails,
6513
- role: params.role ?? "collaborator",
6514
- workspace_ext_id: params.workspaceExtId,
6515
- workspace_key: params.workspaceKey,
6516
- session_pubkey_b64: params.sessionPubkeyB64
6517
- })
6376
+ await arbi.fetch.POST("/v1/signature-requests/{request_ext_id}/decline", {
6377
+ params: { path: { request_ext_id: requestId } },
6378
+ body: { reason: reason ?? null }
6518
6379
  }),
6519
- "Failed to grant temporary access"
6380
+ "Failed to decline the signature request"
6520
6381
  );
6521
6382
  }
6522
- async function removeWorkspaceUsers(arbi, userIds, workspaceExtId) {
6523
- requireOk(
6524
- await arbi.fetch.DELETE("/v1/workspace/users", {
6525
- body: {
6526
- users: userIds.map((id) => ({ user_ext_id: id })),
6527
- ...workspaceExtId ? { workspace_ext_id: workspaceExtId } : {}
6528
- }
6529
- }),
6530
- "Failed to remove users"
6531
- );
6383
+
6384
+ // src/operations/house-template.ts
6385
+ var house_template_exports = {};
6386
+ __export(house_template_exports, {
6387
+ getDeploymentHouseTemplate: () => getDeploymentHouseTemplate,
6388
+ isDeploymentAdmin: () => isDeploymentAdmin,
6389
+ listHouseTemplateCandidates: () => listHouseTemplateCandidates,
6390
+ setDeploymentHouseTemplate: () => setDeploymentHouseTemplate,
6391
+ setWorkspaceHouseTemplate: () => setWorkspaceHouseTemplate,
6392
+ supportsHouseTemplates: () => supportsHouseTemplates,
6393
+ workspaceHouseTemplateId: () => workspaceHouseTemplateId
6394
+ });
6395
+ function supportsHouseTemplates(workspace) {
6396
+ return !!workspace && "house_template_ext_id" in workspace;
6532
6397
  }
6533
- async function setUserRole(arbi, userIds, role) {
6534
- return requireData(
6535
- await arbi.fetch.PATCH("/v1/workspace/users", {
6536
- body: { user_ext_ids: userIds, role }
6537
- }),
6538
- "Failed to update roles"
6539
- );
6398
+ function workspaceHouseTemplateId(workspace) {
6399
+ return workspace?.house_template_ext_id ?? null;
6540
6400
  }
6541
- async function copyDocuments(arbi, targetWorkspaceId, docIds, targetWorkspaceKey) {
6542
- return requireData(
6543
- await arbi.fetch.POST("/v1/workspace/copy", {
6544
- body: {
6545
- target_workspace_ext_id: targetWorkspaceId,
6546
- target_workspace_key: targetWorkspaceKey,
6547
- items: docIds
6548
- }
6549
- }),
6550
- "Failed to copy documents"
6551
- );
6401
+ function isDeploymentAdmin(user) {
6402
+ return user?.is_deployment_admin === true;
6552
6403
  }
6553
- async function getWorkspaceActivity(arbi, workspaceExtId, options = {}) {
6554
- return requireData(
6555
- await arbi.fetch.GET("/v1/workspace/{workspace_ext_id}/activity", {
6556
- params: {
6557
- path: { workspace_ext_id: workspaceExtId },
6558
- query: { cursor: options.cursor ?? void 0, limit: options.limit }
6559
- }
6560
- }),
6561
- "Failed to fetch workspace activity"
6562
- );
6404
+ function filenameOf(response) {
6405
+ const header = response.headers.get("Content-Disposition") ?? "";
6406
+ const star = /filename\*=UTF-8''([^;]+)/i.exec(header);
6407
+ if (star) return decodeURIComponent(star[1]);
6408
+ return /filename="?([^";]+)"?/i.exec(header)?.[1];
6563
6409
  }
6564
- async function primeWorkspaceKey(arbi, workspaceExtId, sessionSealedKey) {
6410
+ async function getDeploymentHouseTemplate(arbi) {
6411
+ const { data, error, response } = await arbi.fetch.GET("/v1/deployment/house-template", {
6412
+ parseAs: "arrayBuffer"
6413
+ });
6414
+ const status = response.status;
6415
+ if (status === 204 || status === 404) return null;
6416
+ if (error || !data)
6417
+ throw new ArbiApiError("Could not read the deployment house template", error, status);
6418
+ return {
6419
+ bytes: new Uint8Array(data),
6420
+ name: filenameOf(response) ?? "House template.dotx"
6421
+ };
6422
+ }
6423
+ async function setDeploymentHouseTemplate(arbi, file) {
6424
+ if (!file) {
6425
+ requireOk(
6426
+ await arbi.fetch.DELETE("/v1/deployment/house-template"),
6427
+ "Could not clear the deployment house template"
6428
+ );
6429
+ return;
6430
+ }
6431
+ const form = new FormData();
6432
+ form.append("file", file);
6565
6433
  requireOk(
6566
- await arbi.fetch.POST("/v1/workspace/{workspace_ext_id}/prime-key", {
6567
- params: { path: { workspace_ext_id: workspaceExtId } },
6568
- body: { workspace_key: sessionSealedKey }
6434
+ await arbi.fetch.PUT("/v1/deployment/house-template", {
6435
+ // The schema types the multipart file as a string; the FormData is sent as is.
6436
+ body: form,
6437
+ bodySerializer: () => form
6569
6438
  }),
6570
- "Failed to prime the workspace key"
6439
+ "Could not set the deployment house template"
6571
6440
  );
6572
6441
  }
6573
- async function planWorkspaceTransfer(arbi, scope, mode) {
6574
- return requireData(
6575
- await arbi.fetch.POST("/v1/workspace/transfer/plan", { body: { scope, mode } }),
6576
- "Failed to plan the transfer"
6442
+ async function setWorkspaceHouseTemplate(arbi, documentId) {
6443
+ requireData(
6444
+ await arbi.fetch.PATCH("/v1/workspace/", { body: { house_template_ext_id: documentId } }),
6445
+ "Could not set the house template"
6577
6446
  );
6578
6447
  }
6579
- async function startWorkspaceTransfer(arbi, params) {
6448
+ async function listHouseTemplateCandidates(arbi) {
6580
6449
  return requireData(
6581
- await arbi.fetch.POST("/v1/workspace/transfer", {
6582
- body: {
6583
- scope: params.scope,
6584
- mode: params.mode,
6585
- target_workspace_ext_id: params.targetWorkspaceId,
6586
- target_workspace_key: params.targetWorkspaceKey,
6587
- on_conflict: params.onConflict ?? "skip"
6588
- }
6589
- }),
6590
- "Failed to start the transfer"
6450
+ await arbi.fetch.GET("/v1/workspace/house-template/candidates"),
6451
+ "Could not list the documents that can be the house template"
6591
6452
  );
6592
6453
  }
6593
- async function resumeWorkspaceTransfer(arbi, transferId, targetWorkspaceKey) {
6594
- return requireData(
6595
- await arbi.fetch.POST("/v1/workspace/transfer/{transfer_ext_id}/resume", {
6596
- params: { path: { transfer_ext_id: transferId } },
6597
- body: { target_workspace_key: targetWorkspaceKey }
6598
- }),
6599
- "Failed to resume the transfer"
6600
- );
6454
+
6455
+ // src/operations/model-connections.ts
6456
+ var model_connections_exports = {};
6457
+ __export(model_connections_exports, {
6458
+ directUsage: () => directUsage,
6459
+ listConnections: () => listConnections,
6460
+ removeConnection: () => removeConnection,
6461
+ savePersonalConnection: () => savePersonalConnection,
6462
+ sealPersonalApiKey: () => sealPersonalApiKey,
6463
+ unlockModelConnections: () => unlockModelConnections
6464
+ });
6465
+ var FAILED = "Could not update model connections";
6466
+ async function listConnections(arbi) {
6467
+ return requireData(await arbi.fetch.GET("/v1/model-connections"), FAILED);
6601
6468
  }
6602
- async function cancelWorkspaceTransfer(arbi, transferId) {
6469
+ async function directUsage(arbi) {
6603
6470
  return requireData(
6604
- await arbi.fetch.POST("/v1/workspace/transfer/{transfer_ext_id}/cancel", {
6605
- params: { path: { transfer_ext_id: transferId } }
6606
- }),
6607
- "Failed to cancel the transfer"
6471
+ await arbi.fetch.GET("/v1/model-connections/usage"),
6472
+ FAILED
6608
6473
  );
6609
6474
  }
6610
- async function getWorkspaceTransfer(arbi, transferId) {
6611
- return requireData(
6612
- await arbi.fetch.GET("/v1/workspace/transfer/{transfer_ext_id}", {
6613
- params: { path: { transfer_ext_id: transferId } }
6475
+ async function savePersonalConnection(arbi, body, id) {
6476
+ const result = id ? await arbi.fetch.PUT("/v1/model-connections/personal/{connection_id}", {
6477
+ params: { path: { connection_id: id } },
6478
+ body
6479
+ }) : await arbi.fetch.POST("/v1/model-connections/personal", { body });
6480
+ return requireData(result, FAILED);
6481
+ }
6482
+ async function removeConnection(arbi, id) {
6483
+ requireOk(
6484
+ await arbi.fetch.DELETE("/v1/model-connections/{connection_id}", {
6485
+ params: { path: { connection_id: id } }
6614
6486
  }),
6615
- "Failed to fetch the transfer"
6487
+ FAILED
6616
6488
  );
6617
6489
  }
6618
- async function listWorkspaceTransfers(arbi) {
6619
- return requireData(
6620
- await arbi.fetch.GET("/v1/workspace/transfer", {}),
6621
- "Failed to list transfers"
6622
- );
6490
+ async function sealPersonalApiKey(apiKey, signingPrivateKey) {
6491
+ await client.initSodium();
6492
+ const pair = client.encryptionKeypairFromSigningKey(signingPrivateKey);
6493
+ const bytes = new TextEncoder().encode(apiKey);
6494
+ try {
6495
+ return client.sealedBoxEncrypt(bytes, pair.publicKey);
6496
+ } finally {
6497
+ bytes.fill(0);
6498
+ pair.secretKey.fill(0);
6499
+ }
6623
6500
  }
6624
- async function exportWorkspaceData(arbi, scope) {
6625
- return requireData(
6626
- await arbi.fetch.POST("/v1/workspace/export", { body: { scope } }),
6627
- "Failed to export the workspace"
6628
- );
6501
+ async function unlockModelConnections(arbi, keys, onlyId) {
6502
+ await client.initSodium();
6503
+ const pair = client.encryptionKeypairFromSigningKey(keys.signingPrivateKey);
6504
+ try {
6505
+ const rows = requireData(
6506
+ await arbi.fetch.GET("/v1/model-connections/sealed-keys"),
6507
+ FAILED
6508
+ );
6509
+ for (const row of rows) {
6510
+ if (onlyId && onlyId !== row.id || !row.sealed_api_key || !row.enabled) continue;
6511
+ const bytes = client.sealedBoxDecrypt(row.sealed_api_key, pair.secretKey);
6512
+ try {
6513
+ requireOk(
6514
+ await arbi.fetch.POST("/v1/model-connections/session-key", {
6515
+ body: {
6516
+ connection_id: row.id,
6517
+ sealed_api_key: client.sealedBoxEncrypt(bytes, keys.serverSessionKey)
6518
+ }
6519
+ }),
6520
+ FAILED
6521
+ );
6522
+ } finally {
6523
+ bytes.fill(0);
6524
+ }
6525
+ }
6526
+ } finally {
6527
+ pair.secretKey.fill(0);
6528
+ }
6629
6529
  }
6630
- async function getWorkspaceAccessStatus(arbi, workspaceId) {
6631
- return requireData(
6632
- await arbi.fetch.GET("/v1/workspace/{workspace_ext_id}/access-status", {
6633
- params: { path: { workspace_ext_id: workspaceId } }
6530
+
6531
+ // src/operations/secure-mail.ts
6532
+ var secure_mail_exports = {};
6533
+ __export(secure_mail_exports, {
6534
+ claimSecureMail: () => claimSecureMail,
6535
+ prepareSecureMail: () => prepareSecureMail,
6536
+ secureMime: () => secureMime
6537
+ });
6538
+ var MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
6539
+ var utf8 = new TextEncoder();
6540
+ var encodedWord = (value) => `=?UTF-8?B?${bytesToBase64(utf8.encode(value))}?=`;
6541
+ var folded = (value) => value.match(/.{1,76}/g)?.join("\r\n") ?? "";
6542
+ var safeHeader = (value) => {
6543
+ if (/[\r\n\0]/.test(value)) throw new Error("Email headers cannot contain newlines");
6544
+ return value;
6545
+ };
6546
+ function secureMime(compose, sender) {
6547
+ const address = (r2) => `${r2.name ? encodedWord(safeHeader(r2.name)) + " " : ""}<${safeHeader(r2.email)}>`;
6548
+ const boundary = "arbi-" + crypto.randomUUID();
6549
+ const headers = [
6550
+ `From: ${address({ email: sender.email, name: sender.display_name })}`,
6551
+ ...compose.to.length ? [`To: ${compose.to.map(address).join(", ")}`] : [],
6552
+ ...compose.cc.length ? [`Cc: ${compose.cc.map(address).join(", ")}`] : [],
6553
+ `Subject: ${encodedWord(safeHeader(compose.subject))}`,
6554
+ `Date: ${(/* @__PURE__ */ new Date()).toUTCString()}`,
6555
+ `Message-ID: <${crypto.randomUUID()}@${sender.email.split("@")[1]}>`,
6556
+ ...compose.in_reply_to ? [`In-Reply-To: ${safeHeader(compose.in_reply_to)}`] : [],
6557
+ ...compose.references?.length ? [`References: ${compose.references.map(safeHeader).join(" ")}`] : [],
6558
+ "MIME-Version: 1.0",
6559
+ "X-ARBI-Secure-Delivery: 1",
6560
+ `Content-Type: multipart/mixed; boundary="${boundary}"`
6561
+ ];
6562
+ const alternative = "alternative-" + crypto.randomUUID();
6563
+ const plainPart = `Content-Type: text/plain; charset="utf-8"\r
6564
+ Content-Transfer-Encoding: base64\r
6565
+ \r
6566
+ ${folded(bytesToBase64(utf8.encode(compose.text)))}`;
6567
+ const bodyPart = compose.html ? `Content-Type: multipart/alternative; boundary="${alternative}"\r
6568
+ \r
6569
+ --${alternative}\r
6570
+ ${plainPart}\r
6571
+ --${alternative}\r
6572
+ Content-Type: text/html; charset="utf-8"\r
6573
+ Content-Transfer-Encoding: base64\r
6574
+ \r
6575
+ ${folded(bytesToBase64(utf8.encode(compose.html)))}\r
6576
+ --${alternative}--\r
6577
+ ` : plainPart;
6578
+ const parts = [
6579
+ `--${boundary}\r
6580
+ ${bodyPart}`,
6581
+ ...compose.attachments.map((a2) => {
6582
+ if (!a2.content_base64) throw new Error("Attachment content is missing");
6583
+ const name = encodeURIComponent(safeHeader(a2.name)).replace(/'/g, "%27");
6584
+ return `--${boundary}\r
6585
+ Content-Type: ${safeHeader(a2.content_type || "application/octet-stream")}\r
6586
+ Content-Disposition: attachment; filename*=UTF-8''${name}\r
6587
+ Content-Transfer-Encoding: base64\r
6588
+ \r
6589
+ ${folded(a2.content_base64)}`;
6634
6590
  }),
6635
- "Could not read workspace access"
6636
- );
6591
+ `--${boundary}--\r
6592
+ `
6593
+ ];
6594
+ return utf8.encode(headers.join("\r\n") + "\r\n\r\n" + parts.join("\r\n"));
6595
+ }
6596
+ async function prepareSecureMail(compose, sender, { requestId, senderPublicKey, frontendOrigin }) {
6597
+ const raw = secureMime(compose, sender);
6598
+ try {
6599
+ if (raw.length > MAX_MESSAGE_BYTES) throw new Error("Email exceeds the message size limit");
6600
+ const metadata = {
6601
+ secure_delivery: true,
6602
+ id: "",
6603
+ subject: compose.subject,
6604
+ sender: [{ email: sender.email, name: sender.display_name }],
6605
+ to: compose.to,
6606
+ cc: compose.cc,
6607
+ bcc: [],
6608
+ received_at: (/* @__PURE__ */ new Date()).toISOString(),
6609
+ preview: compose.text.slice(0, 220),
6610
+ unread: false,
6611
+ text: "",
6612
+ references: compose.references ?? [],
6613
+ attachments: compose.attachments.map((a2, i2) => ({
6614
+ ...a2,
6615
+ id: String(i2),
6616
+ content_base64: null
6617
+ }))
6618
+ };
6619
+ const recipients = [
6620
+ ...new Set([...compose.to, ...compose.cc, ...compose.bcc].map((r2) => r2.email.toLowerCase()))
6621
+ ];
6622
+ const sealed = await client.sealSecureMail(raw, metadata, senderPublicKey);
6623
+ return {
6624
+ request_id: requestId,
6625
+ draft_id: compose.draft_id,
6626
+ recipients: recipients.map((email) => ({
6627
+ id: crypto.randomUUID(),
6628
+ email,
6629
+ fragment_key: sealed.fragment_key
6630
+ })),
6631
+ ciphertext: sealed.ciphertext,
6632
+ metadata_ciphertext: sealed.metadata_ciphertext,
6633
+ sender_wrapped_key: sealed.sender_wrapped_key,
6634
+ frontend_origin: frontendOrigin
6635
+ };
6636
+ } finally {
6637
+ raw.fill(0);
6638
+ }
6639
+ }
6640
+ async function claimSecureMail(mail, id, fragmentKey, recipientPublicKey) {
6641
+ const key = client.decodeSecureMailKey(fragmentKey);
6642
+ try {
6643
+ const path2 = `/secure/${encodeURIComponent(id)}`;
6644
+ const response = await mail(path2);
6645
+ const { raw } = await client.openSecureMail(await response.json(), key);
6646
+ raw.fill(0);
6647
+ const claim = await client.secureMailClaim(key, recipientPublicKey);
6648
+ const claimed = await mail(`${path2}/claim`, { method: "POST", body: JSON.stringify(claim) });
6649
+ return await claimed.json();
6650
+ } finally {
6651
+ key.fill(0);
6652
+ }
6637
6653
  }
6638
6654
 
6639
6655
  // src/operations/conversations.ts
@@ -10068,6 +10084,10 @@ __export(mail_exports, {
10068
10084
  claimNativeAlias: () => claimNativeAlias,
10069
10085
  createMailFetch: () => createMailFetch,
10070
10086
  downloadAttachment: () => downloadAttachment,
10087
+ fileConversation: () => fileConversation,
10088
+ fileMessage: () => fileMessage,
10089
+ fileWaitingNativeMail: () => fileWaitingNativeMail,
10090
+ getFilingState: () => getFilingState,
10071
10091
  getMailPolicy: () => getMailPolicy,
10072
10092
  getMessage: () => getMessage2,
10073
10093
  getNativeThreadSecret: () => getNativeThreadSecret,
@@ -10076,9 +10096,12 @@ __export(mail_exports, {
10076
10096
  listFolders: () => listFolders,
10077
10097
  listMailAccounts: () => listMailAccounts,
10078
10098
  listMessages: () => listMessages,
10099
+ listNativeFiling: () => listNativeFiling,
10079
10100
  openDraftEditor: () => openDraftEditor,
10080
10101
  saveDraft: () => saveDraft,
10081
10102
  sendMessage: () => sendMessage,
10103
+ setNativeFiling: () => setNativeFiling,
10104
+ stopFilingConversation: () => stopFilingConversation,
10082
10105
  submitNativeThreadKeys: () => submitNativeThreadKeys,
10083
10106
  unlockMailCredentials: () => unlockMailCredentials,
10084
10107
  unlockNativeMail: () => unlockNativeMail,
@@ -10144,6 +10167,86 @@ async function submitNativeThreadKeys(mail, keys) {
10144
10167
  );
10145
10168
  return updated;
10146
10169
  }
10170
+ function fileMessage(mail, messageId2, workspaceExtId, accountId = NATIVE_ACCOUNT) {
10171
+ return json(
10172
+ mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId2)}/file`, {
10173
+ method: "POST",
10174
+ body: JSON.stringify({ workspace_ext_id: workspaceExtId })
10175
+ })
10176
+ );
10177
+ }
10178
+ function fileConversation(mail, input) {
10179
+ return json(
10180
+ mail(`${accountPath(input.accountId ?? NATIVE_ACCOUNT)}/conversations/file`, {
10181
+ method: "POST",
10182
+ body: JSON.stringify({
10183
+ workspace_ext_id: input.workspaceExtId,
10184
+ thread_id: input.threadId,
10185
+ message_ids: input.messageIds
10186
+ })
10187
+ })
10188
+ );
10189
+ }
10190
+ async function stopFilingConversation(mail, ruleId, threadId) {
10191
+ const params = new URLSearchParams({ thread_id: threadId });
10192
+ await mail(`/filing/${encodeURIComponent(ruleId)}/threads?${params}`, { method: "DELETE" });
10193
+ }
10194
+ function listNativeFiling(mail) {
10195
+ return json(mail("/native/filing"));
10196
+ }
10197
+ function setNativeFiling(mail, input) {
10198
+ return json(
10199
+ mail("/native/filing", {
10200
+ method: "PUT",
10201
+ body: JSON.stringify({
10202
+ workspace_ext_id: input.workspaceExtId,
10203
+ folders: input.folders,
10204
+ backfill_window: input.backfillWindow ?? 90
10205
+ })
10206
+ })
10207
+ );
10208
+ }
10209
+ async function fileWaitingNativeMail(mail, keys, workspaceExtId) {
10210
+ const params = new URLSearchParams({ workspace_ext_id: workspaceExtId });
10211
+ const waiting = await json(mail(`/native/filing/waiting?${params}`));
10212
+ if (!Object.keys(waiting.keys).length) return { filed: 0, waiting: 0, failed: 0 };
10213
+ await bridgeItemKeys(mail, keys, waiting.keys);
10214
+ return json(
10215
+ mail("/native/filing/run", {
10216
+ method: "POST",
10217
+ body: JSON.stringify({ workspace_ext_id: workspaceExtId })
10218
+ })
10219
+ );
10220
+ }
10221
+ async function bridgeItemKeys(mail, keys, wrapped) {
10222
+ await client.initSodium();
10223
+ const secretKey = client.encryptionKeypairFromSigningKey(keys.signingPrivateKey).secretKey;
10224
+ try {
10225
+ const sealed = {};
10226
+ for (const [id, value] of Object.entries(wrapped)) {
10227
+ const key = client.sealedBoxDecrypt(value, secretKey);
10228
+ try {
10229
+ sealed[id] = await client.sealKeyForSession(key, keys.serverSessionKey);
10230
+ } finally {
10231
+ key.fill(0);
10232
+ }
10233
+ }
10234
+ await mail("/native/session-keys", { method: "POST", body: JSON.stringify({ keys: sealed }) });
10235
+ } finally {
10236
+ secretKey.fill(0);
10237
+ }
10238
+ }
10239
+ function getFilingState(mail, input) {
10240
+ return json(
10241
+ mail(`${accountPath(input.accountId ?? NATIVE_ACCOUNT)}/filing`, {
10242
+ method: "POST",
10243
+ body: JSON.stringify({
10244
+ message_ids: input.messageIds ?? [],
10245
+ thread_ids: input.threadIds ?? []
10246
+ })
10247
+ })
10248
+ );
10249
+ }
10147
10250
  function getMessage2(mail, messageId2, accountId = NATIVE_ACCOUNT) {
10148
10251
  return json(mail(`${accountPath(accountId)}/messages/${encodeURIComponent(messageId2)}`));
10149
10252
  }
@@ -10169,33 +10272,13 @@ function sendMessage(mail, message, accountId = NATIVE_ACCOUNT) {
10169
10272
  );
10170
10273
  }
10171
10274
  async function unlockNativeMail(mail, keys) {
10172
- await client.initSodium();
10173
- const secretKey = client.encryptionKeypairFromSigningKey(keys.signingPrivateKey).secretKey;
10174
- try {
10175
- let cursor = 0;
10176
- while (cursor !== null) {
10177
- const page = await json(
10178
- mail(`/native/keys?cursor=${cursor}`)
10179
- );
10180
- const sealed = {};
10181
- for (const [id, wrapped] of Object.entries(page.keys)) {
10182
- const key = client.sealedBoxDecrypt(wrapped, secretKey);
10183
- try {
10184
- sealed[id] = await client.sealKeyForSession(key, keys.serverSessionKey);
10185
- } finally {
10186
- key.fill(0);
10187
- }
10188
- }
10189
- if (Object.keys(sealed).length) {
10190
- await mail("/native/session-keys", {
10191
- method: "POST",
10192
- body: JSON.stringify({ keys: sealed })
10193
- });
10194
- }
10195
- cursor = page.next_cursor;
10196
- }
10197
- } finally {
10198
- secretKey.fill(0);
10275
+ let cursor = 0;
10276
+ while (cursor !== null) {
10277
+ const page = await json(
10278
+ mail(`/native/keys?cursor=${cursor}`)
10279
+ );
10280
+ if (Object.keys(page.keys).length) await bridgeItemKeys(mail, keys, page.keys);
10281
+ cursor = page.next_cursor;
10199
10282
  }
10200
10283
  }
10201
10284
  async function unlockMailCredentials(mail, accountId, keys) {
@@ -10851,7 +10934,7 @@ var CODE_TEXT = {
10851
10934
  host_only: "Only the host can do that.",
10852
10935
  // transcription
10853
10936
  transcription_off: "Transcription is off.",
10854
- speaker_mismatch: "Only the speaker (or a member, for a workspace guest) can store this line.",
10937
+ speaker_mismatch: "Only the speaker can store this line (or another member, when the speaker is read only).",
10855
10938
  // recording
10856
10939
  storage_quota_exceeded: "The storage quota is full: recording stopped.",
10857
10940
  already_recording: "The call is already being recorded.",
@@ -12195,7 +12278,10 @@ var Arbi = class {
12195
12278
  listUsers: () => listWorkspaceUsers(this.requireClient()),
12196
12279
  /** One page of a workspace's activity feed, newest first (see `getWorkspaceActivity`). */
12197
12280
  activity: (workspaceId, options) => getWorkspaceActivity(this.requireClient(), workspaceId, options),
12198
- /** Add users to the open workspace; `confirmInvite` also invites emails not on ARBI yet. */
12281
+ /**
12282
+ * Add users to the open workspace; `confirmInvite` also invites emails not on ARBI yet. `role`
12283
+ * defaults to `collaborator`; `guest` makes a read-only member (shown as "Read only").
12284
+ */
12199
12285
  addUsers: (emails, role, options) => addWorkspaceUsers(
12200
12286
  this.requireClient(),
12201
12287
  emails,
@@ -12238,6 +12324,7 @@ var Arbi = class {
12238
12324
  userIds,
12239
12325
  await this.targetWorkspace(options?.workspaceId)
12240
12326
  ),
12327
+ /** Change members' role; `guest` is read-only (shown as "Read only"). */
12241
12328
  setUserRole: (userIds, role) => setUserRole(this.requireClient(), userIds, role),
12242
12329
  /**
12243
12330
  * Ask another user to grant you workspace access. Builds the E2E-encrypted
@@ -12563,6 +12650,19 @@ var Arbi = class {
12563
12650
  }
12564
12651
  await unlockMailCredentials(this.mail.fetch, account.id, await this.nativeMailKeys());
12565
12652
  },
12653
+ /**
12654
+ * File the ARBI mail waiting for a workspace (it arrived while the user was away) with this
12655
+ * session: the waiting messages' keys are bridged, then the server files them with the
12656
+ * workspace's key, deposited first without switching to it (see `fileWaitingNativeMail`).
12657
+ */
12658
+ fileWaiting: async (workspaceExtId) => {
12659
+ await this.workspaces.open(workspaceExtId);
12660
+ return fileWaitingNativeMail(
12661
+ this.mail.fetch,
12662
+ await this.nativeMailKeys(),
12663
+ workspaceExtId
12664
+ );
12665
+ },
12566
12666
  /**
12567
12667
  * Open a native draft's body in the Word editor, unlocking its room for this session with the
12568
12668
  * user's key when the server asks (see `openDraftEditor`).