broods 0.36.2 → 0.37.1

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
@@ -101,6 +101,30 @@ declare const MODEL_PROVIDERS: {
101
101
  };
102
102
  type AccountModelProviderName = keyof typeof MODEL_PROVIDERS;
103
103
 
104
+ /**
105
+ * Agent config validation, the only copy of it: Convex config HTTP checks a
106
+ * config on write and core re-checks the stored config on every run. Pure
107
+ * module: safe for the default Convex runtime. The public projection lives in
108
+ * ./responses.ts.
109
+ */
110
+
111
+ declare const AGENT_HARNESS_TYPES: readonly ["claude-code", "codex", "deepagents", "opencode", "pi"];
112
+ declare const AGENT_HARNESS_DEBUG_LEVELS: readonly ["error", "warn", "info", "debug", "trace"];
113
+ declare const AGENT_HARNESS_PERMISSION_MODES: readonly ["allow-reads", "allow-edits", "allow-all"];
114
+ declare const AGENT_LIFECYCLE_EVENT_NAMES: readonly ["agent.started", "agent.step.finished", "agent.finished", "agent.failed", "agent.approval.required", "tool.call.started", "tool.call.finished", "tool.result", "subagent.task.started", "subagent.task.finished"];
115
+
116
+ /**
117
+ * Shared validation for MCP server registrations (#331). One normalizer
118
+ * serves every write path (CLI sync, direct API, dashboard). A `url` makes an "http" row
119
+ * core connects to over the stateless 2026-07-28 transport; a `bundle` makes
120
+ * a "hosted" row served by the tool-runner Lambda, hashed here so sha256
121
+ * always travels with the bundle. Auth header values may carry ${NAME}
122
+ * account env refs; they resolve into the encrypted agent config at sync
123
+ * time, never on this row, and credential-bearing headers must use one
124
+ * instead of an inline secret. `oauth` follows the same rule: clientSecret
125
+ * and refreshToken must be ${NAME} refs, so the row never holds a secret.
126
+ */
127
+
104
128
  /**
105
129
  * OAuth 2.0 refresh-token grant for an external row. Core mints access tokens
106
130
  * at connect time and sends `Authorization: Bearer <token>`, so a server
@@ -116,20 +140,18 @@ interface McpOauth {
116
140
  }
117
141
 
118
142
  /**
119
- * Agent configuration: types for the per-agent settings object, input
120
- * normalization, encryption helpers, patch-merge, and redaction.
143
+ * Agent configuration: types for the per-agent settings object, the runtime
144
+ * projection of a stored config, and encryption helpers. The validation rules
145
+ * are the config plane's (`@broods/convex/model/agentRules`), so a config is
146
+ * judged the same on write and on every run.
121
147
  * Account types and auth live in `./accounts.ts` and `../auth.ts`.
122
148
  */
123
149
 
124
- declare const AGENT_HARNESS_TYPES: readonly ["claude-code", "codex", "deepagents", "opencode", "pi"];
125
- declare const AGENT_HARNESS_DEBUG_LEVELS: readonly ["error", "warn", "info", "debug", "trace"];
126
- declare const AGENT_HARNESS_PERMISSION_MODES: readonly ["allow-reads", "allow-edits", "allow-all"];
127
150
  interface AgentConfig {
128
151
  agent?: AgentBehaviorConfig;
129
152
  harness?: AgentHarnessConfig;
130
153
  model?: AgentModelConfig;
131
154
  provider?: AgentProviderConfig;
132
- sandbox?: string;
133
155
  sandboxes?: string[];
134
156
  workspaces?: AgentWorkspaceRef[];
135
157
  session?: AgentSessionConfig;
@@ -205,7 +227,7 @@ interface AgentSubagentConfig {
205
227
  visibility?: "full" | "result" | "none";
206
228
  [key: string]: unknown;
207
229
  }
208
- interface AgentModelConfig extends LanguageModelCallOptions, Pick<RequestOptions, "maxRetries" | "timeout"> {
230
+ interface AgentModelConfig extends LanguageModelCallOptions, Partial<Pick<RequestOptions, "maxRetries" | "timeout">> {
209
231
  provider?: AccountModelProviderName;
210
232
  modelId?: string;
211
233
  /**
@@ -297,7 +319,7 @@ interface AgentWebhookHookConfig {
297
319
  events?: AgentLifecycleEventName[];
298
320
  [key: string]: unknown;
299
321
  }
300
- type AgentLifecycleEventName = "agent.started" | "agent.step.finished" | "agent.finished" | "agent.failed" | "agent.approval.required" | "tool.call.started" | "tool.call.finished" | "tool.result" | "subagent.task.started" | "subagent.task.finished";
322
+ type AgentLifecycleEventName = (typeof AGENT_LIFECYCLE_EVENT_NAMES)[number];
301
323
 
302
324
  type AgentToolsConfig = Record<string, AgentToolConfig>;
303
325
  interface AgentToolConfig {
@@ -1944,10 +1966,8 @@ type SandboxDefinitionConfig = Omit<SandboxConfig, "envVars" | "options"> & {
1944
1966
  options?: SandboxDefinitionOptions;
1945
1967
  };
1946
1968
  type HarnessType = NonNullable<AgentConfig["harness"]>["type"];
1947
- type HarnessDefinition = Omit<NonNullable<AgentConfig["harness"]>, "type"> & {
1948
- type: HarnessType;
1949
- sandbox: SandboxResource | string;
1950
- };
1969
+ /** Harness settings. The harness runs on the agent's first sandbox. */
1970
+ type HarnessDefinition = NonNullable<AgentConfig["harness"]>;
1951
1971
  interface SkillDefinitionConfig {
1952
1972
  /**
1953
1973
  * Folder containing SKILL.md plus optional scripts/assets. Relative paths are
@@ -1991,8 +2011,9 @@ interface McpDefinitionConfig {
1991
2011
  handler?: McpHandler;
1992
2012
  /**
1993
2013
  * Extra request headers. Credential-bearing headers (Authorization,
1994
- * X-Api-Key, ...) must reference an account env var, e.g.
1995
- * `Bearer ${env("TOKEN")}`. Never carry an inline secret.
2014
+ * X-Api-Key, ...) must reference an account env var by name inside a plain
2015
+ * string, e.g. `"Bearer ${TOKEN}"`. `env()` returns an object, so a template
2016
+ * literal around it sends `[object Object]`. Never carry an inline secret.
1996
2017
  */
1997
2018
  headers?: Record<string, string>;
1998
2019
  /**
@@ -2144,7 +2165,7 @@ type PancakeChannelInput = ChannelRulesInput & {
2144
2165
  };
2145
2166
  /**
2146
2167
  * Per-agent workspace mount with an optional sandbox override. A bare
2147
- * `defineWorkspace(...)` inherits the agent-level sandbox; the object form lets
2168
+ * `defineWorkspace(...)` inherits the agent's first sandbox; the object form lets
2148
2169
  * a single workspace pin its own sandbox, or set `sandbox: null` to force the
2149
2170
  * workspace read-only (no compute attached).
2150
2171
  */
@@ -2321,10 +2342,10 @@ type AgentDefinitionConfig = EnvRefString<Pick<AgentConfig, "agent" | "model" |
2321
2342
  webhooks?: readonly EnvRefString<AgentWebhookHookConfig>[];
2322
2343
  };
2323
2344
  connections?: readonly AnyConnectionDefinition[];
2324
- sandbox?: SandboxResource | string;
2325
2345
  /**
2326
- * Extra sandboxes bash picks by name with no workspace mounted, each with its
2327
- * own image, size, network and permissionMode. Never repeat `sandbox` here.
2346
+ * Sandboxes this agent runs on. The first is the default: bash with no
2347
+ * workspace runs there, workspaces without their own sandbox mount it, and a
2348
+ * harness runs on it. The model reaches the others by name.
2328
2349
  */
2329
2350
  sandboxes?: readonly (SandboxResource | string)[];
2330
2351
  workspaces?: readonly AgentWorkspaceInput[];
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{W,Se,Me,xe,Ae,ze,G,$e,P,we,F,Y,ke,X,I,Oe,Ne,je,qe,De,Le,Ue,Fe,Be,Ve,Ze,He,We,Ge,Ke,Je,Ye,Xe,Qe,et,tt,rt,ie,R,h}from"./chunk-q2n2mxeg.js";import{m,Ce,L,U}from"./chunk-mqsvqhkj.js";export{m as BroodsAccountApiError,U as BroodsAccountClient,F as BroodsClient,ke as BroodsWebSocketClient,P as DEFAULT_CORE_BASE_URL,we as IngressAcceptedError,Me as MAX_OBSERVABILITY_BACKFILL,ke as WebSocketClient,ke as WebsocketClient,Ne as defineAgent,je as defineBroods,qe as defineCron,Ye as defineDiscordChannel,Ze as defineDiscordConnection,Xe as defineGitHubChannel,He as defineGitHubConnection,De as defineHarness,Le as defineMcp,Qe as definePancakeChannel,We as definePancakeConnection,Ue as definePolicy,Fe as defineSandbox,Be as defineSkill,et as defineSlackChannel,Ge as defineSlackConnection,tt as defineTelegramChannel,Ke as defineTelegramConnection,Ve as defineWorkspace,rt as defineZaloChannel,Je as defineZaloConnection,Oe as env,Ce as envPlaceholder,ie as isBroodsConfig,R as isConnectionDefinition,xe as isLogLevel,Ae as isObservabilityClientMessage,h as isResource,ze as isRootSpanKind,G as isSandboxLogId,$e as isTraceId,Y as normalizeHttpServiceUrl,Se as readSseStream,L as resolveEnvCredential,W as resolveRunEvents,X as toWebSocketBaseUrl,I as webSocketSubprotocols};
1
+ import{B,me,xe,Ce,Oe,Ae,F,ze,z,he,j,V,Pe,K,E,Me,Ne,je,qe,Le,De,Ue,Be,Fe,Ze,He,Ve,Ke,We,Ge,Je,Ye,Xe,Qe,et,tt,nt,ne,w,g}from"./chunk-tgqhxn4k.js";import{m,Te,L,D}from"./chunk-9m85p3e3.js";export{m as BroodsAccountApiError,D as BroodsAccountClient,j as BroodsClient,Pe as BroodsWebSocketClient,z as DEFAULT_CORE_BASE_URL,he as IngressAcceptedError,xe as MAX_OBSERVABILITY_BACKFILL,Pe as WebSocketClient,Pe as WebsocketClient,Ne as defineAgent,je as defineBroods,qe as defineCron,Ye as defineDiscordChannel,He as defineDiscordConnection,Xe as defineGitHubChannel,Ve as defineGitHubConnection,Le as defineHarness,De as defineMcp,Qe as definePancakeChannel,Ke as definePancakeConnection,Ue as definePolicy,Be as defineSandbox,Fe as defineSkill,et as defineSlackChannel,We as defineSlackConnection,tt as defineTelegramChannel,Ge as defineTelegramConnection,Ze as defineWorkspace,nt as defineZaloChannel,Je as defineZaloConnection,Me as env,Te as envPlaceholder,ne as isBroodsConfig,w as isConnectionDefinition,Ce as isLogLevel,Oe as isObservabilityClientMessage,g as isResource,Ae as isRootSpanKind,F as isSandboxLogId,ze as isTraceId,V as normalizeHttpServiceUrl,me as readSseStream,L as resolveEnvCredential,B as resolveRunEvents,K as toWebSocketBaseUrl,E as webSocketSubprotocols};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "broods",
3
- "version": "0.36.2",
3
+ "version": "0.37.1",
4
4
  "description": "CLI + TypeScript SDK for the broods agent platform.",
5
5
  "keywords": [
6
6
  "agents",
@@ -77,11 +77,6 @@
77
77
  "peerDependencies": {
78
78
  "ai": "^7.0.99"
79
79
  },
80
- "peerDependenciesMeta": {
81
- "ai": {
82
- "optional": true
83
- }
84
- },
85
80
  "engines": {
86
81
  "node": ">=22.15"
87
82
  }
@@ -1,4 +0,0 @@
1
- import{I}from"./chunk-q2n2mxeg.js";import{ce,le,e,o,i,l,r,t,u,S,s,p,n}from"./cli/index.js";import{spawn as V}from"node:child_process";import{hostname as ee}from"node:os";import{performance as T}from"node:perf_hooks";var j=["cursor_position","double_click","hold_key","key","left_click","left_click_drag","left_mouse_down","left_mouse_up","middle_click","mouse_move","right_click","screenshot","scroll","triple_click","type","wait","zoom"];var k={badFrame:{code:4400,reason:"Malformed frame"},occupied:{code:4423,reason:"Already connected from another daemon"},replaced:{code:4409,reason:"Replaced by a newer connection"},unauthorized:{code:4401,reason:"Unauthorized; check BROODS_API_KEY"},unknownSandbox:{code:4404,reason:"No machine sandbox with that name in this account"}},N="/v1/machines/ws",H=t({action:p(j),coordinate:r(o().int()).length(2).optional().describe("[x, y] in screenshot pixels for mouse actions."),start_coordinate:r(o().int()).length(2).optional().describe("[x, y] where a left_click_drag starts."),text:e().optional().describe("Text for type, the key chord for key and hold_key, or modifiers to hold during a click, drag or scroll."),scroll_direction:p(["down","left","right","up"]).optional(),scroll_amount:o().int().min(1).optional().describe("Scroll clicks, default 3."),duration:o().min(0).max(300).optional().describe("Seconds for wait and hold_key."),region:r(o().int()).length(4).optional().describe("[x0, y0, x1, y1] of the screenshot to zoom into."),repeat:o().int().min(1).max(100).optional().describe("How many times to press the key.")}),P=H.extend({type:n("computer"),id:e()}),U=t({type:n("computer-result"),id:e(),text:e().optional(),image:t({data:e(),mediaType:e()}).optional(),app:e().optional(),error:e().optional()}),B=t({type:n("exec"),id:e(),code:e(),cwd:e().optional(),env:s(e(),e()).optional(),timeoutSeconds:o().positive(),outputLimitBytes:o().positive()}),K=t({type:n("hello"),sandbox:e().min(1),hostname:e().optional(),platform:e().optional(),computer:i().optional(),mcp:r(e()).optional(),instance:e().optional(),force:i().optional()}),W=t({type:n("mcp-call"),id:e(),server:e(),tool:e(),args:s(e(),l())}),G=t({type:n("mcp-list"),id:e(),server:e()}),J=t({type:n("mcp-result"),id:e(),result:u({content:r(l())}).optional(),error:e().optional()}),X=t({type:n("mcp-tools"),id:e(),tools:r(u({name:e(),inputSchema:s(e(),l())})).optional(),error:e().optional()}),Y=t({type:n("ready"),sandboxId:e()}),q=t({type:n("result"),id:e(),exitCode:o().nullable(),stdout:e(),stderr:e(),durationMs:o(),timedOut:i(),truncated:i()}),Z=S("type",[P,B,W,G,Y]),me=S("type",[U,K,J,X,q]);function O(c){let a=new URL(N,c);return a.protocol=a.protocol==="https:"?"wss:":"ws:",a.toString()}function D(c){return Q(Z,c)}function Q(c,a){if(typeof a!=="string")return null;try{let m=c.safeParse(JSON.parse(a));return m.success?m.data:null}catch{return null}}var te=new Set([k.occupied.code,k.replaced.code,k.unauthorized.code,k.unknownSandbox.code]),R=72,L=30000,z=1000;function oe(c,a,m){return new Promise((y)=>{let d=T.now(),b=new C(c.outputLimitBytes),h=new C(c.outputLimitBytes),M=!1,_=!1,w=(v,E)=>{if(_)return;if(_=!0,clearTimeout(g),m?.removeEventListener("abort",f),E)h.append(Buffer.from(`${E}
2
- `));y({type:"result",id:c.id,exitCode:v,stdout:b.text(),stderr:h.text(),durationMs:Math.round(T.now()-d),timedOut:M,truncated:b.truncated||h.truncated})},x=V("bash",["-lc",c.code],{cwd:c.cwd??a,env:{...process.env,...c.env},detached:!0,stdio:["ignore","pipe","pipe"]}),F=()=>{if(!x.pid)return;try{process.kill(-x.pid,"SIGKILL")}catch{x.kill("SIGKILL")}},g=setTimeout(()=>{M=!0,F()},c.timeoutSeconds*1000),f=()=>{F(),w(null,"stopped: the daemon closed its socket")};if(m?.addEventListener("abort",f,{once:!0}),x.stdout.on("data",(v)=>b.append(v)),x.stderr.on("data",(v)=>h.append(v)),x.on("error",(v)=>w(null,v.message)),x.on("close",(v)=>w(v)),m?.aborted)f()})}async function Fe(c){let a=le(),m=crypto.randomUUID(),y=c.mcpFile?await ie(c.mcpFile,c.log):null,d=c.computer?await ne(c.log):null,b=z;try{while(!c.signal.aborted){let h=Date.now(),M=await ae(c,m,a,d,y);if(c.signal.aborted)return;if(te.has(M.code))throw Error(M.reason||`core closed the socket (${M.code})`);if(Date.now()-h>L)b=z;c.log(`disconnected (${M.reason||M.code}), reconnecting in ${Math.round(b/1000)}s`),await ce(b,c.signal),b=Math.min(b*2,L)}}finally{d?.stop(),await y?.stop()}}class C{#o=[];#e;#t=0;truncated=!1;constructor(c){this.#e=c}append(c){if(this.#t>=this.#e){this.truncated=!0;return}let a=this.#e-this.#t;if(c.byteLength>a){this.#o.push(c.subarray(0,a)),this.#t=this.#e,this.truncated=!0;return}this.#o.push(c),this.#t+=c.byteLength}text(){let c=Buffer.concat(this.#o).toString("utf8");return this.truncated?`${c}
3
- [output truncated]`:c}}function re(c){let a=[c.action];if(c.coordinate)a.push(`at ${c.coordinate.join(",")}`);if(c.text!==void 0)a.push(JSON.stringify(A(c.text)));if(c.region)a.push(`region ${c.region.join(",")}`);return a.join(" ")}function A(c){let a=c.trim().split(`
4
- `)[0]??"";return a.length>R?`${a.slice(0,R)}…`:a}async function ne(c){let{startDesktop:a}=await import("./chunk-5tnnqapc.js"),{display:m,driver:y,permissions:d}=await a(!1);if(c(`computer use on, ${m.width}x${m.height} screenshots`),!d.screenRecording||!d.accessibility)c(" screen recording or accessibility is missing, run `broods machine --doctor --request`");return y}async function ie(c,a){let{McpHost:m,readMcpServersFile:y}=await import("./chunk-xwnab9tf.js"),d=new m(y(c),a);return a(`mcp servers from ${c}: ${d.names().join(", ")}`),d}async function se(c,a,m){try{if(c.type==="mcp-list"){let d=await a.listTools(c.server);return m(` mcp ${c.server}: ${d.length} tools`),{type:"mcp-tools",id:c.id,tools:d}}m(` mcp ${c.server}.${c.tool}`);let y=await a.callTool(c.server,c.tool,c.args);return{type:"mcp-result",id:c.id,result:y}}catch(y){let d=y instanceof Error?y.message:String(y);return m(` mcp ${c.server}: ${d}`),{type:c.type==="mcp-call"?"mcp-result":"mcp-tools",id:c.id,error:d}}}function ae(c,a,m,y,d){return new Promise((b)=>{let h=new m(O(c.baseUrl),I(c.apiKey)),M=new AbortController,_=()=>h.close(1000,"daemon stopped"),w=(F)=>{if(h.readyState===h.OPEN)h.send(JSON.stringify(F))},x=(F,g)=>{c.signal.removeEventListener("abort",_),M.abort(),b({code:F,reason:g})};c.signal.addEventListener("abort",_,{once:!0}),h.onopen=()=>w({type:"hello",sandbox:c.sandbox,hostname:ee(),platform:process.platform,computer:y!==null,mcp:d?.names(),instance:a,force:c.force}),h.onmessage=(F)=>{let g=D(F.data);if(g?.type==="ready"){c.log(`connected as ${c.sandbox} (${g.sandboxId})`);return}if(g?.type==="computer"&&y){c.log(` ${re(g)}`),y.run(g).then((f)=>{if(f.error)c.log(` error: ${f.error}`);w(f)});return}if((g?.type==="mcp-call"||g?.type==="mcp-list")&&d){se(g,d,c.log).then(w);return}if(g?.type!=="exec")return;c.log(`$ ${A(g.code)}`),oe(g,c.cwd,M.signal).then((f)=>{c.log(` exit ${f.exitCode??"none"} in ${f.durationMs}ms${f.timedOut?" (timed out)":""}`),w(f)})},h.onerror=()=>x(1006,"connection failed"),h.onclose=(F)=>x(F.code,F.reason)})}export{Fe as runMachineDaemon};
@@ -1 +0,0 @@
1
- import{C,a,D,z,B,V,Z,b,x,H,re,ne,me,fe,he,ge,oe,se,ye,ve,be,O}from"./chunk-vtfkzp4h.js";import"./chunk-ty87cm0z.js";var J=class{_readBuffer;_started=!1;_closed=!1;constructor(r=oe.stdin,o=oe.stdout,c){this._stdin=r,this._stdout=o,this._readBuffer=new he({maxBufferSize:c?.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,c)=>{let l=ge(r),t=!1,f=(_)=>{if(t)return;t=!0,this._stdout.off("error",f),this._stdout.off("drain",p),c(_)},p=()=>{if(t)return;t=!0,this._stdout.off("error",f),this._stdout.off("drain",p),o()};if(this._stdout.once("error",f),this._stdout.write(l)){if(t)return;t=!0,this._stdout.off("error",f),o()}else if(!t)this._stdout.once("drain",p)})}},k=3000,L=class{onclose;onerror;onmessage;_closed=!1;_pendingRequests=new Set;_drainWaiters=[];constructor(r,o,c){this._wire=r,this._onInstanceClose=o,this._outboundIntercept=c}async start(){}async send(r,o){if(H(r)||re(r)){let{id:c}=r;if(c!==void 0)this._settle(c)}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(b(r))this._pendingRequests.add(r.id);else if(x(r)&&r.method==="notifications/cancelled"){let c=r.params?.requestId;if(c!==void 0)this._settle(c)}this.onmessage?.(r,o)}async whenRequestsAnswered(r){if(this._closed||this._pendingRequests.size===0)return!0;return await new Promise((o)=>{let c=()=>{clearTimeout(l),o(!0)},l=setTimeout(()=>{this._drainWaiters=this._drainWaiters.filter((t)=>t!==c),o(!1)},r);this._drainWaiters.push(c)})}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 U(r){let o=r.params;if(r.method==="initialize"&&!ne(o)){let f=o!==null&&typeof o==="object"&&typeof o.protocolVersion==="string"?o.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...f!==void 0&&{requestedVersion:f}}}if(!B(o))return{kind:"legacy",reason:"no-claim"};let c=z(o),l=(c===void 0?[]:Z(c))[0];if(l!==void 0)return{kind:"invalid-envelope",issue:l};let t=V(o);if(t===void 0||!C.includes(t))return{kind:"unsupported-revision",requested:t??"unknown"};return{kind:"modern",revision:t,classification:{era:"modern",revision:t}}}function Q(r,o={}){let c=o.legacy??"serve",l=o.transport??new J,t={phase:"opening"},f,p=!1,_=()=>p||t.phase==="closed",d=(e)=>{try{o.onerror?.(e)}catch{}},y=(e,n,i,s)=>l.send({jsonrpc:"2.0",id:e,error:{code:n,message:i,...s!==void 0&&{data:s}}}).catch((u)=>d(h(u))),w=new ye(o.maxSubscriptions??se),M=(e)=>{if(!x(e))return;let n=w.routeOutbound(e);if(n==="passthrough")return;for(let i of n)l.send({jsonrpc:"2.0",...i}).catch((s)=>d(h(s)));return"handled"},I=async(e)=>{if(b(e)&&e.method==="subscriptions/listen"){let n=z(e.params),i=B(e.params)?(n===void 0?[]:Z(n))[0]:{key:"_meta",problem:"the per-request envelope is required on protocol revision 2026-07-28"},s=V(e.params),u;if(i!==void 0)u={jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid _meta envelope: ${i.key}: ${i.problem}`}};else if(s===void 0||!C.includes(s)){let v=new D({supported:[...C],requested:s??"unknown"});u={jsonrpc:"2.0",id:e.id,error:{code:v.code,message:v.message,data:v.data}}}else u=w.serve(e);return await l.send("error"in u?u:{jsonrpc:"2.0",method:u.method,params:u.params}).catch((v)=>d(h(v))),!0}if(x(e)&&e.method==="notifications/cancelled"){let n=e.params?.requestId;if(n!==void 0&&w.cancel(n))return!0}return!1},q=(e,n,i)=>{let s=me({kind:"legacy",reason:n,...i!==void 0&&{requestedVersion:i}},C);if(s===void 0)return Promise.resolve();return d(Error(`Rejected 2025-era request on a modern-only stdio connection (${s.cell}): ${s.message}`)),y(e.id,s.code,s.message,s.data)},T=(e)=>{if(p||e===f)return;P()},m=async(e,n)=>{let i=await r({era:e}),s=i instanceof O?i.server:i;if(e==="modern")fe(s,n),ve(s,C),w.setServerCapabilities(s.getCapabilities(),be(s));let u=new L(l,()=>T(u),e==="modern"?M:void 0);return await i.connect(u),{product:i,channel:u}},R=(e)=>e.product.close().catch((n)=>d(h(n))),N=async(e)=>{f=e.channel;try{if(!await e.channel.whenRequestsAnswered(k))d(Error(`Discarded the probe instance with requests still unanswered after ${k}ms; continuing with the fallback`));await e.product.close()}catch(n){d(h(n))}finally{f=void 0}},W=async(e)=>{if(t.phase==="closed")return;if(t.phase==="pinned"){if(t.era==="modern"&&b(e)&&e.method==="initialize"&&!ne(e.params)){await q(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 I(e))return;t.instance.channel.deliver(e);return}if(!b(e)&&!x(e)){d(Error("Discarded a JSON-RPC response received before the connection negotiated an era"));return}let n=U(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(b(e))await y(e.id,a.InvalidParams,i,{envelope:n.issue});else d(Error(`Discarded a notification with a malformed envelope: ${i}`));return}case"unsupported-revision":if(b(e)){let i=new D({supported:[...C],requested:n.requested});d(i),await y(e.id,i.code,i.message,i.data)}else d(Error(`Discarded a notification claiming unsupported protocol revision ${n.requested}`));return;case"modern":if(b(e)&&e.method==="server/discover"){if(t.phase==="probe"){t.instance.channel.deliver(e,{classification:n.classification});return}let i=await m("modern",n.revision);if(_()){await R(i);return}t={phase:"probe",instance:i},i.channel.deliver(e,{classification:n.classification});return}if(t.phase==="probe"){if(x(e)){t.instance.channel.deliver(e,{classification:n.classification});return}t={phase:"pinned",era:"modern",instance:t.instance}}else{let i=await m("modern",n.revision);if(_()){await R(i);return}t={phase:"pinned",era:"modern",instance:i}}if(await I(e))return;t.instance.channel.deliver(e,{classification:n.classification});return;case"legacy":{if(c==="reject"){if(b(e))await q(e,n.reason,n.requestedVersion);return}if(t.phase==="probe"){if(await N(t.instance),_())return;t={phase:"opening"}}let i=await m("legacy");if(_()){await R(i);return}t={phase:"pinned",era:"legacy",instance:i},t.instance.channel.deliver(e);return}}},S=[],E=!1,A=async()=>{if(E)return;E=!0;try{while(S.length>0){let e=S.shift();try{await W(e)}catch(n){if(b(e))await y(e.id,a.InternalError,"Internal server error");d(h(n))}}}finally{E=!1}},P=async()=>{if(p||t.phase==="closed")return;p=!0;let e=t;t={phase:"closed"};for(let n of w.teardownAll())await l.send(n).catch((i)=>d(h(i)));if(e.phase==="probe"||e.phase==="pinned")await e.instance.product.close().catch((n)=>d(h(n)));await l.close().catch((n)=>d(h(n)))};l.onmessage=(e)=>{S.push(e),A()},l.onerror=(e)=>{if(d(e),t.phase==="probe"||t.phase==="pinned")t.instance.channel.onerror?.(e)},l.onclose=()=>{if(p||t.phase==="closed")return;p=!0;let e=t;if(t={phase:"closed"},e.phase==="probe"||e.phase==="pinned")e.instance.product.close().catch((n)=>d(h(n)))};let j=l.start().catch((e)=>{throw d(h(e)),e});return j.catch(()=>{}),{close:async()=>{await j.catch(()=>{}),await P()}}}function h(r){return r instanceof Error?r:Error(String(r))}export{Q as serveStdio};
@@ -1 +0,0 @@
1
- import{y,ue,de,Re}from"./cli/index.js";var c=()=>{let a={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function n(t){return a[t]??null}let d={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(t)=>{switch(t.code){case"invalid_type":{let e=o[t.expected]??t.expected,r=Re(t.input),l=o[r]??r;return`Invalid input: expected ${e}, received ${l}`}case"invalid_value":if(t.values.length===1)return`Invalid input: expected ${de(t.values[0])}`;return`Invalid option: expected one of ${ue(t.values,"|")}`;case"too_big":{let e=t.inclusive?"<=":"<",r=n(t.origin);if(r)return`Too big: expected ${t.origin??"value"} to have ${e}${t.maximum.toString()} ${r.unit??"elements"}`;return`Too big: expected ${t.origin??"value"} to be ${e}${t.maximum.toString()}`}case"too_small":{let e=t.inclusive?">=":">",r=n(t.origin);if(r)return`Too small: expected ${t.origin} to have ${e}${t.minimum.toString()} ${r.unit}`;return`Too small: expected ${t.origin} to be ${e}${t.minimum.toString()}`}case"invalid_format":{let e=t;if(e.format==="starts_with")return`Invalid string: must start with "${e.prefix}"`;if(e.format==="ends_with")return`Invalid string: must end with "${e.suffix}"`;if(e.format==="includes")return`Invalid string: must include "${e.includes}"`;if(e.format==="regex")return`Invalid string: must match pattern ${e.pattern}`;return`Invalid ${d[e.format]??t.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${t.divisor}`;case"unrecognized_keys":return`Unrecognized key${t.keys.length>1?"s":""}: ${ue(t.keys,", ")}`;case"invalid_key":return`Invalid key in ${t.origin}`;case"invalid_union":if(t.options&&Array.isArray(t.options)&&t.options.length>0)return`Invalid discriminator value. Expected ${t.options.map((r)=>`'${r}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${t.origin}`;default:return"Invalid input"}}};function i(){return{localeError:c()}}y(i());