alchemylab 2.1.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/111.js +11 -12
- package/dist/24.js +34 -232
- package/dist/293.js +52 -50
- package/dist/356.js +11 -11
- package/dist/414.js +16 -16
- package/dist/478.js +33 -33
- package/dist/579.js +7 -7
- package/dist/60.js +8 -8
- package/dist/729.js +17 -17
- package/dist/776.js +1 -1
- package/dist/800.js +2 -2
- package/dist/816.js +2 -3
- package/dist/939.js +15 -15
- package/dist/991.js +12 -12
- package/dist/994.js +22 -22
- package/dist/cli.js +7309 -7656
- package/dist/document-textconv.js +372 -413
- package/dist/http-server.js +7618 -7708
- package/dist/index.js +7664 -7754
- package/dist/mcp-direct.js +7462 -7552
- package/dist/plugins/hooks/plugin.js +1 -1
- package/dist/plugins/system-logger.js +1 -1
- package/package.json +2 -2
package/dist/111.js
CHANGED
|
@@ -1,15 +1,14 @@
|
|
|
1
1
|
"use strict"
|
|
2
|
-
exports.
|
|
2
|
+
exports.ids=[111],exports.modules={56111(e,exports,t){async function o(e,t){if(t){if(!s||Date.now()-s.at>3e4)try{const t=await e.apiClient.get(`/api/projects/${e.projectId}/session-request-associations?activeOnly=true&limit=500`),o=t?.data??t??[],r=new Map
|
|
3
3
|
for(const e of o)e?.opencodeSessionId&&e?.requestLocalId&&r.set(e.opencodeSessionId,e.requestLocalId)
|
|
4
|
-
|
|
5
|
-
try{const o=await e.apiClient.post(`/api/projects/${e.projectId}/tool-records`,{...
|
|
6
|
-
t.allowed&&t.callId&&r&&(
|
|
7
|
-
const e=[...
|
|
8
|
-
for(const[t]of e){if(
|
|
9
|
-
|
|
10
|
-
let o=
|
|
11
|
-
if(o||(await new Promise(
|
|
4
|
+
s={at:Date.now(),bySession:r}}catch(t){e.logger.debug?.("MCP receipt: could not read associations",{error:(0,r.getErrorMessage)(t)}),s=s??{at:Date.now(),bySession:new Map}}return s.bySession.get(t)}}exports.requestForSession=o,exports.openMcpReceipt=async function(e,t){const s=await o(e,t.sessionId??""),n=t.target?` (${t.target})`:"",i=`${t.tool} on the "${t.connection}" MCP server${n}`,c=t.allowed?`Called ${i}`:`Did not run ${i}: ${t.reason}`,d={connection:t.connection,tool:t.tool,target:t.target??null,gate:t.verdict,status:t.allowed?"started":"refused",sessionId:t.sessionId??null,callId:t.callId??null,startedAt:(new Date).toISOString()}
|
|
5
|
+
try{const o=await e.apiClient.post(`/api/projects/${e.projectId}/tool-records`,{...s?{requestId:s}:{},type:"mcp-call",...t.sessionId?{cliOrigin:{providerId:"opencode",sessionId:t.sessionId,createdAt:(new Date).toISOString()}}:{},metadata:d,note:c}),r=o?.data?.id??o?.id
|
|
6
|
+
t.allowed&&t.callId&&r&&(a.set(t.callId,{recordId:String(r),startedAt:Date.now(),metadata:d}),function(){if(a.size<=500)return
|
|
7
|
+
const e=[...a.entries()].sort((e,t)=>e[1].startedAt-t[1].startedAt)
|
|
8
|
+
for(const[t]of e){if(a.size<=500)break
|
|
9
|
+
a.delete(t)}}())}catch(o){e.logger.error("MCP receipt could not be written",{connection:t.connection,tool:t.tool,error:(0,r.getErrorMessage)(o)})}},exports.recordIdForCall=function(e){if(e)return a.get(e)?.recordId},exports.closeMcpReceipt=async function(e,t){if(!t.callId)return
|
|
10
|
+
let o=a.get(t.callId)
|
|
11
|
+
if(o||(await new Promise(e=>setTimeout(e,250)),o=a.get(t.callId)),o){a.delete(t.callId)
|
|
12
12
|
try{await e.apiClient.patch(`/api/projects/${e.projectId}/tool-records/${o.recordId}`,{metadata:{...o.metadata,status:t.ok?"completed":"failed",durationMs:Date.now()-o.startedAt,finishedAt:(new Date).toISOString(),...t.outputPreview?{outputPreview:t.outputPreview.slice(0,500)}:{},...t.error?{error:String(t.error).slice(0,500)}:{}}})}catch(o){e.logger.warn("MCP receipt could not be closed",{callId:t.callId,error:(0,r.getErrorMessage)(o)})}}}
|
|
13
|
-
const r=t(58824),
|
|
14
|
-
let
|
|
15
|
-
const i=3e4}}
|
|
13
|
+
const r=t(58824),a=new Map
|
|
14
|
+
let s=null}}
|
package/dist/24.js
CHANGED
|
@@ -1,235 +1,37 @@
|
|
|
1
1
|
"use strict"
|
|
2
|
-
exports.
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
let c=null
|
|
6
|
-
try{const{generateProjectMap:e}=await t.e(356).then(t.t.bind(t,69356,23))
|
|
7
|
-
c=e(r||process.cwd())}catch{c=null}return l||c?[l,c].filter(Boolean).join("\n\n"):null}catch(e){return i.warn("pickup-compose failed; the association hook will deliver guidance as an inject",{requestId:s,error:(0,b.getErrorMessage)(e)}),null}}async function o(e){const{apiClient:t,fromSessionId:n,toSessionId:s,body:o,requestId:i,logger:r}=e
|
|
8
|
-
if(!t||!n)return
|
|
9
|
-
const a=t.getSessionMessageClient()
|
|
10
|
-
if(a)try{const e=await a.createInstruction({fromSessionId:n,toSessionId:s,body:o,...i?{requestId:i}:{}})
|
|
11
|
-
return e?.messageCode}catch(e){return void r.warn("Failed to mint instruction code",{error:(0,b.getErrorMessage)(e),fromSessionId:n,toSessionId:s})}}async function i(e,t,n,s,o){if(e&&t&&n)try{await e.proxyPost(`/api/projects/${t}/session-messages/${encodeURIComponent(n)}/delivered`,{ok:s.ok,error:s.detail||s.error,messageId:s.messageId})}catch(e){o.warn("instruction delivery receipt not written",{instructionCode:n,error:(0,b.getErrorMessage)(e)})}}async function r(e,t,r,a,l){const{agent:c="work",prompt:d,requestId:u,allowParallel:g=!1,useExistingSession:p}=e
|
|
12
|
-
if(n(t,"handleSpawn called",{agent:c,promptLength:d.length,requestId:u,useExistingSession:p,cliOriginSessionId:l?.sessionId||null}),!(0,A.isValidAgent)(c))return{content:[{type:"text",text:`\u274c Unknown agent '${c}'.\n\n**Available agents:** ${(0,A.getAgentNames)().join(", ")}\n\nChoose one of the available agents listed above to see detailed descriptions of each agent.`}],isError:!0}
|
|
13
|
-
const f=l?.sessionId,h=f?S.sessionIdentity.getAgentTypeFor(f).then((e=>e||void 0)):Promise.resolve(void 0),m=async function(e){try{const t=`http://localhost:${T}/api/agents/by-name/${encodeURIComponent(e)}`,n=await fetch(t,{signal:AbortSignal.timeout(8e3)})
|
|
14
|
-
if(!n.ok)return null
|
|
15
|
-
const s=await n.json()
|
|
16
|
-
return s.success?s.data??null:null}catch{return null}}(c).catch((()=>null)),x=(0,y.getServerUrl)(t,r),v=(async()=>{if(!a||!u)return null
|
|
17
|
-
const e=a.getSessionRequestAssociationClient()
|
|
18
|
-
return e?await e.getSessionsForRequest(u,!0):null})().catch((e=>(r.debug("Failed to check for existing workers",{error:(0,b.getErrorMessage)(e)}),null))),[E,j,P,R]=await Promise.all([h,m,x,v])
|
|
19
|
-
try{if(n(t,"Spawn agent type check",{callerSessionId:f||null,callerAgentType:E||null,pid:process.pid}),E){const e=(0,A.getAllowedSubagents)(E)
|
|
20
|
-
if(e&&!e.includes(c))return{content:[{type:"text",text:`\u274c Agent type '${E}' cannot spawn '${c}'.\n\n**Allowed subagents for ${E}:** ${e.join(", ")}\n\nUse one of the allowed agent types instead.`}],isError:!0}}}catch(e){n(t,"allowedSubagents check failed",{error:(0,b.getErrorMessage)(e)})}let M=j?.requestContextMode
|
|
21
|
-
if(!M){const e=(0,A.getBuiltInAgentConfig)(c)
|
|
22
|
-
M=e?.requestContextMode}if(M&&"none"!==M&&!u)return{content:[{type:"text",text:`\u274c Agent '${c}' requires a requestId to be provided.\n\nThis agent has requestContextMode: '${M}' which means it needs to work in the context of a specific request.\n\nPlease provide a requestId when spawning this agent.`}],isError:!0}
|
|
23
|
-
if(u&&"required"===M&&a)try{const e=await a.getRequestClient().getRequest(u)
|
|
24
|
-
if("draft"===e?.status){const t=e?.intake,n="rejected"===t?.status?`the intake reviewer rejected it: ${String(t?.objection||"").slice(0,240)||"(no objection text)"}`:"pending"===t?.status?"it is held at intake awaiting a verdict":"it has not been registered"
|
|
25
|
-
return{content:[{type:"text",text:`\u274c ${u} is a DRAFT: ${n}.\n\nWork cannot start on drafts. Wait for the request to be registered (the user resolves the intake question from the timeline), or address the objection with a revised proposal. Do NOT spawn workers for draft requests.`}],isError:!0}}}catch(e){n(t,"draft-spawn guard read failed (continuing)",{error:(0,b.getErrorMessage)(e)})}if(n(t,"serverUrl resolved",{serverUrl:P}),!t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath&&!t.basePath)throw new w.ValidationError("Working directory not available in context")
|
|
26
|
-
const U=l?.sessionId
|
|
27
|
-
let D=""
|
|
28
|
-
if(R){const e=(U?R.filter((e=>e.opencodeSessionId!==U)):R).filter((e=>!1!==e.working))
|
|
29
|
-
if(e.length>0){const t=e.map((e=>e.opencodeSessionId)).join(", ")
|
|
30
|
-
if(!g)return r.warn("Blocked spawn: request already has active workers",{requestId:u,existingWorkerCount:e.length,existingSessionIds:e.map((e=>e.opencodeSessionId))}),{content:[{type:"text",text:`\u274c Cannot spawn: Request ${u} already has ${e.length} active worker(s): ${t}\n\nOptions:\n\u2022 Use \`useExistingSession: "${e[0].opencodeSessionId}"\` to send work to the existing session\n\u2022 Use \`allowParallel: true\` if you really need multiple workers on the same request`}],isError:!0}
|
|
31
|
-
D=`\u26a0\ufe0f Warning: Request ${u} already has ${e.length} active worker(s): ${t}. Proceeding anyway (allowParallel=true).\n\n`,r.warn("Spawning parallel subagent for request with existing active workers",{requestId:u,existingWorkerCount:e.length,existingSessionIds:e.map((e=>e.opencodeSessionId)),allowParallel:!0})}}let L,O,F=d
|
|
32
|
-
u&&(L=`requests/${u}`,n(t,"Setting initialBranch for agent",{agent:c,requestId:u,initialBranch:L,agentRequestContextMode:M||"undefined"}),F="readonly"===M?`Working on request ${u} (READONLY mode - you cannot modify files, only explore and report).\n\n${d}`:`Working on request ${u}.\n\n${d}`)
|
|
33
|
-
let N,_=!1
|
|
34
|
-
if(p){if(O=p,r.info("Using existing session for spawn",{sessionId:O,requestId:u}),!P)throw new w.ValidationError("Could not determine OpenCode server URL")
|
|
35
|
-
try{let e
|
|
36
|
-
try{const t=await fetch(`http://localhost:${T}/api/project-settings`,{signal:AbortSignal.timeout(8e3)})
|
|
37
|
-
if(t.ok){const n=await t.json()
|
|
38
|
-
if(n.data?.defaultModel){const[t,...s]=n.data.defaultModel.split("/")
|
|
39
|
-
e={providerID:t,modelID:s.join("/")}}}}catch{}N=await o({apiClient:a,fromSessionId:l?.sessionId,toSessionId:O,body:F,requestId:u,logger:r})
|
|
40
|
-
let n=F
|
|
41
|
-
const d=await s(a,t.projectId,u,O,r,t.mainBasePath||t.basePath)
|
|
42
|
-
d&&(n=`${d}\n\n---\n\n${n}`)
|
|
43
|
-
const g={body:F,fromSessionId:l?.sessionId,fromAgent:E,...u?{requestId:u}:{},...N?{instructionCode:N}:{}},p=await(0,I.deliverToSession)(O,n,{kind:"agent-delegation",partPayload:g})
|
|
44
|
-
if(await i(a,t.projectId,N,p,r),!p.ok)throw new Error((0,I.deliveryFailureText)(O,p))
|
|
45
|
-
r.info("Prompt delivered to existing session",{sessionId:O,agent:c,messageId:p.messageId})}catch(e){throw new Error(`Failed to use existing session: ${(0,b.getErrorMessage)(e)}`)}}else{_=!0,n(t,"Creating session via spawn-session endpoint")
|
|
46
|
-
const i=U
|
|
47
|
-
q&&(0,k.logSessionIdentity)("subagent_operations.spawn","_meta",{parentSessionId:i})
|
|
48
|
-
try{const p=`http://localhost:${T}/api/spawn-session`,f=await fetch(p,{method:"POST",signal:AbortSignal.timeout(15e3),headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:c,prompt:d,requestId:u,parentSessionId:i,title:e.title,allowParallel:g,callerAgentType:E})})
|
|
49
|
-
if(!f.ok){const e=await f.text().catch((()=>"Unknown error"))
|
|
50
|
-
throw new Error(`Spawn session endpoint failed: ${f.status} ${e}`)}const h=await f.json()
|
|
51
|
-
if(!h.success||!h.data)throw new Error(h.error||"Spawn session returned unsuccessful")
|
|
52
|
-
const{sessionId:m,model:w,serverUrl:y,initialBranch:I}=h.data
|
|
53
|
-
L=I,N=await o({apiClient:a,fromSessionId:l?.sessionId,toSessionId:m,body:F,requestId:u,logger:r})
|
|
54
|
-
let S=F
|
|
55
|
-
const k="pickupGuidance"in(h?.data??{})?h.data.pickupGuidance??null:await s(a,t.projectId,u,m,r,t.mainBasePath||t.basePath)
|
|
56
|
-
k&&(S=`${k}\n\n---\n\n${S}`)
|
|
57
|
-
const b=await(0,$.deliverInitialPrompt)({serverUrl:y,sessionId:m,agent:c,prompt:S,model:w,directory:t.mainBasePath,metadata:{alchemy:{kind:"agent-delegation",payload:{body:F,fromSessionId:l?.sessionId,fromAgent:E,...u?{requestId:u}:{},...N?{instructionCode:N}:{}}}}})
|
|
58
|
-
if(!b.success)throw new Error(`Failed to spawn subagent: ${b.error}`)
|
|
59
|
-
O=m,n(t,"Spawn successful via unified endpoint",{sessionId:m,parentSessionId:i,model:w,instructionCode:N}),r.info("Background subagent spawned via unified endpoint",{agent:c,requestId:u,sessionId:m,parentSessionId:i,instructionCode:N})}catch(e){throw new Error(`Failed to spawn subagent: ${(0,b.getErrorMessage)(e)}`)}}let B=D
|
|
60
|
-
B+=p?`Prompt sent to existing session ${O}.`:`Background ${c} subagent spawned successfully.`,u&&(B+=`\nWorking on: ${u}`),N&&(B+=`\nInstruction code: ${N} (the agent will cite this on its reports/questions via relatesTo)`),B+="\n\nThe subagent is now working independently. You can continue with other tasks."
|
|
61
|
-
const W=!!O&&"unknown"!==O&&"spawning"!==O
|
|
62
|
-
return{content:[{type:"text",text:B}],...(0,C.alchemyMeta)({kind:"spawn-subagent",spawnedSessionId:W?O:void 0,agentType:c,requestId:u||void 0,description:e.title||d.slice(0,50)||c,...N?{instructionCode:N}:{}}),...N?{instructionCode:N}:{}}}async function a(e,t,n,s,r,a,l){if(!await(0,y.getServerUrl)(n,s))throw new w.ValidationError("Could not determine OpenCode server URL")
|
|
63
|
-
if(s.info("Sending message to subagent session",{sessionId:e,promptLength:t.length}),r)try{const t=l?.sessionId
|
|
64
|
-
if(t){const n=r.getCLISessionClient()
|
|
65
|
-
if(n){let o=await n.getByExternalId(t)
|
|
66
|
-
if(o||(o=await n.createOrUpdateSession({externalSessionId:t,providerId:"opencode",status:"active"}),s.info("Created caller session in DB for re-parenting",{callerSessionId:t,dbId:o?.id})),o){const i=await n.getByExternalId(e).catch((()=>null)),r=i?.parentSessionId??null
|
|
67
|
-
r===o.id?s.debug("Parent unchanged for continued agent; no re-parent write",{sessionId:e}):(await n.createOrUpdateSession({externalSessionId:e,providerId:"opencode",parentSessionId:o.id,status:"active"}),s.info("RE-PARENTED continued agent: reports now flow to the current caller",{sessionId:e,fromParentDbId:r,toParentDbId:o.id,toCallerSessionId:t}))}}}}catch(e){s.warn("Failed to update parent session - reports may go to wrong parent",{error:(0,b.getErrorMessage)(e)})}let c=a
|
|
68
|
-
if(!c)try{const t=`http://localhost:${T}/api/sessions/${encodeURIComponent(e)}/agent-type`,n=await fetch(t,{signal:AbortSignal.timeout(8e3)})
|
|
69
|
-
if(n.ok){const e=await n.json()
|
|
70
|
-
e.success&&e.agentType&&(c=e.agentType)}}catch{s.warn("Agent type lookup failed for session",{sessionId:e})}if(!c)throw new w.ValidationError(`Cannot continue session ${e}: unable to determine agent type. The session's agent type could not be looked up from the action server.`)
|
|
71
|
-
try{let a
|
|
72
|
-
try{const e=await fetch(`http://localhost:${T}/api/project-settings`,{signal:AbortSignal.timeout(8e3)})
|
|
73
|
-
if(e.ok){const t=await e.json()
|
|
74
|
-
if(t.data?.defaultModel){const[e,...n]=t.data.defaultModel.split("/")
|
|
75
|
-
a={providerID:e,modelID:n.join("/")}}}}catch{}const d=await o({apiClient:r,fromSessionId:l?.sessionId,toSessionId:e,body:t,logger:s}),u=t,g={body:t,fromSessionId:l?.sessionId,fromAgent:await S.sessionIdentity.getAgentTypeFor(l?.sessionId)||void 0,...d?{instructionCode:d}:{}},p=await(0,I.deliverToSession)(e,u,{kind:"agent-followup",partPayload:g})
|
|
76
|
-
return await i(r,n.projectId,d,p,s),p.ok?(s.info("Message delivered to subagent session",{sessionId:e,agent:c,instructionCode:d,messageId:p.messageId}),{content:[{type:"text",text:[d?`Message delivered to session ${e} (${d}); it is in that session's transcript.`:`Message delivered to session ${e}; it is in that session's transcript.`,c?`That session is a ${c}. It will process this in the background -- it is NOT proof that work started; check for tasks before reporting progress.`:"Role unknown for that session. It will process this in the background -- that is not proof work started; check for tasks before reporting progress."].join("\n")}],...d?{_meta:{alchemy:{kind:"continue-subagent",instructionCode:d}},instructionCode:d}:{}}):{content:[{type:"text",text:(0,I.deliveryFailureText)(e,p)+(c?` That session is a ${c}.`:"")}],isError:!0,...d?{_meta:{alchemy:{kind:"continue-subagent",instructionCode:d,failed:!0}},instructionCode:d}:{}}}catch(e){throw new Error(`Failed to continue session: ${(0,b.getErrorMessage)(e)}`)}}function l(e){const t=Math.floor(e/1e3)
|
|
77
|
-
if(t<60)return`${t}s`
|
|
78
|
-
const n=Math.floor(t/60)
|
|
79
|
-
return n<60?`${n}m ${t%60}s`:`${Math.floor(n/60)}h ${n%60}m`}function c(e){const t=[]
|
|
80
|
-
for(const n of e)if("assistant"===n.info.role&&n.parts)for(const e of n.parts)if("tool"===e.type&&e.tool&&e.state){const s=e.state.input||{}
|
|
81
|
-
let o=e.tool.replace(/^alchemy_/,"")
|
|
82
|
-
const i=s.path||s.file||s.directory,r=s.needle||s.query||s.pattern
|
|
83
|
-
"string"==typeof i?o+=` ${i.split("/").pop()||i}`:"string"==typeof r&&(o+=` "${r.length>30?r.slice(0,27)+"...":r}"`),t.push({name:o,state:e.state.status,time:n.info.time.created})}t.sort(((e,t)=>t.time-e.time))
|
|
84
|
-
const n=t.find((e=>"pending"===e.state||"running"===e.state)),s=t.filter((e=>"completed"===e.state||"error"===e.state)).slice(0,3),o=t.length>0?t[0].time:null
|
|
85
|
-
return{current:n?.name??null,recent:s.map((e=>e.name)),lastActivityTime:o}}function d(e){return e<1e3?"<1s ago":e<6e4?`${Math.floor(e/1e3)}s ago`:e<36e5?`${Math.floor(e/6e4)}m ago`:`${Math.floor(e/36e5)}h ago`}function u(e,t){const n=e||t,s=Date.now()-n
|
|
86
|
-
if(e&&s<j)return{status:"working",detail:`last action ${d(s)}`,isReady:!1}
|
|
87
|
-
const o=d(s).replace(/ ago$/,"")
|
|
88
|
-
return s>P&&e?{status:"stalled",detail:`no activity for ${o}`,isReady:!0}:e?{status:"idle",detail:`no activity for ${o}`,isReady:!0}:{status:"idle",detail:"no tool activity",isReady:!0}}function g(e){let t=0,n=0,s=0
|
|
89
|
-
for(const o of e.trim().split("\n")){if(!o)continue
|
|
90
|
-
const[e,i]=o.split("\t")
|
|
91
|
-
"-"!==e&&(t+=parseInt(e,10)||0),"-"!==i&&(n+=parseInt(i,10)||0),s++}return{additions:t,deletions:n,files:s}}function p(e,t,n,s){const o=e.get(t)
|
|
92
|
-
return e.set(t,{at:s,fingerprint:n}),o&&o.fingerprint===n?`Nothing changed since your last check at ${new Date(o.at).toISOString().slice(11,19)} UTC (${d(s-o.at)}): same activity, same messages, same tokens.`:null}async function f(e,n,s,o){const i=await(0,y.getServerUrl)(n,s)
|
|
93
|
-
if(!i)throw new w.ValidationError("Could not determine OpenCode server URL")
|
|
94
|
-
s.info("Checking status of subagent session",{sessionId:e})
|
|
95
|
-
try{const r=`${i.replace(/\/$/,"")}/session/${e}`,a=await fetch(r,{signal:AbortSignal.timeout(8e3)})
|
|
96
|
-
if(!a.ok)return{content:[{type:"text",text:`Session ${e} not found or has exited.`}],isError:!0}
|
|
97
|
-
const d=await a.json(),f=`${i.replace(/\/$/,"")}/session/${e}/message`,h=await fetch(f,{signal:AbortSignal.timeout(8e3)})
|
|
98
|
-
let m={input:0,output:0,reasoning:0},w="",$=u(null,d.time.updated),y=-1
|
|
99
|
-
if(h.ok){const e=await h.json()
|
|
100
|
-
y=e.length
|
|
101
|
-
for(const t of e)"assistant"===t.info.role&&t.info.tokens&&(m.input+=t.info.tokens.input||0,m.output+=t.info.tokens.output||0,m.reasoning+=t.info.tokens.reasoning||0)
|
|
102
|
-
const t=c(e)
|
|
103
|
-
$=u(t.lastActivityTime,d.time.updated),t.current&&(w+=`\nCurrent: ${t.current}`),t.recent.length>0&&(w+=`\nRecent: ${t.recent.join(", ")}`)}const I=Date.now()-d.time.created,S=$.status,k=$.isReady,b=m.input+m.output+m.reasoning
|
|
104
|
-
let x="",v="",A=null
|
|
105
|
-
if(o)try{const t=o.getSessionRequestAssociationClient()
|
|
106
|
-
if(t){const n=await t.getActiveRequestsForSession(e,!1)
|
|
107
|
-
if(n.length>0){const t=n.filter((e=>!e.endedAt)).sort(((e,t)=>new Date(t.startedAt).getTime()-new Date(e.startedAt).getTime())),o=n.filter((e=>e.endedAt)).sort(((e,t)=>new Date(t.endedAt).getTime()-new Date(e.endedAt).getTime())),i=o[0],r=t[0]
|
|
108
|
-
i&&r?A=new Date(i.endedAt).getTime()>new Date(r.startedAt).getTime()?i.requestLocalId:r.requestLocalId:i?A=i.requestLocalId:r&&(A=r.requestLocalId)
|
|
109
|
-
const a=[]
|
|
110
|
-
t.length>0&&a.push(`Active: ${t.map((e=>e.requestLocalId)).join(", ")}`),o.length>0&&a.push(`Previous: ${o.map((e=>e.requestLocalId)).join(", ")}`),a.length>0&&(v=`\nRequests: ${a.join(" | ")}`),s.debug("Found request associations",{sessionId:e,activeCount:t.length,historicalCount:o.length})}}}catch(e){s.debug("Failed to get request associations, falling back to title extraction",{error:e instanceof Error?e.message:String(e)})}if(A||(A=function(e){const t=e.match(/\[(req\d{6})\]/)
|
|
111
|
-
return t?t[1]:null}(d.title||"")),A&&n.basePath){const e=await async function(e,n){try{const{execFileSync:s}=await Promise.resolve().then(t.t.bind(t,35317,23)),o=`requests/${e}`
|
|
112
|
-
let i=!1
|
|
113
|
-
try{s("git",["rev-parse","--verify",o],{cwd:n,stdio:"pipe"}),i=!0}catch{i=!1}if(i){const e=s("git",["diff",`main...${o}`,"--numstat"],{cwd:n,encoding:"utf8"})
|
|
114
|
-
if(e.trim())return g(e)}try{const t=s("git",["log","main","--merges","--oneline","-n","50",`--grep=${e}`],{cwd:n,encoding:"utf8"}).trim()
|
|
115
|
-
if(t){const e=t.split("\n")[0].split(" ")[0],o=s("git",["diff",`${e}^1...${e}`,"--numstat"],{cwd:n,encoding:"utf8"})
|
|
116
|
-
if(o.trim())return{...g(o),merged:!0}}}catch{}return null}catch{return null}}(A,n.basePath)
|
|
117
|
-
if(e){const t=e.additions+e.deletions,n=e.merged?" (merged)":""
|
|
118
|
-
x=`\nDiff vs main (${A}): +${e.additions}/-${e.deletions} lines (${t} total) in ${e.files} file${1!==e.files?"s":""}${n}`}}const C=p(R,`${n.currentSessionId??""}>${e}`,`${d.time.updated}:${y}:${b}`,Date.now())
|
|
119
|
-
return{content:[{type:"text",text:`${C?`${C}\n\n`:""}Session ${e}\nTitle: ${d.title||"Untitled"}\nStatus: ${S} (${$.detail})\nReady for input: ${k?"Yes":"No"}\nAge: ${l(I)}\nTokens: ${b.toLocaleString()} (in: ${m.input.toLocaleString()}, out: ${m.output.toLocaleString()}${m.reasoning>0?`, reasoning: ${m.reasoning.toLocaleString()}`:""})${w}${v}${x}`}]}}catch(e){throw new Error(`Failed to check session status: ${(0,b.getErrorMessage)(e)}`)}}async function h(e,t,n){const s=await(0,y.getServerUrl)(t,n)
|
|
120
|
-
if(!s)throw new w.ValidationError("Could not determine OpenCode server URL")
|
|
121
|
-
n.info("Aborting subagent session",{sessionId:e})
|
|
122
|
-
try{const t=`${s.replace(/\/$/,"")}/session/${e}/abort`,o=await fetch(t,{signal:AbortSignal.timeout(8e3),method:"POST"})
|
|
123
|
-
if(!o.ok){const e=await o.text().catch((()=>"Unknown error"))
|
|
124
|
-
throw new Error(`Failed to abort session: ${o.status} ${e}`)}return n.info("Session aborted",{sessionId:e}),{content:[{type:"text",text:`Session ${e} has been aborted.`}]}}catch(e){throw new Error(`Failed to abort session: ${(0,b.getErrorMessage)(e)}`)}}async function m(e,t,n,s={}){const{activeOnly:o=!1,requestId:i,limit:r,minTokens:a,maxTokens:d,maxAgeHours:g}=s,p=await(0,y.getServerUrl)(e,t)
|
|
125
|
-
if(!p)throw new w.ValidationError("Could not determine OpenCode server URL")
|
|
126
|
-
t.info("Listing sessions",{filters:s})
|
|
127
|
-
try{const e=`${p.replace(/\/$/,"")}/session?limit=1000`,t=await fetch(e,{signal:AbortSignal.timeout(8e3)})
|
|
128
|
-
if(!t.ok)throw new Error(`Failed to fetch sessions: ${t.status}`)
|
|
129
|
-
let f=await t.json()
|
|
130
|
-
if(0===f.length)return{content:[{type:"text",text:"No sessions found."}]}
|
|
131
|
-
s.parentSessionId&&(f=f.filter((e=>(e.parentId||e.parentID)===s.parentSessionId))),f.sort(((e,t)=>t.time.created-e.time.created))
|
|
132
|
-
const h=`${p.replace(/\/$/,"")}/session/status`,m=await fetch(h,{signal:AbortSignal.timeout(8e3)}),w=m.ok?await m.json():{}
|
|
133
|
-
let $=f
|
|
134
|
-
if(o&&($=$.filter((e=>"idle"!==(w[e.id]?.type||"idle")))),void 0!==g){const e=60*g*60*1e3,t=Date.now()-e
|
|
135
|
-
$=$.filter((e=>e.time.created>=t))}if(0===$.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
|
|
136
|
-
let y={}
|
|
137
|
-
const I=$.map((e=>e.id))
|
|
138
|
-
if(n)try{const e=n.getCLISessionClient()
|
|
139
|
-
e&&(y=await e.batchEnrich(I))}catch{}const S=p.replace(/\/$/,""),k=await Promise.allSettled($.map((e=>fetch(`${S}/session/${e.id}/message`,{signal:AbortSignal.timeout(8e3)}).then((e=>e.ok?e.json():[])).catch((()=>[]))))),b=[]
|
|
140
|
-
for(let e=0;e<$.length;e++){const t=$[e],n=Date.now()-t.time.created
|
|
141
|
-
let o=0,r=null,l=[],g=u(null,t.time.updated)
|
|
142
|
-
const p=k[e],f="fulfilled"===p.status?p.value:[]
|
|
143
|
-
for(const e of f)"assistant"===e.info.role&&e.info.tokens&&(o+=(e.info.tokens.input||0)+(e.info.tokens.output||0)+(e.info.tokens.reasoning||0))
|
|
144
|
-
if(f.length>0){const e=c(f)
|
|
145
|
-
g=u(e.lastActivityTime,t.time.updated),r=e.current||null,l=e.recent}const h=g.status
|
|
146
|
-
if(void 0!==a&&o<a)continue
|
|
147
|
-
if(void 0!==d&&o>d)continue
|
|
148
|
-
const m=y[t.id]
|
|
149
|
-
if(s.agentType&&(!m||m.agentType!==s.agentType))continue
|
|
150
|
-
if("archived"===m?.status)continue
|
|
151
|
-
let w=""
|
|
152
|
-
const I=[],S=[]
|
|
153
|
-
if(m?.associations&&S.push(...m.associations),S.length>0){const e=new Map
|
|
154
|
-
for(const t of S){const n=e.get(t.requestLocalId)
|
|
155
|
-
void 0!==n&&(n||t.endedAt)||e.set(t.requestLocalId,!t.endedAt)}const t=[...e.entries()].filter((([,e])=>e)).map((([e])=>e)),n=[...e.entries()].filter((([,e])=>!e)).map((([e])=>e))
|
|
156
|
-
I.push(...t,...n)
|
|
157
|
-
const s=[]
|
|
158
|
-
if(t.length>0&&s.push(`active: ${t.join(", ")}`),n.length>0){const e=5,t=n.slice(0,e),o=n.length-t.length
|
|
159
|
-
s.push(`prev: ${t.join(", ")}${o>0?` +${o} more`:""}`)}s.length>0&&(w=` [${s.join(" | ")}]`)}if(i&&!I.includes(i))continue
|
|
160
|
-
const x=t.title||"Untitled",v=x.length>50?x.slice(0,47)+"...":x
|
|
161
|
-
b.push({id:t.id,title:v,status:h,age:n,totalTokens:o,requestsInfo:w,allRequestIds:I,statusDetail:g.detail,currentAction:r,recentActions:l})}if(0===b.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
|
|
162
|
-
const x=r?b.slice(0,r):b,v=x.map((e=>{const t=e.currentAction?`\n Current: ${e.currentAction}`:"",n=e.recentActions.length>0?`\n Recent: ${e.recentActions.join(", ")}`:""
|
|
163
|
-
return`\u2022 ${e.id}\n ${e.title}\n Status: ${e.status} (${e.statusDetail}) | Age: ${l(e.age)} | ${e.totalTokens.toLocaleString()} tokens${e.requestsInfo}${t}${n}`})),A=r&&b.length>r?` (showing ${r} of ${b.length})`:""
|
|
164
|
-
return{content:[{type:"text",text:`Found ${x.length} session${1!==x.length?"s":""}${A}:\n\n${v.join("\n\n")}`}]}}catch(e){throw new Error(`Failed to list sessions: ${(0,b.getErrorMessage)(e)}`)}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpawn=r,exports.handleContinue=a,exports.extractRecentActivity=c,exports.formatTimeSince=d,exports.deriveActivityStatus=u,exports.noteStatusCheck=p,exports.handleCheckStatus=f,exports.handleAbort=h,exports.handleListSessions=m,exports.handleSubagentOperations=async function(e,t,n,s,o,i){const l=n.child({tool:"subagent_operations"}),c=s.startTimer("tool_execution_time")
|
|
165
|
-
try{const n=e,{sessionId:d,operation:u}=n
|
|
166
|
-
let g
|
|
167
|
-
switch(l.info("Processing subagent_operations",{operation:u,sessionId:d}),u){case"spawn":g=await r({agent:n.agent,prompt:n.prompt,requestId:n.requestId,allowParallel:n.allowParallel,useExistingSession:n.useExistingSession},t,l,o,i)
|
|
168
|
-
break
|
|
169
|
-
case"continue":g=await a(d,n.prompt,t,l,o,void 0,i)
|
|
170
|
-
break
|
|
171
|
-
case"check-status":g=await f(d,t,l,o)
|
|
172
|
-
break
|
|
173
|
-
case"abort":g=await h(d,t,l)
|
|
174
|
-
break
|
|
175
|
-
case"read-messages":{const e=!(!n.compact&&null==n.select),s=!e&&null==n.limit,o=n.limit??(e?50:8)
|
|
176
|
-
g=await async function(e,t,n,s,o){const i=await(0,y.getServerUrl)(n,s)
|
|
177
|
-
if(!i)throw new w.ValidationError("Could not determine OpenCode server URL")
|
|
178
|
-
s.info("Reading messages from subagent session",{sessionId:e,limit:t,compact:o?.compact,select:o?.select})
|
|
179
|
-
try{const n=`${i.replace(/\/$/,"")}/session/${e}/message?limit=${t}`,s=await fetch(n,{signal:AbortSignal.timeout(8e3)})
|
|
180
|
-
if(!s.ok){if(404===s.status)return{content:[{type:"text",text:`Session ${e} not found.`}],isError:!0}
|
|
181
|
-
throw new Error(`Failed to fetch messages: ${s.status}`)}const r=await s.json()
|
|
182
|
-
if(0===r.length)return{content:[{type:"text",text:`Session ${e} has no messages yet.`}]}
|
|
183
|
-
const a=(e,t)=>e.length>t?e.slice(0,t)+"\u2026[truncated]":e,l=e=>"user"===e.info.role?"USER":"ASSISTANT",c=e=>new Date(e.info.time.created).toLocaleTimeString(),d=e=>`\u{1f527} ${e.tool||"tool"}${"error"===e.state?.status?" \u2717":""}`,u=e=>Array.isArray(e)?e.map((e=>"image"===e?.type?"[image]":"string"==typeof e?.text?e.text:JSON.stringify(e))).join(" "):"string"==typeof e?e:JSON.stringify(e??"")
|
|
184
|
-
if("number"==typeof o?.select){const t=r[o.select-1]
|
|
185
|
-
if(!t)return{content:[{type:"text",text:`No message #${o.select} (session has ${r.length}; use compact to index).`}],isError:!0}
|
|
186
|
-
const n=[`Session ${e}: message ${o.select} of ${r.length}: ${l(t)} (${c(t)}):`,""]
|
|
187
|
-
for(const e of t.parts)if("text"===e.type&&e.text)n.push(`TEXT: ${a(e.text,6e3)}`)
|
|
188
|
-
else if("tool"===e.type){const t=e.state||{}
|
|
189
|
-
n.push(`\u{1f527} ${e.tool||"tool"} [${t.status??"unknown"}]`),n.push(` input: ${a("string"==typeof t.input?t.input:JSON.stringify(t.input??{}),2500)}`)
|
|
190
|
-
const s=u(t.output)
|
|
191
|
-
s&&n.push(` output: ${a(s,1500)}`)}return{content:[{type:"text",text:n.join("\n")}]}}if(o?.compact){const t=r.map(((e,t)=>{const n=e.parts.filter((e=>"tool"===e.type)).map(d),s=e.parts.filter((e=>"text"===e.type&&e.text)).map((e=>e.text)).join(" ").replace(/\s+/g," ").trim().slice(0,140),o=[...n,s?`"${s}${s.length>=140?"\u2026":""}"`:""].filter(Boolean).join(" \xb7 ")
|
|
192
|
-
return`[${t+1}] ${"USER"===l(e)?"USER":"ASST"} (${c(e)}): ${o||"(empty)"}`}))
|
|
193
|
-
return{content:[{type:"text",text:`Session ${e}: ${r.length} messages (compact; use select:N for one in full):\n\n${t.join("\n")}`}]}}const g=(e,t)=>{const n=[`[${t+1}] ${l(e)} (${c(e)}):`]
|
|
194
|
-
for(const t of e.parts)if("text"===t.type&&t.text)n.push(a(t.text,5e3))
|
|
195
|
-
else if("tool"===t.type){const e=t.state||{},s=u(e.output).replace(/\s+/g," ").trim()
|
|
196
|
-
n.push(`\u{1f527} ${t.tool||"tool"} [${e.status??"unknown"}]${s?` \u2192 ${a(s,200)}`:""}`)}return n.length>1?n.join("\n"):`${n[0]}\n(no content)`}
|
|
197
|
-
if(o?.latest){const t=e=>e.parts.some((e=>"text"===e.type&&e.text||"tool"===e.type))
|
|
198
|
-
let n=r.length-1
|
|
199
|
-
for(;n>0&&!t(r[n]);)n--
|
|
200
|
-
const s=r.length-1-n
|
|
201
|
-
return{content:[{type:"text",text:`Session ${e}: latest message${s>0?` (skipped ${s} trailing empty message${1===s?"":"s"}; use compact:true for the full trajectory)`:""}:\n\n${g(r[n],n)}`}]}}const p=r.map(((e,t)=>g(e,t))).join("\n\n---\n\n")
|
|
202
|
-
return{content:[{type:"text",text:`Session ${e}: last ${r.length} messages:\n\n${p}`}]}}catch(e){throw new Error(`Failed to read messages: ${(0,b.getErrorMessage)(e)}`)}}(d,o,t,l,{compact:n.compact,select:n.select,latest:s})
|
|
203
|
-
break}case"list-sessions":const e={activeOnly:n.activeOnly,requestId:n.requestId,limit:n.limit,minTokens:n.minTokens,maxTokens:n.maxTokens,maxAgeHours:n.maxAgeHours,parentSessionId:i?.sessionId}
|
|
204
|
-
g=await m(t,l,o,e)
|
|
205
|
-
break
|
|
206
|
-
default:throw new w.ValidationError(`Unknown operation: ${u}`)}c({success:!0}),s.incrementCounter(`subagent_operations_${u}_success`,1)
|
|
207
|
-
const p=E[u]
|
|
208
|
-
return p?(0,C.withAlchemyKind)(g,p):g}catch(e){return l.error("Subagent operations failed",{error:e instanceof Error?e.stack:String(e)}),c({success:!1}),s.incrementCounter("subagent_operations_errors",1),{content:[{type:"text",text:`Subagent operation failed: ${(0,b.getErrorMessage)(e)}`}],isError:!0}}}
|
|
209
|
-
const w=t(59860),$=t(15899),y=t(47617),I=t(39844),S=t(6688),k=t(87280),b=t(58824),x=t(79896),v=t(16928),A=t(8955),C=t(82272),E={spawn:"spawn-subagent",continue:"continue-subagent","check-status":"check-subagent-status",abort:"abort-subagent","read-messages":"read-subagent-messages","list-sessions":"list-subagent-sessions"},q="true"===process.env.ALCHEMY_DEBUG_LOGS,T=(0,t(79414).getActionServerPort)(),j=6e4,P=3e5,R=new Map},80024:(e,exports,t)=>{exports.formatLiveWorker=function(e){const t=e.agentType?e.agentType:"worker",n=[],s=!0===e.busy?"mid-turn":!1===e.busy?"between turns":"unknown"
|
|
210
|
-
return n.push(`- ${t} (${e.sessionId}): ${e.status}, ${e.detail}; ${s}`),e.current&&n.push(` now: ${e.current}`),e.recent.length>0&&n.push(` recently: ${e.recent.join(", ")}`),e.lastSaid&&n.push(` last said${e.lastSaidAgo?` (${e.lastSaidAgo})`:""}: "${e.lastSaid}"`),e.lastRefusal&&n.push(` last refused (its tool said): ${e.lastRefusal}`),n.join("\n")},exports.readLiveWorker=async function(e,t){if(!e)return null
|
|
211
|
-
const i=t.filter((e=>(0,s.isWorkerAgentType)(e.agentType??""))),r=(i.length>0?i:t).slice(-1)[0]
|
|
2
|
+
exports.ids=[24],exports.modules={80024(t,exports,e){exports.formatLiveWorker=function(t){const e=t.agentType?t.agentType:"worker",s=[],n=!0===t.busy?"mid-turn":!1===t.busy?"between turns":"unknown"
|
|
3
|
+
return s.push(`- ${e} (${t.sessionId}): ${t.status}, ${t.detail}; ${n}`),t.current&&s.push(` now: ${t.current}`),t.recent.length>0&&s.push(` recently: ${t.recent.join(", ")}`),t.lastSaid&&s.push(` last said${t.lastSaidAgo?` (${t.lastSaidAgo})`:""}: "${t.lastSaid}"`),t.lastRefusal&&s.push(` last refused (its tool said): ${t.lastRefusal}`),s.join("\n")},exports.readLiveWorker=async function(t,e){if(!t)return null
|
|
4
|
+
const i=e.filter(t=>(0,n.isWorkerAgentType)(t.agentType??"")),r=(i.length>0?i:e).slice(-1)[0]
|
|
212
5
|
if(!r)return null
|
|
213
|
-
const a=
|
|
214
|
-
try{const[e,
|
|
215
|
-
if(!
|
|
216
|
-
const i=await
|
|
6
|
+
const a=t.replace(/\/$/,"")
|
|
7
|
+
try{const[t,e,n]=await Promise.all([fetch(`${a}/session/${r.sessionId}`,{signal:AbortSignal.timeout(5e3)}),fetch(`${a}/session/${r.sessionId}/message?limit=60`,{signal:AbortSignal.timeout(8e3)}),fetch(`${a}/session/status`,{signal:AbortSignal.timeout(5e3)}).catch(()=>null)])
|
|
8
|
+
if(!t.ok||!e.ok)return null
|
|
9
|
+
const i=await t.json(),l=await e.json()
|
|
217
10
|
let c=null
|
|
218
|
-
if(
|
|
219
|
-
c=void 0!==
|
|
220
|
-
let
|
|
221
|
-
for(let
|
|
222
|
-
if("assistant"!==
|
|
223
|
-
const
|
|
224
|
-
if(
|
|
225
|
-
break}}const
|
|
226
|
-
if("user"===
|
|
227
|
-
const s
|
|
228
|
-
for(let
|
|
229
|
-
if("tool"!==
|
|
230
|
-
const
|
|
231
|
-
if("error"===
|
|
232
|
-
return`${
|
|
233
|
-
if("string"==typeof
|
|
234
|
-
return{sessionId:r.sessionId,agentType:r.agentType,busy:c,status:
|
|
235
|
-
const
|
|
11
|
+
if(n&&n.ok)try{const t=await n.json(),e=t?.[r.sessionId]
|
|
12
|
+
c=void 0!==e&&"busy"===("string"==typeof e?e:e?.type)}catch{}const u=(0,s.extractRecentActivity)(l),f=(0,s.deriveActivityStatus)(u.lastActivityTime,i.time?.updated??Date.now())
|
|
13
|
+
let p=null,d=null
|
|
14
|
+
for(let t=l.length-1;t>=0;t--){const e=l[t]
|
|
15
|
+
if("assistant"!==e.info.role)continue
|
|
16
|
+
const n=(e.parts??[]).filter(t=>"text"===t.type&&t.text).map(t=>t.text).join(" ").replace(/\s+/g," ").trim()
|
|
17
|
+
if(n){p=n.length>220?n.slice(0,217)+"...":n,d=(0,s.formatTimeSince)(Date.now()-(e.info.time.completed??e.info.time.created))
|
|
18
|
+
break}}const g=function(t){for(let e=t.length-1;e>=0;e--){const s=t[e]
|
|
19
|
+
if("user"===s.info.role)return null
|
|
20
|
+
const n=s.parts??[]
|
|
21
|
+
for(let t=n.length-1;t>=0;t--){const e=n[t]
|
|
22
|
+
if("tool"!==e.type)continue
|
|
23
|
+
const s="error"===e.state?.status?String(e.state?.error??""):"string"==typeof e.state?.output?e.state.output:""
|
|
24
|
+
if("error"===e.state?.status||o.test(s)){const t=String(e.tool??"tool").replace(/^alchemy_/,""),n=s.replace(/\s+/g," ").trim()
|
|
25
|
+
return`${t}: ${n.length>240?n.slice(0,237)+"...":n}`}}}return null}(l),y=function(t){for(let e=t.length-1;e>=0;e--){const s=t[e]?.info,n=s?.providerID??s?.model?.providerID
|
|
26
|
+
if("string"==typeof n&&n)return n}return null}(l)
|
|
27
|
+
return{sessionId:r.sessionId,agentType:r.agentType,busy:c,status:f.status,detail:f.detail,current:u.current,recent:u.recent,lastSaid:p,lastSaidAgo:d,lastRefusal:g,provider:y}}catch{return null}}
|
|
28
|
+
const s=e(51725),n=e(87780),o=/^\s*(?:Error:|\u26d4|\u274c|Not filed|Not started|Not kept|Cannot |STOP:)/},51725(t,exports,e){function s(t){return t<1e3?"<1s ago":t<6e4?`${Math.floor(t/1e3)}s ago`:t<36e5?`${Math.floor(t/6e4)}m ago`:`${Math.floor(t/36e5)}h ago`}exports.extractRecentActivity=function(t){const e=[]
|
|
29
|
+
for(const s of t)if("assistant"===s.info.role&&s.parts)for(const t of s.parts)if("tool"===t.type&&t.tool&&t.state){const n=t.state.input||{}
|
|
30
|
+
let o=t.tool.replace(/^alchemy_/,"")
|
|
31
|
+
const i=n.path||n.file||n.directory,r=n.needle||n.query||n.pattern
|
|
32
|
+
"string"==typeof i?o+=` ${i.split("/").pop()||i}`:"string"==typeof r&&(o+=` "${r.length>30?r.slice(0,27)+"...":r}"`),e.push({name:o,state:t.state.status,time:s.info.time.created})}e.sort((t,e)=>e.time-t.time)
|
|
33
|
+
const s=e.find(t=>"pending"===t.state||"running"===t.state),n=e.filter(t=>"completed"===t.state||"error"===t.state).slice(0,3),o=e.length>0?e[0].time:null
|
|
34
|
+
return{current:s?.name??null,recent:n.map(t=>t.name),lastActivityTime:o}},exports.formatTimeSince=s,exports.deriveActivityStatus=function(t,e){const n=t||e,o=Date.now()-n
|
|
35
|
+
if(t&&o<6e4)return{status:"working",detail:`last action ${s(o)}`,isReady:!1}
|
|
36
|
+
const i=s(o).replace(/ ago$/,"")
|
|
37
|
+
return o>3e5&&t?{status:"stalled",detail:`no activity for ${i}`,isReady:!0}:t?{status:"idle",detail:`no activity for ${i}`,isReady:!0}:{status:"idle",detail:"no tool activity",isReady:!0}},e(59860),e(15899),e(47617),e(39844),e(6688),e(87280),e(58824),e(79896),e(16928),e(8955),e(82272),process.env.ALCHEMY_DEBUG_LOGS,(0,e(79414).getActionServerPort)(),new Map}}
|
package/dist/293.js
CHANGED
|
@@ -1,56 +1,58 @@
|
|
|
1
1
|
"use strict"
|
|
2
|
-
exports.
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
const o=
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
if(
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const
|
|
12
|
-
if(
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
const
|
|
16
|
-
if(
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
if(
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
if(0!==
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
t.
|
|
39
|
-
const
|
|
40
|
-
if(0!==i.exit){const t=(i.stderr||i.stdout||`exit ${i.exit}`).trim().split("\n").slice(-6).join("\n")
|
|
41
|
-
return{ok:!1,error:`docker build of ${e.dockerfile} failed: ${t.slice(0,600)}`}}return t.info("MCP connection image built",{name:e.name,image:r}),{ok:!0,image:r}},exports.execCommandFromImageConfig=s,exports.repoCommand=async function(e,t){const r=await(0,l.docker)(["image","inspect","-f","{{json .Config.Entrypoint}}\n{{json .Config.Cmd}}",t],l.DOCKER_OP_TIMEOUT_MS)
|
|
2
|
+
exports.ids=[293],exports.modules={79293(e,exports,t){function r(e){const t=e.lastIndexOf("@"),r=t>0?e.slice(t+1):""
|
|
3
|
+
if(!r||!/^\d/.test(r))throw new Error(`"${e}" has no pinned version. A boxed connection installs once and reuses that build, so it needs an exact version, for example ${function(e){const t=String(e??"").lastIndexOf("@")
|
|
4
|
+
return t>0?e.slice(0,t):String(e??"")}(e)}@1.2.3.`)
|
|
5
|
+
return r}exports.K4=void 0,exports.prepareConnectionArtifact=async function(e,t){const o=String(e.packageSpec??"")
|
|
6
|
+
r(o)
|
|
7
|
+
const u=function(e){return r(e),(0,a.addressedName)("alchemy-mcp-pkg",e)}(o)
|
|
8
|
+
if(await async function(e){return!!await(0,n.volumeExists)(e)&&0===(await(0,n.docker)(["run","--rm","-v",`${e}:/pkg:ro`,"alpine:3.20","test","-f",`/pkg/${l}`],n.DOCKER_OP_TIMEOUT_MS)).exit}(u))return t.info("MCP artifact already installed, reusing",{volume:u,package:o}),{ok:!0,volume:u}
|
|
9
|
+
const d=e.image??c,m=await(0,n.ensureImage)(d)
|
|
10
|
+
if(m)return{ok:!1,error:m}
|
|
11
|
+
const p=await(0,n.docker)(["run","--rm","-u","0","-v",`${u}:/pkg`,"alpine:3.20","sh","-c","touch /pkg/.owner && chown -R 1000:1000 /pkg"],n.DOCKER_OP_TIMEOUT_MS)
|
|
12
|
+
if(0!==p.exit)return{ok:!1,error:`could not prepare the artifact volume: ${(p.stderr||"").trim()}`}
|
|
13
|
+
const g=new i.EgressProxy(`mcp-pkg-${Date.now()}-${process.pid}`,exports.K4,!1)
|
|
14
|
+
let f=[],k=[]
|
|
15
|
+
const h=await g.start().catch(e=>({ok:!1,error:String(e)}))
|
|
16
|
+
if(!h.ok||!h.network)return await g.stop().catch(()=>{}),{ok:!1,error:`could not start the registry proxy, refusing to install with open egress: ${h.error??"unknown"}`}
|
|
17
|
+
f=["--network",h.network],k=Object.entries(h.proxyEnv||{}).flatMap(([e,t])=>["-e",`${e}=${t}`]),t.info("Installing MCP connection artifact",{package:o,volume:u})
|
|
18
|
+
const w=await(0,n.docker)(["run","--rm","--label",s,"--user","1000:1000","--cap-drop","ALL","--security-opt","no-new-privileges","--read-only","--tmpfs","/tmp:rw,nosuid,nodev,exec,size=512m","--ipc","none","--memory","2g","--memory-swap","2g","--cpus","2","--pids-limit","512","-e","HOME=/tmp","-e","npm_config_cache=/tmp/.npm",...f,...k,"-v",`${u}:/pkg`,"-w","/pkg",d,"sh","-c",`npm install --no-audit --no-fund --no-package-lock ${o} && touch /pkg/${l}`],3e5)
|
|
19
|
+
return await g.stop().catch(()=>{}),0!==w.exit?{ok:!1,error:`install failed: ${(w.stderr||w.stdout||`exit ${w.exit}`).trim().slice(0,400)}`}:(t.info("MCP connection artifact installed",{package:o,volume:u}),{ok:!0,volume:u})},exports.ensureConnectionBox=async function(e,t,r){const i=(m=e.projectId,p=e.name,(0,a.addressedName)("alchemy-mcp-box",m,p)),l=function(e,t){return(0,a.addressedName)("alchemy-mcp-state",e,t)}(e.projectId,e.name),u=e.image??c,d=await(0,n.docker)(["inspect","-f",'{{.State.Running}} {{index .Config.Labels "alchemy.image"}}',i],n.DOCKER_OP_TIMEOUT_MS)
|
|
20
|
+
var m,p
|
|
21
|
+
if(0===d.exit){const[e,t]=d.stdout.trim().split(/\s+/,2)
|
|
22
|
+
if("true"===e&&(t??"")===u)return{ok:!0,box:i}
|
|
23
|
+
"true"===e&&r.info("MCP connection box holds another image, replacing it",{box:i,was:t,now:u}),await(0,n.docker)(["rm","-f",i],n.DOCKER_OP_TIMEOUT_MS)}const g=null===t?void 0:await(0,n.ensureImage)(u)
|
|
24
|
+
if(g)return{ok:!1,error:g}
|
|
25
|
+
const f=await(0,n.docker)(["run","--rm","-u","0","-v",`${l}:/state`,"alpine:3.20","sh","-c","touch /state/.owner && chown -R 1000:1000 /state"],n.DOCKER_OP_TIMEOUT_MS)
|
|
26
|
+
if(0!==f.exit)return{ok:!1,error:`could not prepare the state volume: ${(f.stderr||"").trim()}`}
|
|
27
|
+
const k=Object.entries(e.environment??{}).flatMap(([e,t])=>["-e",`${e}=${t}`]),h=await(0,n.docker)(["create","--name",i,"--label",s,"--label",`alchemy.project=${e.projectId}`,"--label",`alchemy.image=${u}`,"--label",`alchemy.connection=${e.name}`,...(0,o.hardenedCreateArgs)({network:(w=e.egress,"open"===w?"bridge":"none"),user:"1000:1000",memory:"1g",cpus:1,pidsLimit:256,...null===t?{extraTmpfs:["/scratch:rw,nosuid,nodev,size=1g"]}:{}}),...k,...null===t?[]:["-v",`${t}:/pkg:ro`],...null===t?["--entrypoint","tail"]:[],"-v",`${l}:/state`,...e.worktreePath?["-v",`${e.worktreePath}:/work:ro`,"-w","/work"]:["-w","/state"],u,...null===t?["-f","/dev/null"]:["tail","-f","/dev/null"]],n.DOCKER_OP_TIMEOUT_MS)
|
|
28
|
+
var w
|
|
29
|
+
if(0!==h.exit)return{ok:!1,error:`could not create the box: ${(h.stderr||"").trim()}`}
|
|
30
|
+
const x=await(0,n.docker)(["start",i],n.DOCKER_OP_TIMEOUT_MS)
|
|
31
|
+
return 0!==x.exit?(await(0,n.docker)(["rm","-f",i],n.DOCKER_OP_TIMEOUT_MS),{ok:!1,error:`could not start the box: ${(x.stderr||"").trim()}`}):(r.info("MCP connection box up",{box:i,image:u,package:e.packageSpec??null,egress:e.egress??"none"}),{ok:!0,box:i})},exports.boxedCommand=function(e,t){return["docker","exec","-i",e,"node",`/pkg/node_modules/.bin/${t}`]},exports.prepareRepoImage=async function(e,t){const r=(i=e.projectId,c=e.name,s=e.dockerfile,l=e.treeHash,`${(0,a.addressedName)("alchemy-mcp-repo",i,c,s,l)}:latest`),o=await(0,n.docker)(["image","inspect",r],n.DOCKER_OP_TIMEOUT_MS)
|
|
32
|
+
var i,c,s,l
|
|
33
|
+
if(o.spawnError)return{ok:!1,error:o.spawnError}
|
|
34
|
+
if(0===o.exit)return{ok:!0,image:r}
|
|
35
|
+
const u=e.context?.trim()||"."
|
|
36
|
+
t.info("Building MCP connection image from the repository",{name:e.name,dockerfile:e.dockerfile,context:u,tree:e.treeHash.slice(0,12),image:r})
|
|
37
|
+
const d=await(0,n.docker)(["build","-f",`${e.projectPath}/${e.dockerfile}`,"-t",r,`${e.projectPath}/${u}`],12e5)
|
|
38
|
+
if(0!==d.exit){const t=(d.stderr||d.stdout||`exit ${d.exit}`).trim().split("\n").slice(-6).join("\n")
|
|
39
|
+
return{ok:!1,error:`docker build of ${e.dockerfile} failed: ${t.slice(0,600)}`}}return t.info("MCP connection image built",{name:e.name,image:r}),{ok:!0,image:r}},exports.repoCommand=async function(e,t){const r=await(0,n.docker)(["image","inspect","-f","{{json .Config.Entrypoint}}\n{{json .Config.Cmd}}",t],n.DOCKER_OP_TIMEOUT_MS)
|
|
42
40
|
if(0!==r.exit)return{ok:!1,error:`could not read the image's entrypoint: ${(r.stderr||"").trim()}`}
|
|
43
|
-
const[
|
|
44
|
-
return Array.isArray(t)?t:null}catch{return null}},
|
|
45
|
-
return
|
|
46
|
-
return await new Promise(
|
|
41
|
+
const[o,i]=r.stdout.trim().split("\n"),a=e=>{try{const t=JSON.parse(e??"null")
|
|
42
|
+
return Array.isArray(t)?t:null}catch{return null}},c=function(e,t,r){return["docker","exec","-i",e,...t??[],...r??[]]}(e,a(o),a(i))
|
|
43
|
+
return c.length<=4?{ok:!1,error:"the image has no ENTRYPOINT or CMD, so there is nothing to run; give the Dockerfile one that starts the MCP server on stdio"}:{ok:!0,command:c}},exports.explainDerivedCommand=async function(e,r=8e3){const{spawn:n}=await Promise.resolve().then(()=>t.t(35317,23))
|
|
44
|
+
return await new Promise(t=>{let o="",i=!1
|
|
47
45
|
const a=e=>{i||(i=!0,t(e))}
|
|
48
46
|
try{const t=n(e[0],e.slice(1),{stdio:["ignore","pipe","pipe"]}),i=e=>{o=(o+e.toString("utf8")).slice(-2e3)}
|
|
49
47
|
t.stdout?.on("data",i),t.stderr?.on("data",i)
|
|
50
|
-
const c=setTimeout((
|
|
51
|
-
t.on("error",
|
|
48
|
+
const c=setTimeout(()=>{try{t.kill("SIGKILL")}catch{}a("")},r)
|
|
49
|
+
t.on("error",e=>{clearTimeout(c),a(String(e.message??e))}),t.on("close",e=>{clearTimeout(c)
|
|
52
50
|
const t=o.trim().split("\n").filter(Boolean).slice(-4).join("\n")
|
|
53
|
-
a(t?`exit ${e}: ${t}`:0===e?"":`exit ${e} with no output`)})
|
|
54
|
-
const
|
|
55
|
-
exports.
|
|
56
|
-
const
|
|
51
|
+
a(t?`exit ${e}: ${t}`:0===e?"":`exit ${e} with no output`)})}catch(e){a(String(e?.message??e))}})}
|
|
52
|
+
const n=t(81618),o=t(26166),i=t(99559),a=t(56149),c="node:20-alpine",s="alchemy.mcp=connection"
|
|
53
|
+
exports.K4=["registry.npmjs.org","npmjs.org","npmjs.com"]
|
|
54
|
+
const l=".alchemy-install-complete"},56149(e,exports,t){exports.Jj=void 0,exports.addressedName=function(e,...t){return`${e}-${function(e,t=exports.Jj){return e.slice(0,t)}(function(...e){const t=(0,r.createHash)("sha256")
|
|
55
|
+
for(const r of e){const e=r??""
|
|
56
|
+
t.update(String(e.length)).update(":").update(e).update("\0")}return t.digest("hex")}(...t))}`}
|
|
57
|
+
const r=t(76982)
|
|
58
|
+
exports.Jj=12}}
|
package/dist/356.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
"use strict"
|
|
2
|
-
exports.
|
|
2
|
+
exports.ids=[356],exports.modules={69356(e,exports,t){function s(e,t="",n=0,r=[]){if(n>4||r.length>=80)return r
|
|
3
3
|
let c=[]
|
|
4
|
-
try{c=a.default.readdirSync(l.default.join(e,t),{withFileTypes:!0})}catch{return r}for(const
|
|
5
|
-
const c=t?`${t}/${
|
|
6
|
-
if(
|
|
7
|
-
else if(
|
|
4
|
+
try{c=a.default.readdirSync(l.default.join(e,t),{withFileTypes:!0})}catch{return r}for(const i of c.sort((e,t)=>e.name.localeCompare(t.name))){if(i.name.startsWith(".")||o.has(i.name))continue
|
|
5
|
+
const c=t?`${t}/${i.name}`:i.name
|
|
6
|
+
if(i.isDirectory())s(e,c,n+1,r)
|
|
7
|
+
else if(i.isFile())try{r.push({rel:c,size:a.default.statSync(l.default.join(e,c)).size})}catch{}if(r.length>=80)break}return r}function n(e,t){let s=""
|
|
8
8
|
try{s=a.default.readFileSync(e,"utf8")}catch{return[]}if(s.length>4e5)return[]
|
|
9
9
|
const n=[],r=e=>{e?.[1]&&!n.includes(e[1])&&n.push(e[1])},l=s.split("\n")
|
|
10
10
|
for(const e of l)if(".py"!==t){if(r(e.match(/^\s{0,2}(?:export\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/)),r(e.match(/^\s{0,2}(?:export\s+)?class\s+([A-Za-z_$][\w$]*)/)),r(e.match(/^\s{0,2}(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/)),n.length>=30)break}else r(e.match(/^(?:async\s+)?def\s+([A-Za-z_]\w*)/)),r(e.match(/^class\s+([A-Za-z_]\w*)/))
|
|
@@ -15,7 +15,7 @@ if(0===t.length)return null
|
|
|
15
15
|
const r=[]
|
|
16
16
|
r.push("Files (path, size):")
|
|
17
17
|
for(const e of t)r.push(` ${e.rel} (${e.size>=1024?`${Math.round(e.size/1024)} KB`:`${e.size} B`})`)
|
|
18
|
-
const o=t.filter(
|
|
18
|
+
const o=t.filter(e=>c.has(l.default.extname(e.rel)))
|
|
19
19
|
for(const t of o.slice(0,12)){const s=n(l.default.join(e,t.rel),l.default.extname(t.rel))
|
|
20
20
|
s.length&&r.push(`${t.rel}: ${s.join(", ")}`)}const i=function(e,t){const s=new Set
|
|
21
21
|
for(const n of t){if(!/\.(m?js|cjs|ts|tsx|jsx)$/.test(n.rel))continue
|
|
@@ -24,8 +24,8 @@ try{t=a.default.readFileSync(l.default.join(e,n.rel),"utf8")}catch{continue}for(
|
|
|
24
24
|
for(const e of t.matchAll(/(?:NYCKEL|KEY|STORAGE)[A-Z_]*\s*=\s*['"`]([^'"`]{1,80})['"`]/g))s.add(e[1])
|
|
25
25
|
if(s.size>20)break}return[...s]}(e,t)
|
|
26
26
|
i.length&&r.push(`Storage keys: ${i.join(", ")}`)
|
|
27
|
-
const
|
|
28
|
-
if(
|
|
29
|
-
t.length&&r.push(`README sections: ${t.join(" | ")}`)}catch{}let
|
|
30
|
-
return
|
|
31
|
-
const a=r(t(79896)),l=r(t(16928)),o=new Set(["node_modules",".git",".alchemy",".alchemy_lab","dist","build","coverage",".next","vendor","__pycache__"]),c=new Set([".js",".mjs",".cjs",".ts",".tsx",".jsx",".py",".go",".rs",".rb",".java",".kt",".swift"])
|
|
27
|
+
const f=t.find(e=>/^readme\.md$/i.test(e.rel))
|
|
28
|
+
if(f)try{const t=a.default.readFileSync(l.default.join(e,f.rel),"utf8").split("\n").filter(e=>/^#{1,3}\s/.test(e)).slice(0,12).map(e=>e.replace(/^#+\s*/,"").trim())
|
|
29
|
+
t.length&&r.push(`README sections: ${t.join(" | ")}`)}catch{}let u=r.join("\n")
|
|
30
|
+
return u.length>3500&&(u=u.slice(0,3500)+"\n[... map clipped]"),`Project map (generated from the worktree at pickup; read this, then open only the files you will change):\n${u}`}
|
|
31
|
+
const a=r(t(79896)),l=r(t(16928)),o=new Set(["node_modules",".git",".alchemy",".alchemy_lab","dist","build","coverage",".next","vendor","__pycache__"]),c=new Set([".js",".mjs",".cjs",".ts",".tsx",".jsx",".py",".go",".rs",".rb",".java",".kt",".swift"])}}
|
package/dist/414.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
"use strict"
|
|
2
|
-
exports.
|
|
3
|
-
if(
|
|
4
|
-
const o=(0,
|
|
5
|
-
if((0,
|
|
6
|
-
if("number"==typeof
|
|
2
|
+
exports.ids=[414],exports.modules={79414(t,exports,e){function n(){return process.env.ALCHEMY_PROJECT_PATH||process.cwd()}function r(t){const e=Date.now(),r=!t
|
|
3
|
+
if(r&&null!==h&&e-p<5e3)return h
|
|
4
|
+
const o=(0,u.join)(t||n(),".alchemy_lab","action-server.json")
|
|
5
|
+
if((0,i.existsSync)(o))try{const t=(0,i.readFileSync)(o,"utf-8"),n=JSON.parse(t)
|
|
6
|
+
if("number"==typeof n.port&&n.port>0&&n.port<65536)return r&&(h=n.port,p=e),n.port}catch{}return r&&(h=3456,p=e),3456}function o(t){return t||n()}async function c(t){try{const e=await(0,l.fetch)(`http://localhost:${t}/health`,{signal:AbortSignal.timeout(1500)})
|
|
7
7
|
if(!e.ok)return null
|
|
8
|
-
const
|
|
9
|
-
return"string"==typeof
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
return
|
|
15
|
-
const
|
|
16
|
-
let
|
|
17
|
-
const
|
|
18
|
-
let
|
|
8
|
+
const n=await e.json()
|
|
9
|
+
return"string"==typeof n?.projectPath?n.projectPath:null}catch{return null}}function s(t){try{return(0,i.realpathSync)(t)}catch{return t}}function a(){const t=Date.now()
|
|
10
|
+
return t-d>3e4&&(d=t,async function(t){const e=o(t),n=Date.now(),a=f.get(e)
|
|
11
|
+
if(a&&n-a.at<3e4)return a.port
|
|
12
|
+
for(const o of[0,1]){1===o&&(h=null,p=0)
|
|
13
|
+
const a=r(t),i=await c(a)
|
|
14
|
+
if(i&&s(i)===s(e))return f.set(e,{port:a,at:n}),a}return f.delete(e),null}().then(t=>{null===t&&(h=null,p=0,console.error(`[alchemy] the recorded action-server port does not serve ${o()}: re-reading it. If this repeats, the server for this project is not running.`))}).catch(()=>{})),`http://localhost:${r()}`}exports.getActionServerPort=r,exports.getActionServerBaseUrl=a,exports.actionServerFetch=function(t,e){return y||(y=new l.Agent({headersTimeout:0,bodyTimeout:0})),(0,l.fetch)(`${a()}${t}`,{...e,dispatcher:y})}
|
|
15
|
+
const i=e(79896),u=e(16928),l=e(9956)
|
|
16
|
+
let h=null,p=0
|
|
17
|
+
const f=new Map
|
|
18
|
+
let y,d=0}}
|