UNPKG

@code-yeongyu/senpi

Version:

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

4 lines (3 loc) • 19.6 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{allocateMonitorId,currentRpcRemoteSource,endpointSockets,matchesTask,subscriptionFor,wantsRecord}from"./chunk-ETOGZ74E.js";import"./chunk-BICMCIHT.js";import{connectAuthenticatedRpcSocket,socketNeedsHandshake}from"./chunk-E25CXSWH.js";import"./chunk-2ZYJNMJZ.js";import{OBSERVE_REQUEST_FIELD}from"./chunk-YQHLIPNR.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader}from"./chunk-SF4MQDKZ.js";import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-HW6AAS3R.js";import"./chunk-IDTQWHTP.js";import"./chunk-QJTWAOBX.js";import"./chunk-ATQFN5HI.js";import"./chunk-YWBNR4MT.js";import"./chunk-IKOFCODM.js";var DELTA_KINDS=new Set(["message_update","tool_execution_update","bash_execution_update"]),SURFACE_KINDS=new Set(["loaded_surfaces_changed","commands_changed"]),LAST_TEXT_LIMIT=60,RpcMonitorCoalescer=class{#windows=new Map;#flush;constructor(flush){this.#flush=flush}accept(sessionKey2,label,record){let type=String(record.type),delta=DELTA_KINDS.has(type);if(!delta&&!SURFACE_KINDS.has(type))return!1;let key=delta?`${sessionKey2}#deltas`:`${sessionKey2}#${type}`,open=this.#windows.get(key),last=delta?lastText(record):"";if(open!==void 0)return open.count+=1,last!==""&&(open.last=last),!0;let window={count:1,last,timer:setTimeout(()=>{this.#windows.delete(key),this.#flush(delta?`rpc ${label()} streaming +${window.count} deltas${window.last===""?"":` (last: "${window.last}")`}`:`rpc ${label()} ${type} x${window.count}`)},delta?2e3:5e3)};return this.#windows.set(key,window),!0}dispose(){for(let window of this.#windows.values())clearTimeout(window.timer);this.#windows.clear()}};function lastText(record){let event=record.assistantMessageEvent,flat=(event?.type==="text_delta"&&typeof event.delta=="string"?event.delta:typeof record.output=="string"?record.output:"").replace(/\s+/g," ").trim();return flat.length>LAST_TEXT_LIMIT?flat.slice(-LAST_TEXT_LIMIT):flat}import{createConnection}from"node:net";var SUBSCRIBE_ID="monitor-subscribe";async function openRpcObserver(socketPath,subscription,handlers,options={}){let secret=socketNeedsHandshake(socketPath)?await readSocketSecret(socketSecretPath(socketPath)):void 0,authenticated=socketNeedsHandshake(socketPath)?void 0:await connectAuthenticatedRpcSocket(socketPath,void 0,options),socket=authenticated?.socket??createConnection(resolveSocketTransportAddress(socketPath,process.platform,secret)),answer=Promise.withResolvers(),ended=!1,end=reason=>{ended||(ended=!0,answer.reject(new Error(`rpc monitor: ${socketPath}: ${reason}`)),handlers.closed(reason))},subscribe=()=>{secret!==void 0&&sendSocketHandshake(socket,secret);let frame={...subscription,[OBSERVE_REQUEST_FIELD]:!0,id:SUBSCRIBE_ID,type:"subscribe_sessions"};socket.write(`${JSON.stringify(frame)} `)},detach=attachJsonlLineReader(socket,line=>{let record;try{record=JSON.parse(line)}catch{return}if(record.type==="response"&&record.id===SUBSCRIBE_ID){record.success===!0?answer.resolve(record):(answer.reject(new Error(`rpc monitor: ${socketPath} refused the subscription: ${String(record.error)}`)),socket.destroy());return}handlers.record(record)},{maxLineLength:MAX_RPC_LINE_CHARACTERS});return socket.on("error",error=>end(error.message)),socket.once("close",()=>{detach(),end("connection closed")}),authenticated?subscribe():socket.once("connect",subscribe),{subscribed:answer.promise,close:()=>socket.destroy()}}var RpcMonitorRenderer=class{#sessions=new Map;#namedThisBatch=new Set;seed(socket,snapshot){return snapshot.map(row=>{let view=this.#view(socket,row);view.status=String(row.status);let model=modelId(row.model),attachments=typeof row.attachments=="number"?row.attachments:0;return`${view.label} ${view.status} (${attachments} attached${model===void 0?"":`, model ${model}`})`})}forgetSocket(socket){let count2=0;for(let key of[...this.#sessions.keys()])key.startsWith(`${socket}#`)&&(this.#sessions.delete(key),count2++);return count2}statuses(){return new Map([...this.#sessions].map(([key,view])=>[key,view.status]))}label(socket,record){let view=this.#view(socket,record),key=sessionKey(socket,record);return this.#namedThisBatch.has(key)?view.label:(this.#namedThisBatch.size===0&&queueMicrotask(()=>this.#namedThisBatch.clear()),this.#namedThisBatch.add(key),`${view.label} (${String(record.sessionId)})`)}render(socket,record){switch(record.type){case"session_status":return this.#status(socket,record);case"effect_status":{let detail=record.disposition??reasonOf(record.outcome);return`rpc ${this.label(socket,record)} effect ${String(record.kind)} ${tail(String(record.effectId))} ${String(record.state)}${detail===void 0?"":` (${String(detail)})`}`}case"agent_end":return`rpc ${this.label(socket,record)} agent_end${record.aborted===!0?` aborted(${String(record.abortSource??"user")})`:""}`;case"model_changed":return`rpc ${this.label(socket,record)} model_changed -> ${modelId(record.model)??"?"}${record.source===void 0?"":` (${String(record.source)})`}`;case"queue_update":return`rpc ${this.label(socket,record)} queue_update steering=${count(record.steering)} followUp=${count(record.followUp)}`;case"session_replaced":return`rpc ${this.label(socket,record)} session_replaced -> ${String(record.durableSessionId??record.newSessionId??"?")}`;case"session_closed":return`rpc ${this.label(socket,record)} session_closed ${String(record.reason??"")}`.trimEnd();case"extension_event":return`rpc ${this.label(socket,record)} extension_event ${String(record.name??record.event??"")}`.trimEnd();case"entry_appended":return`rpc ${this.label(socket,record)} entry_appended ${entryType(record)}`;case"tool_execution_start":case"tool_execution_end":return`rpc ${this.label(socket,record)} tool ${String(record.toolName??"?")} ${record.type==="tool_execution_start"?"started":"ended"}`;case"turn_end":case"turn_start":case"agent_start":case"agent_idle":case"agent_settled":return`rpc ${this.label(socket,record)} ${record.type}`;default:{let{type:_type,sessionId:_sessionId,...rest}=record,json=JSON.stringify(rest),body=json.length>160?`${json.slice(0,160)}...`:json;return`rpc ${this.label(socket,record)} ${String(record.type)} ${body}`}}}#status(socket,record){let view=this.#view(socket,record),to=String(record.status),from=view.status;if(view.status=to,from===to)return;let change=record.lastChange,why=change===void 0?"":` (${String(change.cause)}, by ${String(change.by)})`;return`rpc ${this.label(socket,record)} status ${from} -> ${to}${why} seq=${String(record.seq)}`}#view(socket,record){let key=sessionKey(socket,record),view=this.#sessions.get(key);return view===void 0?(view={label:labelOf(record),status:"unknown"},this.#sessions.set(key,view)):(typeof record.name=="string"||contextTask(record)!==void 0)&&(view.label=labelOf(record)),view}};function sessionKey(socket,record){return`${socket}#${String(record.sessionId)}`}function detachedLabel(key){return key.slice(key.lastIndexOf("#")+1).slice(0,8)}function labelOf(record){let task=contextTask(record);return task!==void 0?task:typeof record.name=="string"&&record.name!==""?record.name:(typeof record.durableSessionId=="string"?record.durableSessionId:String(record.sessionId)).slice(0,8)}function contextTask(record){let context=record.context;return typeof context?.task_id=="string"?context.task_id:void 0}function modelId(model){return typeof model=="object"&&model!==null&&"id"in model?String(model.id):void 0}function reasonOf(outcome){return typeof outcome=="object"&&outcome!==null&&"reason"in outcome?String(outcome.reason):void 0}function count(value){return Array.isArray(value)?value.length:typeof value=="number"?value:0}function tail(id){return id.length>8?id.slice(-8):id}function entryType(record){let entry=record.entry;return String(entry?.type??record.entryType??"?")}var REMOTE_INSTANCE="remote",SETTLED_KEPT=16,RpcRemoteFeed=class{#target;#options;#host;#settled=new Map;#cursor;#opened=[];#subscription;#lostReported=!1;#stopped=!1;constructor(target,options,host){this.#target=target,this.#options=options,this.#host=host;for(let[key,turns]of Object.entries(options.saved?.settled??{}))this.#settled.set(key,[...turns]);this.#cursor=options.saved?.cursor}async start(){let pending=[],ready=!1,run=step=>{this.#stopped||(ready?step():pending.push(step))},{events,exclude,source}=this.#options,subscription=await source.open(this.#target,{events,exclude,...this.#cursor===void 0?{}:{resumeFrom:this.#cursor}},{record:record=>run(()=>this.#record(record)),resynced:state=>run(()=>this.#resync(state)),cursor:cursor=>run(()=>{this.#cursor=cursor,this.#host.checkpoint()}),lost:reason=>run(()=>this.#lost(reason)),ended:reason=>run(()=>this.#ended(reason))});if(this.#stopped)return subscription.stop(),[];this.#subscription=subscription;let{initial}=subscription,device=this.#target.device;this.#host.hosts.set(device,{instanceId:REMOTE_INSTANCE,generation:initial.generation??""}),this.#opened=initial.settledTurns??[];for(let turn of this.#opened)this.#remember(turnKey(device,turn),turn.turnId);initial.cursor!==void 0&&(this.#cursor=initial.cursor);let rows=this.#host.renderer.seed(device,initial.rows);this.#host.checkpoint(),ready=!0;for(let step of pending.splice(0))step();return rows}stop(){this.#stopped=!0,this.#subscription?.stop(),this.#subscription=void 0}checkpoint(){let settled=Object.fromEntries([...this.#settled].map(([key,turns])=>[key,[...turns]]));return this.#cursor===void 0?{settled}:{cursor:this.#cursor,settled}}diffSettled(saved){return this.#opened.filter(turn=>!saved?.settled[turnKey(this.#target.device,turn)]?.includes(turn.turnId)).map(turn=>settledLine(turnKey(this.#target.device,turn),turn.turnId))}#record(record){let device=this.#target.device;if(record.type!=="agent_settled"||typeof record.turnId!="string"){this.#host.record(device,record);return}let key=sessionKey(device,record);this.#seen(key,record.turnId)||(this.#remember(key,record.turnId),this.#host.record(device,record),this.#host.checkpoint())}#resync(state){let device=this.#target.device,lines=[],host=this.#host.hosts.get(device);state.generation!==void 0&&(host!==void 0&&host.generation!==state.generation&&lines.push(`rpc host ${device} restarted (generation ${host.generation} -> ${state.generation})`),this.#host.hosts.set(device,{instanceId:REMOTE_INSTANCE,generation:state.generation}));let before=new Map([...this.#host.renderer.statuses()].filter(([key])=>key.startsWith(`${device}#`))),now=new Map(state.rows.map(row=>[sessionKey(device,row),String(row.status)]));for(let[key,status]of now){let was=before.get(key)??"unknown";was!==status&&lines.push(`rpc ${detachedLabel(key)} status ${was} -> ${status} (changed while detached)`)}for(let key of before.keys())now.has(key)||lines.push(`rpc ${detachedLabel(key)} closed (gone while detached)`);for(let turn of state.settledTurns??[]){let key=turnKey(device,turn);this.#seen(key,turn.turnId)||(this.#remember(key,turn.turnId),lines.push(settledLine(key,turn.turnId)))}this.#host.renderer.forgetSocket(device),this.#host.renderer.seed(device,state.rows),state.cursor!==void 0&&(this.#cursor=state.cursor),this.#lostReported=!1;for(let line of lines)this.#host.line(line);this.#host.checkpoint()}#lost(reason){this.#lostReported||(this.#lostReported=!0,this.#host.line(`rpc device ${this.#target.device} unreachable (${reason}); re-watching`))}#ended(reason){this.#host.line(`rpc ${this.#target.device}/${this.#target.session} access ended (${reason})`),this.#host.ended(`access ended (${reason})`)}#seen(key,turnId){return this.#settled.get(key)?.includes(turnId)===!0}#remember(key,turnId){let turns=this.#settled.get(key)??[];turns.includes(turnId)||(turns.push(turnId),turns.length>SETTLED_KEPT&&turns.shift(),this.#settled.set(key,turns))}};function turnKey(device,turn){return`${device}#${turn.sessionId}`}function settledLine(key,turnId){return`rpc ${detachedLabel(key)} turn ${turnId} settled while detached`}var RPC_RESCAN_MS=3e4,RpcMonitorWatch=class{#options;#observers=new Map;#hosts=new Map;#renderer=new RpcMonitorRenderer;#coalescer;#taskSessions=new Set;#rescan;#remote;#stopped=!1;constructor(options){this.#options=options,this.#coalescer=new RpcMonitorCoalescer(options.line)}async start(){let{target}=this.#options;if(target.kind==="remote")return this.#startRemote(target.device,target.session);let rows=await this.#join();return this.#rescan=setInterval(()=>{this.#join()},RPC_RESCAN_MS),this.#rescan.unref?.(),rows}checkpoint(){return{hosts:Object.fromEntries(this.#hosts),statuses:Object.fromEntries(this.#renderer.statuses()),...this.#remote===void 0?{}:{remote:this.#remote.checkpoint()}}}diffSince(saved){let lines=[];for(let[socket,host]of this.#hosts){let before=saved.hosts[socket];before!==void 0&&before.generation!==host.generation&&lines.push(`rpc host ${socket} restarted (generation ${before.generation} -> ${host.generation})`)}let now=this.#renderer.statuses();for(let[key,status]of Object.entries(saved.statuses)){let label=detachedLabel(key),current=now.get(key),socket=key.slice(0,key.lastIndexOf("#"));current===void 0?lines.push(this.#hosts.has(socket)&&this.#options.target.kind!=="children"?`rpc ${label} closed (gone while detached)`:this.#hosts.has(socket)?`rpc ${label} no longer listed (closed or no longer a child while detached)`:`rpc ${label} unreachable (its host did not answer)`):current!==status&&lines.push(`rpc ${label} status ${status} -> ${current} (changed while detached)`)}return this.#remote!==void 0&&lines.push(...this.#remote.diffSettled(saved.remote)),lines}stop(){this.#stopped=!0,this.#rescan!==void 0&&clearInterval(this.#rescan),this.#coalescer.dispose();for(let observer of this.#observers.values())observer.close();this.#observers.clear(),this.#remote?.stop()}#startRemote(device,session){let{events,exclude,restoredFrom}=this.#options,source=this.#options.remoteSource??currentRpcRemoteSource();return source===void 0?Promise.reject(new Error("remote targets need the omo remote surface; no remote source is registered")):(this.#remote=new RpcRemoteFeed({device,session},{events,exclude,source,...restoredFrom?.remote===void 0?{}:{saved:restoredFrom.remote}},{renderer:this.#renderer,hosts:this.#hosts,record:(socket,record)=>this.#record(socket,record),line:line=>this.#options.line(line),checkpoint:()=>this.#options.checkpoint?.(this.checkpoint()),ended:summary=>this.#options.ended?.(summary)}),this.#remote.start())}async#join(){let fresh=(await(this.#options.endpoints??(()=>endpointSockets(this.#options.agentDir)))().catch(()=>[])).filter(socket=>!this.#observers.has(socket));return(await Promise.all(fresh.map(socket=>this.#observe(socket)))).flat()}async#observe(socket){if(this.#stopped)return[];let{target,events}=this.#options,observer;try{observer=await openRpcObserver(socket,subscriptionFor(target,events),{record:record=>{this.#stopped||this.#record(socket,record)},closed:()=>this.#lost(socket,observer)})}catch{return[]}if(this.#stopped)return observer.close(),[];this.#observers.set(socket,observer);let answer=await observer.subscribed.catch(()=>{});if(this.#stopped)return observer.close(),[];let data=answer?.data;if(data===void 0)return[];this.#hosts.set(socket,{instanceId:String(data.hostInstanceId),generation:String(data.hostGeneration)});let matched=(Array.isArray(data.snapshot)?data.snapshot:[]).filter(row=>matchesTask(target,row));for(let row of matched)this.#taskSessions.add(sessionKey(socket,row));if(target.kind!=="all"&&target.kind!=="children"&&matched.length===0)return observer.close(),this.#observers.delete(socket),[];let rows=this.#renderer.seed(socket,matched);return this.#options.checkpoint?.(this.checkpoint()),rows}#lost(socket,observer){if(this.#observers.get(socket)!==observer||(this.#observers.delete(socket),this.#stopped))return;let forgotten=this.#renderer.forgetSocket(socket);for(let key of[...this.#taskSessions])key.startsWith(`${socket}#`)&&this.#taskSessions.delete(key);(this.#hosts.delete(socket)||forgotten>0)&&(this.#options.line(`rpc host ${socket} gone (${forgotten} session${forgotten===1?"":"s"} no longer watched)`),this.#options.checkpoint?.(this.checkpoint()))}#record(socket,record){let{target,events,exclude}=this.#options,type=String(record.type);if(!wantsRecord(events,exclude,type))return;let key=sessionKey(socket,record);if(target.kind==="task"&&(matchesTask(target,record)&&this.#taskSessions.add(key),!this.#taskSessions.has(key))||this.#coalescer.accept(key,()=>this.#renderer.label(socket,record),record))return;let line=this.#renderer.render(socket,record);line!==void 0&&(this.#options.line(line),type==="session_status"&&this.#options.checkpoint?.(this.checkpoint()))}};var RPC_WATCHER_TIMED_OUT_SUMMARY="watcher timed_out",RpcMonitorSource=class{#records=new Map;#host;#nextId=1;constructor(host){this.#host=host}get(id){return this.#records.get(id)}values(){return this.#records.values()}keys(){return this.#records.keys()}async register(options){let id=`rpc_${this.#nextId++}`,monitorId=options.monitorId??allocateMonitorId(),watch=new RpcMonitorWatch({agentDir:options.agentDir,target:options.target,events:options.events,exclude:options.exclude,...options.endpoints===void 0?{}:{endpoints:options.endpoints},...options.remoteSource===void 0?{}:{remoteSource:options.remoteSource},...options.restoredFrom===void 0?{}:{restoredFrom:options.restoredFrom},ended:summary=>this.settle(id,summary,"exit"),line:line=>this.#line(id,line),...options.onCheckpoint===void 0?{}:{checkpoint:checkpoint=>options.onCheckpoint?.(monitorId,checkpoint)}}),record={id,monitorId,description:options.description,startedAtMs:Date.now(),command:null,filter:options.filter,persistent:options.persistent,deadlineMs:options.persistent||options.timeoutMs===void 0?null:Date.now()+options.timeoutMs,fireCount:0,lastFiredAtMs:null,expiresAt:options.expiresAt,paused:!1,settled:!1,rpcWatch:watch,targetText:options.targetText,mutedDropped:0,lastLine:void 0,deadline:options.persistent||options.timeoutMs===void 0?void 0:setTimeout(()=>this.settle(id,RPC_WATCHER_TIMED_OUT_SUMMARY),options.timeoutMs)};this.#records.set(id,record),this.#host.changed();let rows=await watch.start().catch(error=>{throw watch.stop(),clearTimeout(record.deadline),this.#records.delete(id),this.#host.changed(),error});if(options.restoredFrom!==void 0)for(let line of watch.diffSince(options.restoredFrom))this.#line(id,line);return{id,monitorId,rows}}settle(id,summary,reason){let record=this.#records.get(id);return record===void 0||record.settled?!1:(record.settled=!0,record.rpcWatch.stop(),clearTimeout(record.deadline),this.#records.delete(id),this.#host.changed(),summary!=="watcher disposed"&&this.#host.emit(record,{type:"summary",id,description:record.description,summary}),this.#host.ended(record,reason??(summary===RPC_WATCHER_TIMED_OUT_SUMMARY?"timeout":summary==="watcher disposed"?"disposed":"killed"),null),!0)}settleAll(summary){let ids=[...this.#records.keys()];for(let id of ids)this.settle(id,summary);return ids.length}#line(id,line){let record=this.#records.get(id);if(!(record===void 0||record.settled)&&!(record.filter instanceof RegExp&&!record.filter.test(line))&&line!==record.lastLine){if(record.lastLine=line,record.paused){record.mutedDropped+=1;return}this.#host.emit(record,{type:"line",id,description:record.description,line})}}};export{RpcMonitorSource};