broods 0.33.4 → 0.34.0

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.ts CHANGED
@@ -885,6 +885,8 @@ type WebSocketClientAttachMessage = {
885
885
  agentId: string;
886
886
  conversationKey: string;
887
887
  eventId: string;
888
+ /** The run id the accepting response returned; how core resolves the run. */
889
+ runId: string;
888
890
  afterCursor?: string;
889
891
  };
890
892
  type WebSocketClientCancelMessage = {
@@ -913,7 +915,9 @@ interface Agent {
913
915
  }
914
916
  interface AsyncRequestAccepted {
915
917
  statusUrl: string;
916
- statusId: string;
918
+ /** Account-unique id for this run; what the status URL names. */
919
+ runId: string;
920
+ /** The eventId sent with the request, echoed back. */
917
921
  eventId: string;
918
922
  agentId: string;
919
923
  status?: "accepted" | "queued" | "applied" | "processing";
@@ -1101,6 +1105,12 @@ interface AgentRunResult {
1101
1105
  text: string;
1102
1106
  events: TextStreamPart<ToolSet>[];
1103
1107
  }
1108
+ /** Input for `continue`: the conversation to re-enter. */
1109
+ interface AgentContinueInput {
1110
+ /** The key given to `run`, or the scoped key a dashboard trace row shows. */
1111
+ conversationKey: string;
1112
+ eventId?: string;
1113
+ }
1104
1114
  declare class IngressAcceptedError extends Error {
1105
1115
  readonly accepted: AsyncRequestAccepted;
1106
1116
  constructor(accepted: AsyncRequestAccepted);
@@ -1124,7 +1134,7 @@ interface AgentReference<Name extends string = string> {
1124
1134
  /**
1125
1135
  * Authoritative scope of the stage's runtime key, embedded by codegen
1126
1136
  * from the deploy response. When present the client posts to the scoped URL
1127
- * `/v1/{projectSlug}/agents/{stageSlug}/{endpointId}` (matching the
1137
+ * `/v1/projects/{projectSlug}/stages/{stageSlug}/agents/{endpointId}` (matching the
1128
1138
  * dashboard); when absent it falls back to the base URL.
1129
1139
  */
1130
1140
  readonly endpointId?: string;
@@ -1164,6 +1174,7 @@ type AgentHandle = {
1164
1174
  id: string;
1165
1175
  run: (input: AgentRunInput) => Promise<AgentRunResult>;
1166
1176
  runAsync: (input: AgentRunInput) => Promise<AsyncAgentRun>;
1177
+ continue: (input: AgentContinueInput) => Promise<AsyncAgentRun>;
1167
1178
  stream: (input: AgentRunInput) => AsyncGenerator<TextStreamPart<ToolSet>>;
1168
1179
  };
1169
1180
  type CreateClientCronInput = CreateCronInput | (Omit<CreateCronInput, "agentId"> & {
@@ -1207,14 +1218,19 @@ declare class BroodsClient {
1207
1218
  agentId: string;
1208
1219
  agentName?: string;
1209
1220
  }): Promise<AsyncAgentRun>;
1210
- /** Fetch one async status snapshot by status URL or status id + agent id. */
1211
- getAsyncStatus(status: AsyncRequestAccepted | string, options?: {
1212
- agentId?: string;
1213
- }): Promise<AsyncStatus>;
1221
+ /**
1222
+ * Re-enter a conversation whose last turn stopped short (step cap, provider
1223
+ * fault). Core adds one "continue" user turn on the persisted history and
1224
+ * runs it like a background run; a live channel session answers in its channel.
1225
+ */
1226
+ continue(ref: AgentReference, input: AgentContinueInput): Promise<AsyncAgentRun>;
1227
+ continue(input: AgentContinueInput & {
1228
+ agentId: string;
1229
+ }): Promise<AsyncAgentRun>;
1230
+ /** Fetch one async status snapshot by status URL or run id. */
1231
+ getAsyncStatus(status: AsyncRequestAccepted | string): Promise<AsyncStatus>;
1214
1232
  /** Poll async status until it reaches completed, failed, awaiting_approval, awaiting_input, or timeout. */
1215
- waitForAsyncStatus(status: AsyncRequestAccepted | string, options?: AsyncPollOptions & {
1216
- agentId?: string;
1217
- }): Promise<AsyncStatus>;
1233
+ waitForAsyncStatus(status: AsyncRequestAccepted | string, options?: AsyncPollOptions): Promise<AsyncStatus>;
1218
1234
  createCron(input: CreateClientCronInput): Promise<Cron>;
1219
1235
  listCrons(): Promise<Cron[]>;
1220
1236
  getCron(cronId: string): Promise<Cron | null>;
@@ -1225,11 +1241,15 @@ declare class BroodsClient {
1225
1241
  deleteCron(cronId: string): Promise<boolean>;
1226
1242
  /**
1227
1243
  * Scoped invoke URL for a deployed agent. When codegen embedded the runtime
1228
- * key's scope, this is `/v1/{projectSlug}/agents/{stageSlug}/{endpointId}`
1229
- * (the same URL the dashboard shows, so core can validate the key against the
1230
- * path); otherwise it falls back to the base URL.
1244
+ * key's scope, this is
1245
+ * `/v1/projects/{projectSlug}/stages/{stageSlug}/agents/{endpointId}` (the
1246
+ * same URL the dashboard shows, so core can validate the key against the
1247
+ * path); otherwise it falls back to the single run endpoint.
1231
1248
  */
1232
1249
  private scopedUrl;
1250
+ private asyncAgentRun;
1251
+ /** POST a run body that must answer 202 and wrap the accepted run for polling. */
1252
+ private postAcceptedRun;
1233
1253
  private openStream;
1234
1254
  private fetchCore;
1235
1255
  private apiKeyHeaders;
@@ -1301,7 +1321,8 @@ interface CreateAgentResult {
1301
1321
  /** Write-only account environment variable metadata. */
1302
1322
  interface AccountEnvVar {
1303
1323
  name: string;
1304
- updatedAt: number;
1324
+ /** ISO 8601, like every other timestamp in the API. */
1325
+ updatedAt: string;
1305
1326
  }
1306
1327
  /** Fields accepted by `PATCH /v1/agents/{id}`. `config` is deep-merged; `null` values delete keys. */
1307
1328
  interface UpdateAgentInput {
@@ -2365,4 +2386,4 @@ declare function isConnectionDefinition(value: unknown): value is AnyConnectionD
2365
2386
  declare function isResource(value: unknown): value is AnyResource;
2366
2387
 
2367
2388
  export { BroodsAccountApiError, BroodsAccountClient, BroodsClient, BroodsWebSocketClient, DEFAULT_CORE_BASE_URL, IngressAcceptedError, MAX_OBSERVABILITY_BACKFILL, BroodsWebSocketClient as WebSocketClient, BroodsWebSocketClient as WebsocketClient, defineAgent, defineBroods, defineCron, defineDiscordChannel, defineDiscordConnection, defineGitHubChannel, defineGitHubConnection, defineHarness, defineMcp, definePancakeChannel, definePancakeConnection, definePolicy, defineSandbox, defineSkill, defineSlackChannel, defineSlackConnection, defineTelegramChannel, defineTelegramConnection, defineWorkspace, defineZaloChannel, defineZaloConnection, env, envPlaceholder, isBroodsConfig, isConnectionDefinition, isLogLevel, isObservabilityClientMessage, isResource, isRootSpanKind, isSandboxLogId, isTraceId, normalizeHttpServiceUrl, readSseStream, resolveEnvCredential, resolveRunEvents, toWebSocketBaseUrl, webSocketSubprotocols };
2368
- export type { Account, AccountAgent, AccountChannel, AccountEnvVar, AccountMcp, AccountPolicy, AccountRole, AccountSandbox, AccountWorkspace, Agent, AgentChannelsConfig, AgentCodeHookConfig, AgentConfig, AgentConfigDoc, AgentDefinitionConfig, AgentDiscordChannelConfig, AgentGitHubChannelConfig, AgentHandle, AgentHookEventName, AgentHooks, AgentHooksConfig, AgentPancakeChannelConfig, AgentProviderSettings, AgentReference, AgentResource, AgentRunEventInput, AgentRunInput, AgentRunModelOverrides, AgentRunOverrides, AgentRunResult, AgentSkillsDefinitionConfig, AgentSlackChannelConfig, AgentStreamPart, AgentSubagentDefinitionConfig, AgentTelegramChannelConfig, AgentWebhookHookConfig, AgentWorkspaceInput, AgentWorkspaceRef, AgentWorkspaceRefInput, AgentZaloChannelConfig, AnyConnectionDefinition, AnyResource, AssumeRoleResult, AsyncAgentRun, AsyncPollOptions, AsyncRequestAccepted, AsyncStatus, BroodsAccount, BroodsAccountClientOptions, BroodsClientOptions, BroodsConfigDefinition, BroodsProjectConfig, BroodsWebSocketClientOptions, ChannelAgentInput, ChannelDefinitionConfig, ChannelMessageReceived, ChannelPartition, ChannelRecordConfig, ChannelReference, ChannelReplyIn, ChannelResource, ChannelType, CliManifest, CliManifestResource, ConnectionDefinition, CreateAgentResult, CreateClientCronInput, CreateCronInput, CreateMcpInput, Cron, CronDefinitionConfig, CronDoc, CronLastStatus, CronResource, CronRun, CronStatus, DeleteAccountResult, DiscordChannelInput, DiscordConnectionDefinition, DiscordConnectionInput, DiscordMessageSource, DiscordSource, Doc, EnvAccessor, EnvRef, EnvRefString, GeneratedIds, GitHubChannelInput, GitHubConnectionDefinition, GitHubConnectionInput, GitHubMessageSource, GitHubSource, HarnessDefinition, HarnessType, HookContext, Id, IngressMode, IngressStatus, LogLevel, McpDefinitionConfig, McpHandler, McpOauthInput, McpResource, ObservabilityBackfillMessage, ObservabilityClientMessage, ObservabilityErrorMessage, ObservabilityFetchTraceMessage, ObservabilityLogEntry, ObservabilityLogMessage, ObservabilityReadyMessage, ObservabilityServerMessage, ObservabilitySpanMessage, ObservabilitySpanRow, ObservabilitySubscribeMessage, ObservabilityUnsubscribeMessage, PancakeChannelInput, PancakeConnectionDefinition, PancakeConnectionInput, PancakeMessageSource, PancakeSource, PendingQuestion, PolicyDefinitionConfig, PolicyDocument, PolicyResource, ProjectDoc, ProviderConfigInput, ProviderSettingsInput, ResourceApi, ResourceDefinition, ResourceInput, ResourceKind, RotateSecretResult, Sandbox, SandboxConfig, SandboxConfigDoc, SandboxDefinitionConfig, SandboxDefinitionOptions, SandboxLifecycleResult, SandboxResource, SandboxSnapshotResult, SandboxTerminalTicket, Skill, SkillDefinitionConfig, SkillResource, SkillUploadInput, SlackChannelInput, SlackConnectionDefinition, SlackConnectionInput, SlackMessageSource, SlackSource, StageDoc, StageScope, TelegramChannelInput, TelegramConnectionDefinition, TelegramConnectionInput, TelegramMessageSource, TelegramSource, ToolApprovalSummary, UpdateAgentInput, UpdateCronInput, UpdateMcpInput, WebSocketAttachInput, WebSocketClientAttachMessage, WebSocketClientCancelMessage, WebSocketClientControlMessage, WebSocketClientExecuteMessage, WebSocketClientMessage, WebSocketConstructorLike, WebSocketHandlers, WebSocketLike, WebSocketOutputMessage, WebSocketRunInput, WebSocketServerMessage, WebSocketStreamMessage, WebSocketSubscription, Workspace, WorkspaceConfig, WorkspaceConfigDoc, WorkspaceDefinitionConfig, WorkspaceFileEntry, WorkspaceResource, ZaloChannelInput, ZaloConnectionDefinition, ZaloConnectionInput, ZaloMessageSource, ZaloSource };
2389
+ export type { Account, AccountAgent, AccountChannel, AccountEnvVar, AccountMcp, AccountPolicy, AccountRole, AccountSandbox, AccountWorkspace, Agent, AgentChannelsConfig, AgentCodeHookConfig, AgentConfig, AgentConfigDoc, AgentContinueInput, AgentDefinitionConfig, AgentDiscordChannelConfig, AgentGitHubChannelConfig, AgentHandle, AgentHookEventName, AgentHooks, AgentHooksConfig, AgentPancakeChannelConfig, AgentProviderSettings, AgentReference, AgentResource, AgentRunEventInput, AgentRunInput, AgentRunModelOverrides, AgentRunOverrides, AgentRunResult, AgentSkillsDefinitionConfig, AgentSlackChannelConfig, AgentStreamPart, AgentSubagentDefinitionConfig, AgentTelegramChannelConfig, AgentWebhookHookConfig, AgentWorkspaceInput, AgentWorkspaceRef, AgentWorkspaceRefInput, AgentZaloChannelConfig, AnyConnectionDefinition, AnyResource, AssumeRoleResult, AsyncAgentRun, AsyncPollOptions, AsyncRequestAccepted, AsyncStatus, BroodsAccount, BroodsAccountClientOptions, BroodsClientOptions, BroodsConfigDefinition, BroodsProjectConfig, BroodsWebSocketClientOptions, ChannelAgentInput, ChannelDefinitionConfig, ChannelMessageReceived, ChannelPartition, ChannelRecordConfig, ChannelReference, ChannelReplyIn, ChannelResource, ChannelType, CliManifest, CliManifestResource, ConnectionDefinition, CreateAgentResult, CreateClientCronInput, CreateCronInput, CreateMcpInput, Cron, CronDefinitionConfig, CronDoc, CronLastStatus, CronResource, CronRun, CronStatus, DeleteAccountResult, DiscordChannelInput, DiscordConnectionDefinition, DiscordConnectionInput, DiscordMessageSource, DiscordSource, Doc, EnvAccessor, EnvRef, EnvRefString, GeneratedIds, GitHubChannelInput, GitHubConnectionDefinition, GitHubConnectionInput, GitHubMessageSource, GitHubSource, HarnessDefinition, HarnessType, HookContext, Id, IngressMode, IngressStatus, LogLevel, McpDefinitionConfig, McpHandler, McpOauthInput, McpResource, ObservabilityBackfillMessage, ObservabilityClientMessage, ObservabilityErrorMessage, ObservabilityFetchTraceMessage, ObservabilityLogEntry, ObservabilityLogMessage, ObservabilityReadyMessage, ObservabilityServerMessage, ObservabilitySpanMessage, ObservabilitySpanRow, ObservabilitySubscribeMessage, ObservabilityUnsubscribeMessage, PancakeChannelInput, PancakeConnectionDefinition, PancakeConnectionInput, PancakeMessageSource, PancakeSource, PendingQuestion, PolicyDefinitionConfig, PolicyDocument, PolicyResource, ProjectDoc, ProviderConfigInput, ProviderSettingsInput, ResourceApi, ResourceDefinition, ResourceInput, ResourceKind, RotateSecretResult, Sandbox, SandboxConfig, SandboxConfigDoc, SandboxDefinitionConfig, SandboxDefinitionOptions, SandboxLifecycleResult, SandboxResource, SandboxSnapshotResult, SandboxTerminalTicket, Skill, SkillDefinitionConfig, SkillResource, SkillUploadInput, SlackChannelInput, SlackConnectionDefinition, SlackConnectionInput, SlackMessageSource, SlackSource, StageDoc, StageScope, TelegramChannelInput, TelegramConnectionDefinition, TelegramConnectionInput, TelegramMessageSource, TelegramSource, ToolApprovalSummary, UpdateAgentInput, UpdateCronInput, UpdateMcpInput, WebSocketAttachInput, WebSocketClientAttachMessage, WebSocketClientCancelMessage, WebSocketClientControlMessage, WebSocketClientExecuteMessage, WebSocketClientMessage, WebSocketConstructorLike, WebSocketHandlers, WebSocketLike, WebSocketOutputMessage, WebSocketRunInput, WebSocketServerMessage, WebSocketStreamMessage, WebSocketSubscription, Workspace, WorkspaceConfig, WorkspaceConfigDoc, WorkspaceDefinitionConfig, WorkspaceFileEntry, WorkspaceResource, ZaloChannelInput, ZaloConnectionDefinition, ZaloConnectionInput, ZaloMessageSource, ZaloSource };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{B,pe,xe,Te,ke,Pe,V,Ie,C,me,q,W,$e,K,D,Me,Ae,ze,Oe,Ne,je,qe,De,Le,Ue,Fe,Be,Ve,Ze,He,We,Ke,Ge,Je,Ye,Xe,Qe,ne,_,h}from"./chunk-7xc63gnm.js";import{m,Ce,L,U}from"./chunk-mqwt5n8x.js";export{m as BroodsAccountApiError,U as BroodsAccountClient,q as BroodsClient,$e as BroodsWebSocketClient,C as DEFAULT_CORE_BASE_URL,me as IngressAcceptedError,xe as MAX_OBSERVABILITY_BACKFILL,$e as WebSocketClient,$e as WebsocketClient,Ae as defineAgent,ze as defineBroods,Oe as defineCron,Ke as defineDiscordChannel,Fe as defineDiscordConnection,Ge as defineGitHubChannel,Be as defineGitHubConnection,Ne as defineHarness,je as defineMcp,Je as definePancakeChannel,Ve as definePancakeConnection,qe as definePolicy,De as defineSandbox,Le as defineSkill,Ye as defineSlackChannel,Ze as defineSlackConnection,Xe as defineTelegramChannel,He as defineTelegramConnection,Ue as defineWorkspace,Qe as defineZaloChannel,We as defineZaloConnection,Me as env,Ce as envPlaceholder,ne as isBroodsConfig,_ as isConnectionDefinition,Te as isLogLevel,ke as isObservabilityClientMessage,h as isResource,Pe as isRootSpanKind,V as isSandboxLogId,Ie as isTraceId,W as normalizeHttpServiceUrl,pe as readSseStream,L as resolveEnvCredential,B as resolveRunEvents,K as toWebSocketBaseUrl,D as webSocketSubprotocols};
1
+ import{B,pe,xe,Te,ke,Pe,V,Ie,C,me,q,W,Ce,K,D,Ae,Me,ze,Oe,Ne,je,qe,De,Le,Ue,Fe,Be,Ve,Ze,He,We,Ke,Ge,Je,Ye,Xe,Qe,ne,_,h}from"./chunk-wgwmcq6q.js";import{m,$e,L,U}from"./chunk-yd3vh7k7.js";export{m as BroodsAccountApiError,U as BroodsAccountClient,q as BroodsClient,Ce as BroodsWebSocketClient,C as DEFAULT_CORE_BASE_URL,me as IngressAcceptedError,xe as MAX_OBSERVABILITY_BACKFILL,Ce as WebSocketClient,Ce as WebsocketClient,Me as defineAgent,ze as defineBroods,Oe as defineCron,Ke as defineDiscordChannel,Fe as defineDiscordConnection,Ge as defineGitHubChannel,Be as defineGitHubConnection,Ne as defineHarness,je as defineMcp,Je as definePancakeChannel,Ve as definePancakeConnection,qe as definePolicy,De as defineSandbox,Le as defineSkill,Ye as defineSlackChannel,Ze as defineSlackConnection,Xe as defineTelegramChannel,He as defineTelegramConnection,Ue as defineWorkspace,Qe as defineZaloChannel,We as defineZaloConnection,Ae as env,$e as envPlaceholder,ne as isBroodsConfig,_ as isConnectionDefinition,Te as isLogLevel,ke as isObservabilityClientMessage,h as isResource,Pe as isRootSpanKind,V as isSandboxLogId,Ie as isTraceId,W as normalizeHttpServiceUrl,pe as readSseStream,L as resolveEnvCredential,B as resolveRunEvents,K as toWebSocketBaseUrl,D as webSocketSubprotocols};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "broods",
3
- "version": "0.33.4",
3
+ "version": "0.34.0",
4
4
  "description": "CLI + TypeScript SDK for the broods agent platform.",
5
5
  "keywords": [
6
6
  "agents",
@@ -57,7 +57,7 @@
57
57
  "esbuild": "^0.28.2"
58
58
  },
59
59
  "devDependencies": {
60
- "@ai-sdk/tui": "1.0.94",
60
+ "@ai-sdk/tui": "1.0.95",
61
61
  "@arethetypeswrong/cli": "^0.18.5",
62
62
  "@chat-adapter/discord": "^4.38.1",
63
63
  "@chat-adapter/github": "^4.38.1",
@@ -67,7 +67,7 @@
67
67
  "@modelcontextprotocol/server": "2.0.0",
68
68
  "@types/bun": "^1.3.14",
69
69
  "@typescript/typescript6": "6.0.2",
70
- "ai": "^7.0.93",
70
+ "ai": "^7.0.94",
71
71
  "publint": "^0.3.23",
72
72
  "rollup": "^4.62.4",
73
73
  "rollup-plugin-dts": "^6.5.1",
@@ -75,7 +75,7 @@
75
75
  "zod": "^4.4.3"
76
76
  },
77
77
  "peerDependencies": {
78
- "ai": "^7.0.93"
78
+ "ai": "^7.0.94"
79
79
  },
80
80
  "peerDependenciesMeta": {
81
81
  "ai": {
@@ -1,5 +0,0 @@
1
- function B(e){if(e.events&&e.input!==void 0)throw Error("Run input accepts either `input` or `events`, not both");if(e.events&&e.events.length>0)return e.events;if(typeof e.input==="string")return[{role:"user",content:[{type:"text",text:e.input}]}];throw Error("Run input requires `input` (string) or a non-empty `events` array")}async function*pe(e){let n=e.getReader(),t=new TextDecoder,o="";try{while(!0){let{done:r,value:s}=await n.read();if(r)break;o+=t.decode(s,{stream:!0});let i=o.split(`
2
- `);o=i.pop()??"";for(let a of i)if(a.startsWith("data: "))yield a.slice(6)}}finally{n.releaseLock()}}var xe=500,ge=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,de=/^(?!0{32}$)[0-9a-f]{32}$/;function Te(e){return e==="DEBUG"||e==="INFO"||e==="WARN"||e==="ERROR"}function ke(e){if(typeof e!=="object"||e===null)return!1;let n=e;if(n.type==="subscribe")return fe(n);if(n.type==="unsubscribe")return T(n.stream);if(n.type==="fetchTrace")return Ie(n.traceId);return!1}function Pe(e){return e==="task"||e==="cron"||e==="subtask"}function V(e){return typeof e==="string"&&ge.test(e)}function Ie(e){return typeof e==="string"&&de.test(e)}function T(e){return e==="logs"||e==="traces"}function fe(e){let n=e.stream;if(!T(n))return!1;let t=e.backfill;if(t!==void 0&&(typeof t!=="number"||!Number.isSafeInteger(t)||t<0||t>500))return!1;if(e.liveOnly!==void 0&&typeof e.liveOnly!=="boolean")return!1;let o=e.minLevel;if(o!==void 0&&!Te(o))return!1;let r=e.sandboxId;return r===void 0||n==="logs"&&V(r)}import{mkdir as ye,readFile as be,writeFile as he}from"node:fs/promises";import{homedir as Se}from"node:os";import{dirname as Re,join as Ce}from"node:path";var y="broods",S="_generated",I=Ce(Se(),".broods","config.json"),M="broods.app",P="dashboard",ve="gateway";async function Z(){let e=process.env.BROODS_TOKEN,n=process.env.BROODS_BASE_URL;if(e&&n)return{baseUrl:g(n),token:e,createdAt:new Date().toISOString()};try{let t=JSON.parse(await be(I,"utf8"));if(typeof t.baseUrl!=="string"||!t.baseUrl)return null;return t}catch{return null}}async function H(e){await ye(Re(I),{recursive:!0}),await he(I,`${JSON.stringify(e,null,2)}
3
- `,"utf8")}function w(){return process.env.BROODS_STAGE}function g(e){let n=e.length;while(n>0&&e.charCodeAt(n-1)===47)n-=1;return e.slice(0,n)}function re(e){try{let n=new URL(e);if(!n.hostname.startsWith(`${P}.`))return;let t=n.hostname.slice(P.length+1);if(t!==M&&!t.endsWith(`.${M}`))return;return n.hostname=`${ve}.${t}`,g(n.origin)}catch{return}}import{existsSync as L,readFileSync as N,statSync as we}from"node:fs";import{join as j,resolve as G}from"node:path";var O=new Map,Ee=new Set(Object.keys(process.env)),U=new Set;function f(e=process.cwd()){_e(e);let n=nn();return{dashboardUrl:process.env.BROODS_DASHBOARD_URL??n?.dashboardUrl,baseUrl:process.env.BROODS_BASE_URL??n?.baseUrl,token:process.env.BROODS_TOKEN??n?.token,project:process.env.BROODS_PROJECT,stage:w()}}function z(e,n=process.cwd()){let t=process.env[e];if(t===void 0)return!1;let o=G(n);for(let r of[".env.local",".env"]){let s=j(o,r);if(!L(s))continue;let i=F(N(s,"utf8"));if(i[e]!==void 0)return i[e]!==t}return!0}function _e(e){let n=G(e),t=process.env.BROODS_RELOAD_ENV==="1";for(let o of[".env",".env.local"]){let r=j(n,o);if(!L(r)){O.delete(r);continue}let s=we(r).mtimeMs,i=O.get(r);if(i&&i.mtimeMs===s)continue;O.set(r,{mtimeMs:s});for(let[a,u]of Object.entries(F(N(r,"utf8"))))if(t||!Ee.has(a)||U.has(a))process.env[a]=u,U.add(a)}}function F(e){let n={};for(let t of e.split(/\r?\n/)){let o=t.trim();if(!o||o.startsWith("#"))continue;let r=o.startsWith("export ")?o.slice(7).trim():o,s=r.indexOf("=");if(s<=0)continue;let i=r.slice(0,s).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))continue;n[i]=en(r.slice(s+1).trim())}return n}function en(e){if(e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1).replace(/\\n/g,`
4
- `).replace(/\\"/g,'"');if(e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);let n=e.indexOf(" #");return n>=0?e.slice(0,n).trimEnd():e}function nn(){try{let e=JSON.parse(N(I,"utf8"));if(typeof e.baseUrl!=="string"||typeof e.token!=="string")return null;return{baseUrl:g(e.baseUrl),...typeof e.dashboardUrl==="string"?{dashboardUrl:g(e.dashboardUrl)}:{},token:e.token}}catch{return null}}var C="https://gateway.broods.app";class me extends Error{accepted;constructor(e){super(`Ingress ${e.eventId} was accepted asynchronously with status ${e.status??"queued"}`);this.accepted=e;this.name="IngressAcceptedError"}}class q{baseUrl;apiKey;fetchImpl;constructor(e={}){f(),this.baseUrl=W(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||C),this.apiKey=e.apiKey||process.env.BROODS_API_KEY||void 0,this.fetchImpl=e.fetch??fetch}channelWebhookUrl(e){return`${this.baseUrl}${e.webhookPath.startsWith("/")?"":"/"}${e.webhookPath}`}accountWebhookUrl(e,n){let t=[e,n].map(encodeURIComponent);return`${this.baseUrl}/webhooks/${t.join("/")}`}stageWebhookUrl(e,n,t){let o=[e,"dev",n,t].map(encodeURIComponent);return`${this.baseUrl}/webhooks/${o.join("/")}`}agent(e,n){if(typeof e==="string"){let o=e,r=n??"";if(!r)throw Error(`Agent ${o} is missing a generated id. Run broods dev --once or broods deploy to sync it first.`);return{id:r,run:(s)=>this.run({...s,agentName:o,agentId:r}),runAsync:(s)=>this.runAsync({...s,agentName:o,agentId:r}),stream:(s)=>this.stream({...s,agentName:o,agentId:r})}}let t=e;if(!t.id)throw Error(`Agent ${t.name} is missing a generated id. Run broods dev --once or broods deploy to sync it first.`);return{id:t.id,run:(o)=>this.run(t,o),runAsync:(o)=>this.runAsync(t,o),stream:(o)=>this.stream(t,o)}}async run(e,n){let t=[],o="",r=n?this.stream(e,n):this.stream(e);for await(let s of r)if(t.push(s),s.type==="text-delta")o+=s.text;return{text:o,events:t}}async*stream(e,n){let t=n?{...n,agentId:e.id,agentName:e.name}:e,o=J(t,"cli"),r=n?this.scopedUrl(e):this.baseUrl,s=await this.openStream(o,r);if(!s.ok)throw Error(`Run failed: ${s.status} ${await s.text()}`);if(s.status===202)throw new me(Y(await s.json(),o));if(!s.body)throw Error("Run response has no body");for await(let i of pe(s.body)){let a;try{a=JSON.parse(i)}catch{continue}if(a.type==="error")throw Error(`Agent run failed: ${tn(a.error)}`);yield a}}async runAsync(e,n){let t=n?{...n,agentId:e.id,agentName:e.name}:e,o=J(t,"async"),r=n?this.scopedUrl(e,"/async"):`${this.baseUrl}/async`,s=await this.fetchJson(r,{method:"POST",headers:this.apiKeyHeaders(),body:JSON.stringify(o)});if(s.status!==202)throw Error(`Async run failed: ${s.status} ${await sn(s,"202 JSON")}`);let i=Y(await s.json(),o);return{...i,conversationKey:o.conversationKey,poll:()=>this.getAsyncStatus(i),wait:(a)=>this.waitForAsyncStatus(i,a)}}async getAsyncStatus(e,n={}){let t=this.resolveStatusUrl(e,n),o=await this.fetchJson(t,{method:"GET",headers:this.apiKeyHeaders()});if(o.status===404)return{status:"not_found"};if(!o.ok)throw Error(`Status check failed: ${o.status} ${await o.text()}`);return await o.json()}async waitForAsyncStatus(e,n={}){let t=Date.now()+(n.timeoutMs??180000),o=n.intervalMs??2000;while(Date.now()<t){if(n.signal?.aborted)throw Error("Async status polling aborted.");let r=await this.getAsyncStatus(e,n);if(r.status==="awaiting_approval"||r.status==="awaiting_input"||r.status==="completed"||r.status==="failed"||r.status==="expired"||r.status==="not_found")return r;await an(o,n.signal)}throw Error("Polling timeout")}async createCron(e){let n=await this.fetchJson(`${this.baseUrl}/v1/crons`,{method:"POST",headers:this.apiKeyHeaders(),body:JSON.stringify(rn(e))});if(n.status!==201)throw Error(`Create cron job failed: ${n.status} ${await p(n)}`);return await n.json()}async listCrons(){let e=await this.fetchJson(`${this.baseUrl}/v1/crons`,{method:"GET",headers:this.apiKeyHeaders()});if(!e.ok)throw Error(`List cron jobs failed: ${e.status} ${await p(e)}`);return(await e.json()).crons}async getCron(e){let n=await this.fetchJson(`${this.baseUrl}/v1/crons/${encodeURIComponent(e)}`,{method:"GET",headers:this.apiKeyHeaders()});if(n.status===404)return null;if(!n.ok)throw Error(`Get cron job failed: ${n.status} ${await p(n)}`);return await n.json()}async listCronRuns(e,n={}){let t=new URLSearchParams;if(n.limit!==void 0)t.set("limit",String(n.limit));let o=t.size>0?`?${t}`:"",r=await this.fetchJson(`${this.baseUrl}/v1/crons/${encodeURIComponent(e)}/runs${o}`,{method:"GET",headers:this.apiKeyHeaders()});if(!r.ok)throw Error(`List cron job runs failed: ${r.status} ${await p(r)}`);return(await r.json()).runs}async updateCron(e,n){let t=await this.fetchJson(`${this.baseUrl}/v1/crons/${encodeURIComponent(e)}`,{method:"PATCH",headers:this.apiKeyHeaders(),body:JSON.stringify(n)});if(!t.ok)throw Error(`Update cron job failed: ${t.status} ${await p(t)}`);return await t.json()}async deleteCron(e){let n=await this.fetchJson(`${this.baseUrl}/v1/crons/${encodeURIComponent(e)}`,{method:"DELETE",headers:this.apiKeyHeaders()});if(n.status===404)return!1;if(!n.ok)throw Error(`Delete cron job failed: ${n.status} ${await p(n)}`);return(await n.json()).deleted}scopedUrl(e,n=""){if(e.projectSlug&&e.stageSlug&&e.endpointId)return`${this.baseUrl}/v1/${encodeURIComponent(e.projectSlug)}/agents/${encodeURIComponent(e.stageSlug)}/${encodeURIComponent(e.endpointId)}${n}`;return`${this.baseUrl}${n}`}async openStream(e,n){if(this.apiKey)return await this.fetchCore(e,n,{Authorization:`Bearer ${this.apiKey}`});throw Error(`BroodsClient streams directly from the core service at ${this.baseUrl}. Provide apiKey. For a self-hosted core service, set host/baseUrl or BROODS_HOST/BROODS_BASE_URL.`)}async fetchCore(e,n,t){try{return await this.fetchImpl(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t},body:JSON.stringify(e)})}catch(o){throw Error(`Cannot access the broods core service at ${n}. The SDK uses ${C} by default; set host/baseUrl or BROODS_HOST/BROODS_BASE_URL to your own core service URL if your account uses a custom deployment. Cause: ${o instanceof Error?o.message:String(o)}`)}}apiKeyHeaders(){if(!this.apiKey)throw Error("BroodsClient requires apiKey or BROODS_API_KEY.");return{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}}async fetchJson(e,n){try{return await this.fetchImpl(e,{...n,headers:{"Content-Type":"application/json",...n.headers}})}catch(t){throw Error(`Cannot access the broods core service at ${e}. Cause: ${t instanceof Error?t.message:String(t)}`)}}resolveStatusUrl(e,n){if(typeof e!=="string")return e.statusUrl;if(/^https?:\/\//.test(e))return e;if(!n.agentId)throw Error("Polling by status id requires agentId.");return cn(this.baseUrl,e,n.agentId)}}function W(e){let n=e.trim(),t=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(n)?n:`https://${n}`;return g(t)}async function p(e){let n=await e.text();if(n.includes("Request body must include eventId and conversationKey"))return`${n}. Cron job APIs must be served by the configured baseUrl. Prefer defining stable cron jobs with defineCron(...) in broods/ and syncing with \`broods dev\` or \`broods deploy\`.`;return n}function J(e,n){let t=e.eventId??`${n}-${Date.now()}`;return{agentId:e.agentId,eventId:t,conversationKey:e.conversationKey??t,events:B(e),...e.mode!==void 0?{mode:e.mode}:{},...e.idempotencyKey!==void 0?{idempotencyKey:e.idempotencyKey}:{},...e.system!==void 0?{system:e.system}:{},...e.model!==void 0?{model:e.model}:{}}}function tn(e){if(typeof e==="string")return e;if(!e||typeof e!=="object")return String(e);let n=e,t=n.data?.error?.message??n.message??n.responseBody??JSON.stringify(e),o=n.name?`${n.name}: `:"",r=n.statusCode?` (HTTP ${n.statusCode})`:"";return`${o}${t}${r}`}function Y(e,n){if(!e||typeof e!=="object")throw Error("Async response must be an object");let t=e.statusUrl;if(typeof t!=="string"||t.length===0)throw Error("Async response missing statusUrl");let o=on(t);if(!o.statusId)throw Error("Async response statusUrl missing status id");let r=typeof e.eventId==="string"?e.eventId:o.statusId,{status:s,requestedMode:i}=e;return{statusUrl:t,statusId:o.statusId,eventId:r,agentId:o.agentId??n.agentId,...s==="accepted"||s==="queued"||s==="applied"||s==="processing"?{status:s}:{},...i==="reject"||i==="followup"||i==="collect"||i==="steer"?{requestedMode:i}:{}}}function on(e){let n=new URL(e),t=n.pathname.match(/\/status\/([^/]+)$/);return{statusId:t?.[1]?decodeURIComponent(t[1]):void 0,agentId:n.searchParams.get("agentId")??void 0}}function rn(e){if("agentId"in e)return e;let n=e.agent,t=typeof n==="string"?n:n.id,{agent:o,...r}=e;return{...r,agentId:t}}async function sn(e,n){if((e.headers.get("content-type")??"").toLowerCase().includes("text/event-stream"))return await e.body?.cancel().catch(()=>{}),`expected ${n}, but the server returned an SSE stream. This usually means the core deployment routed /async to the direct streaming runner instead of the async handler.`;let o=await e.text();if(o.length<=2000)return o;return`${o.slice(0,2000)}... [truncated ${o.length-2000} chars]`}function an(e,n){return new Promise((t,o)=>{if(n?.aborted){o(Error("Async status polling aborted."));return}let r=setTimeout(t,e);n?.addEventListener("abort",()=>{clearTimeout(r),o(Error("Async status polling aborted."))},{once:!0})})}function cn(e,n,t){return`${W(e)}/status/${encodeURIComponent(n)}?agentId=${encodeURIComponent(t)}`}var un=2000,X=0,k=1;class $e{baseUrl;apiKey;WebSocketImpl;connectTimeoutMs;constructor(e={}){if(f(),this.baseUrl=se(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||C),this.apiKey=e.apiKey||process.env.BROODS_API_KEY||"",!this.apiKey)throw Error("BroodsWebSocketClient requires apiKey or BROODS_API_KEY.");this.WebSocketImpl=e.WebSocket,this.connectTimeoutMs=e.connectTimeoutMs??un}subscribe(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=ln(e),s=oe(this.baseUrl),i=new t(o,D(this.apiKey)),a=!1,u=!1,l=setTimeout(()=>{if(!a)R(s)},this.connectTimeoutMs),E=(c=1000,x="client closed")=>{if(u)return;if(u=!0,clearTimeout(l),e.signal?.removeEventListener("abort",v),i.readyState===k||i.readyState===X)i.close(c,x)},R=(c)=>{n.onError?.(c),E(1011,"websocket error")},le=()=>{n.onDone?.(),E(1000,"done")},v=()=>{if(i.readyState===k)i.send(JSON.stringify({type:"cancel"}));R(Error("WebSocket run aborted."))};return e.signal?.addEventListener("abort",v,{once:!0}),i.onopen=()=>{if(a=!0,clearTimeout(l),e.signal?.aborted){v();return}i.send(JSON.stringify({type:"execute",agentId:r,events:B(e),sessionId:e.sessionId,...e.eventId!==void 0?{eventId:e.eventId}:{},...e.mode!==void 0?{mode:e.mode}:{},...e.idempotencyKey!==void 0?{idempotencyKey:e.idempotencyKey}:{},...e.system!==void 0?{system:e.system}:{},...e.model!==void 0?{model:e.model}:{}}))},i.onmessage=(c)=>{if(typeof c.data!=="string")return;let x=ee(c.data);if(!x)return;let A=te(x,n);switch(n.onMessage?.(A),A.type){case"meta":n.onMeta?.(A);break;case"done":le();break;case"error":R(Error(Q(A.error)));break}},i.onerror=()=>{R(s)},i.onclose=(c)=>{if(clearTimeout(l),e.signal?.removeEventListener("abort",v),u||c.code===1000)return;R(Error(c.reason||"WebSocket connection closed."))},{url:o,sendControl:function(c){if(i.readyState!==k)throw Error("WebSocket is not open");i.send(JSON.stringify({type:"control",...c}))},close:E}}attach(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=new t(o,D(this.apiKey)),s=!1,i=(a=1000,u="client closed")=>{if(s)return;if(s=!0,r.readyState===k||r.readyState===X)r.close(a,u)};return r.onopen=()=>r.send(JSON.stringify({type:"attach",...e,signal:void 0,agent:void 0})),r.onmessage=(a)=>{if(typeof a.data!=="string")return;let u=ee(a.data);if(!u)return;let l=te(u,n);if(n.onMessage?.(l),l.type==="done")n.onDone?.();if(l.type==="error")n.onError?.(Error(Q(l.error)))},r.onerror=()=>n.onError?.(oe(this.baseUrl)),r.onclose=(a)=>{if(!s&&a.code!==1000)n.onError?.(Error(a.reason||"WebSocket connection closed."))},{url:o,sendControl:function(a){if(r.readyState!==k)throw Error("WebSocket is not open");r.send(JSON.stringify({type:"control",...a}))},close:i}}async*stream(e){let n=[],t=!1,o=null,r=null,s=()=>{r?.(),r=null},i=this.subscribe(e,{onMessage:function(a){n.push(a),s()},onDone:function(){t=!0,s()},onError:function(a){o=a,s()}});try{while(!0){if(n.length>0){yield n.shift();continue}if(o)throw o;if(t)return;await new Promise((a)=>{r=a})}}finally{i.close()}}buildUrl(e){let n=gn(e),t=e.projectSlug??e.agent?.projectSlug,o=e.stageSlug??e.agent?.stageSlug,r=t?`/${t}`:"",s=o?`/${o}`:"";return`${K(this.baseUrl)}/v1${r}/agents${s}/${encodeURIComponent(n)}/ws`}resolveWebSocket(){let e=this.WebSocketImpl??globalThis.WebSocket;if(!e)throw Error("WebSocket is not available. Pass a WebSocket implementation in BroodsWebSocketClient options.");return e}}function K(e){let n=new URL(se(e));if(n.protocol==="https:")n.protocol="wss:";if(n.protocol==="http:")n.protocol="ws:";return g(n.toString())}function D(e){return["broods.v1",`broods.token.${e}`]}function Q(e){if(typeof e==="string")return e;if(e&&typeof e==="object"&&typeof e.message==="string")return e.message;return e===void 0?"WebSocket stream error.":JSON.stringify(e)}function se(e){let n=e.trim();if(/^wss?:\/\//.test(n))return g(n);return W(n)}function ee(e){try{let n=JSON.parse(e);return typeof n==="object"&&n!==null&&typeof n.type==="string"?n:null}catch{return null}}function ln(e){let n=e.agentId??e.agent?.id??e.endpointId;if(!n)throw Error("WebSocket run requires agent, agentId, or endpointId.");return n}function gn(e){let n=e.endpointId??e.agent?.endpointId??e.agent?.id;if(!n)throw Error("WebSocket run requires agent or endpointId.");return n}function te(e,n){if(e.type!=="output")return e;let t=e;return n.onOutput?.(t),t.data}function oe(e){return Error(`Cannot access the WebSocket service at ${e}.`)}var ae=Symbol.for("broods.resource"),ce=Symbol.for("broods.config"),ue=Symbol.for("broods.connection"),ie=/^[A-Z][A-Z0-9_]{0,63}$/,Me=new Proxy((e)=>{if(!ie.test(e))throw Error("env name must match /^[A-Z][A-Z0-9_]*$/ and be at most 64 characters.");return{__beeblastEnv:!0,name:e}},{get:function(e,n,t){if(typeof n==="string"&&ie.test(n))throw Error(`env.${n} is not supported; use env("${n}")`);return Reflect.get(e,n,t)}});function Ae(e){let{name:n,description:t,...o}=e;return d("agent",n,t,o)}function ze(e){return{[ce]:!0,config:e}}function Oe(e){let{name:n,description:t,...o}=e;return d("cron",n,t,o)}function Ne(e){return e}function je(e){let{name:n,description:t,...o}=e;return d("mcp",n,t,o)}function qe(e){let{name:n,description:t,...o}=e;return d("policy",n,t,o)}function De(e){let{name:n,description:t,...o}=e;return d("sandbox",n,t,o)}function Le(e){let{name:n,description:t,...o}=e;return d("skill",n,t,o)}function Ue(e){let{name:n,description:t,...o}=e;return d("workspace",n,t,o)}function Fe(e){return b("discord",e)}function Be(e){return b("github",e)}function Ve(e){return b("pancake",e)}function Ze(e){return b("slack",e)}function He(e){return b("telegram",e)}function We(e){return b("zalo",e)}function Ke(e){let{name:n,description:t,channelId:o,guildId:r,...s}=e;return m(n,t,o,r,s)}function Ge(e){let{name:n,description:t,repo:o,...r}=e,[s,...i]=o.split("/");if(!s||i.length!==1||!i[0])throw Error(`Channel "${n}" repo must be "owner/name", not "${o}"`);return m(n,t,o,s,r)}function Je(e){let{name:n,description:t,conversationId:o,...r}=e;return m(n,t,o,void 0,r)}function Ye(e){let{name:n,description:t,channelId:o,teamId:r,...s}=e;return m(n,t,o,r,s)}function Xe(e){let{name:n,description:t,chatId:o,...r}=e;return m(n,t,o,void 0,r)}function Qe(e){let{name:n,description:t,chatId:o,...r}=e;return m(n,t,o,void 0,r)}function ne(e){return Boolean(e&&typeof e==="object"&&e[ce])}function _(e){return Boolean(e&&typeof e==="object"&&e[ue])}function h(e){return Boolean(e&&typeof e==="object"&&e[ae])}function m(e,n,t,o,r){return d("channelRecord",e,n,{...r,externalId:t,...o?{workspaceRef:o}:{}})}function b(e,n){let{partition:t,...o}=n;return{[ue]:!0,kind:"connection",type:e,...t?{partition:t}:{},config:o}}function d(e,n,t,o){return{[ae]:!0,kind:e,name:n,...t?{description:t}:{},config:o}}
5
- export{B,pe,xe,Te,ke,Pe,V,Ie,y,S,I,Z,H,w,g,re,f,z,C,me,q,W,$e,K,D,Me,Ae,ze,Oe,Ne,je,qe,De,Le,Ue,Fe,Be,Ve,Ze,He,We,Ke,Ge,Je,Ye,Xe,Qe,ne,_,h};
@@ -1,2 +0,0 @@
1
- var u=/^[A-Z][A-Z0-9_]*$/;class m extends Error{status;body;constructor(e,t,n,s){super(`${e} ${t} failed with ${n}: ${s}`);this.name="BroodsAccountApiError",this.status=n,this.body=s}}function Ce(e){if(!u.test(e)||e.length>64)throw Error("envPlaceholder name must match /^[A-Z][A-Z0-9_]*$/ and be at most 64 characters.");return`\${${e}}`}function L(){return o("BROODS_SESSION_TOKEN")??o("BROODS_ACCOUNT_SECRET")}class U{baseUrl;bearerToken;fetchImpl;constructor(e={}){let t=e.baseUrl??o("BROODS_BASE_URL")??"https://gateway.broods.app",n=e.sessionToken??e.accountSecret??L();if(!n)throw Error("BroodsAccountClient requires an accountSecret or sessionToken (or BROODS_ACCOUNT_SECRET / BROODS_SESSION_TOKEN).");let s=t.length;while(s>0&&t.charCodeAt(s-1)===47)s-=1;this.baseUrl=t.slice(0,s),this.bearerToken=n,this.fetchImpl=e.fetch??fetch}async getAccount(){let e=await this.request("GET","/v1/account");if(!e)throw new m("GET","/v1/account",404,"Account not found");return e.account}async updateAccount(e){return(await this.request("PATCH","/v1/account",e))?.account??null}async assumeRole(e,t={}){let n=await this.request("POST","/v1/account/assume-role",{roleId:e,...t.ttlSeconds!==void 0?{ttlSeconds:t.ttlSeconds}:{}});if(!n)throw new m("POST","/v1/account/assume-role",404,"Role not found");return n}async rotateSecret(){let e=await this.request("POST","/v1/account/rotate-secret");if(!e)throw new m("POST","/v1/account/rotate-secret",404,"Account not found");return e}async deleteAccount(){return await this.request("DELETE","/v1/account")??{deleted:!1}}webhookUrl(e,t){let n=[e,t].map(encodeURIComponent);return`${this.baseUrl}/webhooks/${n.join("/")}`}async listAgents(){return(await this.request("GET","/v1/agents"))?.agents??[]}async createAgent(e){let t=await this.request("POST","/v1/agents",e);if(!t)throw new m("POST","/v1/agents",404,"Not found");return t}async getAgent(e){return await this.request("GET",`/v1/agents/${encodeURIComponent(e)}`)}async updateAgent(e,t){return await this.request("PATCH",`/v1/agents/${encodeURIComponent(e)}`,t)}async deleteAgent(e){return(await this.request("DELETE",`/v1/agents/${encodeURIComponent(e)}`))?.deleted??!1}async listEnvVars(){return(await this.request("GET","/v1/env"))?.env??[]}async setEnvVar(e,t){await this.request("PUT",`/v1/env/${encodeURIComponent(e)}`,{value:t})}async deleteEnvVar(e){return(await this.request("DELETE",`/v1/env/${encodeURIComponent(e)}`))?.deleted??!1}async listCrons(){return(await this.request("GET","/v1/crons"))?.crons??[]}async createCron(e){let t=await this.request("POST","/v1/crons",e);if(!t)throw new m("POST","/v1/crons",404,"Not found");return t}async getCron(e){return await this.request("GET",`/v1/crons/${encodeURIComponent(e)}`)}async updateCron(e,t){return await this.request("PATCH",`/v1/crons/${encodeURIComponent(e)}`,t)}async deleteCron(e){return(await this.request("DELETE",`/v1/crons/${encodeURIComponent(e)}`))?.deleted??!1}async listCronRuns(e,t={}){let n=t.limit!==void 0?`?limit=${t.limit}`:"";return(await this.request("GET",`/v1/crons/${encodeURIComponent(e)}/runs${n}`))?.runs??[]}async listWorkspaces(){return(await this.request("GET","/v1/workspaces"))?.workspaces??[]}async createWorkspace(e){let t=await this.request("POST","/v1/workspaces",e);if(!t)throw new m("POST","/v1/workspaces",404,"Not found");return t}async getWorkspace(e){return await this.request("GET",`/v1/workspaces/${encodeURIComponent(e)}`)}async updateWorkspace(e,t){return await this.request("PATCH",`/v1/workspaces/${encodeURIComponent(e)}`,t)}async deleteWorkspace(e){return(await this.request("DELETE",`/v1/workspaces/${encodeURIComponent(e)}`))?.deleted??!1}async listWorkspaceFiles(e){return(await this.request("GET",`/v1/workspaces/${encodeURIComponent(e)}/files`))?.files??[]}async getWorkspaceFileUrl(e,t){let n=`?path=${encodeURIComponent(t)}`;return(await this.request("GET",`/v1/workspaces/${encodeURIComponent(e)}/files${n}`))?.url??null}async uploadWorkspaceFile(e,t){let n=`/v1/workspaces/${encodeURIComponent(e)}/files`,s=await this.request("POST",n,t);if(!s)throw new m("POST",n,404,"Workspace not found");return s.file}async renameWorkspaceFile(e,t,n){return(await this.request("PATCH",`/v1/workspaces/${encodeURIComponent(e)}/files`,{path:t,newPath:n}))?.renamed??!1}async deleteWorkspaceFile(e,t){return(await this.request("DELETE",`/v1/workspaces/${encodeURIComponent(e)}/files`,{path:t}))?.deleted??!1}async listSandboxes(){return(await this.request("GET","/v1/sandboxes"))?.sandboxes??[]}async createSandbox(e){let t=await this.request("POST","/v1/sandboxes",e);if(!t)throw new m("POST","/v1/sandboxes",404,"Not found");return t}async getSandbox(e){return await this.request("GET",`/v1/sandboxes/${encodeURIComponent(e)}`)}async updateSandbox(e,t){return await this.request("PATCH",`/v1/sandboxes/${encodeURIComponent(e)}`,t)}async deleteSandbox(e){return(await this.request("DELETE",`/v1/sandboxes/${encodeURIComponent(e)}`))?.deleted??!1}async suspendSandbox(e,t){return await this.sandboxAction(e,"suspend",{reservationKey:t})}async resumeSandbox(e,t){return await this.sandboxAction(e,"resume",{reservationKey:t})}async terminateSandbox(e,t){return await this.sandboxAction(e,"terminate",{reservationKey:t})}async snapshotSandbox(e,t,n){return await this.sandboxAction(e,"snapshot",{reservationKey:t,name:n})}async openSandboxTerminal(e,t){return await this.sandboxAction(e,"terminal",{reservationKey:t})}async listMcp(e){let t=`/v1/mcp${i(e)}`,n=await this.request("GET",t);if(!n)throw new m("GET",t,404,"Not found");return n.servers??[]}async createMcp(e,t){let n=`/v1/mcp${i(e)}`,s=await this.request("POST",n,t);if(!s)throw new m("POST",n,404,"Not found");return s}async uploadMcpBundle(e){let n=await this.request("POST","/v1/mcp/uploads");if(!n?.uploadUrl)throw new m("POST","/v1/mcp/uploads",502,"response omitted uploadUrl");let s=await this.fetchImpl(n.uploadUrl,{method:"POST",headers:{"Content-Type":"application/javascript"},body:e});if(!s.ok)throw new m("POST","/v1/mcp/uploads",s.status,await s.text());let{storageId:r}=await s.json();if(!r)throw new m("POST","/v1/mcp/uploads",502,"upload response omitted storageId");let a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)),c=Array.from(new Uint8Array(a)).map((l)=>l.toString(16).padStart(2,"0")).join("");return{bundleStorageId:r,sha256:c}}async getMcp(e){return await this.request("GET",`/v1/mcp/${encodeURIComponent(e)}`)}async updateMcp(e,t){return await this.request("PATCH",`/v1/mcp/${encodeURIComponent(e)}`,t)}async deleteMcp(e){return(await this.request("DELETE",`/v1/mcp/${encodeURIComponent(e)}`))?.deleted??!1}async listPolicies(){return(await this.request("GET","/v1/policies"))?.policies??[]}async createPolicy(e){let t=await this.request("POST","/v1/policies",e);if(!t)throw new m("POST","/v1/policies",404,"Not found");return t}async getPolicy(e){return await this.request("GET",`/v1/policies/${encodeURIComponent(e)}`)}async updatePolicy(e,t){return await this.request("PATCH",`/v1/policies/${encodeURIComponent(e)}`,t)}async deletePolicy(e){return(await this.request("DELETE",`/v1/policies/${encodeURIComponent(e)}`))?.deleted??!1}async listRoles(){return(await this.request("GET","/v1/roles"))?.roles??[]}async createRole(e){let t=await this.request("POST","/v1/roles",e);if(!t)throw new m("POST","/v1/roles",404,"Not found");return t}async getRole(e){return await this.request("GET",`/v1/roles/${encodeURIComponent(e)}`)}async updateRole(e,t){return await this.request("PATCH",`/v1/roles/${encodeURIComponent(e)}`,t)}async deleteRole(e){return(await this.request("DELETE",`/v1/roles/${encodeURIComponent(e)}`))?.deleted??!1}async listChannels(){return(await this.request("GET","/v1/channels"))?.channels??[]}async createChannel(e){let t=await this.request("POST","/v1/channels",e);if(!t)throw new m("POST","/v1/channels",404,"Not found");return t}async getChannel(e){return await this.request("GET",`/v1/channels/${encodeURIComponent(e)}`)}async updateChannel(e,t){return await this.request("PATCH",`/v1/channels/${encodeURIComponent(e)}`,t)}async deleteChannel(e){return(await this.request("DELETE",`/v1/channels/${encodeURIComponent(e)}`))?.deleted??!1}async listSkills(){return(await this.request("GET","/v1/skills"))?.skills??[]}async createSkill(e){let t=await this.request("POST","/v1/skills",e);if(!t)throw new m("POST","/v1/skills",404,"Not found");return t}async getSkill(e){return await this.request("GET",`/v1/skills/${encodeURIComponent(e)}`)}async uploadSkill(e,t){let n=`/v1/skills/${encodeURIComponent(e)}`,s=await this.request("PUT",n,t);if(!s)throw new m("PUT",n,404,"Skill not found");return s}async deleteSkill(e){return(await this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`))?.deleted??!1}async sandboxAction(e,t,n){let s=`/v1/sandboxes/${encodeURIComponent(e)}/${t}`,r=await this.request("POST",s,n);if(!r)throw new m("POST",s,404,"Sandbox not found");return r}async request(e,t,n){let s=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:{Authorization:`Bearer ${this.bearerToken}`,...n!==void 0?{"Content-Type":"application/json"}:{}},...n!==void 0?{body:JSON.stringify(n)}:{}});if(s.status===404)return null;if(!s.ok)throw new m(e,t,s.status,await s.text());return await s.json()}}function o(e){return typeof process<"u"?process?.env?.[e]:void 0}function i(e){return`?${new URLSearchParams({project:e.project,stage:e.stage}).toString()}`}
2
- export{m,Ce,L,U};