@arbidocs/sdk 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { p as ConfigStore, m as CliConfig, n as CliCredentials, C as ChatSession, ab as SkippedFile, ak as UploadResult, j as AuthHeaders, ag as UploadBatchResult, aj as UploadOptions, ah as UploadDirectOptions, ai as UploadDirectResult, a9 as SUPPORTED_EXTENSIONS, v as DmCryptoContext } from './browser-U90kdb7T.cjs';
2
- export { b as AgentStepEvent, c as Arbi, d as ArbiApiError, e as ArbiError, g as ArbiOptions, h as ArtifactEvent, i as AuthContext, k as AuthenticatedClient, l as CitationSummary, o as CommandDescriptor, q as ConnectOptions, D as DOC_TERMINAL_STATUSES, w as DocNameMap, x as DocumentListFields, y as DocumentListOrder, z as DocumentWaiter, B as DocumentWaiterOptions, H as FormattedWsMessage, L as ListAllOptions, J as ListPaginatedOptions, M as MessageLevel, K as MessageMetadataPayload, N as MessageQueuedEvent, O as OutputTokensDetails, P as ParsedSlashCommand, R as ProjectInvoicesResponse, S as ProjectUsageResponse, T as QueryOptions, U as ReconnectOptions, V as ReconnectableWsConnection, W as ResolvedCitation, X as ResolvedRecipient, Y as ResponseCompletedEvent, Z as ResponseContentPartAddedEvent, _ as ResponseCreatedEvent, $ as ResponseFailedEvent, a0 as ResponseOutputItemAddedEvent, a1 as ResponseOutputItemDoneEvent, a2 as ResponseOutputTextDeltaEvent, a3 as ResponseOutputTextDoneEvent, a4 as ResponseUsage, a5 as SSEEvent, a6 as SSEStreamCallbacks, a7 as SSEStreamResult, a8 as SSEStreamStartData, aa as SkillSummary, ad as TokenBudgetContext, al as UserDailyUsageResponse, am as UserInfo, an as UserInputRequestEvent, ao as UserMessageEvent, ap as WebSocketAuthError, aq as WorkspaceContext, ar as WsConnection, as as agentconfig, at as assistant, au as authenticatedFetch, av as buildDocNameMap, aw as buildRetrievalChunkTool, ax as buildRetrievalFullContextTool, ay as buildRetrievalTocTool, az as connectWebSocket, aA as connectWithReconnect, aB as consumeSSEStream, aC as contacts, aD as conversations, aE as countCitations, aF as createAuthenticatedClient, aG as createDocumentWaiter, aH as dm, aI as doctags, aJ as documents, aK as facts, aL as files, aM as filterSkills, aN as formatAgentStepLabel, aO as formatFileSize, aP as formatItemLabel, aQ as formatStreamSummary, aR as formatUserName, aS as formatWorkspaceChoices, aT as formatWsMessage, aU as generateEncryptedWorkspaceKey, aV as generateNewWorkspaceKey, aW as getErrorCode, aX as getErrorMessage, aY as getRawWorkspaceKey, aZ as health, a_ as parseSSEEvents, a$ as parseSlashCommand, b0 as parseSlashTokenInProgress, b1 as performPasswordLogin, b2 as performSigningKeyLogin, b3 as performSsoDeviceFlowLogin, b4 as projects, b5 as requireData, b6 as requireOk, b7 as resolveAuth, b8 as resolveCitations, b9 as resolveWorkspace, ba as responses, bb as selectWorkspace, bc as selectWorkspaceById, bd as settings, be as streamSSE, bf as stripCitationMarkdown, bg as summarizeCitations, bh as tags, bi as tasks, bj as workspaces } from './browser-U90kdb7T.cjs';
1
+ import { q as ConfigStore, n as CliConfig, o as CliCredentials, C as ChatSession, ac as SkippedFile, al as UploadResult, k as AuthHeaders, ah as UploadBatchResult, ak as UploadOptions, ai as UploadDirectOptions, aj as UploadDirectResult, aa as SUPPORTED_EXTENSIONS, w as DmCryptoContext } from './browser-Bdzn5DIN.cjs';
2
+ export { b as AgentStepEvent, c as Arbi, d as ArbiApiError, e as ArbiError, g as ArbiOptions, h as ArbiSessionExpiredError, i as ArtifactEvent, j as AuthContext, l as AuthenticatedClient, m as CitationSummary, p as CommandDescriptor, r as ConnectOptions, D as DOC_TERMINAL_STATUSES, x as DocNameMap, y as DocumentListFields, z as DocumentListOrder, B as DocumentWaiter, E as DocumentWaiterOptions, I as FormattedWsMessage, L as ListAllOptions, K as ListPaginatedOptions, M as MessageLevel, N as MessageMetadataPayload, O as MessageQueuedEvent, P as OutputTokensDetails, Q as ParsedSlashCommand, S as ProjectInvoicesResponse, T as ProjectUsageResponse, U as QueryOptions, V as ReconnectOptions, W as ReconnectableWsConnection, X as ResolvedCitation, Y as ResolvedRecipient, Z as ResponseCompletedEvent, _ as ResponseContentPartAddedEvent, $ as ResponseCreatedEvent, a0 as ResponseFailedEvent, a1 as ResponseOutputItemAddedEvent, a2 as ResponseOutputItemDoneEvent, a3 as ResponseOutputTextDeltaEvent, a4 as ResponseOutputTextDoneEvent, a5 as ResponseUsage, a6 as SSEEvent, a7 as SSEStreamCallbacks, a8 as SSEStreamResult, a9 as SSEStreamStartData, ab as SkillSummary, ae as TokenBudgetContext, am as UserDailyUsageResponse, an as UserInfo, ao as UserInputRequestEvent, ap as UserMessageEvent, aq as WebSocketAuthError, ar as WorkspaceContext, as as WsConnection, at as agentconfig, au as assistant, av as authenticatedFetch, aw as buildDocNameMap, ax as buildRetrievalChunkTool, ay as buildRetrievalFullContextTool, az as buildRetrievalTocTool, aA as connectWebSocket, aB as connectWithReconnect, aC as consumeSSEStream, aD as contacts, aE as conversations, aF as countCitations, aG as createAuthenticatedClient, aH as createDocumentWaiter, aI as dm, aJ as doctags, aK as documents, aL as facts, aM as files, aN as filterSkills, aO as formatAgentStepLabel, aP as formatFileSize, aQ as formatItemLabel, aR as formatStreamSummary, aS as formatUserName, aT as formatWorkspaceChoices, aU as formatWsMessage, aV as generateEncryptedWorkspaceKey, aW as generateNewWorkspaceKey, aX as getErrorCode, aY as getErrorMessage, aZ as getRawWorkspaceKey, a_ as health, a$ as parseSSEEvents, b0 as parseSlashCommand, b1 as parseSlashTokenInProgress, b2 as performPasswordLogin, b3 as performSigningKeyLogin, b4 as performSsoDeviceFlowLogin, b5 as projects, b6 as requireData, b7 as requireOk, b8 as resolveAuth, b9 as resolveCitations, ba as resolveWorkspace, bb as responses, bc as selectWorkspace, bd as selectWorkspaceById, be as settings, bf as streamSSE, bg as stripCitationMarkdown, bh as summarizeCitations, bi as tags, bj as tasks, bk as workspaces } from './browser-Bdzn5DIN.cjs';
3
3
  import { SessionStorageProvider, ArbiClient, components } from '@arbidocs/client';
4
4
 
5
5
  /**
@@ -380,6 +380,8 @@ declare namespace documentsNode {
380
380
  type UserResponse = components['schemas']['UserResponse'];
381
381
  type CreateAgentResponse = components['schemas']['CreateAgentResponse'];
382
382
  type AgentWorkspaceResponse = components['schemas']['AgentWorkspaceResponse'];
383
+ type AuthorizeAgentResponse = components['schemas']['AuthorizeAgentResponse'];
384
+ type AuthorizeLimitsResponse = components['schemas']['AuthorizeLimitsResponse'];
383
385
  declare function listAgents(arbi: ArbiClient): Promise<UserResponse[]>;
384
386
  /**
385
387
  * Create a persistent agent. Only `name` is accepted (alphanumeric, `_`/`-`).
@@ -677,14 +679,27 @@ declare function listAgentWorkspaces(arbi: ArbiClient, agentExtId: string): Prom
677
679
  declare function deleteAgents(arbi: ArbiClient, agentExtIds: string[]): Promise<{
678
680
  [x: string]: unknown;
679
681
  }>;
682
+ /**
683
+ * Mint a fresh, TTL'd run session for the caller's own agent
684
+ * (`POST /v1/agents/{id}/authorize`). The response carries the session's public key; deposit a
685
+ * temporary workspace key on it with `Arbi.workspaces.grantTemporaryAccess()` (or do both in one
686
+ * call with `Arbi.agents.grantTemporaryAccess()`). `ttlSeconds` omitted = the deployment default.
687
+ */
688
+ declare function authorizeAgent(arbi: ArbiClient, agentExtId: string, workspaceExtId: string, ttlSeconds?: number): Promise<AuthorizeAgentResponse>;
689
+ /** The default and maximum lifetime of a temporary agent authorization. */
690
+ declare function getAuthorizeLimits(arbi: ArbiClient): Promise<AuthorizeLimitsResponse>;
680
691
 
692
+ type agents_AuthorizeAgentResponse = AuthorizeAgentResponse;
693
+ type agents_AuthorizeLimitsResponse = AuthorizeLimitsResponse;
694
+ declare const agents_authorizeAgent: typeof authorizeAgent;
681
695
  declare const agents_createAgent: typeof createAgent;
682
696
  declare const agents_deleteAgents: typeof deleteAgents;
683
697
  declare const agents_getAgentConfig: typeof getAgentConfig;
698
+ declare const agents_getAuthorizeLimits: typeof getAuthorizeLimits;
684
699
  declare const agents_listAgentWorkspaces: typeof listAgentWorkspaces;
685
700
  declare const agents_listAgents: typeof listAgents;
686
701
  declare namespace agents {
687
- export { agents_createAgent as createAgent, agents_deleteAgents as deleteAgents, agents_getAgentConfig as getAgentConfig, agents_listAgentWorkspaces as listAgentWorkspaces, agents_listAgents as listAgents };
702
+ export { type agents_AuthorizeAgentResponse as AuthorizeAgentResponse, type agents_AuthorizeLimitsResponse as AuthorizeLimitsResponse, agents_authorizeAgent as authorizeAgent, agents_createAgent as createAgent, agents_deleteAgents as deleteAgents, agents_getAgentConfig as getAgentConfig, agents_getAuthorizeLimits as getAuthorizeLimits, agents_listAgentWorkspaces as listAgentWorkspaces, agents_listAgents as listAgents };
688
703
  }
689
704
 
690
705
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { p as ConfigStore, m as CliConfig, n as CliCredentials, C as ChatSession, ab as SkippedFile, ak as UploadResult, j as AuthHeaders, ag as UploadBatchResult, aj as UploadOptions, ah as UploadDirectOptions, ai as UploadDirectResult, a9 as SUPPORTED_EXTENSIONS, v as DmCryptoContext } from './browser-U90kdb7T.js';
2
- export { b as AgentStepEvent, c as Arbi, d as ArbiApiError, e as ArbiError, g as ArbiOptions, h as ArtifactEvent, i as AuthContext, k as AuthenticatedClient, l as CitationSummary, o as CommandDescriptor, q as ConnectOptions, D as DOC_TERMINAL_STATUSES, w as DocNameMap, x as DocumentListFields, y as DocumentListOrder, z as DocumentWaiter, B as DocumentWaiterOptions, H as FormattedWsMessage, L as ListAllOptions, J as ListPaginatedOptions, M as MessageLevel, K as MessageMetadataPayload, N as MessageQueuedEvent, O as OutputTokensDetails, P as ParsedSlashCommand, R as ProjectInvoicesResponse, S as ProjectUsageResponse, T as QueryOptions, U as ReconnectOptions, V as ReconnectableWsConnection, W as ResolvedCitation, X as ResolvedRecipient, Y as ResponseCompletedEvent, Z as ResponseContentPartAddedEvent, _ as ResponseCreatedEvent, $ as ResponseFailedEvent, a0 as ResponseOutputItemAddedEvent, a1 as ResponseOutputItemDoneEvent, a2 as ResponseOutputTextDeltaEvent, a3 as ResponseOutputTextDoneEvent, a4 as ResponseUsage, a5 as SSEEvent, a6 as SSEStreamCallbacks, a7 as SSEStreamResult, a8 as SSEStreamStartData, aa as SkillSummary, ad as TokenBudgetContext, al as UserDailyUsageResponse, am as UserInfo, an as UserInputRequestEvent, ao as UserMessageEvent, ap as WebSocketAuthError, aq as WorkspaceContext, ar as WsConnection, as as agentconfig, at as assistant, au as authenticatedFetch, av as buildDocNameMap, aw as buildRetrievalChunkTool, ax as buildRetrievalFullContextTool, ay as buildRetrievalTocTool, az as connectWebSocket, aA as connectWithReconnect, aB as consumeSSEStream, aC as contacts, aD as conversations, aE as countCitations, aF as createAuthenticatedClient, aG as createDocumentWaiter, aH as dm, aI as doctags, aJ as documents, aK as facts, aL as files, aM as filterSkills, aN as formatAgentStepLabel, aO as formatFileSize, aP as formatItemLabel, aQ as formatStreamSummary, aR as formatUserName, aS as formatWorkspaceChoices, aT as formatWsMessage, aU as generateEncryptedWorkspaceKey, aV as generateNewWorkspaceKey, aW as getErrorCode, aX as getErrorMessage, aY as getRawWorkspaceKey, aZ as health, a_ as parseSSEEvents, a$ as parseSlashCommand, b0 as parseSlashTokenInProgress, b1 as performPasswordLogin, b2 as performSigningKeyLogin, b3 as performSsoDeviceFlowLogin, b4 as projects, b5 as requireData, b6 as requireOk, b7 as resolveAuth, b8 as resolveCitations, b9 as resolveWorkspace, ba as responses, bb as selectWorkspace, bc as selectWorkspaceById, bd as settings, be as streamSSE, bf as stripCitationMarkdown, bg as summarizeCitations, bh as tags, bi as tasks, bj as workspaces } from './browser-U90kdb7T.js';
1
+ import { q as ConfigStore, n as CliConfig, o as CliCredentials, C as ChatSession, ac as SkippedFile, al as UploadResult, k as AuthHeaders, ah as UploadBatchResult, ak as UploadOptions, ai as UploadDirectOptions, aj as UploadDirectResult, aa as SUPPORTED_EXTENSIONS, w as DmCryptoContext } from './browser-Bdzn5DIN.js';
2
+ export { b as AgentStepEvent, c as Arbi, d as ArbiApiError, e as ArbiError, g as ArbiOptions, h as ArbiSessionExpiredError, i as ArtifactEvent, j as AuthContext, l as AuthenticatedClient, m as CitationSummary, p as CommandDescriptor, r as ConnectOptions, D as DOC_TERMINAL_STATUSES, x as DocNameMap, y as DocumentListFields, z as DocumentListOrder, B as DocumentWaiter, E as DocumentWaiterOptions, I as FormattedWsMessage, L as ListAllOptions, K as ListPaginatedOptions, M as MessageLevel, N as MessageMetadataPayload, O as MessageQueuedEvent, P as OutputTokensDetails, Q as ParsedSlashCommand, S as ProjectInvoicesResponse, T as ProjectUsageResponse, U as QueryOptions, V as ReconnectOptions, W as ReconnectableWsConnection, X as ResolvedCitation, Y as ResolvedRecipient, Z as ResponseCompletedEvent, _ as ResponseContentPartAddedEvent, $ as ResponseCreatedEvent, a0 as ResponseFailedEvent, a1 as ResponseOutputItemAddedEvent, a2 as ResponseOutputItemDoneEvent, a3 as ResponseOutputTextDeltaEvent, a4 as ResponseOutputTextDoneEvent, a5 as ResponseUsage, a6 as SSEEvent, a7 as SSEStreamCallbacks, a8 as SSEStreamResult, a9 as SSEStreamStartData, ab as SkillSummary, ae as TokenBudgetContext, am as UserDailyUsageResponse, an as UserInfo, ao as UserInputRequestEvent, ap as UserMessageEvent, aq as WebSocketAuthError, ar as WorkspaceContext, as as WsConnection, at as agentconfig, au as assistant, av as authenticatedFetch, aw as buildDocNameMap, ax as buildRetrievalChunkTool, ay as buildRetrievalFullContextTool, az as buildRetrievalTocTool, aA as connectWebSocket, aB as connectWithReconnect, aC as consumeSSEStream, aD as contacts, aE as conversations, aF as countCitations, aG as createAuthenticatedClient, aH as createDocumentWaiter, aI as dm, aJ as doctags, aK as documents, aL as facts, aM as files, aN as filterSkills, aO as formatAgentStepLabel, aP as formatFileSize, aQ as formatItemLabel, aR as formatStreamSummary, aS as formatUserName, aT as formatWorkspaceChoices, aU as formatWsMessage, aV as generateEncryptedWorkspaceKey, aW as generateNewWorkspaceKey, aX as getErrorCode, aY as getErrorMessage, aZ as getRawWorkspaceKey, a_ as health, a$ as parseSSEEvents, b0 as parseSlashCommand, b1 as parseSlashTokenInProgress, b2 as performPasswordLogin, b3 as performSigningKeyLogin, b4 as performSsoDeviceFlowLogin, b5 as projects, b6 as requireData, b7 as requireOk, b8 as resolveAuth, b9 as resolveCitations, ba as resolveWorkspace, bb as responses, bc as selectWorkspace, bd as selectWorkspaceById, be as settings, bf as streamSSE, bg as stripCitationMarkdown, bh as summarizeCitations, bi as tags, bj as tasks, bk as workspaces } from './browser-Bdzn5DIN.js';
3
3
  import { SessionStorageProvider, ArbiClient, components } from '@arbidocs/client';
4
4
 
5
5
  /**
@@ -380,6 +380,8 @@ declare namespace documentsNode {
380
380
  type UserResponse = components['schemas']['UserResponse'];
381
381
  type CreateAgentResponse = components['schemas']['CreateAgentResponse'];
382
382
  type AgentWorkspaceResponse = components['schemas']['AgentWorkspaceResponse'];
383
+ type AuthorizeAgentResponse = components['schemas']['AuthorizeAgentResponse'];
384
+ type AuthorizeLimitsResponse = components['schemas']['AuthorizeLimitsResponse'];
383
385
  declare function listAgents(arbi: ArbiClient): Promise<UserResponse[]>;
384
386
  /**
385
387
  * Create a persistent agent. Only `name` is accepted (alphanumeric, `_`/`-`).
@@ -677,14 +679,27 @@ declare function listAgentWorkspaces(arbi: ArbiClient, agentExtId: string): Prom
677
679
  declare function deleteAgents(arbi: ArbiClient, agentExtIds: string[]): Promise<{
678
680
  [x: string]: unknown;
679
681
  }>;
682
+ /**
683
+ * Mint a fresh, TTL'd run session for the caller's own agent
684
+ * (`POST /v1/agents/{id}/authorize`). The response carries the session's public key; deposit a
685
+ * temporary workspace key on it with `Arbi.workspaces.grantTemporaryAccess()` (or do both in one
686
+ * call with `Arbi.agents.grantTemporaryAccess()`). `ttlSeconds` omitted = the deployment default.
687
+ */
688
+ declare function authorizeAgent(arbi: ArbiClient, agentExtId: string, workspaceExtId: string, ttlSeconds?: number): Promise<AuthorizeAgentResponse>;
689
+ /** The default and maximum lifetime of a temporary agent authorization. */
690
+ declare function getAuthorizeLimits(arbi: ArbiClient): Promise<AuthorizeLimitsResponse>;
680
691
 
692
+ type agents_AuthorizeAgentResponse = AuthorizeAgentResponse;
693
+ type agents_AuthorizeLimitsResponse = AuthorizeLimitsResponse;
694
+ declare const agents_authorizeAgent: typeof authorizeAgent;
681
695
  declare const agents_createAgent: typeof createAgent;
682
696
  declare const agents_deleteAgents: typeof deleteAgents;
683
697
  declare const agents_getAgentConfig: typeof getAgentConfig;
698
+ declare const agents_getAuthorizeLimits: typeof getAuthorizeLimits;
684
699
  declare const agents_listAgentWorkspaces: typeof listAgentWorkspaces;
685
700
  declare const agents_listAgents: typeof listAgents;
686
701
  declare namespace agents {
687
- export { agents_createAgent as createAgent, agents_deleteAgents as deleteAgents, agents_getAgentConfig as getAgentConfig, agents_listAgentWorkspaces as listAgentWorkspaces, agents_listAgents as listAgents };
702
+ export { type agents_AuthorizeAgentResponse as AuthorizeAgentResponse, type agents_AuthorizeLimitsResponse as AuthorizeLimitsResponse, agents_authorizeAgent as authorizeAgent, agents_createAgent as createAgent, agents_deleteAgents as deleteAgents, agents_getAgentConfig as getAgentConfig, agents_getAuthorizeLimits as getAuthorizeLimits, agents_listAgentWorkspaces as listAgentWorkspaces, agents_listAgents as listAgents };
688
703
  }
689
704
 
690
705
  /**
package/dist/index.js CHANGED
@@ -3487,6 +3487,12 @@ var ArbiError = class extends Error {
3487
3487
  this.name = "ArbiError";
3488
3488
  }
3489
3489
  };
3490
+ var ArbiSessionExpiredError = class extends ArbiError {
3491
+ constructor(message = "Your session expired. Sign in again.") {
3492
+ super(message);
3493
+ this.name = "ArbiSessionExpiredError";
3494
+ }
3495
+ };
3490
3496
  var ArbiApiError = class extends ArbiError {
3491
3497
  apiError;
3492
3498
  constructor(message, apiError) {
@@ -5210,6 +5216,7 @@ __export(workspaces_exports, {
5210
5216
  copyDocuments: () => copyDocuments,
5211
5217
  createWorkspace: () => createWorkspace,
5212
5218
  deleteWorkspaces: () => deleteWorkspaces,
5219
+ grantTemporaryWorkspaceAccess: () => grantTemporaryWorkspaceAccess,
5213
5220
  listWorkspaceUsers: () => listWorkspaceUsers,
5214
5221
  listWorkspaces: () => listWorkspaces,
5215
5222
  removeWorkspaceUsers: () => removeWorkspaceUsers,
@@ -5250,14 +5257,33 @@ async function updateWorkspace(arbi, body) {
5250
5257
  async function listWorkspaceUsers(arbi) {
5251
5258
  return requireData(await arbi.fetch.GET("/v1/workspace/users"), "Failed to fetch workspace users");
5252
5259
  }
5253
- async function addWorkspaceUsers(arbi, emails, role = "collaborator") {
5260
+ async function addWorkspaceUsers(arbi, emails, role = "collaborator", target) {
5254
5261
  return requireData(
5255
5262
  await arbi.fetch.POST("/v1/workspace/users", {
5256
- body: { emails, role }
5263
+ body: target ? {
5264
+ emails,
5265
+ role,
5266
+ workspace_ext_id: target.workspaceExtId,
5267
+ workspace_key: target.workspaceKey
5268
+ } : { emails, role }
5257
5269
  }),
5258
5270
  "Failed to add users"
5259
5271
  );
5260
5272
  }
5273
+ async function grantTemporaryWorkspaceAccess(arbi, params) {
5274
+ return requireData(
5275
+ await arbi.fetch.POST("/v1/workspace/users", {
5276
+ body: {
5277
+ emails: params.emails,
5278
+ role: params.role ?? "collaborator",
5279
+ workspace_ext_id: params.workspaceExtId,
5280
+ workspace_key: params.workspaceKey,
5281
+ session_pubkey_b64: params.sessionPubkeyB64
5282
+ }
5283
+ }),
5284
+ "Failed to grant temporary access"
5285
+ );
5286
+ }
5261
5287
  async function removeWorkspaceUsers(arbi, userIds) {
5262
5288
  requireOk(
5263
5289
  await arbi.fetch.DELETE("/v1/workspace/users", {
@@ -5653,9 +5679,11 @@ __export(dm_exports, {
5653
5679
  // src/operations/agents.ts
5654
5680
  var agents_exports = {};
5655
5681
  __export(agents_exports, {
5682
+ authorizeAgent: () => authorizeAgent,
5656
5683
  createAgent: () => createAgent,
5657
5684
  deleteAgents: () => deleteAgents,
5658
5685
  getAgentConfig: () => getAgentConfig,
5686
+ getAuthorizeLimits: () => getAuthorizeLimits,
5659
5687
  listAgentWorkspaces: () => listAgentWorkspaces,
5660
5688
  listAgents: () => listAgents
5661
5689
  });
@@ -5690,6 +5718,21 @@ async function deleteAgents(arbi, agentExtIds) {
5690
5718
  "Failed to delete agents"
5691
5719
  );
5692
5720
  }
5721
+ async function authorizeAgent(arbi, agentExtId, workspaceExtId, ttlSeconds) {
5722
+ return requireData(
5723
+ await arbi.fetch.POST("/v1/agents/{agent_ext_id}/authorize", {
5724
+ params: { path: { agent_ext_id: agentExtId } },
5725
+ body: { workspace_ext_id: workspaceExtId, ttl_seconds: ttlSeconds ?? null }
5726
+ }),
5727
+ "Failed to authorize agent"
5728
+ );
5729
+ }
5730
+ async function getAuthorizeLimits(arbi) {
5731
+ return requireData(
5732
+ await arbi.fetch.GET("/v1/agents/authorize-limits"),
5733
+ "Failed to fetch authorize limits"
5734
+ );
5735
+ }
5693
5736
 
5694
5737
  // src/operations/dm.ts
5695
5738
  function createDmCryptoContext(arbi, signingPrivateKeyBytes, userExtId) {
@@ -6076,6 +6119,7 @@ __export(tasks_exports, {
6076
6119
  createTask: () => createTask,
6077
6120
  deleteTask: () => deleteTask,
6078
6121
  getTask: () => getTask,
6122
+ listTaskRuns: () => listTaskRuns,
6079
6123
  listTasks: () => listTasks,
6080
6124
  runTask: () => runTask,
6081
6125
  updateTask: () => updateTask
@@ -6113,6 +6157,12 @@ async function runTask(arbi, taskId) {
6113
6157
  "Failed to run task"
6114
6158
  );
6115
6159
  }
6160
+ async function listTaskRuns(arbi, taskId) {
6161
+ return requireData(
6162
+ await arbi.fetch.GET("/v1/tasks/{task_id}/runs", { params: { path: { task_id: taskId } } }),
6163
+ "Failed to list task runs"
6164
+ );
6165
+ }
6116
6166
 
6117
6167
  // src/operations/facts.ts
6118
6168
  var facts_exports = {};
@@ -6182,11 +6232,23 @@ async function remindFact(arbi, factId, options = {}) {
6182
6232
  }
6183
6233
 
6184
6234
  // src/arbi.ts
6235
+ function tokenExpiresWithin(token, seconds) {
6236
+ const payload = token?.split(".")[1];
6237
+ if (!payload) return false;
6238
+ try {
6239
+ const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
6240
+ const { exp } = JSON.parse(json);
6241
+ return typeof exp === "number" && exp * 1e3 - Date.now() < seconds * 1e3;
6242
+ } catch {
6243
+ return false;
6244
+ }
6245
+ }
6185
6246
  var Arbi = class {
6186
6247
  client = null;
6187
6248
  loginResult = null;
6188
6249
  currentWorkspaceId = null;
6189
6250
  dmCryptoContext = null;
6251
+ sessionExpiredListeners = /* @__PURE__ */ new Set();
6190
6252
  options;
6191
6253
  constructor(options) {
6192
6254
  this.options = options;
@@ -6199,7 +6261,13 @@ var Arbi = class {
6199
6261
  this.client = createArbiClient({
6200
6262
  baseUrl: this.options.url,
6201
6263
  deploymentDomain: domain,
6202
- credentials: this.options.credentials ?? "omit"
6264
+ credentials: this.options.credentials ?? "omit",
6265
+ // A silent re-login rotates the server session key: keep ours in step, or the next
6266
+ // workspace open would seal the key for a session the server no longer has.
6267
+ onReloginSuccess: ({ serverSessionKey }) => {
6268
+ if (this.loginResult) this.loginResult = { ...this.loginResult, serverSessionKey };
6269
+ },
6270
+ onSessionExpired: () => this.expireSession()
6203
6271
  });
6204
6272
  await this.client.crypto.initSodium();
6205
6273
  return this.client;
@@ -6236,6 +6304,22 @@ var Arbi = class {
6236
6304
  const signingPrivateKey = client.crypto.base64ToBytes(signingPrivateKeyBase64);
6237
6305
  this.loginResult = await client.auth.loginWithKey({ email, signingPrivateKey });
6238
6306
  }
6307
+ /** A workspace's key, sealed to the caller's own session (what `/open` and `POST /workspace/users` take). */
6308
+ async sealWorkspaceKey(workspaceId) {
6309
+ const client = this.requireClient();
6310
+ const lr2 = this.requireLogin();
6311
+ const all = await listWorkspaces(client);
6312
+ const ws = all.find((w2) => w2.external_id === workspaceId);
6313
+ if (!ws || !ws.wrapped_key) {
6314
+ throw new ArbiError(`Workspace ${workspaceId} not found or has no encryption key`);
6315
+ }
6316
+ return generateEncryptedWorkspaceKey(
6317
+ client,
6318
+ ws.wrapped_key,
6319
+ lr2.serverSessionKey,
6320
+ client.crypto.bytesToBase64(lr2.signingPrivateKey)
6321
+ );
6322
+ }
6239
6323
  /**
6240
6324
  * Select a workspace by ID. Fetches the workspace list, finds the matching
6241
6325
  * workspace, decrypts the wrapped key, and sets up auth headers.
@@ -6262,6 +6346,52 @@ var Arbi = class {
6262
6346
  });
6263
6347
  this.currentWorkspaceId = ws.external_id;
6264
6348
  }
6349
+ /**
6350
+ * Subscribe to "the session cannot be recovered". Fires when a request failed with 401 or
6351
+ * "No active workspace" and neither a workspace re-open nor a silent re-login was possible
6352
+ * (the server refused; an unreachable server does not fire). The local session is already
6353
+ * cleared when it fires: show "Your session expired, sign in again". Returns an unsubscribe.
6354
+ */
6355
+ onSessionExpired(listener) {
6356
+ this.sessionExpiredListeners.add(listener);
6357
+ return () => this.sessionExpiredListeners.delete(listener);
6358
+ }
6359
+ expireSession() {
6360
+ if (this.loginResult) {
6361
+ this.loginResult.signingPrivateKey.fill(0);
6362
+ this.loginResult.serverSessionKey.fill(0);
6363
+ }
6364
+ this.loginResult = null;
6365
+ this.currentWorkspaceId = null;
6366
+ this.dmCryptoContext = null;
6367
+ this.client?.session.clear();
6368
+ for (const listener of [...this.sessionExpiredListeners]) listener();
6369
+ }
6370
+ /**
6371
+ * Run a raw-fetch operation (streaming, multipart: no middleware) and, when it fails because
6372
+ * the token expired or the server lost the open workspace, recover once and run it again.
6373
+ * `run` must read the auth headers itself so the retry carries the fresh token.
6374
+ */
6375
+ async recovering(run) {
6376
+ if (this.client && tokenExpiresWithin(this.client.session.getState().accessToken, 30)) {
6377
+ await this.client.auth.relogin();
6378
+ }
6379
+ try {
6380
+ return await run();
6381
+ } catch (error) {
6382
+ const message = error instanceof Error ? error.message : "";
6383
+ const noWorkspace = /no active workspace/i.test(message);
6384
+ const unauthorised = /\b401\b|token has expired/i.test(message);
6385
+ if (!(error instanceof ArbiApiError) || !(noWorkspace || unauthorised)) throw error;
6386
+ const client = this.requireClient();
6387
+ const recovered = noWorkspace && await client.auth.reopenWorkspace() || await client.auth.relogin() !== null;
6388
+ if (!recovered) {
6389
+ this.expireSession();
6390
+ throw new ArbiSessionExpiredError();
6391
+ }
6392
+ return run();
6393
+ }
6394
+ }
6265
6395
  /** Log out and clear internal state. */
6266
6396
  async logout() {
6267
6397
  if (this.client) {
@@ -6372,6 +6502,30 @@ var Arbi = class {
6372
6502
  update: (body) => updateWorkspace(this.requireClient(), body),
6373
6503
  listUsers: () => listWorkspaceUsers(this.requireClient()),
6374
6504
  addUsers: (emails, role) => addWorkspaceUsers(this.requireClient(), emails, role),
6505
+ /**
6506
+ * Grant users a temporary key scoped to ONE session (identified by its public key), for
6507
+ * example an agent's run session minted by `agents.authorize()`. Nothing standing is created:
6508
+ * the grant expires with that session. Works for any workspace the caller holds a key for;
6509
+ * it does not need to be the open one.
6510
+ */
6511
+ grantTemporaryAccess: async (params) => {
6512
+ const client = this.requireClient();
6513
+ return grantTemporaryWorkspaceAccess(client, {
6514
+ emails: params.emails,
6515
+ workspaceExtId: params.workspaceId,
6516
+ workspaceKey: await this.sealWorkspaceKey(params.workspaceId),
6517
+ sessionPubkeyB64: params.sessionPubkeyB64,
6518
+ role: params.role
6519
+ });
6520
+ },
6521
+ /**
6522
+ * Add users (standing, permanent membership) to ANY workspace the caller holds a key for,
6523
+ * without opening it. `addUsers` does the same for the currently open workspace.
6524
+ */
6525
+ grantAccess: async (params) => addWorkspaceUsers(this.requireClient(), params.emails, params.role, {
6526
+ workspaceExtId: params.workspaceId,
6527
+ workspaceKey: await this.sealWorkspaceKey(params.workspaceId)
6528
+ }),
6375
6529
  removeUsers: (userIds) => removeWorkspaceUsers(this.requireClient(), userIds),
6376
6530
  setUserRole: (userIds, role) => setUserRole(this.requireClient(), userIds, role),
6377
6531
  /**
@@ -6428,16 +6582,18 @@ var Arbi = class {
6428
6582
  },
6429
6583
  uploadFile: (fileData, fileName, options) => {
6430
6584
  this.requireWorkspace();
6431
- return uploadFile(
6432
- this.getAuthHeaders(),
6433
- fileData,
6434
- fileName,
6435
- options?.folder ? { folder: options.folder } : void 0
6585
+ return this.recovering(
6586
+ () => uploadFile(
6587
+ this.getAuthHeaders(),
6588
+ fileData,
6589
+ fileName,
6590
+ options?.folder ? { folder: options.folder } : void 0
6591
+ )
6436
6592
  );
6437
6593
  },
6438
- download: (docId) => downloadDocument(this.getAuthHeaders(), docId),
6439
- getParsedContent: (docId, stage) => getParsedContent(this.getAuthHeaders(), docId, stage),
6440
- getThumbnails: (docIds) => getThumbnails(this.getAuthHeaders(), docIds)
6594
+ download: (docId) => this.recovering(() => downloadDocument(this.getAuthHeaders(), docId)),
6595
+ getParsedContent: (docId, stage) => this.recovering(() => getParsedContent(this.getAuthHeaders(), docId, stage)),
6596
+ getThumbnails: (docIds) => this.recovering(() => getThumbnails(this.getAuthHeaders(), docIds))
6441
6597
  };
6442
6598
  // ── Conversations ─────────────────────────────────────────────────────
6443
6599
  conversations = {
@@ -6456,16 +6612,17 @@ var Arbi = class {
6456
6612
  * Returns the accumulated result after the stream completes.
6457
6613
  */
6458
6614
  query: async (question, options) => {
6459
- const auth = this.getAuthHeaders();
6460
6615
  const workspaceId = this.requireWorkspace();
6461
- const response = await queryAssistant({
6462
- ...auth,
6463
- workspaceId,
6464
- question,
6465
- docIds: options.docIds,
6466
- previousResponseId: options.previousResponseId,
6467
- model: options.model
6468
- });
6616
+ const response = await this.recovering(
6617
+ () => queryAssistant({
6618
+ ...this.getAuthHeaders(),
6619
+ workspaceId,
6620
+ question,
6621
+ docIds: options.docIds,
6622
+ previousResponseId: options.previousResponseId,
6623
+ model: options.model
6624
+ })
6625
+ );
6469
6626
  const callbacks = {
6470
6627
  onToken: options.onToken,
6471
6628
  onStreamStart: options.onStreamStart,
@@ -6484,6 +6641,8 @@ var Arbi = class {
6484
6641
  * Respond to an agent's question during a human-in-the-loop workflow.
6485
6642
  */
6486
6643
  respond: (assistantMessageExtId, answer) => respondToAgent(this.requireClient(), assistantMessageExtId, answer),
6644
+ /** The skills the caller can run (own + shared marketplace), metadata only. */
6645
+ listSkills: (options) => listSkills(this.requireClient(), options),
6487
6646
  /**
6488
6647
  * Search documents without LLM generation (retrieval only).
6489
6648
  */
@@ -6629,8 +6788,10 @@ var Arbi = class {
6629
6788
  list: (options) => listFiles(this.requireClient(), options),
6630
6789
  get: (fileId) => getFile(this.requireClient(), fileId),
6631
6790
  delete: (fileId) => deleteFile(this.requireClient(), fileId),
6632
- upload: (fileData, fileName, purpose) => uploadFile2(this.getAuthHeaders(), fileData, fileName, purpose),
6633
- getContent: (fileId) => getFileContent(this.getAuthHeaders(), fileId)
6791
+ upload: (fileData, fileName, purpose) => this.recovering(
6792
+ () => uploadFile2(this.getAuthHeaders(), fileData, fileName, purpose)
6793
+ ),
6794
+ getContent: (fileId) => this.recovering(() => getFileContent(this.getAuthHeaders(), fileId))
6634
6795
  };
6635
6796
  // ── Agents ──────────────────────────────────────────────────────────
6636
6797
  agents = {
@@ -6638,7 +6799,28 @@ var Arbi = class {
6638
6799
  create: (name) => createAgent(this.requireClient(), name),
6639
6800
  getConfig: (agentExtId) => getAgentConfig(this.requireClient(), agentExtId),
6640
6801
  listWorkspaces: (agentExtId) => listAgentWorkspaces(this.requireClient(), agentExtId),
6641
- delete: (agentExtIds) => deleteAgents(this.requireClient(), agentExtIds)
6802
+ delete: (agentExtIds) => deleteAgents(this.requireClient(), agentExtIds),
6803
+ /** Mint a TTL'd run session for an agent; see `grantTemporaryAccess` to also deposit a key. */
6804
+ authorize: (agentExtId, workspaceId, ttlSeconds) => authorizeAgent(this.requireClient(), agentExtId, workspaceId, ttlSeconds),
6805
+ authorizeLimits: () => getAuthorizeLimits(this.requireClient()),
6806
+ /**
6807
+ * Give an agent temporary, session-scoped access to a workspace: mint its run session, then
6808
+ * deposit the workspace key on it. Returns the session details (`ttl` in seconds).
6809
+ */
6810
+ grantTemporaryAccess: async (agentExtId, workspaceId, ttlSeconds) => {
6811
+ const session = await authorizeAgent(
6812
+ this.requireClient(),
6813
+ agentExtId,
6814
+ workspaceId,
6815
+ ttlSeconds
6816
+ );
6817
+ await this.workspaces.grantTemporaryAccess({
6818
+ workspaceId,
6819
+ emails: [session.agent_email],
6820
+ sessionPubkeyB64: session.session_pubkey_b64
6821
+ });
6822
+ return session;
6823
+ }
6642
6824
  };
6643
6825
  // ── Scheduled tasks ───────────────────────────────────────────────────
6644
6826
  tasks = {
@@ -6647,7 +6829,26 @@ var Arbi = class {
6647
6829
  get: (taskId) => getTask(this.requireClient(), taskId),
6648
6830
  update: (taskId, body) => updateTask(this.requireClient(), taskId, body),
6649
6831
  delete: (taskId) => deleteTask(this.requireClient(), taskId),
6650
- run: (taskId) => runTask(this.requireClient(), taskId)
6832
+ run: (taskId) => runTask(this.requireClient(), taskId),
6833
+ listRuns: (taskId) => listTaskRuns(this.requireClient(), taskId),
6834
+ /**
6835
+ * Run a task and, when the run is parked waiting for workspace access (a temporary
6836
+ * authorization tier), grant the agent's run session a temporary key and run it again.
6837
+ * A task that needs no approval returns from the first call already running.
6838
+ */
6839
+ runWithAuth: async (taskId) => {
6840
+ const client = this.requireClient();
6841
+ const first = await runTask(client, taskId);
6842
+ if (!first.pending_auth_request_id || !first.pending_auth_session_pubkey || !first.pending_auth_agent_email || !first.workspace_ext_id) {
6843
+ return first;
6844
+ }
6845
+ await this.workspaces.grantTemporaryAccess({
6846
+ workspaceId: first.workspace_ext_id,
6847
+ emails: [first.pending_auth_agent_email],
6848
+ sessionPubkeyB64: first.pending_auth_session_pubkey
6849
+ });
6850
+ return runTask(client, taskId);
6851
+ }
6651
6852
  };
6652
6853
  // ── Workspace facts ─────────────────────────────────────────────────
6653
6854
  facts = {
@@ -7812,6 +8013,6 @@ async function startDmListener(options) {
7812
8013
  };
7813
8014
  }
7814
8015
 
7815
- export { Arbi, ArbiApiError, ArbiError, ClaudeOrchestrator, DOC_TERMINAL_STATUSES, FileConfigStore, OpenClawOrchestrator, WebSocketAuthError, agentconfig_exports as agentconfig, agents_exports as agents, assistant_exports as assistant, authenticatedFetch, buildDocNameMap, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, connectWebSocket, connectWithReconnect, consumeSSEStream, contacts_exports as contacts, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, device_flow_exports as deviceFlow, dm_exports as dm, doctags_exports as doctags, documents_exports as documents, documents_node_exports as documentsNode, facts_exports as facts, files_exports as files, filterSkills, formatAgentStepLabel, formatFileSize, formatItemLabel, formatStreamSummary, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getErrorCode, getErrorMessage, getRawWorkspaceKey, health_exports as health, listen_exports as listen, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, profile_exports as profile, projects_exports as projects, requireData, requireOk, resolveAuth, resolveCitations, resolveWorkspace, responses_exports as responses, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, startDmListener, streamSSE, stripCitationMarkdown, summarizeCitations, tags_exports as tags, tasks_exports as tasks, workspaces_exports as workspaces };
8016
+ export { Arbi, ArbiApiError, ArbiError, ArbiSessionExpiredError, ClaudeOrchestrator, DOC_TERMINAL_STATUSES, FileConfigStore, OpenClawOrchestrator, WebSocketAuthError, agentconfig_exports as agentconfig, agents_exports as agents, assistant_exports as assistant, authenticatedFetch, buildDocNameMap, buildRetrievalChunkTool, buildRetrievalFullContextTool, buildRetrievalTocTool, connectWebSocket, connectWithReconnect, consumeSSEStream, contacts_exports as contacts, conversations_exports as conversations, countCitations, createAuthenticatedClient, createDocumentWaiter, device_flow_exports as deviceFlow, dm_exports as dm, doctags_exports as doctags, documents_exports as documents, documents_node_exports as documentsNode, facts_exports as facts, files_exports as files, filterSkills, formatAgentStepLabel, formatFileSize, formatItemLabel, formatStreamSummary, formatUserName, formatWorkspaceChoices, formatWsMessage, generateEncryptedWorkspaceKey, generateNewWorkspaceKey, getErrorCode, getErrorMessage, getRawWorkspaceKey, health_exports as health, listen_exports as listen, parseSSEEvents, parseSlashCommand, parseSlashTokenInProgress, performPasswordLogin, performSigningKeyLogin, performSsoDeviceFlowLogin, profile_exports as profile, projects_exports as projects, requireData, requireOk, resolveAuth, resolveCitations, resolveWorkspace, responses_exports as responses, selectWorkspace, selectWorkspaceById, sessions_exports as sessions, settings_exports as settings, startDmListener, streamSSE, stripCitationMarkdown, summarizeCitations, tags_exports as tags, tasks_exports as tasks, workspaces_exports as workspaces };
7816
8017
  //# sourceMappingURL=index.js.map
7817
8018
  //# sourceMappingURL=index.js.map