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