broods 0.28.0 → 0.30.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/account.d.ts +36 -14
- package/dist/account.js +1 -1
- package/dist/chunk-2tqw3gxy.js +1 -0
- package/dist/{chunk-2149yqc1.js → chunk-3qpgf0c1.js} +2 -2
- package/dist/chunk-736tg90p.js +1 -0
- package/dist/chunk-e66afphr.js +66 -0
- package/dist/chunk-rx5qcgbh.js +2 -0
- package/dist/chunk-yy11cxjg.js +2 -0
- package/dist/chunk-zk2w6bee.js +15 -0
- package/dist/cli/index.js +123 -140
- package/dist/index.d.ts +56 -27
- package/dist/index.js +1 -1
- package/package.json +5 -2
- package/dist/chunk-3cvxks4m.js +0 -2
- package/dist/chunk-mnc0tart.js +0 -2
package/dist/account.d.ts
CHANGED
|
@@ -122,7 +122,7 @@ interface AgentConfig {
|
|
|
122
122
|
channels?: AgentChannelsConfig;
|
|
123
123
|
tools?: AgentToolsConfig;
|
|
124
124
|
/** Connected MCP servers, keyed by their config-plane row id (#331). */
|
|
125
|
-
|
|
125
|
+
mcp?: AgentMcpConfig;
|
|
126
126
|
/**
|
|
127
127
|
* Tool names withheld for this run, applied after the tool set is built.
|
|
128
128
|
* Set by a channel record; a channel can take a tool away, never add one.
|
|
@@ -287,8 +287,8 @@ interface AgentToolConfig {
|
|
|
287
287
|
config?: Record<string, unknown>;
|
|
288
288
|
[key: string]: unknown;
|
|
289
289
|
}
|
|
290
|
-
type
|
|
291
|
-
interface
|
|
290
|
+
type AgentMcpConfig = Record<string, AgentMcpEntry>;
|
|
291
|
+
interface AgentMcpEntry {
|
|
292
292
|
enabled?: boolean;
|
|
293
293
|
/** Applies to every tool the server exposes. */
|
|
294
294
|
needsApproval?: boolean;
|
|
@@ -845,7 +845,7 @@ interface StageScope {
|
|
|
845
845
|
stage: string;
|
|
846
846
|
}
|
|
847
847
|
/** Public MCP server registration returned by the `/v1/mcp` routes (#331). */
|
|
848
|
-
interface
|
|
848
|
+
interface AccountMcp {
|
|
849
849
|
accountId: string;
|
|
850
850
|
serverId: string;
|
|
851
851
|
projectId: string;
|
|
@@ -865,21 +865,28 @@ interface AccountMcpServer {
|
|
|
865
865
|
updatedAt: string;
|
|
866
866
|
deletedAt?: string;
|
|
867
867
|
}
|
|
868
|
-
/**
|
|
869
|
-
|
|
868
|
+
/**
|
|
869
|
+
* Fields accepted by `POST /v1/mcp`: `url` connects, `bundle` uploads inline
|
|
870
|
+
* (≤10 MB); a larger bundle goes through `uploadMcpBundle` first.
|
|
871
|
+
*/
|
|
872
|
+
interface CreateMcpInput {
|
|
870
873
|
name: string;
|
|
871
874
|
description?: string;
|
|
872
875
|
url?: string;
|
|
873
876
|
bundle?: string;
|
|
877
|
+
bundleStorageId?: string;
|
|
878
|
+
sha256?: string;
|
|
874
879
|
headers?: Record<string, string>;
|
|
875
880
|
allowedTools?: string[];
|
|
876
881
|
}
|
|
877
882
|
/** Fields accepted by `PATCH /v1/mcp/{serverId}`; every field is optional. */
|
|
878
|
-
interface
|
|
883
|
+
interface UpdateMcpInput {
|
|
879
884
|
name?: string;
|
|
880
885
|
description?: string;
|
|
881
886
|
url?: string;
|
|
882
887
|
bundle?: string;
|
|
888
|
+
bundleStorageId?: string;
|
|
889
|
+
sha256?: string;
|
|
883
890
|
headers?: Record<string, string>;
|
|
884
891
|
allowedTools?: string[];
|
|
885
892
|
disabled?: boolean;
|
|
@@ -933,6 +940,13 @@ declare class BroodsAccountApiError extends Error {
|
|
|
933
940
|
readonly body: string;
|
|
934
941
|
constructor(method: string, path: string, status: number, body: string);
|
|
935
942
|
}
|
|
943
|
+
/**
|
|
944
|
+
* The credential the environment supplies, with a role session winning over
|
|
945
|
+
* the account secret. The constructor throws through this same resolution, so
|
|
946
|
+
* callers that can run without an account credential (`broods mcp` with only a
|
|
947
|
+
* stored login) probe here instead of catching the constructor.
|
|
948
|
+
*/
|
|
949
|
+
declare function resolveEnvCredential(): string | undefined;
|
|
936
950
|
/**
|
|
937
951
|
* Typed client for the broods account config API. All `get`/`update`/`delete`
|
|
938
952
|
* methods return `null`/`false` when the resource does not exist (HTTP 404) so
|
|
@@ -1049,11 +1063,19 @@ declare class BroodsAccountClient {
|
|
|
1049
1063
|
/** Mint a short-lived sealed ticket for an interactive PTY session on a persistent sandbox (`sandbox`/`lambda` providers). Throws on 404/403/409. */
|
|
1050
1064
|
openSandboxTerminal(sandboxId: string, reservationKey: string): Promise<SandboxTerminalTicket>;
|
|
1051
1065
|
/** MCP servers live in one stage, so the collection routes need a scope. */
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1066
|
+
listMcp(scope: StageScope): Promise<AccountMcp[]>;
|
|
1067
|
+
createMcp(scope: StageScope, input: CreateMcpInput): Promise<AccountMcp>;
|
|
1068
|
+
/**
|
|
1069
|
+
* Upload a hosted MCP bundle too large for the JSON body; returns the
|
|
1070
|
+
* `bundleStorageId` + `sha256` pair `createMcp`/`updateMcp` accept.
|
|
1071
|
+
*/
|
|
1072
|
+
uploadMcpBundle(bundle: string): Promise<{
|
|
1073
|
+
bundleStorageId: string;
|
|
1074
|
+
sha256: string;
|
|
1075
|
+
}>;
|
|
1076
|
+
getMcp(serverId: string): Promise<AccountMcp | null>;
|
|
1077
|
+
updateMcp(serverId: string, patch: UpdateMcpInput): Promise<AccountMcp | null>;
|
|
1078
|
+
deleteMcp(serverId: string): Promise<boolean>;
|
|
1057
1079
|
listPolicies(): Promise<AccountPolicy[]>;
|
|
1058
1080
|
createPolicy(input: {
|
|
1059
1081
|
name: string;
|
|
@@ -1119,5 +1141,5 @@ declare class BroodsAccountClient {
|
|
|
1119
1141
|
private request;
|
|
1120
1142
|
}
|
|
1121
1143
|
|
|
1122
|
-
export { BroodsAccountApiError, BroodsAccountClient, envPlaceholder };
|
|
1123
|
-
export type { AccountAgent, AccountChannel, AccountEnvVar,
|
|
1144
|
+
export { BroodsAccountApiError, BroodsAccountClient, envPlaceholder, resolveEnvCredential };
|
|
1145
|
+
export type { AccountAgent, AccountChannel, AccountEnvVar, AccountMcp, AccountPolicy, AccountRole, AccountSandbox, AccountWorkspace, AssumeRoleResult, BroodsAccount, BroodsAccountClientOptions, ChannelRecordConfig, CreateAgentResult, CreateMcpInput, DeleteAccountResult, RotateSecretResult, SandboxLifecycleResult, SandboxSnapshotResult, SandboxTerminalTicket, SkillUploadInput, StageScope, UpdateAgentInput, UpdateMcpInput, WorkspaceFileEntry };
|
package/dist/account.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
1
|
+
import{R as a,S as b,T as c,U as d}from"./chunk-yy11cxjg.js";import"./chunk-rx5qcgbh.js";export{b as BroodsAccountApiError,d as BroodsAccountClient,a as envPlaceholder,c as resolveEnvCredential};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{T as R,U as E}from"./chunk-yy11cxjg.js";import{V as o,pa as g}from"./chunk-zk2w6bee.js";import"./chunk-e66afphr.js";import"./chunk-rx5qcgbh.js";var y={project:o.string().optional(),stage:o.string().optional()},I={sandboxId:o.string().min(1),reservationKey:o.string().min(1)},h=o.boolean().describe("Must be true, after the owner has agreed to this delete."),S="'********' keeps a stored secret and null deletes a field: never send a placeholder you did not read from a get.",C=[{singular:"agent",plural:"agents",key:"agentId",createHint:"Needs name and config; a 409 returns the existing agentId.",deleteHint:"Deleting an agent also drops its runtime rows.",updateHint:S,list:(e)=>e.listAgents(),get:(e,t)=>e.getAgent(t),create:(e,t)=>e.createAgent(t),update:(e,t,s)=>e.updateAgent(t,s),remove:(e,t)=>e.deleteAgent(t)},{singular:"cron",plural:"crons",key:"cronId",createHint:"Needs name, agentId, scheduleExpression (rate/cron/at) and input or events.",list:(e)=>e.listCrons(),get:(e,t)=>e.getCron(t),create:(e,t)=>e.createCron(t),update:(e,t,s)=>e.updateCron(t,s),remove:(e,t)=>e.deleteCron(t)},{singular:"sandbox",plural:"sandboxes",key:"sandboxId",updateHint:S,list:(e)=>e.listSandboxes(),get:(e,t)=>e.getSandbox(t),create:(e,t)=>e.createSandbox(t),update:(e,t,s)=>e.updateSandbox(t,s),remove:(e,t)=>e.deleteSandbox(t)},{singular:"workspace",plural:"workspaces",key:"workspaceId",list:(e)=>e.listWorkspaces(),get:(e,t)=>e.getWorkspace(t),create:(e,t)=>e.createWorkspace(t),update:(e,t,s)=>e.updateWorkspace(t,s),remove:(e,t)=>e.deleteWorkspace(t)},{singular:"policy",plural:"policies",key:"policyId",createHint:"Agent-runtime policy document (tool.call, skill.load), not API credential scoping.",list:(e)=>e.listPolicies(),get:(e,t)=>e.getPolicy(t),create:(e,t)=>e.createPolicy(t),update:(e,t,s)=>e.updatePolicy(t,s),remove:(e,t)=>e.deletePolicy(t)},{singular:"role",plural:"roles",key:"roleId",createHint:"Needs name and a version-1 policy over the API namespace, e.g. agents:read. Account secret only.",list:(e)=>e.listRoles(),get:(e,t)=>e.getRole(t),create:(e,t)=>e.createRole(t),update:(e,t,s)=>e.updateRole(t,s),remove:(e,t)=>e.deleteRole(t)},{singular:"channel",plural:"channels",key:"channelId",list:(e)=>e.listChannels(),get:(e,t)=>e.getChannel(t),create:(e,t)=>e.createChannel(t),update:(e,t,s)=>e.updateChannel(t,s),remove:(e,t)=>e.deleteChannel(t)},{singular:"skill",plural:"skills",key:"skillName",createHint:'source is "files" (base64), "json" or "github". The stored name comes from the SKILL.md frontmatter.',list:(e)=>e.listSkills(),get:(e,t)=>e.getSkill(t),create:(e,t)=>e.createSkill(t),remove:(e,t)=>e.deleteSkill(t)},{singular:"mcp",plural:"mcp",key:"serverId",scoped:!0,list:(e,t)=>e.listMcp(t),get:(e,t)=>e.getMcp(t),create:(e,t,s)=>e.createMcp(s,t),update:(e,t,s)=>e.updateMcp(t,s),remove:(e,t)=>e.deleteMcp(t)}];function Mt(e={}){let t=R()?new E({}):null;if(!t&&!e.cli)throw Error("broods mcp needs a credential: set BROODS_SESSION_TOKEN or BROODS_ACCOUNT_SECRET, or run `broods login`.");let s=new g({name:"broods",version:"1"},{capabilities:{tools:{}}});if(t){for(let r of C)k(s,t,r,e.scope??{});P(s,t)}if(e.cli)O(s,e.cli);if(e.allowDestructive)q(s,t,e.cli??null);return s}function M(e){return{content:[{type:"text",text:JSON.stringify(e??null,null,2)}]}}function A(e){return{content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}function f(e,t){if(!e)throw Error(`Refusing without confirm:true. ${t}`)}async function a(e){try{return M(await e())}catch(t){return A(t)}}function _(e,t,s,r){if(!e.scoped)return;let n=s??t.project,c=r??t.stage;if(!n||!c)throw Error(`${e.plural} live in one stage, so this call needs both 'project' and 'stage'`);return{project:n,stage:c}}function k(e,t,s,r){let n=o.string().min(1).describe(`The ${s.key}.`),c=s.scoped?` ${s.plural} live in one stage, so this also takes 'project' and 'stage'.`:"",{list:d,get:p,create:m,update:v,remove:w}=s;if(d){let i=`List every ${s.singular} on the account.${c}`;if(s.scoped)e.registerTool(`list-${s.plural}`,{description:i,inputSchema:y},async({project:l,stage:u})=>await a(async()=>await d(t,_(s,r,l,u))));else e.registerTool(`list-${s.plural}`,{description:i,inputSchema:{}},async()=>await a(async()=>await d(t)))}if(p)e.registerTool(`get-${s.singular}`,{description:`Read one ${s.singular} by ${s.key}.`,inputSchema:{id:n}},async({id:i})=>await a(async()=>await p(t,i)));if(m){let i=`Create one ${s.singular}. 'body' is the request body the config plane documents.`+(s.createHint?` ${s.createHint}`:"")+c+" Prefer changing the broods/ manifest and deploying for anything the project already declares.",l=o.record(o.string(),o.unknown());if(s.scoped)e.registerTool(`create-${s.singular}`,{description:i,inputSchema:{body:l,...y}},async({body:u,project:b,stage:T})=>await a(async()=>await m(t,u,_(s,r,b,T))));else e.registerTool(`create-${s.singular}`,{description:i,inputSchema:{body:l}},async({body:u})=>await a(async()=>await m(t,u)))}if(v)e.registerTool(`update-${s.singular}`,{description:`Deep-merge a patch into one ${s.singular} and return the updated record, so there is no need to read it back.`+(s.updateHint?` ${s.updateHint}`:""),inputSchema:{id:n,body:o.record(o.string(),o.unknown())}},async({id:i,body:l})=>await a(async()=>await v(t,i,l)));if(w)e.registerTool(`delete-${s.singular}`,{description:`Delete one ${s.singular}. Requires confirm:true, and takes one ${s.key} per call: never loop this over a list.`+(s.deleteHint?` ${s.deleteHint}`:""),inputSchema:{id:n,confirm:h}},async({id:i,confirm:l})=>await a(async()=>(f(l,`Deleting ${s.singular} '${i}' goes away for good: name it, get the owner's agreement, then retry.`),{deleted:await w(t,i),id:i})))}function P(e,t){e.registerTool("list-cron-runs",{description:"Run history for one cron, newest first. Check this before telling anyone a cron fired.",inputSchema:{cronId:o.string().min(1),limit:o.number().int().positive().max(100).optional()}},async({cronId:r,limit:n})=>await a(async()=>await t.listCronRuns(r,n===void 0?{}:{limit:n})));let s=[["suspend-sandbox","Suspend a persistent sandbox reservation.",(r,n)=>t.suspendSandbox(r,n)],["resume-sandbox","Resume a suspended sandbox reservation.",(r,n)=>t.resumeSandbox(r,n)],["terminate-sandbox","Terminate a sandbox reservation and drop its live-instance row. Terminate only a sandbox you created, and never one holding state you did not put there.",(r,n)=>t.terminateSandbox(r,n)],["open-sandbox-terminal","Mint a short-lived sealed ticket for an interactive PTY session on a persistent sandbox.",(r,n)=>t.openSandboxTerminal(r,n)]];for(let[r,n,c]of s)e.registerTool(r,{description:n,inputSchema:I},async({sandboxId:d,reservationKey:p})=>await a(async()=>await c(d,p)));e.registerTool("snapshot-sandbox",{description:"Snapshot a sandbox reservation into a reusable image (self-hosted provider).",inputSchema:{sandboxId:o.string().min(1),reservationKey:o.string().min(1),name:o.string().min(1)}},async({sandboxId:r,reservationKey:n,name:c})=>await a(async()=>await t.snapshotSandbox(r,n,c))),e.registerTool("upload-skill",{description:"Replace one skill's bundle wholesale (PUT, not a merge) by skillName. 'body' is the same source shape create-skill takes.",inputSchema:{id:o.string().min(1).describe("The skillName."),body:o.record(o.string(),o.unknown())}},async({id:r,body:n})=>await a(async()=>await t.uploadSkill(r,n))),e.registerTool("list-env-vars",{description:"List environment variable names. Values are write-only: the plane never returns them, so there is no read.",inputSchema:{}},async()=>await a(async()=>await t.listEnvVars())),e.registerTool("set-env-var",{description:"Create or replace one write-only environment variable. Reference it from a config as ${NAME} rather than inlining the value.",inputSchema:{name:o.string().min(1),value:o.string()}},async({name:r,value:n})=>await a(async()=>(await t.setEnvVar(r,n),{name:r,stored:!0}))),e.registerTool("delete-env-var",{description:"Delete one environment variable.",inputSchema:{name:o.string().min(1),confirm:h}},async({name:r,confirm:n})=>await a(async()=>(f(n,`Anything referencing \${${r}} breaks the moment this env var goes.`),{deleted:await t.deleteEnvVar(r),name:r}))),e.registerTool("assume-role",{description:"Exchange a role for a short-lived session token (default 1h, max 12h). Hand the returned token to whatever tool needs narrow access, as BROODS_SESSION_TOKEN. It is shown once and is not stored here.",inputSchema:{roleId:o.string().min(1),ttlSeconds:o.number().int().positive().max(43200).optional()}},async({roleId:r,ttlSeconds:n})=>await a(async()=>await t.assumeRole(r,n===void 0?{}:{ttlSeconds:n}))),e.registerTool("update-account",{description:"Rename this account or change its description. Everything else about an account is derived, not settable.",inputSchema:{username:o.string().optional(),description:o.string().nullable().optional()}},async({username:r,description:n})=>await a(async()=>await t.updateAccount({...r===void 0?{}:{username:r},...n===void 0?{}:{description:n}}))),e.registerTool("get-account",{description:"The account this server's credential resolves to. Run it first to confirm which tenant you are about to change.",inputSchema:{}},async()=>await a(async()=>await t.getAccount()))}function O(e,t){e.registerTool("list-orgs",{description:"Every organization this login can reach, with the current one marked.",inputSchema:{}},async()=>await a(async()=>{let s=await t.getOnboarding();return{currentOrgId:s.currentOrgId,orgs:s.orgs}})),e.registerTool("create-org",{description:"Create an organization and switch this login to it. Later calls act in the new org.",inputSchema:{name:o.string().min(1)}},async({name:s})=>await a(async()=>await t.createOnboardingOrg(s))),e.registerTool("select-org",{description:"Switch this login to another organization, by an orgId from list-orgs.",inputSchema:{orgId:o.string().min(1)}},async({orgId:s})=>await a(async()=>await t.selectOnboardingOrg(s))),e.registerTool("list-projects",{description:"Every project in the current org, empty ones last. Project names are not unique, so take the id from here.",inputSchema:{}},async()=>await a(async()=>await t.listProjects())),e.registerTool("list-stages",{description:"Every stage of one project, by project name.",inputSchema:{project:o.string().min(1)}},async({project:s})=>await a(async()=>await t.listStages(s))),e.registerTool("create-stage",{description:"Create a stage in a project, optionally cloning another stage's architecture and env vars. A project name that does not exist yet is created with it, which is the only way to make a project without deploying a manifest.",inputSchema:{project:o.string().min(1),name:o.string().min(1),from:o.string().optional().describe("Stage to clone architecture and env vars from.")}},async({project:s,name:r,from:n})=>await a(async()=>await t.createStage(s,r,n)))}function q(e,t,s){if(t)e.registerTool("rotate-secret",{description:"Rotate the account secret. The current secret stops working immediately and the new one is shown once, so this breaks every deployment and CI job still holding the old one. Requires confirm:true.",inputSchema:{confirm:h}},async({confirm:r})=>await a(async()=>(f(r,"Everything holding the current secret breaks the moment this runs."),await t.rotateSecret())));if(s)e.registerTool("delete-project",{description:"Delete a project and everything under it: stages, agents, canvas, env vars, crons and workspace files. Takes a projectId from list-projects and requires confirm:true.",inputSchema:{projectId:o.string().min(1),confirm:h}},async({projectId:r,confirm:n})=>await a(async()=>(f(n,`Project '${r}' and everything under it goes away: name it, get the owner's agreement, then retry.`),await s.deleteProject(r))))}export{Mt as createBroodsMcpServer};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
function k(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*D(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
2
|
`);o=i.pop()??"";for(let a of i)if(a.startsWith("data: "))yield a.slice(6)}}finally{n.releaseLock()}}import{mkdir as Q,readFile as ee,writeFile as ne}from"node:fs/promises";import{homedir as te}from"node:os";import{dirname as oe,join as re}from"node:path";var Ee="broods",De="_generated",h=re(te(),".broods","config.json"),N="broods.app",O="dashboard",se="gateway";async function Ne(){let e=process.env.BROODS_TOKEN,n=process.env.BROODS_BASE_URL;if(e&&n)return{baseUrl:d(n),token:e,createdAt:new Date().toISOString()};try{let t=JSON.parse(await ee(h,"utf8"));if(typeof t.baseUrl!=="string"||!t.baseUrl)return null;return t}catch{return null}}async function Oe(e){await Q(oe(h),{recursive:!0}),await ne(h,`${JSON.stringify(e,null,2)}
|
|
3
3
|
`,"utf8")}function T(){return process.env.BROODS_STAGE}function d(e){let n=e.length;while(n>0&&e.charCodeAt(n-1)===47)n-=1;return e.slice(0,n)}function Te(e){try{let n=new URL(e);if(!n.hostname.startsWith(`${O}.`))return;let t=n.hostname.slice(O.length+1);if(t!==N&&!t.endsWith(`.${N}`))return;return n.hostname=`${se}.${t}`,d(n.origin)}catch{return}}import{existsSync as U,readFileSync as E,statSync as ie}from"node:fs";import{join as W,resolve as M}from"node:path";var v=new Map,ae=new Set(Object.keys(process.env)),P=new Set;function I(e=process.cwd()){ce(e);let n=de();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:T()}}function $e(e,n=process.cwd()){let t=process.env[e];if(t===void 0)return!1;let o=M(n);for(let r of[".env.local",".env"]){let s=W(o,r);if(!U(s))continue;let i=_(E(s,"utf8"));if(i[e]!==void 0)return i[e]!==t}return!0}function ce(e){let n=M(e),t=process.env.BROODS_RELOAD_ENV==="1";for(let o of[".env",".env.local"]){let r=W(n,o);if(!U(r)){v.delete(r);continue}let s=ie(r).mtimeMs,i=v.get(r);if(i&&i.mtimeMs===s)continue;v.set(r,{mtimeMs:s});for(let[a,u]of Object.entries(_(E(r,"utf8"))))if(t||!ae.has(a)||P.has(a))process.env[a]=u,P.add(a)}}function _(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]=ue(r.slice(s+1).trim())}return n}function ue(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 de(){try{let e=JSON.parse(E(h,"utf8"));if(typeof e.baseUrl!=="string"||typeof e.token!=="string")return null;return{baseUrl:d(e.baseUrl),...typeof e.dashboardUrl==="string"?{dashboardUrl:d(e.dashboardUrl)}:{},token:e.token}}catch{return null}}var x="https://gateway.broods.app";class B extends Error{accepted;constructor(e){super(`Ingress ${e.eventId} was accepted asynchronously with status ${e.status??"queued"}`);this.accepted=e;this.name="IngressAcceptedError"}}class ge{baseUrl;apiKey;fetchImpl;constructor(e={}){I(),this.baseUrl=A(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||x),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=K(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 B(H(await s.json(),o));if(!s.body)throw Error("Run response has no body");for await(let i of D(s.body)){let a;try{a=JSON.parse(i)}catch{continue}if(a.type==="error")throw Error(`Agent run failed: ${he(a.error)}`);yield a}}async runAsync(e,n){let t=n?{...n,agentId:e.id,agentName:e.name}:e,o=K(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 fe(s,"202 JSON")}`);let i=H(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==="completed"||r.status==="failed"||r.status==="expired"||r.status==="not_found")return r;await ye(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(me(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 ${x} 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 pe(this.baseUrl,e,n.agentId)}}function A(e){let n=e.trim(),t=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(n)?n:`https://${n}`;return d(t)}function K(e,n){let t=e.eventId??`${n}-${Date.now()}`;return{agentId:e.agentId,eventId:t,conversationKey:e.conversationKey??t,events:k(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 H(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=le(t);if(!o.statusId)throw Error("Async response statusUrl missing status id");let r=typeof e.eventId==="string"?e.eventId:o.statusId,s=e.status,i=e.requestedMode;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 le(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 pe(e,n,t){return`${A(e)}/status/${encodeURIComponent(n)}?agentId=${encodeURIComponent(t)}`}async function fe(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]`}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 me(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}}function ye(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 he(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}`}var Ce=2000,j=0,C=1;class Se{baseUrl;apiKey;WebSocketImpl;connectTimeoutMs;constructor(e={}){if(I(),this.baseUrl=F(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||x),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??Ce}subscribe(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=Re(e),s=L(this.baseUrl),i=new t(o),a=!1,u=!1,g=setTimeout(()=>{if(!a)y(s)},this.connectTimeoutMs),w=(c=1000,R="client closed")=>{if(u)return;if(u=!0,clearTimeout(g),e.signal?.removeEventListener("abort",S),i.readyState===C||i.readyState===j)i.close(c,R)},y=(c)=>{n.onError?.(c),w(1011,"websocket error")},X=()=>{n.onDone?.(),w(1000,"done")},S=()=>{if(i.readyState===C)i.send(JSON.stringify({type:"cancel"}));y(Error("WebSocket run aborted."))};return e.signal?.addEventListener("abort",S,{once:!0}),i.onopen=()=>{if(a=!0,clearTimeout(g),e.signal?.aborted){S();return}i.send(JSON.stringify({type:"execute",agentId:r,events:k(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 R=q(c.data);if(!R)return;let b=G(R,n);switch(n.onMessage?.(b),b.type){case"meta":n.onMeta?.(b);break;case"done":X();break;case"error":y(Error(J(b.error)));break}},i.onerror=()=>{y(s)},i.onclose=(c)=>{if(clearTimeout(g),e.signal?.removeEventListener("abort",S),u||c.code===1000)return;y(Error(c.reason||"WebSocket connection closed."))},{url:o,sendControl:function(c){if(i.readyState!==C)throw Error("WebSocket is not open");i.send(JSON.stringify({type:"control",...c}))},close:w}}attach(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=new t(o),s=!1,i=(a=1000,u="client closed")=>{if(s)return;if(s=!0,r.readyState===C||r.readyState===j)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=q(a.data);if(!u)return;let g=G(u,n);if(n.onMessage?.(g),g.type==="done")n.onDone?.();if(g.type==="error")n.onError?.(Error(J(g.error)))},r.onerror=()=>n.onError?.(L(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!==C)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=be(e),t=e.projectSlug??e.agent?.projectSlug,o=e.stageSlug??e.agent?.stageSlug,r=t?`/${t}`:"",s=o?`/${o}`:"";return`${ke(this.baseUrl)}/v1${r}/agents${s}/${encodeURIComponent(n)}/ws?token=${encodeURIComponent(this.apiKey)}`}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 Re(e){let n=e.agentId??e.agent?.id??e.endpointId;if(!n)throw Error("WebSocket run requires agent, agentId, or endpointId.");return n}function be(e){let n=e.endpointId??e.agent?.endpointId??e.agent?.id;if(!n)throw Error("WebSocket run requires agent or endpointId.");return n}function ke(e){let n=new URL(F(e));if(n.protocol==="https:")n.protocol="wss:";if(n.protocol==="http:")n.protocol="ws:";return d(n.toString())}function F(e){let n=e.trim();if(/^wss?:\/\//.test(n))return d(n);return A(n)}function L(e){return Error(`Cannot access the WebSocket service at ${e}.`)}function G(e,n){if(e.type!=="output")return e;let t=e;return n.onOutput?.(t),t.data}function q(e){try{let n=JSON.parse(e);return typeof n==="object"&&n!==null&&typeof n.type==="string"?n:null}catch{return null}}function J(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)}var z=Symbol.for("broods.resource"),V=Symbol.for("broods.config"),Y=Symbol.for("broods.connection"),Z=/^[A-Z][A-Z0-9_]{0,63}$/,ze=new Proxy((e)=>{if(!Z.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"&&Z.test(n))throw Error(`env.${n} is not supported; use env("${n}")`);return Reflect.get(e,n,t)}});function l(e,n,t,o){return{[z]:!0,kind:e,name:n,...t?{description:t}:{},config:o}}function f(e,n){let{partition:t,...o}=n;return{[Y]:!0,kind:"connection",type:e,...t?{partition:t}:{},config:o}}function m(e,n,t,o,r){return l("channelRecord",e,n,{...r,externalId:t,...o?{workspaceRef:o}:{}})}function Ve(e){return f("discord",e)}function Ye(e){return f("github",e)}function Xe(e){return f("pancake",e)}function Qe(e){return f("slack",e)}function en(e){return f("telegram",e)}function nn(e){return f("zalo",e)}function tn(e){let{name:n,description:t,channelId:o,guildId:r,...s}=e;return m(n,t,o,r,s)}function on(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 rn(e){let{name:n,description:t,conversationId:o,...r}=e;return m(n,t,o,void 0,r)}function sn(e){let{name:n,description:t,channelId:o,teamId:r,...s}=e;return m(n,t,o,r,s)}function an(e){let{name:n,description:t,chatId:o,...r}=e;return m(n,t,o,void 0,r)}function cn(e){let{name:n,description:t,chatId:o,...r}=e;return m(n,t,o,void 0,r)}function un(e){return{[V]:!0,config:e}}function dn(e){let{name:n,description:t,...o}=e;return l("agent",n,t,o)}function gn(e){return e}function ln(e){let{name:n,description:t,...o}=e;return l("workspace",n,t,o)}function pn(e){let{name:n,description:t,...o}=e;return l("sandbox",n,t,o)}function fn(e){let{name:n,description:t,...o}=e;return l("skill",n,t,o)}function mn(e){let{name:n,description:t,...o}=e;return l("mcp",n,t,o)}function yn(e){let{name:n,description:t,...o}=e;return l("policy",n,t,o)}function hn(e){let{name:n,description:t,...o}=e;return l("cron",n,t,o)}function Cn(e){return Boolean(e&&typeof e==="object"&&e[z])}function Sn(e){return Boolean(e&&typeof e==="object"&&e[Y])}function Rn(e){return Boolean(e&&typeof e==="object"&&e[V])}
|
|
5
|
-
export{k as
|
|
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 de(){try{let e=JSON.parse(E(h,"utf8"));if(typeof e.baseUrl!=="string"||typeof e.token!=="string")return null;return{baseUrl:d(e.baseUrl),...typeof e.dashboardUrl==="string"?{dashboardUrl:d(e.dashboardUrl)}:{},token:e.token}}catch{return null}}var x="https://gateway.broods.app";class B extends Error{accepted;constructor(e){super(`Ingress ${e.eventId} was accepted asynchronously with status ${e.status??"queued"}`);this.accepted=e;this.name="IngressAcceptedError"}}class le{baseUrl;apiKey;fetchImpl;constructor(e={}){I(),this.baseUrl=A(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||x),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=K(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 B(H(await s.json(),o));if(!s.body)throw Error("Run response has no body");for await(let i of D(s.body)){let a;try{a=JSON.parse(i)}catch{continue}if(a.type==="error")throw Error(`Agent run failed: ${he(a.error)}`);yield a}}async runAsync(e,n){let t=n?{...n,agentId:e.id,agentName:e.name}:e,o=K(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 fe(s,"202 JSON")}`);let i=H(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==="completed"||r.status==="failed"||r.status==="expired"||r.status==="not_found")return r;await ye(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(me(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 ${x} 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 pe(this.baseUrl,e,n.agentId)}}function A(e){let n=e.trim(),t=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(n)?n:`https://${n}`;return d(t)}function K(e,n){let t=e.eventId??`${n}-${Date.now()}`;return{agentId:e.agentId,eventId:t,conversationKey:e.conversationKey??t,events:k(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 H(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=ge(t);if(!o.statusId)throw Error("Async response statusUrl missing status id");let r=typeof e.eventId==="string"?e.eventId:o.statusId,s=e.status,i=e.requestedMode;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 ge(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 pe(e,n,t){return`${A(e)}/status/${encodeURIComponent(n)}?agentId=${encodeURIComponent(t)}`}async function fe(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]`}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 me(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}}function ye(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 he(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}`}var Ce=2000,j=0,C=1;class Se{baseUrl;apiKey;WebSocketImpl;connectTimeoutMs;constructor(e={}){if(I(),this.baseUrl=F(e.baseUrl||e.host||process.env.BROODS_BASE_URL||process.env.BROODS_HOST||x),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??Ce}subscribe(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=Re(e),s=L(this.baseUrl),i=new t(o),a=!1,u=!1,l=setTimeout(()=>{if(!a)y(s)},this.connectTimeoutMs),w=(c=1000,R="client closed")=>{if(u)return;if(u=!0,clearTimeout(l),e.signal?.removeEventListener("abort",S),i.readyState===C||i.readyState===j)i.close(c,R)},y=(c)=>{n.onError?.(c),w(1011,"websocket error")},X=()=>{n.onDone?.(),w(1000,"done")},S=()=>{if(i.readyState===C)i.send(JSON.stringify({type:"cancel"}));y(Error("WebSocket run aborted."))};return e.signal?.addEventListener("abort",S,{once:!0}),i.onopen=()=>{if(a=!0,clearTimeout(l),e.signal?.aborted){S();return}i.send(JSON.stringify({type:"execute",agentId:r,events:k(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 R=q(c.data);if(!R)return;let b=G(R,n);switch(n.onMessage?.(b),b.type){case"meta":n.onMeta?.(b);break;case"done":X();break;case"error":y(Error(J(b.error)));break}},i.onerror=()=>{y(s)},i.onclose=(c)=>{if(clearTimeout(l),e.signal?.removeEventListener("abort",S),u||c.code===1000)return;y(Error(c.reason||"WebSocket connection closed."))},{url:o,sendControl:function(c){if(i.readyState!==C)throw Error("WebSocket is not open");i.send(JSON.stringify({type:"control",...c}))},close:w}}attach(e,n={}){let t=this.resolveWebSocket(),o=this.buildUrl(e),r=new t(o),s=!1,i=(a=1000,u="client closed")=>{if(s)return;if(s=!0,r.readyState===C||r.readyState===j)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=q(a.data);if(!u)return;let l=G(u,n);if(n.onMessage?.(l),l.type==="done")n.onDone?.();if(l.type==="error")n.onError?.(Error(J(l.error)))},r.onerror=()=>n.onError?.(L(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!==C)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=be(e),t=e.projectSlug??e.agent?.projectSlug,o=e.stageSlug??e.agent?.stageSlug,r=t?`/${t}`:"",s=o?`/${o}`:"";return`${ke(this.baseUrl)}/v1${r}/agents${s}/${encodeURIComponent(n)}/ws?token=${encodeURIComponent(this.apiKey)}`}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 Re(e){let n=e.agentId??e.agent?.id??e.endpointId;if(!n)throw Error("WebSocket run requires agent, agentId, or endpointId.");return n}function be(e){let n=e.endpointId??e.agent?.endpointId??e.agent?.id;if(!n)throw Error("WebSocket run requires agent or endpointId.");return n}function ke(e){let n=new URL(F(e));if(n.protocol==="https:")n.protocol="wss:";if(n.protocol==="http:")n.protocol="ws:";return d(n.toString())}function F(e){let n=e.trim();if(/^wss?:\/\//.test(n))return d(n);return A(n)}function L(e){return Error(`Cannot access the WebSocket service at ${e}.`)}function G(e,n){if(e.type!=="output")return e;let t=e;return n.onOutput?.(t),t.data}function q(e){try{let n=JSON.parse(e);return typeof n==="object"&&n!==null&&typeof n.type==="string"?n:null}catch{return null}}function J(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)}var z=Symbol.for("broods.resource"),V=Symbol.for("broods.config"),Y=Symbol.for("broods.connection"),Z=/^[A-Z][A-Z0-9_]{0,63}$/,ze=new Proxy((e)=>{if(!Z.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"&&Z.test(n))throw Error(`env.${n} is not supported; use env("${n}")`);return Reflect.get(e,n,t)}});function g(e,n,t,o){return{[z]:!0,kind:e,name:n,...t?{description:t}:{},config:o}}function f(e,n){let{partition:t,...o}=n;return{[Y]:!0,kind:"connection",type:e,...t?{partition:t}:{},config:o}}function m(e,n,t,o,r){return g("channelRecord",e,n,{...r,externalId:t,...o?{workspaceRef:o}:{}})}function Ve(e){return f("discord",e)}function Ye(e){return f("github",e)}function Xe(e){return f("pancake",e)}function Qe(e){return f("slack",e)}function en(e){return f("telegram",e)}function nn(e){return f("zalo",e)}function tn(e){let{name:n,description:t,channelId:o,guildId:r,...s}=e;return m(n,t,o,r,s)}function on(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 rn(e){let{name:n,description:t,conversationId:o,...r}=e;return m(n,t,o,void 0,r)}function sn(e){let{name:n,description:t,channelId:o,teamId:r,...s}=e;return m(n,t,o,r,s)}function an(e){let{name:n,description:t,chatId:o,...r}=e;return m(n,t,o,void 0,r)}function cn(e){let{name:n,description:t,chatId:o,...r}=e;return m(n,t,o,void 0,r)}function un(e){return{[V]:!0,config:e}}function dn(e){let{name:n,description:t,...o}=e;return g("agent",n,t,o)}function ln(e){return e}function gn(e){let{name:n,description:t,...o}=e;return g("workspace",n,t,o)}function pn(e){let{name:n,description:t,...o}=e;return g("sandbox",n,t,o)}function fn(e){let{name:n,description:t,...o}=e;return g("skill",n,t,o)}function mn(e){let{name:n,description:t,...o}=e;return g("mcp",n,t,o)}function yn(e){let{name:n,description:t,...o}=e;return g("policy",n,t,o)}function hn(e){let{name:n,description:t,...o}=e;return g("cron",n,t,o)}function Cn(e){return Boolean(e&&typeof e==="object"&&e[z])}function Sn(e){return Boolean(e&&typeof e==="object"&&e[Y])}function Rn(e){return Boolean(e&&typeof e==="object"&&e[V])}
|
|
5
|
+
export{k as a,D as b,Ee as c,De as d,h as e,Ne as f,Oe as g,T as h,d as i,Te as j,I as k,$e as l,x as m,B as n,le as o,A as p,Se as q,ke as r,ze as s,Ve as t,Ye as u,Xe as v,Qe as w,en as x,nn as y,tn as z,on as A,rn as B,sn as C,an as D,cn as E,un as F,dn as G,ln as H,gn as I,pn as J,fn as K,mn as L,yn as M,hn as N,Cn as O,Sn as P,Rn as Q};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$ as k,W as _,X as q,Y as C,Z as P,_ as j,aa as D,ba as p,ca as v,da as z,ea as A,fa as M,ga as J,ha as L,ia as U,ja as x,ka as O,la as g,ma as F,na as X,oa as H,pa as Q}from"./chunk-zk2w6bee.js";import"./chunk-e66afphr.js";import"./chunk-rx5qcgbh.js";var re=class{_readBuffer;_started=!1;_closed=!1;constructor(r=O.stdin,o=O.stdout,a){this._stdin=r,this._stdout=o,this._readBuffer=new U({maxBufferSize:a?.maxBufferSize})}onclose;onerror;onmessage;_ondata=(r)=>{try{this._readBuffer.append(r),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}};_onerror=(r)=>{this.onerror?.(r)};_onstdouterror=(r)=>{this.onerror?.(r),this.close().catch(()=>{})};async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror),this._stdout.on("error",this._onstdouterror)}processReadBuffer(){while(!0)try{let r=this._readBuffer.readMessage();if(r===null)break;this.onmessage?.(r)}catch(r){this.onerror?.(r)}}async close(){if(this._closed)return;if(this._closed=!0,this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdout.off("error",this._onstdouterror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(r){if(this._closed)return Promise.reject(Error("StdioServerTransport is closed"));return new Promise((o,a)=>{let d=x(r),t=!1,u=(w)=>{if(t)return;t=!0,this._stdout.off("error",u),this._stdout.off("drain",h),a(w)},h=()=>{if(t)return;t=!0,this._stdout.off("error",u),this._stdout.off("drain",h),o()};if(this._stdout.once("error",u),this._stdout.write(d)){if(t)return;t=!0,this._stdout.off("error",u),o()}else if(!t)this._stdout.once("drain",h)})}},W=3000,te=class{onclose;onerror;onmessage;_closed=!1;_pendingRequests=new Set;_drainWaiters=[];constructor(r,o,a){this._wire=r,this._onInstanceClose=o,this._outboundIntercept=a}async start(){}async send(r,o){if(z(r)||A(r)){let{id:a}=r;if(a!==void 0)this._settle(a)}if(this._closed)return;if(this._outboundIntercept?.(r)==="handled")return;return this._wire.send(r,o)}setProtocolVersion=(r)=>{this._wire.setProtocolVersion?.(r)};deliver(r,o){if(this._closed)return;if(p(r))this._pendingRequests.add(r.id);else if(v(r)&&r.method==="notifications/cancelled"){let a=r.params?.requestId;if(a!==void 0)this._settle(a)}this.onmessage?.(r,o)}async whenRequestsAnswered(r){if(this._closed||this._pendingRequests.size===0)return!0;return await new Promise((o)=>{let a=()=>{clearTimeout(d),o(!0)},d=setTimeout(()=>{this._drainWaiters=this._drainWaiters.filter((t)=>t!==a),o(!1)},r);this._drainWaiters.push(a)})}async close(){if(this._closed)return;this._closed=!0,this._pendingRequests.clear(),this._releaseDrainWaiters();try{this._onInstanceClose()}finally{this.onclose?.()}}_settle(r){if(this._pendingRequests.delete(r),this._pendingRequests.size===0)this._releaseDrainWaiters()}_releaseDrainWaiters(){let r=this._drainWaiters;this._drainWaiters=[];for(let o of r)o()}};function ne(r){let o=r.params;if(r.method==="initialize"&&!M(o)){let u=o!==null&&typeof o==="object"&&typeof o.protocolVersion==="string"?o.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...u!==void 0&&{requestedVersion:u}}}if(!j(o))return{kind:"legacy",reason:"no-claim"};let a=P(o),d=(a===void 0?[]:D(a))[0];if(d!==void 0)return{kind:"invalid-envelope",issue:d};let t=k(o);if(t===void 0||!_.includes(t))return{kind:"unsupported-revision",requested:t??"unknown"};return{kind:"modern",revision:t,classification:{era:"modern",revision:t}}}function ae(r,o={}){let a=o.legacy??"serve",d=o.transport??new re,t={phase:"opening"},u,h=!1,w=()=>h||t.phase==="closed",c=(e)=>{try{o.onerror?.(e)}catch{}},R=(e,n,i,s)=>d.send({jsonrpc:"2.0",id:e,error:{code:n,message:i,...s!==void 0&&{data:s}}}).catch((l)=>c(f(l))),y=new F(o.maxSubscriptions??g),Y=(e)=>{if(!v(e))return;let n=y.routeOutbound(e);if(n==="passthrough")return;for(let i of n)d.send({jsonrpc:"2.0",...i}).catch((s)=>c(f(s)));return"handled"},V=async(e)=>{if(p(e)&&e.method==="subscriptions/listen"){let n=P(e.params),i=j(e.params)?(n===void 0?[]:D(n))[0]:{key:"_meta",problem:"the per-request envelope is required on protocol revision 2026-07-28"},s=k(e.params),l;if(i!==void 0)l={jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid _meta envelope: ${i.key}: ${i.problem}`}};else if(s===void 0||!_.includes(s)){let m=new C({supported:[..._],requested:s??"unknown"});l={jsonrpc:"2.0",id:e.id,error:{code:m.code,message:m.message,data:m.data}}}else l=y.serve(e);return await d.send("error"in l?l:{jsonrpc:"2.0",method:l.method,params:l.params}).catch((m)=>c(f(m))),!0}if(v(e)&&e.method==="notifications/cancelled"){let n=e.params?.requestId;if(n!==void 0&&y.cancel(n))return!0}return!1},T=(e,n,i)=>{let s=J({kind:"legacy",reason:n,...i!==void 0&&{requestedVersion:i}},_);if(s===void 0)return Promise.resolve();return c(Error(`Rejected 2025-era request on a modern-only stdio connection (${s.cell}): ${s.message}`)),R(e.id,s.code,s.message,s.data)},G=(e)=>{if(h||e===u)return;B()},S=async(e,n)=>{let i=await r({era:e}),s=i instanceof Q?i.server:i;if(e==="modern")L(s,n),X(s,_),y.setServerCapabilities(s.getCapabilities(),H(s));let l=new te(d,()=>G(l),e==="modern"?Y:void 0);return await i.connect(l),{product:i,channel:l}},E=(e)=>e.product.close().catch((n)=>c(f(n))),K=async(e)=>{u=e.channel;try{if(!await e.channel.whenRequestsAnswered(W))c(Error(`Discarded the probe instance with requests still unanswered after ${W}ms; continuing with the fallback`));await e.product.close()}catch(n){c(f(n))}finally{u=void 0}},Z=async(e)=>{if(t.phase==="closed")return;if(t.phase==="pinned"){if(t.era==="modern"&&p(e)&&e.method==="initialize"&&!M(e.params)){await T(e,"initialize",e.params!==null&&typeof e.params==="object"&&typeof e.params.protocolVersion==="string"?e.params.protocolVersion:void 0);return}if(t.era==="modern"&&await V(e))return;t.instance.channel.deliver(e);return}if(!p(e)&&!v(e)){c(Error("Discarded a JSON-RPC response received before the connection negotiated an era"));return}let n=ne(e);switch(n.kind){case"invalid-envelope":{let i=`Invalid _meta envelope for protocol revision 2026-07-28: ${n.issue.key}: ${n.issue.problem}`;if(p(e))await R(e.id,q.InvalidParams,i,{envelope:n.issue});else c(Error(`Discarded a notification with a malformed envelope: ${i}`));return}case"unsupported-revision":if(p(e)){let i=new C({supported:[..._],requested:n.requested});c(i),await R(e.id,i.code,i.message,i.data)}else c(Error(`Discarded a notification claiming unsupported protocol revision ${n.requested}`));return;case"modern":if(p(e)&&e.method==="server/discover"){if(t.phase==="probe"){t.instance.channel.deliver(e,{classification:n.classification});return}let i=await S("modern",n.revision);if(w()){await E(i);return}t={phase:"probe",instance:i},i.channel.deliver(e,{classification:n.classification});return}if(t.phase==="probe"){if(v(e)){t.instance.channel.deliver(e,{classification:n.classification});return}t={phase:"pinned",era:"modern",instance:t.instance}}else{let i=await S("modern",n.revision);if(w()){await E(i);return}t={phase:"pinned",era:"modern",instance:i}}if(await V(e))return;t.instance.channel.deliver(e,{classification:n.classification});return;case"legacy":{if(a==="reject"){if(p(e))await T(e,n.reason,n.requestedVersion);return}if(t.phase==="probe"){if(await K(t.instance),w())return;t={phase:"opening"}}let i=await S("legacy");if(w()){await E(i);return}t={phase:"pinned",era:"legacy",instance:i},t.instance.channel.deliver(e);return}}},I=[],b=!1,ee=async()=>{if(b)return;b=!0;try{while(I.length>0){let e=I.shift();try{await Z(e)}catch(n){if(p(e))await R(e.id,q.InternalError,"Internal server error");c(f(n))}}}finally{b=!1}},B=async()=>{if(h||t.phase==="closed")return;h=!0;let e=t;t={phase:"closed"};for(let n of y.teardownAll())await d.send(n).catch((i)=>c(f(i)));if(e.phase==="probe"||e.phase==="pinned")await e.instance.product.close().catch((n)=>c(f(n)));await d.close().catch((n)=>c(f(n)))};d.onmessage=(e)=>{I.push(e),ee()},d.onerror=(e)=>{if(c(e),t.phase==="probe"||t.phase==="pinned")t.instance.channel.onerror?.(e)},d.onclose=()=>{if(h||t.phase==="closed")return;h=!0;let e=t;if(t={phase:"closed"},e.phase==="probe"||e.phase==="pinned")e.instance.product.close().catch((n)=>c(f(n)))};let N=d.start().catch((e)=>{throw c(f(e)),e});return N.catch(()=>{}),{close:async()=>{await N.catch(()=>{}),await B()}}}function f(r){return r instanceof Error?r:Error(String(r))}export{re as StdioServerTransport,ae as serveStdio};
|