UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

3 lines (2 loc) • 9.76 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } } import{SHOW_HTML_PAGE_NAME,handedPageText,reserveHandedPage}from"./chunk-3VN5RC6W.js";import{createReliableTransport,createRemoteToolHost}from"./chunk-DPNC7S74.js";import"./chunk-OBXBNBXE.js";import"./chunk-XDEZA6U6.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-7K42R46I.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-QD45L5SP.js";import"./chunk-WDTJ6JKE.js";import"./chunk-AFDUWYAX.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import{resolveSocketTransportAddress}from"./chunk-HW6AAS3R.js";import"./chunk-MIKPY3E7.js";import"./chunk-IKOFCODM.js";import{posix,win32}from"node:path";var isJsonObject=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function withHandPageBudget(host,session){let pending=new Map,unsubscribe=session.agent.subscribe(event=>{event.type==="agent_end"&&pending.clear()});return{...host.deviceFiles===void 0?{}:{deviceFiles:host.deviceFiles.bind(host)},close(){unsubscribe(),host.close()},async execute(call,options){let decisions=new Map,budgeted=(toolCallId,toolName,result)=>{if(toolName!==SHOW_HTML_PAGE_NAME)return;decisions.has(toolCallId)||decisions.set(toolCallId,overBudget(call.calls,toolCallId,result.details,session,pending));let downgrade=decisions.get(toolCallId);return downgrade===void 0?void 0:applied(downgrade,result.content)},emit=event=>options.emit(budgetedEvent(event,budgeted)),outcome=await host.execute(call,{...options,emit});return{...outcome,messages:outcome.messages.map(message=>({...message,...budgeted(message.toolCallId,message.toolName,message)}))}}}}function budgetedEvent(event,budgeted){if(event.type==="tool_execution_end"){let override=budgeted(event.toolCallId,event.toolName,event.result);return override===void 0?event:{...event,result:{...event.result,...override}}}if((event.type==="message_start"||event.type==="message_end")&&event.message.role==="toolResult"){let override=budgeted(event.message.toolCallId,event.message.toolName,event.message);return override===void 0?event:{...event,message:{...event.message,...override}}}return event}function applied(downgrade,content){let{ownText}=downgrade,own=ownText===void 0?olderHandOwnText(downgrade,content):content.findIndex(part=>part.type==="text"&&part.text===ownText),text={type:"text",text:downgrade.text},unmatched=ownText===void 0?[text,...content]:[...content,text];return{content:own===-1?unmatched:content.map((part,index)=>index===own?text:part),details:downgrade.details}}function olderHandOwnText(downgrade,content){let path=downgrade.details.path,named=typeof path=="string"?content.findIndex(part=>part.type==="text"&&part.text.includes(path)):-1;return named===-1?content.findIndex(part=>part.type==="text"):named}function overBudget(calls,toolCallId,details,session,pending){let written=calls.find(call=>call.id===toolCallId)?.arguments.html;if(!isJsonObject(details)||details.imagesInlined!==!0||typeof details.html!="string"||typeof details.path!="string"||typeof written!="string")return;let reservation=reserveHandedPage(session.sessionManager,pending,toolCallId,details.html.length);if(reservation.inlined)return;let text=handedPageText({path:details.path,shown:session.promptSurface==="app",imagesInlined:!1,fitsPage:!0,alreadyHanded:reservation.alreadyHanded,inlinedLength:details.html.length});return{text,ownText:typeof details.resultText=="string"?details.resultText:void 0,details:{...details,html:written,imagesInlined:!1,resultText:text}}}var HAND_SELECTION_ENTRY="hand_selection";function unreachableHost(){let transport=createReliableTransport({clock:{now:()=>Date.now(),setTimer:()=>()=>{}},onHandlerError:()=>{}});return transport.close(),createRemoteToolHost({transport,placement:"cross-machine"})}function recordedDevice(session){let device=null;for(let entry of session.sessionManager.getEntries()){if(entry.type!=="custom"||entry.customType!==HAND_SELECTION_ENTRY)continue;let recorded=Reflect.get(Object(entry.data),"device");device=typeof recorded=="string"?recorded:null}return device}function createHandSelection(directory,options={}){let sessions=new Map,gate=options.gate??((_id,host)=>host),stateOf=(durableSessionId,session)=>{let known=sessions.get(durableSessionId);if(known!==void 0)return known;let fresh={own:session.agent.toolHost,device:null,remote:void 0,linked:!1};return sessions.set(durableSessionId,fresh),fresh},install=(durableSessionId,session,device,remote)=>{let state=stateOf(durableSessionId,session);state.remote?.close();let host=remote===void 0?void 0:withHandPageBudget(remote.host,session);sessions.set(durableSessionId,{own:state.own,device,remote:host,linked:remote?.linked??!1}),session.agent.toolHost=host===void 0?state.own:gate(durableSessionId,host),options.onChange?.(durableSessionId,device)},unreachable=()=>({host:unreachableHost(),linked:!1}),linkTo=(device,session)=>{try{return{host:createRemoteToolHost({...directory.link(device),promptSurface:()=>session.promptSurface}),linked:!0}}catch{return unreachable()}};return{hands:()=>directory.list(),selected:durableSessionId=>sessions.get(durableSessionId)?.device??null,select:(durableSessionId,session,device)=>{let current=stateOf(durableSessionId,session);if(current.device===device&&(device===null||current.linked))return{ok:!0};if(session.isStreaming)return{ok:!1,refusal:"session_busy"};let remote;if(device!==null){let row=directory.list().find(hand=>hand.device===device);if(row===void 0)return{ok:!1,refusal:"hand_not_listed"};if(!row.reachable)return{ok:!1,refusal:"hand_unreachable"};if(remote=linkTo(device,session),!remote.linked)return remote.host.close(),{ok:!1,refusal:"hand_unreachable"}}try{current.device!==device&&session.sessionManager.appendCustomEntry(HAND_SELECTION_ENTRY,{device})}catch(cause){throw remote?.host.close(),cause}return install(durableSessionId,session,device,remote),{ok:!0}},restore:(durableSessionId,session)=>{sessions.get(durableSessionId)?.remote?.close(),sessions.delete(durableSessionId),stateOf(durableSessionId,session);let device=recordedDevice(session);if(device===null)return;let row=directory.list().find(hand=>hand.device===device);install(durableSessionId,session,device,row?.reachable===!0?linkTo(device,session):unreachable())},release:durableSessionId=>{sessions.get(durableSessionId)?.remote?.close(),sessions.delete(durableSessionId),options.onRelease?.(durableSessionId)}}}function gatePresence(agent,presence,sessionId){let prepareRequest=agent.prepareRequest;agent.prepareRequest=async(request,signal)=>(await presence.ready(sessionId,"request",signal),await prepareRequest?.(request,signal)??void 0);let host=agent.toolHost;if(host===void 0)return;let deviceFiles=host.deviceFiles?.bind(host);agent.toolHost={execute:async(call,options)=>(await presence.ready(sessionId,"tools",options.signal),host.execute(call,options)),...deviceFiles===void 0?{}:{deviceFiles}}}var HEADLESS_SOCKET_FILE="headless.sock";function headlessSocketPath(agentDir,platform=process.platform){return(platform==="win32"?win32:posix).join(agentDir,"rpc",HEADLESS_SOCKET_FILE)}function headlessEndpoint(agentDir,platform=process.platform,secret){return resolveSocketTransportAddress(headlessSocketPath(agentDir,platform),platform,secret)}function headlessHostOptions(options){let{presence,hands,...host}=options,runtimes=new Map,handSelection=hands===void 0?void 0:createHandSelection(hands,presence===void 0?{}:presenceHooks(presence,runtimes)),gated=presence===void 0?host.createRuntime:presenceRuntime(host.createRuntime,presence);return{...host,sessionOwner:"machine",listen:options.listen??`unix://${headlessSocketPath(options.agentDir)}`,createRuntime:handSelection===void 0?gated:handRuntime(gated,handSelection,runtimes),...presence===void 0?{}:{sessionPresence:presence.presence},...handSelection===void 0?{}:{handSelection}}}function presenceHooks(binding,runtimes){let tracking=new Map;return{gate:(sessionId,host)=>({execute:async(call,options)=>(await tracking.get(sessionId),await binding.presence.ready(sessionId,"tools",options.signal),host.execute(call,options))}),onChange:(sessionId,device)=>{let runtime=runtimes.get(sessionId),sessionHands=device!==null?[device]:runtime===void 0?[]:binding.handsOf(runtime),update=binding.presence.track(sessionId,sessionHands);update.catch(()=>{}),tracking.set(sessionId,update)},onRelease:sessionId=>{tracking.delete(sessionId)}}}function handRuntime(createRuntime,selection,runtimes){return Object.assign(async input=>{let runtime=await createRuntime(input),{session}=runtime,sessionId=session.sessionId;runtimes.set(sessionId,runtime),selection.restore(sessionId,session);let dispose=session.dispose.bind(session);return session.dispose=()=>{runtimes.get(sessionId)===runtime&&(runtimes.delete(sessionId),selection.release(sessionId)),dispose()},runtime},createRuntime)}function presenceRuntime(createRuntime,binding){return Object.assign(async input=>{let runtime=await createRuntime(input),{session}=runtime;return await binding.presence.track(session.sessionId,binding.handsOf(runtime)),gatePresence(session.agent,binding.presence,session.sessionId),runtime},createRuntime)}export{headlessEndpoint,headlessHostOptions,headlessSocketPath};