@urun-sh/openai 0.5.4 → 0.5.6
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/{ResponsesClient-BYx3YLGo.d.ts → ResponsesClient-BE3-hx3m.d.ts} +2 -0
- package/dist/{ResponsesClient-Dft3bg3b.d.cts → ResponsesClient-DjZWjlFH.d.cts} +2 -0
- package/dist/chunk-2T2YYBVX.js +1 -0
- package/dist/chunk-3WAJD62J.js +4 -0
- package/dist/{chunk-K23AZPI4.js → chunk-5HKWNK3O.js} +1 -1
- package/dist/chunk-7M6LY6DR.js +2 -0
- package/dist/chunk-BSHT6RZZ.js +1 -0
- package/dist/{chunk-GBBY3PCZ.js → chunk-FP4RSAIE.js} +1 -1
- package/dist/chunk-HR5H6S7L.js +1 -0
- package/dist/chunk-NY23USZF.js +57 -0
- package/dist/chunk-VLRMJRLS.js +6 -0
- package/dist/gemini-live.cjs +2 -2
- package/dist/gemini-live.d.cts +17 -2
- package/dist/gemini-live.d.ts +7 -2
- package/dist/gemini-live.js +1 -1
- package/dist/hosted/bin.cjs +65 -37
- package/dist/hosted/bin.js +3 -3
- package/dist/hosted/index.cjs +46 -19
- package/dist/hosted/index.d.cts +760 -272
- package/dist/hosted/index.d.ts +203 -107
- package/dist/hosted/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/{models-NYMZrklp.d.cts → models-DUdx_Y6X.d.cts} +1 -1
- package/dist/pi-extension/index.cjs +7 -7
- package/dist/pi-extension/index.d.cts +1 -1
- package/dist/pi-extension/index.d.ts +1 -1
- package/dist/pi-extension/index.js +1 -1
- package/dist/pi-extension/standalone.cjs +48 -48
- package/dist/proxy/cli.cjs +54 -40
- package/dist/proxy/cli.js +14 -14
- package/dist/proxy/index.cjs +33 -22
- package/dist/proxy/index.d.cts +546 -4
- package/dist/proxy/index.d.ts +185 -4
- package/dist/proxy/index.js +1 -1
- package/dist/responses-turn-Dr37N3kH.d.ts +486 -0
- package/dist/responses-turn-tNUHq5b0.d.cts +1807 -0
- package/dist/{translator-C9uPKypK.d.ts → translator-BCoRFaTs.d.ts} +1 -1
- package/dist/{translator-CcDBEfvm.d.cts → translator-Bh0Bp_Ie.d.cts} +3 -3
- package/dist/{video-out-D20UuJ8G.d.cts → video-out-CCksIcj8.d.cts} +5 -5
- package/package.json +12 -11
- package/dist/chunk-4MSBS7M6.js +0 -1
- package/dist/chunk-5NXM4IO3.js +0 -2
- package/dist/chunk-CWJRDBDC.js +0 -1
- package/dist/chunk-OI2OY32M.js +0 -1
- package/dist/chunk-RQBD4OAA.js +0 -6
- package/dist/chunk-STFRT5OY.js +0 -1
- package/dist/chunk-VNM4M4P3.js +0 -40
- package/dist/server-DuH_5OD9.d.ts +0 -84
- package/dist/server-wmUnMewW.d.cts +0 -206
- /package/dist/{chunk-YSFSRI3D.js → chunk-5CCJUNH7.js} +0 -0
- /package/dist/{models-NYMZrklp.d.ts → models-DUdx_Y6X.d.ts} +0 -0
- /package/dist/{video-out-CWesbk12.d.ts → video-out-IGQ4YQ-c.d.ts} +0 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}catch(o){if(!
|
|
3
|
-
`)}catch{}}}}var
|
|
4
|
-
`)}}function
|
|
1
|
+
"use strict";var Me=Object.create;var F=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var De=(e,t)=>{for(var n in t)F(e,n,{get:t[n],enumerable:!0})},se=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Oe(t))!Le.call(e,r)&&r!==n&&F(e,r,{get:()=>t[r],enumerable:!(o=Ue(t,r))||o.enumerable});return e};var ie=(e,t,n)=>(n=e!=null?Me(Ne(e)):{},se(t||!e||!e.__esModule?F(n,"default",{value:e,enumerable:!0}):n,e)),Fe=e=>se(F({},"__esModule",{value:!0}),e);var mt={};De(mt,{SessionPool:()=>W,URUN_API:()=>ee,applyServeUsage:()=>Pe,coalesceSameRole:()=>$e,createFileDiagnosticSink:()=>be,createUrunExtension:()=>Ae,default:()=>gt,makeSessionFactory:()=>xe,makeStreamSimple:()=>Te,notify:()=>Z,piDiagnosticLogPath:()=>q,resolveSessionEnv:()=>Re,toResponsesInput:()=>Ee});module.exports=Fe(mt);var je=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,m=je();var ve=require("@earendil-works/pi-ai"),M=require("fs"),ke=require("path");function ae(e,t,n,o){let r=e.response??{},l={request_id:n,consumer_id:o,stream:!0,kind:"chat",messages:t};return typeof r.instructions=="string"&&(l.instructions=r.instructions),Array.isArray(r.modalities)&&(l.modalities=r.modalities),typeof r.temperature=="number"&&(l.temperature=r.temperature),typeof r.max_output_tokens=="number"&&(l.max_output_tokens=r.max_output_tokens),r.tools!==void 0&&(l.tools=r.tools),l}function le(e,t,n){let o={request_id:t,consumer_id:n,stream:!!e.stream,kind:"responses",input:e.input};return e.model&&(o.model=e.model),e.tools!==void 0&&(o.tools=e.tools),e.tool_choice!==void 0&&(o.tool_choice=e.tool_choice),typeof e.temperature=="number"&&(o.temperature=e.temperature),typeof e.max_output_tokens=="number"&&(o.max_output_tokens=e.max_output_tokens),typeof e.top_p=="number"&&(o.top_p=e.top_p),Array.isArray(e.stop)&&e.stop.length>0&&(o.stop=e.stop),typeof e.reasoning_effort=="string"&&(o.reasoning_effort=e.reasoning_effort),e.chat_template_kwargs!==void 0&&(o.chat_template_kwargs=e.chat_template_kwargs),e.response_format!==void 0&&(o.response_format=e.response_format),o}function ue(e){if(e instanceof Error)return{type:"error",error:{type:"urun_error",code:e.name||null,message:e.message}};if(e&&typeof e=="object"&&e.t==="error"){let t=e,n=t.body??{},o=n.error,r=o?.message??n.message??`unreadable serve error body: ${JSON.stringify(t.body??null)}`;return{type:"error",error:{type:o?.type??"urun_error",code:t.code??o?.code??null,message:r}}}return{type:"error",error:{type:"urun_error",code:null,message:String(e)}}}var Ke="llm-resp";async function*Y(e,t){let n=`${Ke}:${t}`,o=`resp_${t}`;yield{type:"response.created",response:{id:o,status:"in_progress"}};let r=new Map;for await(let l of e.stream(n).messages()){let i=l;if(i.t==="delta"){if(typeof i.delta=="string"&&(yield{type:"response.output_text.delta",item_id:o,delta:i.delta}),typeof i.reasoning=="string"&&(yield{type:"response.reasoning_text.delta",item_id:o,delta:i.reasoning}),Array.isArray(i.tool_calls))for(let u of i.tool_calls){let g=typeof u.index=="number"?u.index:0,a=r.get(g)??{};u.id&&(a.id=u.id),u.function?.name&&(a.name=u.function.name),r.set(g,a),yield{type:"response.function_call_arguments.delta",item_id:`fc_${t}_${g}`,tool_index:g,call_id:a.id,name:a.name,delta:u.function?.arguments??""}}}else if(i.t==="response"){yield{type:"response.completed",response:{id:o,status:"completed",...i.body}};return}else if(i.t==="error"){yield ue(i);return}}}var Je="llm",j=class{constructor(t){this.session=t;this.sessionTag=t.sessionId??globalThis.crypto.randomUUID()}session;sessionTag;get consumerId(){return this.session.consumerId}write(t){t.session_tag=this.sessionTag,this.session.doc(Je).set({requests:{[t.request_id]:{payload:t,consumer_id:t.consumer_id,stream:t.stream}}})}sendResponses(t,n){let o=le(t,n,this.consumerId);return this.write(o),Y(this.session,n)}sendResponseCreate(t,n,o){let r=ae(t,n,o,this.consumerId);return this.write(r),Y(this.session,o)}};var ce=0;function Be(){return ce+=1,`req_${Date.now().toString(36)}_${ce.toString(36)}`}var K=class{transport;constructor(t){this.transport=new j(t)}responses={create:async t=>{let n=Be(),o=this.transport.sendResponses(t,n);return Object.assign((async function*(){yield*o})(),{requestId:n})}}};var J=require("fs"),pe=ie(require("os"),1),B=require("path"),fe=require("util");function q(e=pe.default.homedir()){return(0,B.join)(e,".urun","logs","pi-extension.log")}var de=!1;function ge(e,t){let n=q();try{(0,J.mkdirSync)((0,B.dirname)(n),{recursive:!0}),(0,J.appendFileSync)(n,`${new Date().toISOString()} [console.${e}] [urun] ${(0,fe.format)(...t)}
|
|
2
|
+
`)}catch(o){if(!de){de=!0;try{process.stderr.write(`[urun] pi-extension quiet console: cannot write ${n} (${String(o)}); further urun-side console output will be dropped
|
|
3
|
+
`)}catch{}}}}var f=e=>(...t)=>ge(e,t),X={log:f("log"),info:f("info"),warn:f("warn"),error:f("error"),debug:f("debug"),trace:f("trace"),dir:f("dir"),table:f("table"),group:f("group"),groupCollapsed:f("groupCollapsed"),groupEnd:f("groupEnd"),count:f("count"),countReset:f("countReset"),time:f("time"),timeLog:f("timeLog"),timeEnd:f("timeEnd"),assert:(e,...t)=>{e||ge("assert",t.length>0?t:["Assertion failed"])}};function V(e){try{process.stderr.write(e)}catch{}}var Q="https://api.urun.sh/v1";async function me(e){let t=e.fetchImpl??fetch,n=`${e.apiUrl.replace(/\/+$/,"")}/apps`,o=await t(n,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:"application/json"}});if(!o.ok)throw new Error(`org apps listing failed: GET ${n} \u2192 ${o.status}`);let r=await o.json();if(!Array.isArray(r.apps))throw new Error(`org apps listing returned no "apps" array (GET ${n})`);if(r.truncated===!0)throw new Error(`org apps listing was truncated (GET ${n} returned ${r.apps.length} of more) \u2014 model discovery would silently omit deployed apps`);return r.apps}async function he(e){let t=await me(e),n=t.filter(o=>o.function_name===e.fnName&&o.deployment_status==="active").map(o=>o.app_slug);if(n.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${e.fnName}" (GET ${e.apiUrl}/apps returned ${t.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return n.sort()}var ee="urun-serve",He="serve",Ge=131072,ze=16384,ye=3,Ye=42e4,Xe=6e4,we=2,Ve=15e3;function Qe(e){let t=(e.URUN_API_KEY??"").trim();if(!t)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:t,apiUrl:(e.URUN_API_URL??"").trim()||Q,fnName:(e.URUN_FUNCTION??"").trim()||He}}function Re(e){let t=(e.URUN_BASE_URL??"").trim(),n=(e.URUN_ORG_ID??"").trim();if(!t)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(t).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${t} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!n)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let o=(e.URUN_JWT??"").trim();if(o)return{baseUrl:t,orgId:n,auth:{lane:"jwt",jwt:o}};let r=(e.URUN_API_KEY??"").trim();if(!r)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let l=(e.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:t,orgId:n,auth:{lane:"api-key",apiKey:r,gatewayUrl:l}}}function be(e){let t=null;return n=>{t===null&&((0,M.mkdirSync)((0,ke.dirname)(e),{recursive:!0}),t=(0,M.openSync)(e,"a"));let o=n.detail?` ${JSON.stringify(n.detail)}`:"";(0,M.writeSync)(t,`${new Date().toISOString()} [${n.level}] [urun] ${n.message}${o}
|
|
4
|
+
`)}}function xe(e){let t=be(q());return async(n,o,r)=>{let{baseUrl:l,orgId:i,auth:u}=Re(n),{App:g,createClientToken:a}=await e(),y=(u.lane==="jwt"?g(o,{baseUrl:l,orgId:i,jwt:u.jwt,diagnosticSink:t}):g(o,{baseUrl:l,orgId:i,diagnosticSink:t,getAccessToken:async()=>(await a(u.apiKey,{baseUrl:u.gatewayUrl,expiresIn:300,allowedFunctions:[`${o}/${r}`]})).token}))[r];if(typeof y!="function")throw new Error(`urun pi extension: app "${o}" has no function "${r}"`);let _=y();if(typeof _.end!="function")throw new Error(`urun pi extension: app "${o}" function "${r}" returned a session without end()`);let T=_.connect;return typeof T=="function"&&await T.call(_),_}}var Ze=xe(async()=>{let{createRequire:e}=await import("module"),t=e(m);if(typeof globalThis.RTCPeerConnection>"u")try{t.resolve("werift")}catch{throw new Error('urun pi extension: token streams require a WebRTC data channel, and this Node runtime has no RTCPeerConnection and no "werift" backend installed (@urun-sh/core\'s optional Node WebRTC backend \u2014 it was probably stripped by a --no-optional install). Install werift (`npm i werift`) and retry.')}return t("@urun-sh/core")});function et(e,t){try{return Promise.resolve(e.end()).then(()=>{},n=>t(n))}catch(n){return t(n),Promise.resolve()}}function tt(e){if(e?.hasUI===!1)return!0;if(e?.hasUI===!0)return!1;let t=process.argv.slice(2);if(t.includes("-p")||t.includes("--print"))return!0;let n=t.indexOf("--mode");return n!==-1&&(t[n+1]==="json"||t[n+1]==="rpc")?!0:!process.stdin.isTTY||!process.stdout.isTTY}function Se(e,t){return`uRun: releasing the pooled "${e}" session failed \u2014 the backend session may stay allocated until the platform reclaims it: ${t instanceof Error?t.message:String(t)}`}var W=class{constructor(t,n,o,r=(l,i)=>X.warn(Se(l,i))){this.open=t;this.env=n;this.fnName=o;this.onReleaseError=r}open;env;fnName;onReleaseError;pool=new Map;releasing=new Set;acquire(t){let n=this.pool.get(t);if(!n){let o=Promise.resolve(this.open(this.env,t,this.fnName)).then(r=>({session:r,responses:new K(r)}));n=o,this.pool.set(t,o),o.catch(()=>{this.pool.get(t)===o&&this.pool.delete(t)})}return n}evict(t){let n=this.pool.get(t);if(!n)return Promise.resolve();this.pool.delete(t);let o=n.then(r=>et(r.session,l=>this.onReleaseError(t,l)),()=>{});return this.releasing.add(o),o.then(()=>this.releasing.delete(o)),o}closeAll(){let t=[...this.pool.keys()].map(n=>this.evict(n));return Promise.all([...t,...this.releasing]).then(()=>{})}};function Ee(e){let t=[];e.systemPrompt&&t.push({role:"system",content:e.systemPrompt});for(let n of e.messages){if(n.role==="toolResult"){t.push({type:"function_call_output",call_id:n.toolCallId,output:ot(n.content)});continue}if(n.role==="assistant"&&Array.isArray(n.content)){let r="",l=()=>{r&&(t.push({role:"assistant",content:r}),r="")};for(let i of n.content)if(i.type==="text")r+=String(i.text??"");else if(i.type==="toolCall")l(),t.push({type:"function_call",call_id:String(i.id??""),name:String(i.name??""),arguments:JSON.stringify(i.arguments??{})});else{if(i.type==="thinking")continue;throw new Error(`urun pi extension: unsupported assistant content part "${String(i.type)}"`)}l();continue}let o=n.role==="assistant"?"assistant":"user";t.push({role:o,content:nt(n.content)})}return $e(t)}function $e(e){let t=[];for(let n of e){let o=t[t.length-1];o&&"role"in o&&"role"in n&&o.role===n.role?o.content=[o.content,n.content].filter(r=>r.length>0).join(`
|
|
5
5
|
|
|
6
|
-
`):
|
|
7
|
-
`);return}let n=
|
|
8
|
-
`):X.warn(
|
|
6
|
+
`):t.push({...n})}return t}function nt(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&"text"in t?String(t.text):"").join(""):""}function ot(e){if(typeof e=="string")return e;if(!Array.isArray(e))return"";let t="";for(let n of e){let o=String(n.type??"");if(o!=="text")throw new Error(`urun pi extension: unsupported toolResult content part "${o}" \u2014 the serve lane carries text tool results only`);t+=String(n.text??"")}return t}function rt(e){if(!(!Array.isArray(e)||e.length===0))return e.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters}))}function _e(e,t){if(!t.trim())return{};try{return JSON.parse(t)}catch{throw new Error(`uRun serve error: tool call "${e}" arguments are not valid JSON: ${t}`)}}function st(e){let t=e?.output;return Array.isArray(t)?t.filter(n=>n.type==="function_call"):[]}function Pe(e,t){let n=t?.usage;if(!n||typeof n!="object")return;let o=typeof n.input_tokens=="number"?n.input_tokens:void 0,r=typeof n.output_tokens=="number"?n.output_tokens:void 0;o===void 0||r===void 0||(e.input=o,e.output=r,e.totalTokens=typeof n.total_tokens=="number"?n.total_tokens:o+r)}function it(e){let t=e?.output;if(!Array.isArray(t))return"";let n="";for(let o of t)if(!(o.type!=="reasoning"||!Array.isArray(o.content)))for(let r of o.content)r.type==="reasoning_text"&&(n+=String(r.text??""));return n}var at=["<tool_call>","<function="];function lt(e,t){let n=at.find(o=>t.includes(o));if(n)return new Error(`serving row emitted a prose tool call (literal ${JSON.stringify(n)} in the assistant text) for a request that carried tools, and no structured tool_calls arrived \u2014 the tool-call parser is not configured on the model row "${e}" (see catalog parser_defaults)`)}var H=class extends Error{};function ut(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return/\b529\b/.test(t)||/overloaded/i.test(t)||n===529||n==="529"}function ct(e){return new Promise(t=>setTimeout(t,e))}function dt(e,t,n,o){return new Promise((r,l)=>{let i=!1,u=s=>{i||(i=!0,clearTimeout(g),o?.removeEventListener("abort",a),s())},g=setTimeout(()=>u(()=>l(n())),t),a=()=>u(()=>l(new Error("aborted")));if(o?.aborted){a();return}o?.addEventListener("abort",a,{once:!0}),Promise.resolve(e).then(s=>u(()=>r(s)),s=>u(()=>l(s)))})}async function*pt(e,t){let n=e[Symbol.asyncIterator](),o,r=new Promise((l,i)=>{o=()=>i(new Error("aborted")),t.addEventListener("abort",o,{once:!0})});try{for(;;){if(t.aborted)throw new Error("aborted");let l=await Promise.race([n.next(),r]);if(l.done)return;yield l.value}}finally{o&&t.removeEventListener("abort",o),n.return?.(void 0)}}function Z(e,t){if(e?.hasUI===!1){V(`${t}
|
|
7
|
+
`);return}let n=e?.sendMessage;if(typeof n=="function")try{n.call(e,{customType:"urun-status",content:t,display:!0},{triggerTurn:!1})}catch{}}function Te(e,t={},n){let o=t.connectDeadlineMs??Ye,r=t.stallTimeoutMs??Xe,l=t.phaseHeartbeatMs??Ve;return(i,u,g)=>{let a=(0,ve.createAssistantMessageEventStream)(),s={role:"assistant",content:[],api:i.api,provider:i.provider,model:i.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()},y=new AbortController,_=g?.signal,T=!1,L=()=>{T=!0,y.abort()};_&&(_.aborted?L():_.addEventListener("abort",L,{once:!0}));let U=!1,A,te=()=>{A&&clearTimeout(A),A=setTimeout(()=>{U=!0,y.abort()},r)},D=()=>{A&&clearTimeout(A),A=void 0},x=null,S=null,v=null,ne="",O=!1,G=()=>{if(!S)return;let p=S;S=null,a.push({type:"thinking_end",contentIndex:s.content.indexOf(p),content:p.thinking,partial:s})},oe=()=>{if(!x)return;let p=x;x=null,a.push({type:"text_end",contentIndex:s.content.indexOf(p),content:p.text,partial:s})},z=()=>{if(!v)return;let{call:p,args:k,contentIndex:E}=v;v=null,p.arguments=_e(p.name,k),a.push({type:"toolcall_end",contentIndex:E,toolCall:p,partial:s})},Ce=p=>{let k={type:"toolCall",id:String(p.call_id??p.id??`call_${s.content.length}`),name:String(p.name??""),arguments:{}};s.content.push(k);let E=s.content.length-1;a.push({type:"toolcall_start",contentIndex:E,partial:s});let N=typeof p.arguments=="string"?p.arguments:"";N&&a.push({type:"toolcall_delta",contentIndex:E,delta:N,partial:s}),k.arguments=_e(k.name,N),a.push({type:"toolcall_end",contentIndex:E,toolCall:k,partial:s})};return(async()=>{a.push({type:"start",partial:s});let p=!1,k,E=()=>{k&&clearInterval(k),k=void 0},N=Date.now();k=setInterval(()=>{let R=Math.round((Date.now()-N)/1e3);Z(n,`uRun: still opening the "${i.id}" session\u2026 (${R}s \u2014 serve apps scale to zero, first turn can cold-start ~6min)`)},l);let Ie=async R=>{let{responses:b}=await dt(e.acquire(i.id),o,()=>new Error(`uRun session for "${i.id}" did not connect within ${Math.round(o/1e3)}s \u2014 likely cold-starting (scaled to zero) or queued behind capacity. Retry shortly.`),y.signal);E();let C,$;for(let c=1;c<=ye;c++)try{let w=await b.responses.create({model:i.id,input:R,stream:!0,tools:rt(u.tools),max_output_tokens:i.maxTokens,...g?.reasoning!=null&&g.reasoning!=="off"&&i.reasoning!==!1?{}:{chat_template_kwargs:{enable_thinking:!1}}});te();for await(let P of pt(w,y.signal)){te();let h=P;if(h.type==="response.output_text.delta"){let d=typeof h.delta=="string"?h.delta:"";d&&(O=!0,G(),z(),x||(x={type:"text",text:""},s.content.push(x),a.push({type:"text_start",contentIndex:s.content.length-1,partial:s})),x.text+=d,ne+=d,a.push({type:"text_delta",contentIndex:s.content.indexOf(x),delta:d,partial:s}))}else if(h.type==="response.reasoning_text.delta"){let d=typeof h.delta=="string"?h.delta:"";d&&(O=!0,S||(S={type:"thinking",thinking:""},s.content.push(S),a.push({type:"thinking_start",contentIndex:s.content.length-1,partial:s})),S.thinking+=d,a.push({type:"thinking_delta",contentIndex:s.content.indexOf(S),delta:d,partial:s}))}else if(h.type==="response.function_call_arguments.delta"&&typeof h.tool_index=="number"){let d=h;if(O=!0,G(),oe(),!v||v.toolIndex!==d.tool_index){z();let re={type:"toolCall",id:d.call_id??`call_${d.tool_index}`,name:d.name??"",arguments:{}};s.content.push(re),v={call:re,args:"",contentIndex:s.content.length-1,toolIndex:d.tool_index},a.push({type:"toolcall_start",contentIndex:v.contentIndex,partial:s})}d.call_id&&(v.call.id=d.call_id),d.name&&(v.call.name=d.name);let I=typeof d.delta=="string"?d.delta:"";I&&(v.args+=I,a.push({type:"toolcall_delta",contentIndex:v.contentIndex,delta:I,partial:s}))}else if(h.type==="response.completed"){C=h.response;break}else if(h.type==="error"){let d=h.error,I=new Error(`uRun serve error: ${d?.message??"unknown error"}`);throw I.code=d?.code??null,I}}if(!C)throw new H(`uRun backhaul for "${i.id}" closed before the turn completed \u2014 the serving session ended mid-turn (its pod was restarted, drained or deleted).`);$=void 0;break}catch(w){if($=w,y.signal.aborted)throw w;if(c<ye&&ut(w)&&!O){await ct(c*500);continue}throw w}if($)throw $;return C};try{let R=Ee(u),b;for(let c=1;c<=we;c++)try{b=await Ie(R);break}catch(w){let P=U||w instanceof H;if(c>=we||!P||O||T)throw w;D(),e.evict(i.id),U=!1,y=new AbortController,Z(n,`uRun: the "${i.id}" session ended mid-turn \u2014 re-homing to a fresh assignment and replaying the turn\u2026`)}if(D(),G(),oe(),z(),!s.content.some(c=>c.type==="toolCall"))for(let c of st(b))Ce(c);if(!s.content.some(c=>c.type==="thinking")){let c=it(b);if(c){let w={type:"thinking",thinking:""};s.content.push(w);let P=s.content.length-1;a.push({type:"thinking_start",contentIndex:P,partial:s}),w.thinking=c,a.push({type:"thinking_delta",contentIndex:P,delta:c,partial:s}),a.push({type:"thinking_end",contentIndex:P,content:c,partial:s})}}let C=s.content.filter(c=>c.type==="toolCall").length;if((u.tools?.length??0)>0&&C===0){let c=lt(i.id,ne);if(c)throw c}let $=C>0?"toolUse":b?.status==="incomplete"?"length":"stop";s.stopReason=$,Pe(s.usage,b),a.push({type:"done",reason:$,message:s}),a.end(s)}catch(R){if(p=!0,D(),T||_?.aborted&&!U)s.stopReason="aborted",s.errorMessage="aborted by user",a.push({type:"error",reason:"aborted",error:s});else{let b=U?`uRun stream stalled \u2014 no output for ${Math.round(r/1e3)}s; the model may be hung. Retry, or Ctrl-C to abort.`:R instanceof Error?R.message:String(R);s.stopReason="error",s.errorMessage=b,a.push({type:"error",reason:"error",error:s})}a.end(s)}finally{D(),E(),_&&_.removeEventListener("abort",L),p&&e.evict(i.id)}})(),a}}function ft(e){return{id:e,name:`uRun ${e}`,api:ee,reasoning:!0,input:["text"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:Ge,maxTokens:ze}}function Ae(e={}){return async t=>{let n=e.env??process.env,{apiKey:o,apiUrl:r,fnName:l}=Qe(n),i=await he({apiUrl:r,apiKey:o,fnName:l,fetchImpl:e.fetchImpl}),u=new W(e.openSession??Ze,n,l,(a,s)=>{let y=Se(a,s);tt(t)?V(`${y}
|
|
8
|
+
`):X.warn(y)});t.on("session_shutdown",()=>u.closeAll());let g={name:"uRun",api:ee,baseUrl:"urun://session",apiKey:"$URUN_API_KEY",models:i.map(ft),streamSimple:Te(u,e.timing??{},t)};t.registerProvider("urun",g)}}var gt=Ae();0&&(module.exports={SessionPool,URUN_API,applyServeUsage,coalesceSameRole,createFileDiagnosticSink,createUrunExtension,makeSessionFactory,makeStreamSimple,notify,piDiagnosticLogPath,resolveSessionEnv,toResponsesInput});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import { Api, AssistantMessage, Model, Context, SimpleStreamOptions, AssistantMessageEventStream } from '@earendil-works/pi-ai';
|
|
3
|
-
import { U as UrunResponses } from '../ResponsesClient-
|
|
3
|
+
import { U as UrunResponses } from '../ResponsesClient-DjZWjlFH.cjs';
|
|
4
4
|
import { b as UrunSessionLike } from '../types-lsVTbNcH.cjs';
|
|
5
5
|
|
|
6
6
|
/** Where the pi lane's quiet diagnostics land (the compat log convention). */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import { Api, AssistantMessage, Model, Context, SimpleStreamOptions, AssistantMessageEventStream } from '@earendil-works/pi-ai';
|
|
3
|
-
import { U as UrunResponses } from '../ResponsesClient-
|
|
3
|
+
import { U as UrunResponses } from '../ResponsesClient-BE3-hx3m.js';
|
|
4
4
|
import { b as UrunSessionLike } from '../types-lsVTbNcH.js';
|
|
5
5
|
|
|
6
6
|
declare function piDiagnosticLogPath(home?: string): string;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as z}from"../chunk-
|
|
1
|
+
import{a as z}from"../chunk-FP4RSAIE.js";import{c as W,f as Q}from"../chunk-3WAJD62J.js";import"../chunk-2T2YYBVX.js";import{c as C}from"../chunk-5CCJUNH7.js";C();import{createAssistantMessageEventStream as he}from"@earendil-works/pi-ai";import{mkdirSync as we,openSync as _e,writeSync as ke}from"fs";import{dirname as ve}from"path";C();import{appendFileSync as de,mkdirSync as pe}from"fs";import fe from"os";import{dirname as ge,join as me}from"path";import{format as ye}from"util";function J(t=fe.homedir()){return me(t,".urun","logs","pi-extension.log")}var V=!1;function te(t,e){let n=J();try{pe(ge(n),{recursive:!0}),de(n,`${new Date().toISOString()} [console.${t}] [urun] ${ye(...e)}
|
|
2
2
|
`)}catch(o){if(!V){V=!0;try{process.stderr.write(`[urun] pi-extension quiet console: cannot write ${n} (${String(o)}); further urun-side console output will be dropped
|
|
3
3
|
`)}catch{}}}}var f=t=>(...e)=>te(t,e),j={log:f("log"),info:f("info"),warn:f("warn"),error:f("error"),debug:f("debug"),trace:f("trace"),dir:f("dir"),table:f("table"),group:f("group"),groupCollapsed:f("groupCollapsed"),groupEnd:f("groupEnd"),count:f("count"),countReset:f("countReset"),time:f("time"),timeLog:f("timeLog"),timeEnd:f("timeEnd"),assert:(t,...e)=>{t||te("assert",e.length>0?e:["Assertion failed"])}};function q(t){try{process.stderr.write(t)}catch{}}C();async function ne(t){let e=await Q(t),n=e.filter(o=>o.function_name===t.fnName&&o.deployment_status==="active").map(o=>o.app_slug);if(n.length===0)throw new Error(`urun pi extension: the org has no active deployed app exposing "${t.fnName}" (GET ${t.apiUrl}/apps returned ${e.length} app(s), none servable) \u2014 deploy one with \`urun serve <model>\` first`);return n.sort()}var ae="urun-serve",xe="serve",Re=131072,be=16384,oe=3,Te=42e4,Ee=6e4,re=2,Se=15e3;function Ae(t){let e=(t.URUN_API_KEY??"").trim();if(!e)throw new Error("urun pi extension: URUN_API_KEY is required \u2014 model discovery lists the org's deployed serve apps via the org API (URUN_JWT alone cannot list apps)");return{apiKey:e,apiUrl:(t.URUN_API_URL??"").trim()||W,fnName:(t.URUN_FUNCTION??"").trim()||xe}}function Ue(t){let e=(t.URUN_BASE_URL??"").trim(),n=(t.URUN_ORG_ID??"").trim();if(!e)throw new Error("urun pi extension: URUN_BASE_URL is required to open a session");if(/\/v1\/*$/.test(new URL(e).pathname))throw new Error(`urun pi extension: URUN_BASE_URL must be the session-gateway base (e.g. https://api.urun.sh), got ${e} \u2014 a trailing /v1 is the org API form (URUN_API_URL); session allocation 404s against it. Drop the /v1.`);if(!n)throw new Error("urun pi extension: URUN_ORG_ID is required to open a session");let o=(t.URUN_JWT??"").trim();if(o)return{baseUrl:e,orgId:n,auth:{lane:"jwt",jwt:o}};let s=(t.URUN_API_KEY??"").trim();if(!s)throw new Error("urun pi extension: URUN_JWT or URUN_API_KEY is required to open a session");let l=(t.URUN_GATEWAY_URL??"").trim()||void 0;return{baseUrl:e,orgId:n,auth:{lane:"api-key",apiKey:s,gatewayUrl:l}}}function Ie(t){let e=null;return n=>{e===null&&(we(ve(t),{recursive:!0}),e=_e(t,"a"));let o=n.detail?` ${JSON.stringify(n.detail)}`:"";ke(e,`${new Date().toISOString()} [${n.level}] [urun] ${n.message}${o}
|
|
4
4
|
`)}}function Pe(t){let e=Ie(J());return async(n,o,s)=>{let{baseUrl:l,orgId:i,auth:p}=Ue(n),{App:k,createClientToken:a}=await t(),m=(p.lane==="jwt"?k(o,{baseUrl:l,orgId:i,jwt:p.jwt,diagnosticSink:e}):k(o,{baseUrl:l,orgId:i,diagnosticSink:e,getAccessToken:async()=>(await a(p.apiKey,{baseUrl:p.gatewayUrl,expiresIn:300,allowedFunctions:[`${o}/${s}`]})).token}))[s];if(typeof m!="function")throw new Error(`urun pi extension: app "${o}" has no function "${s}"`);let h=m();if(typeof h.end!="function")throw new Error(`urun pi extension: app "${o}" function "${s}" returned a session without end()`);let A=h.connect;return typeof A=="function"&&await A.call(h),h}}var Ce=Pe(async()=>{let{createRequire:t}=await import("module"),e=t(import.meta.url);if(typeof globalThis.RTCPeerConnection>"u")try{e.resolve("werift")}catch{throw new Error('urun pi extension: token streams require a WebRTC data channel, and this Node runtime has no RTCPeerConnection and no "werift" backend installed (@urun-sh/core\'s optional Node WebRTC backend \u2014 it was probably stripped by a --no-optional install). Install werift (`npm i werift`) and retry.')}return e("@urun-sh/core")});function Ne(t,e){try{return Promise.resolve(t.end()).then(()=>{},n=>e(n))}catch(n){return e(n),Promise.resolve()}}function $e(t){if(t?.hasUI===!1)return!0;if(t?.hasUI===!0)return!1;let e=process.argv.slice(2);if(e.includes("-p")||e.includes("--print"))return!0;let n=e.indexOf("--mode");return n!==-1&&(e[n+1]==="json"||e[n+1]==="rpc")?!0:!process.stdin.isTTY||!process.stdout.isTTY}function le(t,e){return`uRun: releasing the pooled "${t}" session failed \u2014 the backend session may stay allocated until the platform reclaims it: ${e instanceof Error?e.message:String(e)}`}var H=class{constructor(e,n,o,s=(l,i)=>j.warn(le(l,i))){this.open=e;this.env=n;this.fnName=o;this.onReleaseError=s}open;env;fnName;onReleaseError;pool=new Map;releasing=new Set;acquire(e){let n=this.pool.get(e);if(!n){let o=Promise.resolve(this.open(this.env,e,this.fnName)).then(s=>({session:s,responses:new z(s)}));n=o,this.pool.set(e,o),o.catch(()=>{this.pool.get(e)===o&&this.pool.delete(e)})}return n}evict(e){let n=this.pool.get(e);if(!n)return Promise.resolve();this.pool.delete(e);let o=n.then(s=>Ne(s.session,l=>this.onReleaseError(e,l)),()=>{});return this.releasing.add(o),o.then(()=>this.releasing.delete(o)),o}closeAll(){let e=[...this.pool.keys()].map(n=>this.evict(n));return Promise.all([...e,...this.releasing]).then(()=>{})}};function Le(t){let e=[];t.systemPrompt&&e.push({role:"system",content:t.systemPrompt});for(let n of t.messages){if(n.role==="toolResult"){e.push({type:"function_call_output",call_id:n.toolCallId,output:De(n.content)});continue}if(n.role==="assistant"&&Array.isArray(n.content)){let s="",l=()=>{s&&(e.push({role:"assistant",content:s}),s="")};for(let i of n.content)if(i.type==="text")s+=String(i.text??"");else if(i.type==="toolCall")l(),e.push({type:"function_call",call_id:String(i.id??""),name:String(i.name??""),arguments:JSON.stringify(i.arguments??{})});else{if(i.type==="thinking")continue;throw new Error(`urun pi extension: unsupported assistant content part "${String(i.type)}"`)}l();continue}let o=n.role==="assistant"?"assistant":"user";e.push({role:o,content:Me(n.content)})}return Oe(e)}function Oe(t){let e=[];for(let n of t){let o=e[e.length-1];o&&"role"in o&&"role"in n&&o.role===n.role?o.content=[o.content,n.content].filter(s=>s.length>0).join(`
|