@stackbone/cli 0.1.0-alpha.10 → 0.1.0-alpha.11

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/CHANGELOG.md CHANGED
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.1.0-alpha.11] - 2026-06-12
11
+
12
+ ### Fixed
13
+
14
+ - `stackbone dev` (and the self-host runtime) no longer crash on boot with
15
+ `BUNDLE_IMPORT_FAILED` when an agent splits its code across files and uses
16
+ idiomatic extensionless relative imports (e.g. `import { x } from './schema'`).
17
+ The dev/self-host runner imports the creator's raw TypeScript through Node's
18
+ native type-stripping, whose ESM resolver never adds a file extension — so a
19
+ multi-file agent that ran fine once published would crash locally. The
20
+ generated dev entry now registers a module-resolution hook that mirrors
21
+ esbuild's TypeScript resolution (the same `stackbone publish` relies on): it
22
+ adds the missing `.ts`/`.tsx`/`.mts`/`.cts` extension (and the directory
23
+ `index` form), and applies the NodeNext `./x.js` → `./x.ts` rewrite. Dev and
24
+ self-host now resolve modules exactly like a published agent.
25
+
10
26
  ## [0.1.0-alpha.10] - 2026-06-12
11
27
 
12
28
  ### Fixed
package/main.js CHANGED
@@ -2560,7 +2560,7 @@ var decryptValue = async (envelope, rawKey) => {
2560
2560
  var DEV_HMAC_SECRET = "dev-stackbone-local-emulator-hmac-secret";
2561
2561
  //#endregion
2562
2562
  //#region ../../libs/runtime/agent-emulator/src/lib/server/contract.ts
2563
- var STACKBONE_CLI_BUILD_VERSION = "0.1.0-alpha.10";
2563
+ var STACKBONE_CLI_BUILD_VERSION = "0.1.0-alpha.11";
2564
2564
  /**
2565
2565
  * Capabilities the local emulator advertises on `GET /api/contract`, derived
2566
2566
  * from the route registry above so the advertised set and the mounted routes
@@ -4139,9 +4139,17 @@ var buildAgentEnv = (base, injection, options) => {
4139
4139
  };
4140
4140
  //#endregion
4141
4141
  //#region ../../libs/runtime/agent-runner/src/lib/agent-entry-template.ts
4142
- var AGENT_ENTRY_TEMPLATE = () => `import { createAgentRequestHandler, createNodeHttpServer, loadSpec, loadSystemSecretsIntoEnv } from '@stackbone/agent-server';
4142
+ var AGENT_ENTRY_TEMPLATE = () => `import { register } from 'node:module';
4143
+ import { createAgentRequestHandler, createNodeHttpServer, loadSpec, loadSystemSecretsIntoEnv } from '@stackbone/agent-server';
4143
4144
  import { createStructuredLogger, installInvocationConsoleCapture } from '@stackbone/sdk';
4144
4145
 
4146
+ // Match what 'stackbone publish' gets from esbuild while we import the creator's
4147
+ // RAW TypeScript: Node's ESM resolver never adds a file extension, so register a
4148
+ // hook that turns "import './schema'" into "./schema.ts" (and the NodeNext
4149
+ // "./x.js" -> "./x.ts" swap) BEFORE loadSpec pulls the creator bundle in. Without
4150
+ // it a multi-file agent crash-loops on boot with BUNDLE_IMPORT_FAILED.
4151
+ register('./${DEV_RESOLVER_FILE}', import.meta.url);
4152
+
4145
4153
  // Re-emit any in-invoke console.* as correlated structured logs (run_id /
4146
4154
  // trace_id) so a creator's stray console.log is still tied to its run. Outside
4147
4155
  // an invoke it passes through untouched, keeping boot output readable.
@@ -4187,6 +4195,53 @@ await createNodeHttpServer({
4187
4195
  host: '127.0.0.1',
4188
4196
  });
4189
4197
  `;
4198
+ var DEV_RESOLVER_FILE = "ts-extension-resolver.mjs";
4199
+ var TS_EXTENSION_RESOLVER_TEMPLATE = () => `const TS_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts'];
4200
+
4201
+ // TypeScript's NodeNext convention writes "./x.js" in source for an "./x.ts"
4202
+ // file on disk; esbuild rewrites those at publish time, so mirror the swap.
4203
+ const JS_TO_TS = new Map([
4204
+ ['.js', '.ts'],
4205
+ ['.jsx', '.tsx'],
4206
+ ['.mjs', '.mts'],
4207
+ ['.cjs', '.cts'],
4208
+ ]);
4209
+
4210
+ const isRelative = (specifier) => specifier.startsWith('./') || specifier.startsWith('../');
4211
+
4212
+ async function firstResolvable(candidates, context, nextResolve) {
4213
+ for (const candidate of candidates) {
4214
+ try {
4215
+ return await nextResolve(candidate, context);
4216
+ } catch {
4217
+ // Try the next candidate; the caller rethrows the original error when
4218
+ // none of them resolve.
4219
+ }
4220
+ }
4221
+ return null;
4222
+ }
4223
+
4224
+ export async function resolve(specifier, context, nextResolve) {
4225
+ try {
4226
+ return await nextResolve(specifier, context);
4227
+ } catch (err) {
4228
+ if (!isRelative(specifier) || err?.code !== 'ERR_MODULE_NOT_FOUND') throw err;
4229
+
4230
+ const candidates = [];
4231
+ const jsExt = [...JS_TO_TS.keys()].find((ext) => specifier.endsWith(ext));
4232
+ if (jsExt) {
4233
+ candidates.push(specifier.slice(0, -jsExt.length) + JS_TO_TS.get(jsExt));
4234
+ } else {
4235
+ for (const ext of TS_EXTENSIONS) candidates.push(specifier + ext);
4236
+ for (const ext of TS_EXTENSIONS) candidates.push(specifier + '/index' + ext);
4237
+ }
4238
+
4239
+ const resolved = await firstResolvable(candidates, context, nextResolve);
4240
+ if (resolved) return resolved;
4241
+ throw err;
4242
+ }
4243
+ }
4244
+ `;
4190
4245
  //#endregion
4191
4246
  //#region ../../libs/runtime/agent-runner/src/lib/agent-entry.ts
4192
4247
  var isENOENT = (err) => err instanceof Error && err.code === "ENOENT";
@@ -4212,13 +4267,20 @@ var resolveAgentEntryPath = (projectRoot) => {
4212
4267
  };
4213
4268
  /**
4214
4269
  * Writes the canonical agent entry to `<projectRoot>/.stackbone/dev/agent-entry.mjs`
4215
- * and returns its absolute path. The directory is created if absent. Called on
4216
- * every emulator boot the file is intentionally overwritten so a template
4217
- * change is never masked by a stale copy.
4270
+ * (plus its sibling `ts-extension-resolver.mjs` module-resolution hook) and
4271
+ * returns the entry's absolute path. The directory is created if absent. Called
4272
+ * on every emulator boot both files are intentionally overwritten so a
4273
+ * template change is never masked by a stale copy.
4274
+ *
4275
+ * The resolver MUST land next to the entry: the entry `register(...)`s it by a
4276
+ * relative `./ts-extension-resolver.mjs` specifier before it `loadSpec`s the
4277
+ * creator bundle, so the agent boots even when the creator wrote idiomatic
4278
+ * extensionless imports (`./schema` instead of `./schema.ts`).
4218
4279
  */
4219
4280
  var writeAgentEntry = (projectRoot) => {
4220
4281
  const devDir = resolve(projectRoot, DEV_DIR);
4221
4282
  mkdirSync(devDir, { recursive: true });
4283
+ writeFileSync(resolve(devDir, DEV_RESOLVER_FILE), TS_EXTENSION_RESOLVER_TEMPLATE(), "utf8");
4222
4284
  const entryPath = resolve(devDir, ENTRY_FILE);
4223
4285
  writeFileSync(entryPath, AGENT_ENTRY_TEMPLATE(), "utf8");
4224
4286
  return entryPath;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackbone/cli",
3
- "version": "0.1.0-alpha.10",
3
+ "version": "0.1.0-alpha.11",
4
4
  "license": "UNLICENSED",
5
5
  "type": "module",
6
6
  "bin": {
@@ -407,7 +407,7 @@ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
407
407
 
408
408
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
409
409
  `);this.baseURL=c.baseURL,this.timeout=c.timeout??yj.DEFAULT_TIMEOUT,this.logger=c.logger??console;let l="warn";this.logLevel=l,this.logLevel=Z$(c.logLevel,"ClientOptions.logLevel",this)??Z$(bc("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??K3(),gr(this,p9,tfe,"f");let u=bc("OPENAI_CUSTOM_HEADERS");if(u){let I={};for(let d of u.split(`
410
- `)){let C=d.indexOf(":");C>=0&&(I[d.substring(0,C).trim()]=d.substring(C+1).trim())}c.defaultHeaders=vt([I,c.defaultHeaders])}this._options=c,o&&(this._workloadIdentityAuth=new Z3(o,this.fetch)),this.apiKey=typeof r=="string"?r:null,this.adminAPIKey=i,this.organization=n,this.project=A,this.webhookSecret=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&i.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return vt([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return vt([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return vt([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return vt([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return gfe(e)}getUserAgent(){return`${this.constructor.name}/JS ${kh}`}defaultIdempotencyKey(){return`stainless-node-retry-${T$()}`}makeStatusError(e,r,i,n){return vn.generate(e,r,i,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(i){throw i instanceof zt?i:new zt(`Failed to get token from 'apiKey' function: ${i.message}`,{cause:i})}if(typeof r!="string"||!r)throw new zt(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,i){let n=!$e(this,Qj,"m",zfe).call(this)&&i||this.baseURL,A=KCe(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),o=Object.fromEntries(A.searchParams);return(!O$(s)||!O$(o))&&(r={...o,...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(A.search=this.stringifyQuery(r)),A.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:i}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,i){return this.request(Promise.resolve(i).then(n=>({method:e,path:r,...n})))}request(e,r=null){return new Kd(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,i){let n=await e,A=n.maxRetries??this.maxRetries;r==null&&(r=A),await this.prepareOptions(n);let{req:s,url:o,timeout:a}=await this.buildRequest(n,{retryCount:A-r});await this.prepareRequest(s,{url:o,options:n});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=i===void 0?"":`, retryOf: ${i}`,u=Date.now();if(Ln(this).debug(`[${c}] sending request`,Fl({retryOfRequestLogID:i,method:n.method,url:o,options:n,headers:s.headers})),n.signal?.aborted)throw new jn;let I=n.__security??{bearerAuth:!0},d=new AbortController,C=await this.fetchWithAuth(o,s,a,d,I).catch(hy),p=Date.now();if(C instanceof globalThis.Error){let S=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new jn;let k=uy(C)||/timed? ?out/i.test(String(C)+("cause"in C?String(C.cause):""));if(r)return Ln(this).info(`[${c}] connection ${k?"timed out":"failed"} - ${S}`),Ln(this).debug(`[${c}] connection ${k?"timed out":"failed"} (${S})`,Fl({retryOfRequestLogID:i,url:o,durationMs:p-u,message:C.message})),this.retryRequest(n,r,i??c);throw Ln(this).info(`[${c}] connection ${k?"timed out":"failed"} - error; no more retries left`),Ln(this).debug(`[${c}] connection ${k?"timed out":"failed"} (error; no more retries left)`,Fl({retryOfRequestLogID:i,url:o,durationMs:p-u,message:C.message})),C instanceof Jd||C instanceof Iy?C:k?new Dh:new bh({message:tje(C),cause:C})}let Q=[...C.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,k])=>", "+S+": "+JSON.stringify(k)).join(""),y=`[${c}${l}${Q}] ${s.method} ${o} ${C.ok?"succeeded":"failed"} with status ${C.status} in ${p-u}ms`;if(!C.ok){if(C.status===401&&this._workloadIdentityAuth&&I.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Y$(C.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},r,i??c);let S=await this.shouldRetry(C);if(r&&S){let $=`retrying, ${r} attempts remaining`;return await Y$(C.body),Ln(this).info(`${y} - ${$}`),Ln(this).debug(`[${c}] response error (${$})`,Fl({retryOfRequestLogID:i,url:C.url,status:C.status,headers:C.headers,durationMs:p-u})),this.retryRequest(n,r,i??c,C.headers)}let k=S?"error; no more retries left":"error; not retryable";Ln(this).info(`${y} - ${k}`);let x=await C.text().catch($=>hy($).message),U=jCe(x),T=U?void 0:x;throw Ln(this).debug(`[${c}] response error (${k})`,Fl({retryOfRequestLogID:i,url:C.url,status:C.status,headers:C.headers,message:T,durationMs:Date.now()-u})),this.makeStatusError(C.status,U,T,C.headers)}return Ln(this).info(y),Ln(this).debug(`[${c}] response start`,Fl({retryOfRequestLogID:i,url:C.url,status:C.status,headers:C.headers,durationMs:p-u})),{response:C,options:n,controller:d,requestLogID:c,retryOfRequestLogID:i,startTime:u}}getAPIList(e,r,i){return this.requestAPIList(r,i&&"then"in i?i.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...i})}requestAPIList(e,r){let i=this.makeRequest(r,null,void 0);return new By(this,i,e)}async fetchWithAuth(e,r,i,n,A={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&A.bearerAuth){let o=r.headers,a=o.get("Authorization");if(!a||a===`Bearer ${eje}`){let c=await this._workloadIdentityAuth.getToken();o.set("Authorization",`Bearer ${c}`)}}return await this.fetchWithTimeout(e,r,i,n)}async fetchWithTimeout(e,r,i,n){let{signal:A,method:s,...o}=r||{},a=this._makeAbort(n);A&&A.addEventListener("abort",a,{once:!0});let c=setTimeout(a,i),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:n.signal,...l?{duplex:"half"}:{},method:"GET",...o};s&&(u.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,i,n){let A,s=n?.get("retry-after-ms");if(s){let a=parseFloat(s);Number.isNaN(a)||(A=a)}let o=n?.get("retry-after");if(o&&!A){let a=parseFloat(o);Number.isNaN(a)?A=Date.parse(o)-Date.now():A=a*1e3}if(A===void 0){let a=e.maxRetries??this.maxRetries;A=this.calculateDefaultRetryTimeoutMillis(r,a)}return await wg(A),this.makeRequest(e,r-1,i)}calculateDefaultRetryTimeoutMillis(e,r){let A=r-e,s=Math.min(.5*Math.pow(2,A),8),o=1-Math.random()*.25;return s*o*1e3}async buildRequest(e,{retryCount:r=0}={}){let i={...e},{method:n,path:A,query:s,defaultBaseURL:o}=i,a=this.buildURL(A,s,o);"timeout"in i&&$Ce("timeout",i.timeout),i.timeout=i.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:i});u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let I=await this.buildHeaders({options:e,method:n,bodyHeaders:c,retryCount:r});return{req:{method:n,headers:I,...i.signal&&{signal:i.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...i.fetchOptions??{}},url:a,timeout:i.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:i,retryCount:n}){let A={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),A[this.idempotencyHeader]=e.idempotencyKey);let s=vt([A,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...XCe(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,i,e.headers]);return this.validateHeaders(s,e.__security??{bearerAuth:!0}),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let i=vt([r]),n=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,A=!n&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&i.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||n?{bodyHeaders:void 0,body:e,isStreamingBody:!A}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:q3(e),isStreamingBody:!0}:typeof e=="object"&&i.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{...$e(this,p9,"f").call(this,{body:e,headers:i}),isStreamingBody:!1}}};yj=fr,p9=new WeakMap,Qj=new WeakSet,zfe=function(){return this.baseURL!=="https://api.openai.com/v1"};fr.OpenAI=yj;fr.DEFAULT_TIMEOUT=6e5;fr.OpenAIError=zt;fr.APIError=vn;fr.APIConnectionError=bh;fr.APIConnectionTimeoutError=Dh;fr.APIUserAbortError=jn;fr.NotFoundError=dB;fr.ConflictError=CB;fr.RateLimitError=pB;fr.BadRequestError=uB;fr.AuthenticationError=hB;fr.InternalServerError=BB;fr.PermissionDeniedError=IB;fr.UnprocessableEntityError=fB;fr.InvalidWebhookSignatureError=yg;fr.toFile=e9;fr.Completions=iC;fr.Chat=Rh;fr.Embeddings=AC;fr.Files=oC;fr.Images=lC;fr.Audio=Dg;fr.Moderations=hC;fr.Models=uC;fr.FineTuning=_c;fr.Graders=Oh;fr.VectorStores=Ll;fr.Webhooks=CC;fr.Beta=kc;fr.Batches=Zd;fr.Uploads=Jh;fr.Admin=Nh;fr.Responses=_g;fr.Realtime=Pl;fr.Conversations=Th;fr.Evals=Lh;fr.Containers=Ph;fr.Skills=Tl;fr.Videos=dC;function tje(t){if(rje(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function rje(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let i=e;if(i.code==="UND_ERR_INVALID_ARG"&&typeof i.message=="string"&&i.message.includes("invalid onRequestStart method"))return!0;e=i.cause}return!1}var B9=class{constructor(e,r,i){this._resolved=e;this._openai=null;this._chat=null;this._embeddings=null;this._images=null;this._models=null;r&&(this._openai=r),this._gate=i??nA("ai",e)}get chat(){return this._chat??={completions:new wj(()=>this.shared(),this._gate)},this._chat}get embeddings(){return this._embeddings??=new Sj(()=>this.shared(),this._gate),this._embeddings}get images(){return this._images??=new bj(()=>this.shared(),this._gate),this._images}get models(){return this._models??=new Dj(()=>this.shared(),this._gate),this._models}shared(){if(this._openai)return nr(this._openai);let e=sje(this._resolved);return e?(this._openai=new fr({apiKey:e,baseURL:oje(this._resolved),defaultHeaders:Wfe}),nr(this._openai)):Aje()}},wj=class{constructor(e,r){this._getClient=e;this._gate=r}async create(e,r){return zi(this._gate,async()=>kj(this._getClient,e.model,i=>i.chat.completions.create(e,{signal:r?.signal})))}},Sj=class{constructor(e,r){this._getClient=e;this._gate=r}async create(e,r){return zi(this._gate,async()=>{let i=typeof e.model=="string"?e.model:void 0;return kj(this._getClient,i,n=>n.embeddings.create(e,{signal:r?.signal}))})}},bj=class{constructor(e,r){this._getClient=e;this._gate=r}async generate(e,r){return zi(this._gate,async()=>{let i={model:e.model,messages:[{role:"user",content:e.prompt}],modalities:["image","text"],...e.imageConfig?{image_config:e.imageConfig}:{}},n=await kj(this._getClient,e.model,s=>s.chat.completions.create(i,{signal:r?.signal}));if(n.error)return n;let A=cje(n.data);return A.length===0?et({code:"ai_no_image_generated",message:`Model ${e.model} did not return any images. Make sure the model supports image output via OpenRouter.`,meta:{model:e.model}}):nr({created:n.data.created,data:A})})}},Dj=class{constructor(e,r){this._getClient=e;this._gate=r}async list(e){return zi(this._gate,async()=>{let r=this._getClient();if(r.error)return r;let{apiKey:i,baseURL:n}=r.data,A=n.replace(/\/+$/,""),s={headers:{Authorization:`Bearer ${i}`,...Wfe}};e?.signal&&(s.signal=e.signal);try{let o=await fetch(`${A}/models`,s);if(!o.ok){let c=await o.json().catch(()=>({}));return et({code:Vfe(o.status),message:c.error?.message??`HTTP ${o.status}`,meta:{status:o.status}})}let a=await o.json();return nr(a)}catch(o){return et(Zfe(o))}})}},Wfe={"HTTP-Referer":"https://stackbone.ai","X-Title":"Stackbone Agent Platform"},ije="https://openrouter.ai/api/v1",nje="Cannot reach OpenRouter \u2014 set `OPENROUTER_API_KEY` in the container or pass `openrouterKey` to `createClient({...})`.";function Aje(){return et({code:"openrouter_key_missing",message:nje})}function sje(t){return t.openrouterKey}function oje(t){return t.openrouterBaseUrl??ije}async function kj(t,e,r){let i=t();if(i.error)return i;try{return nr(await r(i.data))}catch(n){return et(Zfe(n,e))}}var aje=/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.*)$/;function cje(t){let r=t.choices[0]?.message?.images??[],i=[];for(let n of r){let A=n?.image_url?.url;if(!A)continue;let s=aje.exec(A);s&&s[1]&&s[2]?i.push({url:A,mimeType:s[1],b64Json:s[2]}):i.push({url:A})}return i}function Vfe(t){return t===401?"ai_unauthorized":t===402?"ai_credits_exhausted":t===403?"ai_forbidden":t===408?"ai_timeout":t===422||t===400?"ai_validation_error":t===429?"ai_rate_limited":t===451?"ai_moderation_blocked":"ai_provider_error"}function Zfe(t,e){if(t instanceof fr.APIError){let r={status:t.status};return e&&(r.model=e),t.code!=null&&(r.openrouterCode=t.code),t.type!=null&&(r.openrouterType=t.type),t instanceof fr.APIUserAbortError?{code:"ai_aborted",message:t.message,cause:t,meta:r}:t instanceof fr.APIConnectionTimeoutError?{code:"ai_timeout",message:t.message,cause:t,meta:r}:t instanceof fr.APIConnectionError?{code:"ai_network_error",message:t.message,cause:t,meta:r}:{code:t.status!=null?Vfe(t.status):"ai_provider_error",message:t.message,cause:t,meta:r}}return{code:"ai_network_error",message:t instanceof Error?t.message:String(t),cause:t}}var zg=be(nre(),1),y5e=be(E5e(),1);var m5e=be(nre()),O1t=".r2.cloudflarestorage.com";function sre(t){return new m5e.S3Client({endpoint:t.endpoint,region:t.region??H1t(t.endpoint),forcePathStyle:!0,credentials:{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}})}function H1t(t){return J1t(t)?"auto":"us-east-1"}function J1t(t){let e=Y1t(t);return e!==void 0&&e.endsWith(O1t)}function Y1t(t){try{return new URL(t).hostname}catch{return}}var K1t=3600,m6=class{constructor(e,r){this._resolved=e;this._s3=null;this._gate=r??nA("storage",e)}from(e){return new ore(e,()=>this.settings(),this._gate)}settings(){let e=this._resolved.s3AccessKeyId,r=this._resolved.s3SecretAccessKey,i=this._resolved.s3Endpoint,n=this._resolved.s3Bucket,A=this._resolved.agentId,s=this._resolved.s3Region;return!e||!r||!i?et({code:"s3_credentials_missing",message:q1t}):n?A?(this._s3??=sre({endpoint:i,region:s,accessKeyId:e,secretAccessKey:r}),nr({client:this._s3,endpoint:i,bucket:n,agentId:A})):et({code:"agent_id_missing",message:j1t}):et({code:"s3_bucket_missing",message:$1t})}},ore=class{constructor(e,r,i){this.bucketName=e;this.resolveSettings=r;this.gate=i}async upload(e,r,i){return zi(this.gate,async()=>{let n=this.resolve(e);if(n.error)return et(n.error);let{client:A,bucket:s,fullKey:o}=n.data;try{let a=await A.send(new zg.PutObjectCommand({Bucket:s,Key:o,Body:r,ContentType:i?.contentType,Metadata:i?.metadata})),c=Q5e(a.ETag);return nr(c===void 0?{key:e}:{key:e,etag:c})}catch(a){return et(aS("Upload failed",a))}})}async download(e){return zi(this.gate,async()=>{let r=this.resolve(e);if(r.error)return et(r.error);let{client:i,bucket:n,fullKey:A}=r.data;try{let s=await i.send(new zg.GetObjectCommand({Bucket:n,Key:A})),o=s.Body;if(!o)return et({code:"s3_empty_response",message:`S3 returned an empty body for ${A}`});let a=await o.transformToByteArray();return nr(new Blob([a],{type:s.ContentType??"application/octet-stream"}))}catch(s){return et(aS("Download failed",s))}})}async list(e){return zi(this.gate,async()=>{let r=this.resolve(e?.prefix??"");if(r.error)return et(r.error);let{client:i,bucket:n,agentId:A,fullKey:s}=r.data,o=e?.limit;if(o!==void 0&&o<=0)return et({code:"s3_invalid_argument",message:"`limit` must be a positive integer"});try{let a=await i.send(new zg.ListObjectsV2Command({Bucket:n,Prefix:s,...o!==void 0?{MaxKeys:o}:{},...e?.cursor?{ContinuationToken:e.cursor}:{}})),c=`${A}/${this.bucketName}/`,l=(a.Contents??[]).map(I=>{let C={key:I.Key?.startsWith(c)?I.Key.slice(c.length):I.Key??"",size:I.Size??0};I.LastModified&&(C.lastModified=I.LastModified);let p=Q5e(I.ETag);return p&&(C.etag=p),C}),u=a.IsTruncated&&a.NextContinuationToken?a.NextContinuationToken:void 0;return nr(u===void 0?{objects:l}:{objects:l,nextCursor:u})}catch(a){return et(aS("List failed",a))}})}async remove(e){return zi(this.gate,async()=>{let r=this.resolve(e);if(r.error)return et(r.error);let{client:i,bucket:n,fullKey:A}=r.data;try{return await i.send(new zg.DeleteObjectCommand({Bucket:n,Key:A})),nr({key:e})}catch(s){return et(aS("Delete failed",s))}})}getPublicUrl(e){let r=this.resolve(e);if(r.error)return et(r.error);let{endpoint:i,bucket:n,fullKey:A}=r.data,s=i.replace(/\/+$/,"");return nr(`${s}/${n}/${z1t(A)}`)}async getSignedUploadUrl(e,r){return this.signUrl(e,r,"Signing upload URL failed",({bucket:i,fullKey:n})=>new zg.PutObjectCommand({Bucket:i,Key:n,ContentType:r?.contentType}))}async getSignedDownloadUrl(e,r){return this.signUrl(e,r,"Signing download URL failed",({bucket:i,fullKey:n})=>new zg.GetObjectCommand({Bucket:i,Key:n}))}async signUrl(e,r,i,n){return zi(this.gate,async()=>{let A=this.resolve(e);if(A.error)return et(A.error);let{client:s,bucket:o,fullKey:a}=A.data,c=r?.expiresIn??K1t;try{let l=await(0,y5e.getSignedUrl)(s,n({bucket:o,fullKey:a}),{expiresIn:c});return nr({url:l,expiresAt:new Date(Date.now()+c*1e3)})}catch(l){return et(aS(i,l))}})}resolve(e){let r=this.resolveSettings();if(r.error)return et(r.error);let i=e.replace(/^\/+/,"");if(/(^|\/)\.\.(\/|$)/.test(i))return et({code:"s3_invalid_key",message:`Invalid storage key: path traversal segments are not allowed (received "${e}")`});let{agentId:n}=r.data,A=i?`${n}/${this.bucketName}/${i}`:`${n}/${this.bucketName}/`;return nr({...r.data,fullKey:A})}},q1t="Cannot reach object storage \u2014 set `STACKBONE_S3_ACCESS_KEY`, `STACKBONE_S3_SECRET_KEY`, and `STACKBONE_S3_ENDPOINT` in the container or pass `s3` to `createClient({...})`.",$1t="No storage bucket configured \u2014 set `STACKBONE_S3_BUCKET` in the container or pass `s3.bucket` to `createClient({...})`.",j1t="No agent identity configured \u2014 set `STACKBONE_AGENT_ID` in the container or pass `agentId` to `createClient({...})`.";function Q5e(t){return t?.replace(/^"|"$/g,"")}function z1t(t){return t.split("/").map(encodeURIComponent).join("/")}function aS(t,e){if(e instanceof Error){let r=e,i={name:r.name};return r.$metadata?.httpStatusCode!==void 0&&(i.httpStatusCode=r.$metadata.httpStatusCode),r.$fault&&(i.fault=r.$fault),{code:"s3_error",message:`${t}: ${e.message}`,cause:e,meta:i}}return{code:"s3_error",message:t,cause:e}}var w5e="api/v1/agent/connections",S5e={prefix:"connections",overrides:{409:"connections_ambiguous"}},Q6=class{constructor(e,r,i){this._http=r;this._gate=i??nA("connections",e)}async list(){return zi(this._gate,async()=>this._http.request({method:"GET",path:`${w5e}`,responseSchema:YU,errorMapping:S5e}))}async invoke(e,r,i,n){return zi(this._gate,async()=>{let A={connector:e,action:r,args:i};return n?.connection!==void 0&&(A.connection=n.connection),this._http.request({method:"POST",path:`${w5e}/invoke`,body:A,responseSchema:KU,errorMapping:S5e})})}};var y6=class{constructor(e){}async add(e,r){return ng("memory.add")}async search(e,r){return ng("memory.search")}async delete(e){return ng("memory.delete")}async deleteAll(e){return ng("memory.deleteAll")}async get(e){return ng("memory.get")}async list(e){return ng("memory.list")}async update(e,r){return ng("memory.update")}async history(e){return ng("memory.history")}async endSession(e,r){return ng("memory.endSession")}};var w6="api/v1/agent/queues",S6={prefix:"queues"},b6=class{constructor(e,r,i){this._http=r;this._gate=i??nA("queues",e)}async publish(e){return zi(this._gate,async()=>{let r={name:e.name,payload:e.payload};return e.retries!==void 0&&(r.retries=e.retries),e.delay!==void 0&&(r.delay=e.delay),e.deduplicationId!==void 0&&(r.deduplicationId=e.deduplicationId),this._http.request({method:"POST",path:`${w6}/publish`,body:r,responseSchema:xG,errorMapping:S6})})}async schedule(e){return zi(this._gate,async()=>{let r={name:e.name,payload:e.payload,cron:e.cron};return e.tz!==void 0&&(r.tz=e.tz),e.retries!==void 0&&(r.retries=e.retries),this._http.request({method:"POST",path:`${w6}/schedule`,body:r,responseSchema:RG,errorMapping:S6})})}async unschedule(e){return zi(this._gate,async()=>this._http.request({method:"POST",path:`${w6}/unschedule`,body:{name:e.name},responseSchema:FG,errorMapping:S6}))}async listSchedules(){return zi(this._gate,async()=>this._http.request({method:"GET",path:`${w6}/schedules`,responseSchema:NG,errorMapping:S6}))}};var D6=class{constructor(e){this.resolved=e;this._contractStore=DD(e)}http(){return this._httpClient??=new kD(this.resolved),this._httpClient}get database(){return this._database??=new hk(this.resolved,nA("database",this.resolved,this._contractStore)),this._database}get storage(){return this._storage??=new m6(this.resolved,nA("storage",this.resolved,this._contractStore)),this._storage}get ai(){return this._ai??=new B9(this.resolved,void 0,nA("ai",this.resolved,this._contractStore)),this._ai}get rag(){return this._rag??=new L3(this.resolved,()=>this.database,()=>this.ai,nA("rag",this.resolved,this._contractStore)),this._rag}get approval(){return this._approval??=new _D(this.resolved,()=>this.database),this._approval}get secrets(){return this._secrets??=new J3(this.resolved,()=>this.database),this._secrets}get config(){return this._config??=new vD(this.resolved,()=>this.database),this._config}get queues(){return this._queues??=new b6(this.resolved,this.http(),nA("queues",this.resolved,this._contractStore)),this._queues}get connections(){return this._connections??=new Q6(this.resolved,this.http(),nA("connections",this.resolved,this._contractStore)),this._connections}get memory(){return this._memory??=new y6(this.resolved),this._memory}get prompts(){return this._prompts??=new dk(this.resolved,()=>this.database),this._prompts}get contract(){return this._contractStore.peek(this.resolved.stackboneApiUrl)}};function are(t={}){return new D6(pS(t))}var cre=["invoke"];import{AsyncLocalStorage as W1t}from"node:async_hooks";var V1t=new W1t;function gre(t,e){return V1t.run(t,e)}var b5e={AWS_ACCESS_KEY_ID:"STACKBONE_S3_ACCESS_KEY",AWS_SECRET_ACCESS_KEY:"STACKBONE_S3_SECRET_KEY",S3_ENDPOINT:"STACKBONE_S3_ENDPOINT",S3_BUCKET:"STACKBONE_S3_BUCKET",S3_REGION:"STACKBONE_S3_REGION",OPENROUTER_API_KEY:"OPENROUTER_API_KEY",OPENROUTER_BASE_URL:"OPENROUTER_BASE_URL",AXIOM_TOKEN:"AXIOM_TOKEN"};function D5e(t,e,r,i){let n=[],A=(o,a)=>{t[o]===void 0&&(t[o]=a,n.push(o))};for(let o of e){let a=b5e[o.name];a&&A(a,r.decrypt({version:o.version,nonce:o.nonce,ciphertext:o.ciphertext}))}A("STACKBONE_POSTGRES_URL",i);let s=t.HMAC_SECRET;return s&&A("STACKBONE_APPROVAL_SIGNING_KEY",s),n.sort()}var Z1t=`
410
+ `)){let C=d.indexOf(":");C>=0&&(I[d.substring(0,C).trim()]=d.substring(C+1).trim())}c.defaultHeaders=vt([I,c.defaultHeaders])}this._options=c,o&&(this._workloadIdentityAuth=new Z3(o,this.fetch)),this.apiKey=typeof r=="string"?r:null,this.adminAPIKey=i,this.organization=n,this.project=A,this.webhookSecret=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&i.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return vt([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return vt([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return vt([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return vt([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return gfe(e)}getUserAgent(){return`${this.constructor.name}/JS ${kh}`}defaultIdempotencyKey(){return`stainless-node-retry-${T$()}`}makeStatusError(e,r,i,n){return vn.generate(e,r,i,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(i){throw i instanceof zt?i:new zt(`Failed to get token from 'apiKey' function: ${i.message}`,{cause:i})}if(typeof r!="string"||!r)throw new zt(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,i){let n=!$e(this,Qj,"m",zfe).call(this)&&i||this.baseURL,A=KCe(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),o=Object.fromEntries(A.searchParams);return(!O$(s)||!O$(o))&&(r={...o,...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(A.search=this.stringifyQuery(r)),A.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:i}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,i){return this.request(Promise.resolve(i).then(n=>({method:e,path:r,...n})))}request(e,r=null){return new Kd(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,i){let n=await e,A=n.maxRetries??this.maxRetries;r==null&&(r=A),await this.prepareOptions(n);let{req:s,url:o,timeout:a}=await this.buildRequest(n,{retryCount:A-r});await this.prepareRequest(s,{url:o,options:n});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=i===void 0?"":`, retryOf: ${i}`,u=Date.now();if(Ln(this).debug(`[${c}] sending request`,Fl({retryOfRequestLogID:i,method:n.method,url:o,options:n,headers:s.headers})),n.signal?.aborted)throw new jn;let I=n.__security??{bearerAuth:!0},d=new AbortController,C=await this.fetchWithAuth(o,s,a,d,I).catch(hy),p=Date.now();if(C instanceof globalThis.Error){let S=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new jn;let k=uy(C)||/timed? ?out/i.test(String(C)+("cause"in C?String(C.cause):""));if(r)return Ln(this).info(`[${c}] connection ${k?"timed out":"failed"} - ${S}`),Ln(this).debug(`[${c}] connection ${k?"timed out":"failed"} (${S})`,Fl({retryOfRequestLogID:i,url:o,durationMs:p-u,message:C.message})),this.retryRequest(n,r,i??c);throw Ln(this).info(`[${c}] connection ${k?"timed out":"failed"} - error; no more retries left`),Ln(this).debug(`[${c}] connection ${k?"timed out":"failed"} (error; no more retries left)`,Fl({retryOfRequestLogID:i,url:o,durationMs:p-u,message:C.message})),C instanceof Jd||C instanceof Iy?C:k?new Dh:new bh({message:tje(C),cause:C})}let Q=[...C.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,k])=>", "+S+": "+JSON.stringify(k)).join(""),y=`[${c}${l}${Q}] ${s.method} ${o} ${C.ok?"succeeded":"failed"} with status ${C.status} in ${p-u}ms`;if(!C.ok){if(C.status===401&&this._workloadIdentityAuth&&I.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Y$(C.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},r,i??c);let S=await this.shouldRetry(C);if(r&&S){let $=`retrying, ${r} attempts remaining`;return await Y$(C.body),Ln(this).info(`${y} - ${$}`),Ln(this).debug(`[${c}] response error (${$})`,Fl({retryOfRequestLogID:i,url:C.url,status:C.status,headers:C.headers,durationMs:p-u})),this.retryRequest(n,r,i??c,C.headers)}let k=S?"error; no more retries left":"error; not retryable";Ln(this).info(`${y} - ${k}`);let x=await C.text().catch($=>hy($).message),U=jCe(x),T=U?void 0:x;throw Ln(this).debug(`[${c}] response error (${k})`,Fl({retryOfRequestLogID:i,url:C.url,status:C.status,headers:C.headers,message:T,durationMs:Date.now()-u})),this.makeStatusError(C.status,U,T,C.headers)}return Ln(this).info(y),Ln(this).debug(`[${c}] response start`,Fl({retryOfRequestLogID:i,url:C.url,status:C.status,headers:C.headers,durationMs:p-u})),{response:C,options:n,controller:d,requestLogID:c,retryOfRequestLogID:i,startTime:u}}getAPIList(e,r,i){return this.requestAPIList(r,i&&"then"in i?i.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...i})}requestAPIList(e,r){let i=this.makeRequest(r,null,void 0);return new By(this,i,e)}async fetchWithAuth(e,r,i,n,A={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&A.bearerAuth){let o=r.headers,a=o.get("Authorization");if(!a||a===`Bearer ${eje}`){let c=await this._workloadIdentityAuth.getToken();o.set("Authorization",`Bearer ${c}`)}}return await this.fetchWithTimeout(e,r,i,n)}async fetchWithTimeout(e,r,i,n){let{signal:A,method:s,...o}=r||{},a=this._makeAbort(n);A&&A.addEventListener("abort",a,{once:!0});let c=setTimeout(a,i),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:n.signal,...l?{duplex:"half"}:{},method:"GET",...o};s&&(u.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,i,n){let A,s=n?.get("retry-after-ms");if(s){let a=parseFloat(s);Number.isNaN(a)||(A=a)}let o=n?.get("retry-after");if(o&&!A){let a=parseFloat(o);Number.isNaN(a)?A=Date.parse(o)-Date.now():A=a*1e3}if(A===void 0){let a=e.maxRetries??this.maxRetries;A=this.calculateDefaultRetryTimeoutMillis(r,a)}return await wg(A),this.makeRequest(e,r-1,i)}calculateDefaultRetryTimeoutMillis(e,r){let A=r-e,s=Math.min(.5*Math.pow(2,A),8),o=1-Math.random()*.25;return s*o*1e3}async buildRequest(e,{retryCount:r=0}={}){let i={...e},{method:n,path:A,query:s,defaultBaseURL:o}=i,a=this.buildURL(A,s,o);"timeout"in i&&$Ce("timeout",i.timeout),i.timeout=i.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:i});u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let I=await this.buildHeaders({options:e,method:n,bodyHeaders:c,retryCount:r});return{req:{method:n,headers:I,...i.signal&&{signal:i.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...i.fetchOptions??{}},url:a,timeout:i.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:i,retryCount:n}){let A={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),A[this.idempotencyHeader]=e.idempotencyKey);let s=vt([A,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...XCe(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,i,e.headers]);return this.validateHeaders(s,e.__security??{bearerAuth:!0}),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let i=vt([r]),n=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,A=!n&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&i.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||n?{bodyHeaders:void 0,body:e,isStreamingBody:!A}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:q3(e),isStreamingBody:!0}:typeof e=="object"&&i.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{...$e(this,p9,"f").call(this,{body:e,headers:i}),isStreamingBody:!1}}};yj=fr,p9=new WeakMap,Qj=new WeakSet,zfe=function(){return this.baseURL!=="https://api.openai.com/v1"};fr.OpenAI=yj;fr.DEFAULT_TIMEOUT=6e5;fr.OpenAIError=zt;fr.APIError=vn;fr.APIConnectionError=bh;fr.APIConnectionTimeoutError=Dh;fr.APIUserAbortError=jn;fr.NotFoundError=dB;fr.ConflictError=CB;fr.RateLimitError=pB;fr.BadRequestError=uB;fr.AuthenticationError=hB;fr.InternalServerError=BB;fr.PermissionDeniedError=IB;fr.UnprocessableEntityError=fB;fr.InvalidWebhookSignatureError=yg;fr.toFile=e9;fr.Completions=iC;fr.Chat=Rh;fr.Embeddings=AC;fr.Files=oC;fr.Images=lC;fr.Audio=Dg;fr.Moderations=hC;fr.Models=uC;fr.FineTuning=_c;fr.Graders=Oh;fr.VectorStores=Ll;fr.Webhooks=CC;fr.Beta=kc;fr.Batches=Zd;fr.Uploads=Jh;fr.Admin=Nh;fr.Responses=_g;fr.Realtime=Pl;fr.Conversations=Th;fr.Evals=Lh;fr.Containers=Ph;fr.Skills=Tl;fr.Videos=dC;function tje(t){if(rje(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function rje(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let i=e;if(i.code==="UND_ERR_INVALID_ARG"&&typeof i.message=="string"&&i.message.includes("invalid onRequestStart method"))return!0;e=i.cause}return!1}var B9=class{constructor(e,r,i){this._resolved=e;this._openai=null;this._chat=null;this._embeddings=null;this._images=null;this._models=null;r&&(this._openai=r),this._gate=i??nA("ai",e)}get chat(){return this._chat??={completions:new wj(()=>this.shared(),this._gate)},this._chat}get embeddings(){return this._embeddings??=new Sj(()=>this.shared(),this._gate),this._embeddings}get images(){return this._images??=new bj(()=>this.shared(),this._gate),this._images}get models(){return this._models??=new Dj(()=>this.shared(),this._gate),this._models}shared(){if(this._openai)return nr(this._openai);let e=sje(this._resolved);return e?(this._openai=new fr({apiKey:e,baseURL:oje(this._resolved),defaultHeaders:Wfe}),nr(this._openai)):Aje()}},wj=class{constructor(e,r){this._getClient=e;this._gate=r}async create(e,r){return zi(this._gate,async()=>kj(this._getClient,e.model,i=>i.chat.completions.create(e,{signal:r?.signal})))}},Sj=class{constructor(e,r){this._getClient=e;this._gate=r}async create(e,r){return zi(this._gate,async()=>{let i=typeof e.model=="string"?e.model:void 0;return kj(this._getClient,i,n=>n.embeddings.create(e,{signal:r?.signal}))})}},bj=class{constructor(e,r){this._getClient=e;this._gate=r}async generate(e,r){return zi(this._gate,async()=>{let i={model:e.model,messages:[{role:"user",content:e.prompt}],modalities:["image","text"],...e.imageConfig?{image_config:e.imageConfig}:{}},n=await kj(this._getClient,e.model,s=>s.chat.completions.create(i,{signal:r?.signal}));if(n.error)return n;let A=cje(n.data);return A.length===0?et({code:"ai_no_image_generated",message:`Model ${e.model} did not return any images. Make sure the model supports image output via OpenRouter.`,meta:{model:e.model}}):nr({created:n.data.created,data:A})})}},Dj=class{constructor(e,r){this._getClient=e;this._gate=r}async list(e){return zi(this._gate,async()=>{let r=this._getClient();if(r.error)return r;let{apiKey:i,baseURL:n}=r.data,A=n.replace(/\/+$/,""),s={headers:{Authorization:`Bearer ${i}`,...Wfe}};e?.signal&&(s.signal=e.signal);try{let o=await fetch(`${A}/models`,s);if(!o.ok){let c=await o.json().catch(()=>({}));return et({code:Vfe(o.status),message:c.error?.message??`HTTP ${o.status}`,meta:{status:o.status}})}let a=await o.json();return nr(a)}catch(o){return et(Zfe(o))}})}},Wfe={"HTTP-Referer":"https://stackbone.ai","X-Title":"Stackbone Agent Platform"},ije="https://openrouter.ai/api/v1",nje="Cannot reach OpenRouter \u2014 set `OPENROUTER_API_KEY` in the container or pass `openrouterKey` to `createClient({...})`.";function Aje(){return et({code:"openrouter_key_missing",message:nje})}function sje(t){return t.openrouterKey}function oje(t){return t.openrouterBaseUrl??ije}async function kj(t,e,r){let i=t();if(i.error)return i;try{return nr(await r(i.data))}catch(n){return et(Zfe(n,e))}}var aje=/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.*)$/;function cje(t){let r=t.choices[0]?.message?.images??[],i=[];for(let n of r){let A=n?.image_url?.url;if(!A)continue;let s=aje.exec(A);s&&s[1]&&s[2]?i.push({url:A,mimeType:s[1],b64Json:s[2]}):i.push({url:A})}return i}function Vfe(t){return t===401?"ai_unauthorized":t===402?"ai_credits_exhausted":t===403?"ai_forbidden":t===408?"ai_timeout":t===422||t===400?"ai_validation_error":t===429?"ai_rate_limited":t===451?"ai_moderation_blocked":"ai_provider_error"}function Zfe(t,e){if(t instanceof fr.APIError){let r={status:t.status};return e&&(r.model=e),t.code!=null&&(r.openrouterCode=t.code),t.type!=null&&(r.openrouterType=t.type),t instanceof fr.APIUserAbortError?{code:"ai_aborted",message:t.message,cause:t,meta:r}:t instanceof fr.APIConnectionTimeoutError?{code:"ai_timeout",message:t.message,cause:t,meta:r}:t instanceof fr.APIConnectionError?{code:"ai_network_error",message:t.message,cause:t,meta:r}:{code:t.status!=null?Vfe(t.status):"ai_provider_error",message:t.message,cause:t,meta:r}}return{code:"ai_network_error",message:t instanceof Error?t.message:String(t),cause:t}}var zg=be(nre(),1),y5e=be(E5e(),1);var m5e=be(nre()),O1t=".r2.cloudflarestorage.com";function sre(t){return new m5e.S3Client({endpoint:t.endpoint,region:t.region??H1t(t.endpoint),forcePathStyle:!0,credentials:{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey}})}function H1t(t){return J1t(t)?"auto":"us-east-1"}function J1t(t){let e=Y1t(t);return e!==void 0&&e.endsWith(O1t)}function Y1t(t){try{return new URL(t).hostname}catch{return}}var K1t=3600,m6=class{constructor(e,r){this._resolved=e;this._s3=null;this._gate=r??nA("storage",e)}from(e){return new ore(e,()=>this.settings(),this._gate)}settings(){let e=this._resolved.s3AccessKeyId,r=this._resolved.s3SecretAccessKey,i=this._resolved.s3Endpoint,n=this._resolved.s3Bucket,A=this._resolved.agentId,s=this._resolved.s3Region;return!e||!r||!i?et({code:"s3_credentials_missing",message:q1t}):n?A?(this._s3??=sre({endpoint:i,region:s,accessKeyId:e,secretAccessKey:r}),nr({client:this._s3,endpoint:i,bucket:n,agentId:A})):et({code:"agent_id_missing",message:j1t}):et({code:"s3_bucket_missing",message:$1t})}},ore=class{constructor(e,r,i){this.bucketName=e;this.resolveSettings=r;this.gate=i}async upload(e,r,i){return zi(this.gate,async()=>{let n=this.resolve(e);if(n.error)return et(n.error);let{client:A,bucket:s,fullKey:o}=n.data;try{let a=await A.send(new zg.PutObjectCommand({Bucket:s,Key:o,Body:r,ContentType:i?.contentType,Metadata:i?.metadata})),c=Q5e(a.ETag);return nr(c===void 0?{key:e}:{key:e,etag:c})}catch(a){return et(aS("Upload failed",a))}})}async download(e){return zi(this.gate,async()=>{let r=this.resolve(e);if(r.error)return et(r.error);let{client:i,bucket:n,fullKey:A}=r.data;try{let s=await i.send(new zg.GetObjectCommand({Bucket:n,Key:A})),o=s.Body;if(!o)return et({code:"s3_empty_response",message:`S3 returned an empty body for ${A}`});let a=await o.transformToByteArray();return nr(new Blob([a],{type:s.ContentType??"application/octet-stream"}))}catch(s){return et(aS("Download failed",s))}})}async list(e){return zi(this.gate,async()=>{let r=this.resolve(e?.prefix??"");if(r.error)return et(r.error);let{client:i,bucket:n,agentId:A,fullKey:s}=r.data,o=e?.limit;if(o!==void 0&&o<=0)return et({code:"s3_invalid_argument",message:"`limit` must be a positive integer"});try{let a=await i.send(new zg.ListObjectsV2Command({Bucket:n,Prefix:s,...o!==void 0?{MaxKeys:o}:{},...e?.cursor?{ContinuationToken:e.cursor}:{}})),c=`${A}/${this.bucketName}/`,l=(a.Contents??[]).map(I=>{let C={key:I.Key?.startsWith(c)?I.Key.slice(c.length):I.Key??"",size:I.Size??0};I.LastModified&&(C.lastModified=I.LastModified);let p=Q5e(I.ETag);return p&&(C.etag=p),C}),u=a.IsTruncated&&a.NextContinuationToken?a.NextContinuationToken:void 0;return nr(u===void 0?{objects:l}:{objects:l,nextCursor:u})}catch(a){return et(aS("List failed",a))}})}async remove(e){return zi(this.gate,async()=>{let r=this.resolve(e);if(r.error)return et(r.error);let{client:i,bucket:n,fullKey:A}=r.data;try{return await i.send(new zg.DeleteObjectCommand({Bucket:n,Key:A})),nr({key:e})}catch(s){return et(aS("Delete failed",s))}})}getPublicUrl(e){let r=this.resolve(e);if(r.error)return et(r.error);let{endpoint:i,bucket:n,fullKey:A}=r.data,s=i.replace(/\/+$/,"");return nr(`${s}/${n}/${z1t(A)}`)}async getSignedUploadUrl(e,r){return this.signUrl(e,r,"Signing upload URL failed",({bucket:i,fullKey:n})=>new zg.PutObjectCommand({Bucket:i,Key:n,ContentType:r?.contentType}))}async getSignedDownloadUrl(e,r){return this.signUrl(e,r,"Signing download URL failed",({bucket:i,fullKey:n})=>new zg.GetObjectCommand({Bucket:i,Key:n}))}async signUrl(e,r,i,n){return zi(this.gate,async()=>{let A=this.resolve(e);if(A.error)return et(A.error);let{client:s,bucket:o,fullKey:a}=A.data,c=r?.expiresIn??K1t;try{let l=await(0,y5e.getSignedUrl)(s,n({bucket:o,fullKey:a}),{expiresIn:c});return nr({url:l,expiresAt:new Date(Date.now()+c*1e3)})}catch(l){return et(aS(i,l))}})}resolve(e){let r=this.resolveSettings();if(r.error)return et(r.error);let i=e.replace(/^\/+/,"");if(/(^|\/)\.\.(\/|$)/.test(i))return et({code:"s3_invalid_key",message:`Invalid storage key: path traversal segments are not allowed (received "${e}")`});let{agentId:n}=r.data,A=i?`${n}/${this.bucketName}/${i}`:`${n}/${this.bucketName}/`;return nr({...r.data,fullKey:A})}},q1t="Cannot reach object storage \u2014 set `STACKBONE_S3_ACCESS_KEY`, `STACKBONE_S3_SECRET_KEY`, and `STACKBONE_S3_ENDPOINT` in the container or pass `s3` to `createClient({...})`.",$1t="No storage bucket configured \u2014 set `STACKBONE_S3_BUCKET` in the container or pass `s3.bucket` to `createClient({...})`.",j1t="No agent identity configured \u2014 set `STACKBONE_AGENT_ID` in the container or pass `agentId` to `createClient({...})`.";function Q5e(t){return t?.replace(/^"|"$/g,"")}function z1t(t){return t.split("/").map(encodeURIComponent).join("/")}function aS(t,e){if(e instanceof Error){let r=e,i={name:r.name};return r.$metadata?.httpStatusCode!==void 0&&(i.httpStatusCode=r.$metadata.httpStatusCode),r.$fault&&(i.fault=r.$fault),{code:"s3_error",message:`${t}: ${e.message}`,cause:e,meta:i}}return{code:"s3_error",message:t,cause:e}}var w5e="api/v1/agent/connections",S5e={prefix:"connections",overrides:{409:"connections_ambiguous"}},Q6=class{constructor(e,r,i){this._http=r;this._gate=i??nA("connections",e)}async list(){return zi(this._gate,async()=>this._http.request({method:"GET",path:`${w5e}`,responseSchema:YU,errorMapping:S5e}))}async invoke(e,r,i,n){return zi(this._gate,async()=>{let A={connector:e,action:r,args:i};return n?.connection!==void 0&&(A.connection=n.connection),this._http.request({method:"POST",path:`${w5e}/invoke`,body:A,responseSchema:KU,errorMapping:S5e})})}};var y6=class{constructor(e){}async add(e,r){return ng("memory.add")}async search(e,r){return ng("memory.search")}async delete(e){return ng("memory.delete")}async deleteAll(e){return ng("memory.deleteAll")}async get(e){return ng("memory.get")}async list(e){return ng("memory.list")}async update(e,r){return ng("memory.update")}async history(e){return ng("memory.history")}async endSession(e,r){return ng("memory.endSession")}};var w6="api/v1/agent/queues",S6={prefix:"queues"},b6=class{constructor(e,r,i){this._http=r;this._gate=i??nA("queues",e)}async publish(e){return zi(this._gate,async()=>{let r={name:e.name,payload:e.payload};return e.retries!==void 0&&(r.retries=e.retries),e.delay!==void 0&&(r.delay=e.delay),e.deduplicationId!==void 0&&(r.deduplicationId=e.deduplicationId),this._http.request({method:"POST",path:`${w6}/publish`,body:r,responseSchema:xG,errorMapping:S6})})}async schedule(e){return zi(this._gate,async()=>{let r={name:e.name,payload:e.payload,cron:e.cron};return e.tz!==void 0&&(r.tz=e.tz),e.retries!==void 0&&(r.retries=e.retries),this._http.request({method:"POST",path:`${w6}/schedule`,body:r,responseSchema:RG,errorMapping:S6})})}async unschedule(e){return zi(this._gate,async()=>this._http.request({method:"POST",path:`${w6}/unschedule`,body:{name:e.name},responseSchema:FG,errorMapping:S6}))}async listSchedules(){return zi(this._gate,async()=>this._http.request({method:"GET",path:`${w6}/schedules`,responseSchema:NG,errorMapping:S6}))}};var D6=class{constructor(e){this.resolved=e;this._contractStore=DD(e)}http(){return this._httpClient??=new kD(this.resolved),this._httpClient}get database(){return this._database??=new hk(this.resolved,nA("database",this.resolved,this._contractStore)),this._database}get storage(){return this._storage??=new m6(this.resolved,nA("storage",this.resolved,this._contractStore)),this._storage}get ai(){return this._ai??=new B9(this.resolved,void 0,nA("ai",this.resolved,this._contractStore)),this._ai}get rag(){return this._rag??=new L3(this.resolved,()=>this.database,()=>this.ai,nA("rag",this.resolved,this._contractStore)),this._rag}get approval(){return this._approval??=new _D(this.resolved,()=>this.database),this._approval}get secrets(){return this._secrets??=new J3(this.resolved,()=>this.database),this._secrets}get config(){return this._config??=new vD(this.resolved,()=>this.database),this._config}get queues(){return this._queues??=new b6(this.resolved,this.http(),nA("queues",this.resolved,this._contractStore)),this._queues}get connections(){return this._connections??=new Q6(this.resolved,this.http(),nA("connections",this.resolved,this._contractStore)),this._connections}get memory(){return this._memory??=new y6(this.resolved),this._memory}get prompts(){return this._prompts??=new dk(this.resolved,()=>this.database),this._prompts}get contract(){return this._contractStore.peek(this.resolved.stackboneApiUrl)}};function are(t={}){return new D6(pS(t))}var cre=["invoke"];import{AsyncLocalStorage as W1t}from"node:async_hooks";var V1t=new W1t;function gre(t,e){return V1t.run(t,e)}var b5e={AWS_ACCESS_KEY_ID:"STACKBONE_S3_ACCESS_KEY",AWS_SECRET_ACCESS_KEY:"STACKBONE_S3_SECRET_KEY",S3_ENDPOINT:"STACKBONE_S3_ENDPOINT",S3_BUCKET:"STACKBONE_S3_BUCKET",S3_REGION:"STACKBONE_S3_REGION",OPENROUTER_API_KEY:"OPENROUTER_API_KEY",OPENROUTER_BASE_URL:"OPENROUTER_BASE_URL"};function D5e(t,e,r,i){let n=[],A=(o,a)=>{t[o]===void 0&&(t[o]=a,n.push(o))};for(let o of e){let a=b5e[o.name];a&&A(a,r.decrypt({version:o.version,nonce:o.nonce,ciphertext:o.ciphertext}))}A("STACKBONE_POSTGRES_URL",i);let s=t.HMAC_SECRET;return s&&A("STACKBONE_APPROVAL_SIGNING_KEY",s),n.sort()}var Z1t=`
411
411
  SELECT name, version, nonce, ciphertext
412
412
  FROM stackbone_platform.secrets
413
413
  WHERE is_system = true
Binary file
Binary file