alchemylab 1.4.6 → 1.4.8

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/cli.js CHANGED
@@ -26,7 +26,7 @@ const{sessionId:s,hookId:n}=e.params,a=await o.post(`/api/projects/${r}/hook-ite
26
26
  t.json(a)}catch(e){n.debug("Failed to increment hook iteration",{error:(0,r.getErrorMessage)(e)}),t.json({success:!0,data:{iterationCount:0}})}}(e,s,t)))}
27
27
  const r=t(8824)},441(e,exports){"use strict"
28
28
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.BAD_REQUEST=exports.INTERNAL_ERROR=exports.NOT_FOUND=exports.FORBIDDEN=exports.UNAUTHORIZED=exports.VALIDATION_ERROR=exports.MCP_PROTOCOL_ERROR=exports.REQUEST_VALIDATION_FAILED=exports.REQUEST_ID_INVALID_FORMAT=exports.REQUEST_NOT_FOUND=exports.CONNECTION_ERROR=exports.SERVICE_UNAVAILABLE=exports.CONNECTION_TIMEOUT=exports.SERVER_ERROR=exports.NETWORK_ERROR=exports.TASK_VALIDATION_FAILED=exports.TASK_ID_INVALID_FORMAT=exports.TASK_NOT_FOUND=void 0,exports.TASK_NOT_FOUND="TASK_NOT_FOUND",exports.TASK_ID_INVALID_FORMAT="TASK_ID_INVALID_FORMAT",exports.TASK_VALIDATION_FAILED="TASK_VALIDATION_FAILED",exports.NETWORK_ERROR="NETWORK_ERROR",exports.SERVER_ERROR="SERVER_ERROR",exports.CONNECTION_TIMEOUT="CONNECTION_TIMEOUT",exports.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",exports.CONNECTION_ERROR="CONNECTION_ERROR",exports.REQUEST_NOT_FOUND="REQUEST_NOT_FOUND",exports.REQUEST_ID_INVALID_FORMAT="REQUEST_ID_INVALID_FORMAT",exports.REQUEST_VALIDATION_FAILED="REQUEST_VALIDATION_FAILED",exports.MCP_PROTOCOL_ERROR="MCP_PROTOCOL_ERROR",exports.VALIDATION_ERROR="VALIDATION_ERROR",exports.UNAUTHORIZED="UNAUTHORIZED",exports.FORBIDDEN="FORBIDDEN",exports.NOT_FOUND="NOT_FOUND",exports.INTERNAL_ERROR="INTERNAL_ERROR",exports.BAD_REQUEST="BAD_REQUEST"},489(e,exports,t){"use strict"
29
- function r(e,t){return(0,h.join)(e,p,m,"pool-"+t)}function s(){const e=C.shift()
29
+ function r(e,t){return(0,h.join)(e,p,m,"pool-"+t)}function s(){const e=S.shift()
30
30
  e&&setImmediate(e)}async function o(e,t){const o=Date.now()
31
31
  !function(e){let t=!1
32
32
  for(const r of E.values())r.busy&&r.busySince&&e-r.busySince>I&&(r.busy=!1,r.busySince=void 0,t=!0)
@@ -41,13 +41,13 @@ try{n=await d.promises.readdir(o,{withFileTypes:!0})}catch{return}for(const e of
41
41
  return new Set(t)}catch{return null}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getSlotPath=r,exports.acquireSlot=async function(e,t,r=b){return await o(e,t)||new Promise(((i,a)=>{let c=!1
42
42
  const l=Date.now(),d=setTimeout((()=>{if(c)return
43
43
  c=!0
44
- const e=C.indexOf(u)
45
- 0>e||C.splice(e,1),a(Error(`All ${t} pool slot(s) busy after waiting ${Math.round((Date.now()-l)/1e3)}s`))}),r)
44
+ const e=S.indexOf(u)
45
+ 0>e||S.splice(e,1),a(Error(`All ${t} pool slot(s) busy after waiting ${Math.round((Date.now()-l)/1e3)}s`))}),r)
46
46
  d.unref()
47
47
  const u=async()=>{if(c)return
48
48
  const r=await o(e,t)
49
- c?r&&n(r.path):r?(c=!0,clearTimeout(d),i(r)):(C.unshift(u),s())}
50
- C.push(u)}))},exports.releaseSlot=n,exports.scheduleSlotRelease=i,exports.watchPidAndRelease=function(e,t,r,s=5e3){if(i(t,r),!e||0>=e)return
49
+ c?r&&n(r.path):r?(c=!0,clearTimeout(d),i(r)):(S.unshift(u),s())}
50
+ S.push(u)}))},exports.releaseSlot=n,exports.scheduleSlotRelease=i,exports.watchPidAndRelease=function(e,t,r,s=5e3){if(i(t,r),!e||0>=e)return
51
51
  const o=setInterval((()=>{try{process.kill(e,0)}catch{n(t),clearInterval(o)}}),s)
52
52
  o.unref()},exports.readSlotFingerprint=a,exports.writeSlotFingerprint=async function(e,t){try{await d.promises.writeFile((0,h.join)(e,f),t,"utf-8")}catch(e){console.warn("worktree-pool: writeSlotFingerprint failed (non-fatal):",(0,g.getErrorMessage)(e))}},exports.computeFingerprint=async function(e,t){if(!t||0===t.length)return""
53
53
  const r=(0,u.createHash)("sha256")
@@ -57,8 +57,8 @@ await d.promises.writeFile((0,h.join)(e,y),t.join("\n")+"\n","utf-8")}catch(e){c
57
57
  if(!t)return{removed:0}
58
58
  const r=await c(e)
59
59
  let s=0
60
- for(const o of r)if(!t.has(o))try{await d.promises.rm((0,h.join)(e,o),{force:!0}),s++}catch{}return{removed:s}},exports._resetForTests=function(){E.clear(),C.length=0}
61
- const d=t(9896),u=t(6982),h=t(6928),g=t(8824),p=".alchemy_lab",m="test-worktrees",f=".fingerprint.sha256",y=".alchemy-warm-snapshot.txt",v=new Set([f,y]),w=new Set([".git"]),I=12e5,b=6e5,E=new Map,C=[]},833(e,exports,t){"use strict"
60
+ for(const o of r)if(!t.has(o))try{await d.promises.rm((0,h.join)(e,o),{force:!0}),s++}catch{}return{removed:s}},exports._resetForTests=function(){E.clear(),S.length=0}
61
+ const d=t(9896),u=t(6982),h=t(6928),g=t(8824),p=".alchemy_lab",m="test-worktrees",f=".fingerprint.sha256",y=".alchemy-warm-snapshot.txt",v=new Set([f,y]),w=new Set([".git"]),I=12e5,b=6e5,E=new Map,S=[]},833(e,exports,t){"use strict"
62
62
  var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
63
63
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.getOpenCodeUrlFromConfig=function(e){const t=o.default.join(e,".alchemy_lab","opencode.json")
64
64
  try{if(!s.default.existsSync(t))return null
@@ -204,11 +204,11 @@ if(!y.id)throw Error("Session created in OpenCode but no ID returned")
204
204
  const v=y.id
205
205
  u.info("Pre-created OpenCode session",{sessionId:v,title:p,agent:t})
206
206
  const w=this.registerSession({sessionId:v,parentSessionId:a,projectId:h,agent:t,title:p,specialization:c,specializationHeadline:l,callerAgentType:d,requestId:i}),I=this.resolveModel(t,n),b=i?(0,r.ensureRequestWorktree)(n,i,u).catch((e=>{u.warn("Pre-spawn worktree creation failed (non-fatal)",{requestId:i,error:(0,o.getErrorMessage)(e)})})):Promise.resolve(),[,E]=await Promise.all([w,I,b])
207
- return{sessionId:v,model:E,serverUrl:g,initialBranch:i?"requests/"+i:void 0}}async registerSession(e){const{sessionId:t,parentSessionId:r,projectId:s,agent:n,title:i,specialization:a,specializationHeadline:c,callerAgentType:l,requestId:d}=e,{apiClient:u,logger:h}=this.deps
208
- try{let e,g
209
- if(r)try{const t=await u.post(`/api/projects/${s}/cli-sessions`,{externalSessionId:r,providerId:"opencode",status:"active",agentType:l||void 0}),o=t?.data||t
210
- e=o?.id,g=o?.workflowId,h.info("Parent session upsert result",{parentExternalId:r,parentDbId:e??null,parentWorkflowId:g??null,responseHasSuccess:void 0!==t?.success,responseDataKeys:o?Object.keys(o):[]})}catch(e){h.warn("Failed to register parent session",{parentSessionId:r,error:(0,o.getErrorMessage)(e)})}const p={externalSessionId:t,providerId:"opencode",parentSessionId:e||null,title:i,status:"active",agentType:n,specialization:a,specializationHeadline:c,workflowId:g||void 0}
211
- if(h.info("Child session upsert payload",{sessionId:t,agent:n,parentExternalId:r??null,parentDbIdSent:p.parentSessionId,workflowIdSent:p.workflowId??null}),await u.post(`/api/projects/${s}/cli-sessions`,p),h.info("Registered session in alchemy DB",{sessionId:t,agent:n,parentSessionId:r}),d){try{await u.post(`/api/projects/${s}/session-request-associations`,{opencodeSessionId:t,requestLocalId:d}),h.info("Created session-request association",{sessionId:t,requestId:d})}catch(e){h.warn("Failed to create session-request association",{error:(0,o.getErrorMessage)(e)})}if("coder"===n)try{await u.patch(`/api/projects/${s}/requests/${d}`,{cliOrigin:{providerId:"opencode",sessionId:t,createdAt:(new Date).toISOString()}}),h.debug("Updated request cliOrigin",{sessionId:t,requestId:d})}catch(e){h.warn("Failed to update request cliOrigin",{error:(0,o.getErrorMessage)(e)})}}}catch(e){h.warn("Failed to register session in alchemy DB",{error:(0,o.getErrorMessage)(e)})}}async resolveModel(e,t){const{logger:r}=this.deps,s=this.fetchProjectDefaultModel()||void 0
207
+ return{sessionId:v,model:E,serverUrl:g,initialBranch:i?"requests/"+i:void 0}}async registerSession(e){const{sessionId:t,parentSessionId:r,projectId:s,agent:n,title:a,specialization:c,specializationHeadline:l,callerAgentType:d,requestId:u}=e,{apiClient:h,logger:g}=this.deps
208
+ try{let e,p
209
+ if(r)try{const t=await h.post(`/api/projects/${s}/cli-sessions`,{externalSessionId:r,providerId:"opencode",status:"active",agentType:d||void 0}),o=t?.data||t
210
+ e=o?.id,p=o?.workflowId,g.info("Parent session upsert result",{parentExternalId:r,parentDbId:e??null,parentWorkflowId:p??null,responseHasSuccess:void 0!==t?.success,responseDataKeys:o?Object.keys(o):[]})}catch(e){g.warn("Failed to register parent session",{parentSessionId:r,error:(0,o.getErrorMessage)(e)})}const m={externalSessionId:t,providerId:"opencode",parentSessionId:e||null,title:a,status:"active",agentType:n,specialization:c,specializationHeadline:l,workflowId:p||void 0,persistent:i.PERSISTENT_ORCHESTRATOR_AGENTS.includes(n)||void 0}
211
+ if(g.info("Child session upsert payload",{sessionId:t,agent:n,parentExternalId:r??null,parentDbIdSent:m.parentSessionId,workflowIdSent:m.workflowId??null}),await h.post(`/api/projects/${s}/cli-sessions`,m),g.info("Registered session in alchemy DB",{sessionId:t,agent:n,parentSessionId:r}),u){try{await h.post(`/api/projects/${s}/session-request-associations`,{opencodeSessionId:t,requestLocalId:u}),g.info("Created session-request association",{sessionId:t,requestId:u})}catch(e){g.warn("Failed to create session-request association",{error:(0,o.getErrorMessage)(e)})}if("coder"===n)try{await h.patch(`/api/projects/${s}/requests/${u}`,{cliOrigin:{providerId:"opencode",sessionId:t,createdAt:(new Date).toISOString()}}),g.debug("Updated request cliOrigin",{sessionId:t,requestId:u})}catch(e){g.warn("Failed to update request cliOrigin",{error:(0,o.getErrorMessage)(e)})}}}catch(e){g.warn("Failed to register session in alchemy DB",{error:(0,o.getErrorMessage)(e)})}}async resolveModel(e,t){const{logger:r}=this.deps,s=this.fetchProjectDefaultModel()||void 0
212
212
  let a
213
213
  try{const r=await this.fetchAgentConfig(e)
214
214
  if(r){const e=r.preferredProvider||"inherit",o=r.preferredModelTier||"same",i=(0,n.resolveAgentModel)(t,e,o,s)
@@ -227,21 +227,29 @@ for(const t of e){if(this.inFlight.has(t.id))continue
227
227
  const e=t.metadata||{}
228
228
  if((e.status||o.QUEST_STATUS_OPEN)!==o.QUEST_STATUS_OPEN)continue
229
229
  const r=e.tickIntervalSeconds||o.QUEST_DEFAULTS.tickIntervalSeconds,s=e.lastTickAt?Date.parse(e.lastTickAt):NaN,n=Number.isFinite(s)?s:0,i=Date.now()
230
- n>0&&r>(i-n)/1e3||(this.inFlight.add(t.id),this.fireTick(t).finally((()=>this.inFlight.delete(t.id))))}}}async fireTick(e){const t=e.metadata||{},n=t.maxInFlight??o.QUEST_DEFAULTS.maxInFlight,i=t.maxPerDay??o.QUEST_DEFAULTS.maxPerDay,a=e.localId||e.id
231
- let c
232
- try{c=await this.fetchQuestRequests(e.id)}catch(e){return void this.logger.warn("Quest tick: fetch requests failed; skipping",{questId:a,error:e+""})}const l=new Set
233
- try{const e=await this.apiClient.get(`/api/projects/${this.projectId}/tasks?status=in_progress,pending&limit=1000`),t=e?.data||e||[],r=new Set(c.map((e=>e.id)))
234
- for(const e of t)e.requestId&&r.has(e.requestId)&&l.add(e.requestId)}catch(e){this.logger.warn("Quest tick: task fetch failed; counting by status only",{questId:a,error:e+""})}const{openCount:d,statusCount:u,taskOnlyCount:h}=r(c,l)
235
- if(d>=n)return void this.logger.info("Quest tick: maxInFlight reached, skipping",{questId:a,openCount:d,maxInFlight:n,statusCount:u,taskOnlyCount:h})
236
- const g=(new Date).toISOString().slice(0,10),p=t.ticksTodayDate===g?t.ticksTodayCount??0:0
237
- if(p>=i)return void this.logger.info("Quest tick: maxPerDay reached, skipping",{questId:a,ticksToday:p,maxPerDay:i})
238
- const m=await this.findAlchemistSessionId()
239
- if(!m)return void this.logger.info("Quest tick: no persistent alchemist session in project, skipping",{questId:a,projectId:this.projectId})
240
- const f=(t.currentIteration||0)+1
241
- let y=!1
242
- try{y=await this.bumpQuestMetadata(e,f)}catch(e){return void this.logger.warn("Quest tick: metadata PATCH failed; skipping prompt",{questId:a,error:e+""})}if(!y)return void this.logger.info("Quest tick: status changed during tick; skipping prompt",{questId:a})
243
- const v=this.buildTickPrompt(e,f,d,h,p+1),w={logger:this.logger,projectId:this.projectId,projectPath:this.projectPath,apiClient:this.apiClient,cachedDefaultModel:this.getDefaultModel()??null},I={alchemy:{kind:"quest-tick",payload:{questId:a,iteration:f,criteria:t.criteria||"",openCount:d,taskOnlyCount:h,maxInFlight:n,ticksToday:p+1,maxPerDay:i,minIterations:t.minIterations??o.QUEST_DEFAULTS.minIterations}}}
244
- try{await(0,s.executeSameSession)(v,m,w,I),this.logger.info("Quest tick fired",{questId:a,iteration:f,alchemistSessionId:m})}catch(e){this.logger.warn("Quest tick: prompt send failed",{questId:a,error:e+""})}}invalidateCache(){this.lastQuestsFetch=0}invalidateAlchemistCache(){this.cachedAlchemistSessionId=null,this.cachedAlchemistAt=0}async fetchOpenQuests(){const e=Date.now()
230
+ n>0&&r>(i-n)/1e3||(this.inFlight.add(t.id),this.fireTick(t).finally((()=>this.inFlight.delete(t.id))))}}}async nudge(e){if(!this.projectId)return
231
+ if(this.inFlight.has(e))return void this.logger.info("Quest nudge: already in flight, skipping",{questId:e})
232
+ let t
233
+ try{const r=await this.apiClient.get(`/api/projects/${this.projectId}/documents/${encodeURIComponent(e)}`),s=r?.data||r
234
+ if(!s||"Quest"!==s.type)return void this.logger.warn("Quest nudge: doc not found or wrong type",{questId:e,type:s?.type})
235
+ t=s}catch(t){return void this.logger.warn("Quest nudge: fetch failed",{questId:e,error:t+""})}const r=t.metadata||{}
236
+ if((r.status||o.QUEST_STATUS_OPEN)===o.QUEST_STATUS_OPEN){this.inFlight.add(t.id)
237
+ try{await this.fireTick(t,{idleOnly:!0})}finally{this.inFlight.delete(t.id)}}else this.logger.info("Quest nudge: not open, skipping",{questId:e,status:r.status})}async fireTick(e,t){const n=!0===t?.idleOnly,i=e.metadata||{},a=i.maxInFlight??o.QUEST_DEFAULTS.maxInFlight,c=i.maxPerDay??o.QUEST_DEFAULTS.maxPerDay,l=e.localId||e.id
238
+ let d
239
+ try{d=await this.fetchQuestRequests(e.id)}catch(e){return void this.logger.warn("Quest tick: fetch requests failed; skipping",{questId:l,error:e+""})}const u=new Set
240
+ try{const e=await this.apiClient.get(`/api/projects/${this.projectId}/tasks?status=in_progress,pending&limit=1000`),t=e?.data||e||[],r=new Set(d.map((e=>e.id)))
241
+ for(const e of t)e.requestId&&r.has(e.requestId)&&u.add(e.requestId)}catch(e){this.logger.warn("Quest tick: task fetch failed; counting by status only",{questId:l,error:e+""})}const{openCount:h,statusCount:g,taskOnlyCount:p}=r(d,u)
242
+ if(h>=a)return void this.logger.info("Quest tick: maxInFlight reached, skipping",{questId:l,openCount:h,maxInFlight:a,statusCount:g,taskOnlyCount:p})
243
+ if(n&&h>0)return void this.logger.info("Quest nudge: not idle, skipping",{questId:l,openCount:h})
244
+ const m=(new Date).toISOString().slice(0,10),f=i.ticksTodayDate===m?i.ticksTodayCount??0:0
245
+ if(f>=c)return void this.logger.info("Quest tick: maxPerDay reached, skipping",{questId:l,ticksToday:f,maxPerDay:c})
246
+ const y=await this.findAlchemistSessionId()
247
+ if(!y)return void this.logger.info("Quest tick: no persistent alchemist session in project, skipping",{questId:l,projectId:this.projectId})
248
+ const v=(i.currentIteration||0)+1
249
+ let w=!1
250
+ try{w=await this.bumpQuestMetadata(e,v)}catch(e){return void this.logger.warn("Quest tick: metadata PATCH failed; skipping prompt",{questId:l,error:e+""})}if(!w)return void this.logger.info("Quest tick: status changed during tick; skipping prompt",{questId:l})
251
+ const I=this.buildTickPrompt(e,v,h,p,f+1),b={logger:this.logger,projectId:this.projectId,projectPath:this.projectPath,apiClient:this.apiClient,cachedDefaultModel:this.getDefaultModel()??null},E={alchemy:{kind:"quest-tick",payload:{questId:l,iteration:v,criteria:i.criteria||[],openCount:h,taskOnlyCount:p,maxInFlight:a,ticksToday:f+1,maxPerDay:c,minIterations:i.minIterations??(0,o.defaultMinIterations)(i.completionMode),completionMode:i.completionMode||o.QUEST_COMPLETION_MODE_DEFAULT,consecutiveDoneAudits:i.consecutiveDoneAudits??0}}}
252
+ try{await(0,s.executeSameSession)(I,y,b,E),this.logger.info("Quest tick fired",{questId:l,iteration:v,alchemistSessionId:y})}catch(e){this.logger.warn("Quest tick: prompt send failed",{questId:l,error:e+""})}}invalidateCache(){this.lastQuestsFetch=0}invalidateAlchemistCache(){this.cachedAlchemistSessionId=null,this.cachedAlchemistAt=0}async fetchOpenQuests(){const e=Date.now()
245
253
  if(18e5>e-this.lastQuestsFetch)return this.cachedQuests
246
254
  try{const t=await this.apiClient.get(`/api/projects/${this.projectId}/plans?type=Quest&limit=100`),r=t?.data||t||[]
247
255
  return this.cachedQuests=r.filter((e=>e&&(e.metadata?.status||o.QUEST_STATUS_OPEN)===o.QUEST_STATUS_OPEN)),this.lastQuestsFetch=e,this.cachedQuests}catch(t){throw this.lastQuestsFetch=e,t}}async fetchQuestRequests(e){const t=await this.apiClient.get(`/api/projects/${this.projectId}/requests?questDocumentId=${encodeURIComponent(e)}&limit=1000`)
@@ -254,8 +262,8 @@ this.logger.info("Quest tick: project active alchemist not active, ignoring",{pr
254
262
  return 0===r.length?(this.logger.info("Quest tick: no alchemist session found in project",{projectId:this.projectId}),e(null)):(this.logger.info("Quest tick: active-alchemist not set, using first alchemist as fallback",{projectId:this.projectId,alchemistCount:r.length}),e(r[0].externalSessionId))}catch(e){return this.logger.warn("Quest tick: alchemist fallback lookup failed",{error:e+""}),null}}async bumpQuestMetadata(e,t){const r=await this.apiClient.get(`/api/projects/${this.projectId}/documents/${encodeURIComponent(e.id)}`),s=r?.data||r,n=s?.metadata||{}
255
263
  if((n.status||o.QUEST_STATUS_OPEN)!==o.QUEST_STATUS_OPEN)return!1
256
264
  const i=(new Date).toISOString().slice(0,10),a=(n.ticksTodayDate===i?n.ticksTodayCount??0:0)+1,c={...n,lastTickAt:(new Date).toISOString(),currentIteration:t,ticksTodayDate:i,ticksTodayCount:a}
257
- return await this.apiClient.patch(`/api/projects/${this.projectId}/documents/${encodeURIComponent(e.id)}`,{metadata:c}),!0}buildTickPrompt(e,t,r,s,n){const i=e.metadata||{},a=e.localId||e.id,c=i.minIterations??o.QUEST_DEFAULTS.minIterations
258
- return[`[Quest tick: ${a}, iteration ${t}]`,"","Filename: "+(e.filename||"(unknown)"),"Criteria: "+(i.criteria||"(none specified)"),"",`Caps: maxInFlight=${i.maxInFlight??o.QUEST_DEFAULTS.maxInFlight}, maxPerDay=${i.maxPerDay??o.QUEST_DEFAULTS.maxPerDay}, minIterations=${c}.`,`Currently in flight under this quest: ${r}${s>0?` (incl. ${s} via in-progress/pending tasks under non-active requests)`:""}. Ticks today (incl. this): ${n}/${i.maxPerDay??o.QUEST_DEFAULTS.maxPerDay}.`,'\nDecide what to take action on this tick. If progress requires a request, call specialist_ops with operation="delegate". Inside the prompt you write for the specialist, you MUST include this exact line so the spawned request is tagged to the quest:',` "When you call create_request, pass questDocumentId="${a}"."`,"Without that instruction in the specialist's prompt, the spawned request will not be tagged and the runner can't track it.\nDo NOT mark this quest complete \u2014 quest end is a user action, not yours. Just do this tick's work and stop."].join("\n")}}},1405(e,exports,t){"use strict"
265
+ return await this.apiClient.patch(`/api/projects/${this.projectId}/documents/${encodeURIComponent(e.id)}`,{metadata:c}),!0}buildTickPrompt(e,t,r,s,n){const i=e.metadata||{},a=e.localId||e.id,c=i.minIterations??(0,o.defaultMinIterations)(i.completionMode),l=i.maxInFlight??o.QUEST_DEFAULTS.maxInFlight,d=i.maxPerDay??o.QUEST_DEFAULTS.maxPerDay,u=i.completionMode||o.QUEST_COMPLETION_MODE_DEFAULT,h=i.consecutiveDoneAudits??0,g="auto-close"===u?["A) If every requirement is satisfied with concrete evidence:",` Call quest_audit_complete(questId="${a}", summary, evidence?). The server bumps your audit streak. When the streak reaches ${c}, the quest auto-closes (the user opted into auto-close mode). Do NOT spawn work in this branch, that resets the streak to 0.`]:["A) If every requirement is satisfied with concrete evidence:",` Call quest_audit_complete(questId="${a}", summary, evidence?). The server bumps your audit streak. When the streak reaches ${c}, status flips to pending_review and the user adjudicates (close or reopen). Do NOT spawn work in this branch, that resets the streak to 0.`]
266
+ return[`[Quest tick: ${a}, iteration ${t}]`,"","Filename: "+(e.filename||"(unknown)"),"","## Quest body (prose context written by the planner)","",e.content&&e.content.trim().length>0?e.content.trim():"(empty body \u2014 no Goal / Criteria / Notes have been written yet)","",...i.criteria&&Array.isArray(i.criteria)&&i.criteria.length>0?[`## Structured criteria checklist (${i.criteria.filter((e=>"verified"===e.status)).length}/${i.criteria.length} verified)`,"",...i.criteria.map((e=>`- [${"verified"===e.status?"x":" "}] ${e.id}: ${e.description}${e.evidence?" \u2014 evidence: "+e.evidence:""}`)),"","Per-item statuses are authoritative when this list is present. The audit step below should reason per-criterion rather than against prose alone.",""]:[],"completionMode: "+u,`Audit streak: ${h}/${c} consecutive criteria-met audits`,`Caps: maxInFlight=${l} (room for ${Math.max(0,l-r)} more this tick), maxPerDay=${d}.`,`Currently in flight under this quest: ${r}${s>0?` (incl. ${s} via in-progress/pending tasks under non-active requests)`:""}. Ticks today (incl. this): ${n}/${d}.`,"",...1===t?["## First tick \u2014 kickoff","","This is the first tick of this quest. No work has been spawned yet and no prior state to audit. Skip the usual audit-then-act flow; instead:","1. Read the quest body above carefully. Derive concrete requirements from the Goal / Criteria for done / Notes (and the structured checklist if one is set up).",`2. Plan the initial work. You have room for ${l} parallel request(s) this tick. Identify which requirements can be tackled now and how they split into independent specialist requests.`,"3. Spawn one or more specialists via specialist_ops delegate \u2014 one per independent piece, up to the room above. If the work is one cohesive task, spawn a single request and let it finish before the next tick fans out.","4. Every specialist_ops delegate call MUST include this exact line in the prompt you write for the specialist so the spawned request is tagged to the quest:",` "When you call create_request, pass questDocumentId="${a}"."`," Without that the request will not be tagged and the runner cannot track it.","","If the quest body is empty or unclear, do NOT spawn work blind \u2014 ask the user a brief clarifying question via session_message_operations send instead. The quest-planner should have shaped the body during planning; if it didn't, something went wrong upstream.","","Do NOT call quest_audit_complete on the first tick. From the next tick onward you'll get the full audit-then-act prompt as the quest's state evolves.",""]:["## Audit step (do this first, every tick)","","Before deciding what to do, audit the current state against the criteria above. Criteria can come from two places: the quest body (prose Goal / Criteria for done / Notes the planner wrote) and, optionally, the structured checklist (per-item statuses). When the structured checklist is present, treat per-item statuses as the source of truth and use the body as context. When only the body is present, derive concrete requirements from the prose.","- Derive concrete requirements from the body (and per-item checklist if present). Number them if useful.","- For each requirement, identify the authoritative evidence that would prove it: files, command output, test results, merged requests, runtime behavior.","- Inspect the current evidence in the worktree right now. Use read_files, search, query_history, request_diff, get_request_information as needed. Do not rely on memory of earlier ticks.","- For each requirement, judge: proved, contradicted, incomplete, too-weak-to-verify, or missing.","- Treat indirect, weak, or merely-consistent-with-completion evidence as not achieved.","- Match the verification scope to the requirement's scope; do not use a narrow check to support a broad claim.","","## Action this tick (pick exactly one based on what the audit shows)","",...g,"","B) If the audit shows remaining work:",` You have room for ${Math.max(0,l-r)} more request(s) this tick (maxInFlight=${l}, currently in flight=${r}). Use the full fan-out width when the remaining work splits cleanly.`," - If the remaining work breaks into INDEPENDENT pieces (different files, no merge conflicts between them, no ordering dependency), make multiple specialist_ops delegate calls THIS tick \u2014 one per piece, up to the room above. Each goes to its own specialist; do not pack multiple pieces into one specialist prompt."," - If the remaining work is one cohesive task, or the pieces depend on each other, spawn a single request and let it finish before the next tick fans out."," Every specialist_ops delegate call you make this tick MUST include this exact line in the prompt you write for the specialist so the spawned request is tagged to the quest:",` "When you call create_request, pass questDocumentId="${a}"."`," Without that the request will not be tagged and the runner cannot track it. Spawning any request resets the audit streak to 0 (criteria are not actually met yet).",""],"## Fidelity","","- Optimize this tick for movement toward the actual end state described in the criteria, not the safest-looking next step.","- Do not narrow the criteria to fit what is already done.","- An edit, request, or audit is aligned only if it makes the criteria more true. Useful-looking work that preserves a different end state is misaligned.","- Only the user can flip status to 'closed' (except via auto-close mode, which is an explicit user opt-in on this quest). You may flip to 'pending_review' via quest_audit_complete when audit-then-pending mode is configured."].join("\n")}}},1405(e,exports,t){"use strict"
259
267
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleStartBuildingAction=async function(e,t){const{plannerSessionId:n,parentSessionId:i,requestIds:a,summary:c}=e,{logger:l,apiClient:d,projectId:u,projectPath:h}=t
260
268
  if(!n)return{success:!1,message:"plannerSessionId is required",error:"missing_params"}
261
269
  l.info("Starting start-building action",{plannerSessionId:n,requestIds:a,payloadParent:i})
@@ -297,8 +305,8 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.partMeta=function
297
305
  return{...e,_meta:{...s,alchemy:{...o,...r,kind:t}}}},exports.readAlchemyMeta=function(e){return e?._meta?.alchemy}},2366(e,exports,t){"use strict"
298
306
  var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
299
307
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.AlchemyActionServer=void 0
300
- const s=r(t(7252)),o=r(t(8577)),n=t(9896),i=t(5959),a=t(2640),c=t(4192),l=t(1152),d=r(t(6928)),u=r(t(9896)),h=r(t(857)),g=t(5607),p=t(8984),m=t(8524),f=t(8824),y=t(2096),v=t(7210),w=t(7227),I=t(5419),b=t(3962),E=t(2928),C=t(6563),S=t(1401),k=t(1292),T=t(8649),_=t(4306),j=t(9068),A=t(3435),P=t(8463),M=t(489),O=t(3807),R=t(7478),D=t(5317),x=t(355),$=t(833)
301
- class F{updateAuthToken(e){this.options.authToken=e,this.apiClient.authToken=e,this.configurer.authToken=e}constructor(e,t){this.directReportDedup=new Map,this.activeMcpCalls=new Map,this.pendingAgentResync=!1,this.settingsSyncCounter=0,this.versionWarnings=[],this.updateBlocked=!1,this._pendingUpdateBlock=!1,this.isPolling=!1,this.isProcessingAction=!1,this.openCodeUrlCache=null,this.openCodePort=null,this.proxyAbortControllers=new Map,this.trackedChildPids=new Set,this.sseEventBuffer=[],this.droppedEventCount=0,this.firstDropAt=0,this.hasRemoteEventConsumers=!1,this.cachedProjectConfig=null,this.logger=e,this.options=t,this.port=t.port||3456,this.startTime=new Date
308
+ const s=r(t(7252)),o=r(t(8577)),n=t(9896),i=t(5959),a=t(2640),c=t(4192),l=t(1152),d=r(t(6928)),u=r(t(9896)),h=r(t(857)),g=t(5607),p=t(8984),m=t(8524),f=t(8824),y=t(2096),v=t(7210),w=t(7227),I=t(5419),b=t(3962),E=t(2928),S=t(6563),C=t(1401),k=t(1292),T=t(8649),_=t(4306),j=t(9068),A=t(3435),P=t(8463),M=t(489),O=t(3807),R=t(7478),D=t(5317),x=t(355),$=t(833)
309
+ class q{updateAuthToken(e){this.options.authToken=e,this.apiClient.authToken=e,this.configurer.authToken=e}constructor(e,t){this.directReportDedup=new Map,this.activeMcpCalls=new Map,this.pendingAgentResync=!1,this.settingsSyncCounter=0,this.versionWarnings=[],this.updateBlocked=!1,this._pendingUpdateBlock=!1,this.isPolling=!1,this.isProcessingAction=!1,this.openCodeUrlCache=null,this.openCodePort=null,this.proxyAbortControllers=new Map,this.trackedChildPids=new Set,this.sseEventBuffer=[],this.droppedEventCount=0,this.firstDropAt=0,this.hasRemoteEventConsumers=!1,this.cachedProjectConfig=null,this.logger=e,this.options=t,this.port=t.port||3456,this.startTime=new Date
302
310
  const r=(0,l.createMetricsCollector)(!1)
303
311
  this.apiClient=new c.BaseApiClient(t.remoteServerUrl,e,r,t.authToken,{timeout:35e3}),this.configurer=new p.MCPClientConfigurer(e,t.remoteServerUrl,t.authToken),this.cliBridge=new m.CLIBridgeWebSocket(e),(0,m.setCLIBridge)(this.cliBridge),this.hookExecutor=new v.HookExecutor(e,"",t.projectPath,this.apiClient,{cachedDefaultModel:this.cachedDefaultModel,trackChildPid:e=>this.trackedChildPids.add(e)}),this.app=this.createApp()}createApp(){const e=(0,s.default)()
304
312
  return e.use(((e,t,r)=>{t.setHeader("Access-Control-Allow-Private-Network","true"),r()})),e.use((0,o.default)()),e.use(s.default.json({limit:"10mb"})),e.get("/health",this.handleHealth.bind(this)),e.get("/api/commands/running",(async(e,t)=>{try{const e=16384,r=await Promise.all((0,i.listEntries)().map((async t=>{let r,s="",o=0,i=t.finishedAt??t.startedAt
@@ -444,7 +452,7 @@ t.json({success:!0,data:{sessionId:i.sessionId,worktreePath:i.worktreePath,branc
444
452
  if(!r)return void t.status(400).json({success:!1,error:"Project not registered"})
445
453
  const{agentName:s}=e.params,o=await this.apiClient.get(`/api/projects/${r}/agents`),n=(o?.data||o||[]).find((e=>e.name===s))
446
454
  if(!n)return void t.status(404).json({success:!1,error:`Agent '${s}' not found`})
447
- t.json({success:!0,data:n})}catch(e){this.logger.debug("Failed to get agent by name",{error:(0,f.getErrorMessage)(e)}),t.status(500).json({success:!1,error:(0,f.getErrorMessage)(e)})}}readProjectConfig(){if(this.cachedProjectConfig&&Date.now()-this.cachedProjectConfig.timestamp<F.PROJECT_CONFIG_TTL)return this.cachedProjectConfig.config
455
+ t.json({success:!0,data:n})}catch(e){this.logger.debug("Failed to get agent by name",{error:(0,f.getErrorMessage)(e)}),t.status(500).json({success:!1,error:(0,f.getErrorMessage)(e)})}}readProjectConfig(){if(this.cachedProjectConfig&&Date.now()-this.cachedProjectConfig.timestamp<q.PROJECT_CONFIG_TTL)return this.cachedProjectConfig.config
448
456
  const e=d.default.join(this.options.projectPath,".alchemy_lab","project.json")
449
457
  try{if(!u.default.existsSync(e))return this.cachedProjectConfig={config:null,timestamp:Date.now()},null
450
458
  const t=u.default.readFileSync(e,"utf-8"),r=JSON.parse(t)
@@ -543,7 +551,9 @@ if(n.success&&n.data&&void 0!==n.data.hasRemoteEventConsumers&&(this.hasRemoteEv
543
551
  if(void 0!==e&&this.updateDefaultModel(e),void 0!==t&&t!==this.cachedAutoJournal){this.logger.info("autoJournal setting changed",{oldValue:this.cachedAutoJournal,newValue:t})
544
552
  const e=new y.ProjectConfigService(this.logger)
545
553
  await e.saveProjectConfig(this.options.projectPath,t),this.cachedAutoJournal=t}}if(n.success&&Array.isArray(n.data?.invalidations)&&n.data.invalidations.length>0){const e=n.data.invalidations
546
- this.logger.info("Received cache invalidations from remote",{invalidations:e}),e.includes("hooks")&&this.timerHookScheduler?.invalidateCache(),e.includes("quests")&&this.questTickScheduler?.invalidateCache(),e.includes("alchemist")&&this.questTickScheduler?.invalidateAlchemistCache()}if(n.success&&Array.isArray(n.data?.versionWarnings)&&this.applyVersionWarnings(n.data.versionWarnings),n.success&&n.data?.actions?.length>0){const e=[],t=[]
554
+ this.logger.info("Received cache invalidations from remote",{invalidations:e}),e.includes("hooks")&&this.timerHookScheduler?.invalidateCache(),e.includes("quests")&&this.questTickScheduler?.invalidateCache(),e.includes("alchemist")&&this.questTickScheduler?.invalidateAlchemistCache()}if(n.success&&Array.isArray(n.data?.questNudges)&&n.data.questNudges.length>0){const e=n.data.questNudges
555
+ this.logger.info("Received quest nudges from remote",{questNudges:e})
556
+ for(const t of e)this.questTickScheduler?.nudge(t).catch((e=>{this.logger.warn("Quest nudge dispatch failed",{questId:t,error:e+""})}))}if(n.success&&Array.isArray(n.data?.versionWarnings)&&this.applyVersionWarnings(n.data.versionWarnings),n.success&&n.data?.actions?.length>0){const e=[],t=[]
547
557
  for(const r of n.data.actions)"opencode-proxy"===r.type||"run-tests"===r.type?e.push(r):t.push(r)
548
558
  for(const t of e)this.processAction(t).catch((e=>this.logger.warn("Proxy action failed",{actionId:t.id,error:(0,f.getErrorMessage)(e)})))
549
559
  if(t.length>0&&!this.isProcessingAction){this.isProcessingAction=!0
@@ -588,7 +598,7 @@ if(s.ok){const e=await s.json(),t=e?.data?.settings||e?.settings
588
598
  void 0!==t?.defaultModel&&(this.updateDefaultModel(t.defaultModel),this.logger.info("Fetched defaultModel on startup via quick poll",{defaultModel:this.cachedDefaultModel}))}}catch(e){this.logger.debug("Quick poll for startup settings failed",{error:(0,f.getErrorMessage)(e)})}this.startPolling(),this.projectId&&this.startSSEEventForwarder(),this.projectId&&this.startStuckSessionWatchdog(),this.projectId&&this.startTimerHookScheduler(),this.projectId&&this.startQuestTickScheduler(),this.startMcpStaleCleanup()}trackChildPid(e){this.trackedChildPids.add(e)}killTrackedProcesses(){for(const e of this.trackedChildPids)try{process.kill(-e,"SIGTERM"),this.logger.info("Killed tracked process group",{pid:e})}catch(t){if("ESRCH"!==t?.code){try{process.kill(e,"SIGTERM")}catch{}this.logger.debug("Could not kill process group, fell back to single kill",{pid:e,error:(0,f.getErrorMessage)(t)})}}this.trackedChildPids.clear()
589
599
  try{const e=d.default.join(this.options.projectPath,".alchemy_lab","opencode.json")
590
600
  if(u.default.existsSync(e)){const t=u.default.readFileSync(e,"utf-8"),r=JSON.parse(t)
591
- if(r.pid)try{process.kill(-r.pid,"SIGTERM"),this.logger.info("Killed OpenCode process group from config",{pid:r.pid})}catch(e){if("ESRCH"!==e?.code){try{process.kill(r.pid,"SIGTERM")}catch{}this.logger.debug("Could not kill OpenCode group, fell back to single kill",{pid:r.pid,error:(0,f.getErrorMessage)(e)})}}}}catch{}}startTimerHookScheduler(){this.timerHookScheduler=new C.TimerHookScheduler({hookExecutor:this.hookExecutor,apiClient:this.apiClient,logger:this.logger,getOpenCodeUrl:()=>this.getOpenCodeUrl(),getDefaultModel:()=>this.cachedDefaultModel||void 0,projectId:this.projectId||"",projectPath:this.options.projectPath}),this.timerHookScheduler.start()}startQuestTickScheduler(){this.questTickScheduler=new S.QuestTickScheduler({apiClient:this.apiClient,logger:this.logger,getOpenCodeUrl:()=>this.getOpenCodeUrl(),getDefaultModel:()=>this.cachedDefaultModel||void 0,projectId:this.projectId||"",projectPath:this.options.projectPath}),this.questTickScheduler.start()}startStuckSessionWatchdog(){this.stuckSessionWatchdog=new E.StuckSessionWatchdog({getOpenCodeUrl:()=>this.getOpenCodeUrl(),getDefaultModel:()=>this.cachedDefaultModel||void 0,logger:this.logger,onStuckDetected:e=>this.handleStuckSessionDetected(e),onStuckResolved:e=>this.handleStuckSessionResolved(e)}),this.stuckSessionWatchdog.start()}handleStuckSessionDetected(e){this.sseEventBuffer.push({type:"session.stuck",data:{type:"session.stuck",properties:{sessionId:e.sessionId,messageId:e.messageId,detectedAt:e.detectedAt,sessionTitle:e.sessionTitle,retryCount:e.retryCount}}}),this.logger.warn("Stuck session detected",{sessionId:e.sessionId,title:e.sessionTitle})}handleStuckSessionResolved(e){this.sseEventBuffer.push({type:"session.unstuck",data:{type:"session.unstuck",properties:{sessionId:e}}})}handleGetStuckSessions(e,t){const r=this.stuckSessionWatchdog?.getStuckSessions()??[]
601
+ if(r.pid)try{process.kill(-r.pid,"SIGTERM"),this.logger.info("Killed OpenCode process group from config",{pid:r.pid})}catch(e){if("ESRCH"!==e?.code){try{process.kill(r.pid,"SIGTERM")}catch{}this.logger.debug("Could not kill OpenCode group, fell back to single kill",{pid:r.pid,error:(0,f.getErrorMessage)(e)})}}}}catch{}}startTimerHookScheduler(){this.timerHookScheduler=new S.TimerHookScheduler({hookExecutor:this.hookExecutor,apiClient:this.apiClient,logger:this.logger,getOpenCodeUrl:()=>this.getOpenCodeUrl(),getDefaultModel:()=>this.cachedDefaultModel||void 0,projectId:this.projectId||"",projectPath:this.options.projectPath}),this.timerHookScheduler.start()}startQuestTickScheduler(){this.questTickScheduler=new C.QuestTickScheduler({apiClient:this.apiClient,logger:this.logger,getOpenCodeUrl:()=>this.getOpenCodeUrl(),getDefaultModel:()=>this.cachedDefaultModel||void 0,projectId:this.projectId||"",projectPath:this.options.projectPath}),this.questTickScheduler.start()}startStuckSessionWatchdog(){this.stuckSessionWatchdog=new E.StuckSessionWatchdog({getOpenCodeUrl:()=>this.getOpenCodeUrl(),getDefaultModel:()=>this.cachedDefaultModel||void 0,logger:this.logger,onStuckDetected:e=>this.handleStuckSessionDetected(e),onStuckResolved:e=>this.handleStuckSessionResolved(e)}),this.stuckSessionWatchdog.start()}handleStuckSessionDetected(e){this.sseEventBuffer.push({type:"session.stuck",data:{type:"session.stuck",properties:{sessionId:e.sessionId,messageId:e.messageId,detectedAt:e.detectedAt,sessionTitle:e.sessionTitle,retryCount:e.retryCount}}}),this.logger.warn("Stuck session detected",{sessionId:e.sessionId,title:e.sessionTitle})}handleStuckSessionResolved(e){this.sseEventBuffer.push({type:"session.unstuck",data:{type:"session.unstuck",properties:{sessionId:e}}})}handleGetStuckSessions(e,t){const r=this.stuckSessionWatchdog?.getStuckSessions()??[]
592
602
  t.json({success:!0,data:r})}handleTestInjectStuckSession(e,t){if(!this.stuckSessionWatchdog)return void t.status(503).json({success:!1,error:"Watchdog not running"})
593
603
  const{sessionId:r,title:s}=e.body||{},o=this.stuckSessionWatchdog.injectTestStuck(r,s)
594
604
  this.logger.info("Test-injected stuck session",{sessionId:o.sessionId}),t.json({success:!0,data:o})}async handleRetryStuckSession(e,t){const{sessionId:r}=e.params
@@ -602,7 +612,7 @@ for(const[e]of this.proxyAbortControllers)try{e.abort()}catch{}this.proxyAbortCo
602
612
  try{const e=d.default.join(this.options.projectPath,".alchemy_lab","action-server.json")
603
613
  u.default.existsSync(e)&&u.default.unlinkSync(e)}catch{}if(this.projectId)try{const{removeEntry:e}=await Promise.resolve().then(t.bind(t,2640))
604
614
  e(this.projectId)}catch{}if(this.isPolling=!1,this.pollAbortController&&this.pollAbortController.abort(),this.pollingInterval&&clearInterval(this.pollingInterval),this.heartbeatInterval&&clearInterval(this.heartbeatInterval),this.serverId)try{await this.apiClient.post(`/api/servers/${this.serverId}/disconnect`)}catch{}this.cliBridge.close(),await new Promise((e=>{if(this.server){const t=setTimeout((()=>{this.logger.warn("Graceful shutdown timed out after 10s, forcing close"),e()}),1e4)
605
- this.server.close((()=>{clearTimeout(t),e()}))}else e()})),this.logger.info("AlchemyActionServer stopped")}getPort(){return this.port}isRunning(){return!!this.server}}exports.AlchemyActionServer=F,F.PROJECT_CONFIG_TTL=3e4},2424(e,exports,t){"use strict"
615
+ this.server.close((()=>{clearTimeout(t),e()}))}else e()})),this.logger.info("AlchemyActionServer stopped")}getPort(){return this.port}isRunning(){return!!this.server}}exports.AlchemyActionServer=q,q.PROJECT_CONFIG_TTL=3e4},2424(e,exports,t){"use strict"
606
616
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.ensureRequestWorktree=async function(e,t,i){const a="requests/"+t,c=(0,s.join)(e,n.ALCHEMY_DIR_NAME,"worktrees"),l=(0,s.join)(c,t)
607
617
  if((0,r.existsSync)(l))return void i.info("Worktree already exists on disk, skipping pre-spawn creation",{requestId:t,worktreePath:l})
608
618
  const d=(0,o.simpleGit)(e);(0,r.mkdirSync)(c,{recursive:!0})
@@ -707,7 +717,7 @@ break
707
717
  case"parent_session":case"ancestor_chain":await(0,o.executeInjectPrompt)(e,e.promptTemplate,i,a,this.ctx)}else await(0,o.executeBackground)(e,t,i,a.requestId,this.ctx)
708
718
  const c=(0,s.determineEventToEmit)(e,a)
709
719
  c&&await this.processCustomEvent(c,a,r+1)}}async notifyHookTrigger(e){try{await this.ctx.apiClient.post(`/api/projects/${this.ctx.projectId}/hook-triggers`,{hookId:e.id,hookName:e.name,eventType:e.eventType,action:e.action,target:e.target,agent:e.agent})}catch{}}}},3416(e,exports){"use strict"
710
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.KIND_META=exports.QUEST_STATUS_DRAFT=exports.QUEST_STATUS_CLOSED=exports.QUEST_STATUS_OPEN=exports.QUEST_DEFAULTS=exports.PLAN_KINDS=void 0,exports.PLAN_KINDS=["plan","quest"],exports.QUEST_DEFAULTS={tickIntervalSeconds:1800,maxInFlight:1,maxPerDay:24,minIterations:3},exports.QUEST_STATUS_OPEN="open",exports.QUEST_STATUS_CLOSED="closed",exports.QUEST_STATUS_DRAFT="draft",exports.KIND_META={plan:{docType:"Plan",filenamePrefix:"PLAN-",label:"plan",idLabel:"Plan ID",headingCreated:"Plan Created",errorVerb:"create plan",alchemyKind:"plan-create",canBeActivePlan:!0},quest:{docType:"Quest",filenamePrefix:"QUEST-",label:"quest",idLabel:"Quest ID",headingCreated:"Quest Created",errorVerb:"create quest",alchemyKind:"quest-create",canBeActivePlan:!1}}},3435(e,exports,t){"use strict"
720
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.QUEST_METADATA_KEYS=exports.QUEST_COMPLETION_MODE_DEFAULT=exports.QUEST_COMPLETION_MODES=exports.QUEST_STATUSES=exports.QUEST_STATUS_DRAFT=exports.QUEST_STATUS_CLOSED=exports.QUEST_STATUS_PENDING_REVIEW=exports.QUEST_STATUS_OPEN=exports.QUEST_DEFAULTS=void 0,exports.defaultMinIterations=function(e){return"auto-close"===e?3:1},exports.QUEST_DEFAULTS={tickIntervalSeconds:1800,maxInFlight:1,maxPerDay:24,minIterations:3,consecutiveDoneAudits:0},exports.QUEST_STATUS_OPEN="open",exports.QUEST_STATUS_PENDING_REVIEW="pending_review",exports.QUEST_STATUS_CLOSED="closed",exports.QUEST_STATUS_DRAFT="draft",exports.QUEST_STATUSES=[exports.QUEST_STATUS_DRAFT,exports.QUEST_STATUS_OPEN,exports.QUEST_STATUS_PENDING_REVIEW,exports.QUEST_STATUS_CLOSED],exports.QUEST_COMPLETION_MODES=["auto-close","audit-then-pending"],exports.QUEST_COMPLETION_MODE_DEFAULT="audit-then-pending",exports.QUEST_METADATA_KEYS=["criteria","tickIntervalSeconds","maxInFlight","maxPerDay","minIterations","status","completionMode"]},3435(e,exports,t){"use strict"
711
721
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateRequest=function(e,t,r,s=[]){if(!r)return t.status(400).json({success:!1,error:"No project configured"}),!1
712
722
  const o=e.body??{},n=s.filter((e=>void 0===o[e]||null===o[e]||""===o[e]))
713
723
  if(n.length>0){const e=1===n.length?"is":"are"
@@ -889,9 +899,9 @@ break}await s(500)}for(;Date.now()<n;){const o=await r(e,t)
889
899
  if("error"===o)return{status:"error"}
890
900
  if(("idle"===o||"completed"===o)&&i)return{status:"completed"}
891
901
  "busy"!==o&&"running"!==o||(i=!0),await s(2e3)}return{status:"timeout"}}(y,w,g),b=Date.now()-v,E=await async function(e,t){try{const r=await fetch(`${e}/session/${t}/message?limit=200`,{signal:AbortSignal.timeout(1e4)})
892
- return r.ok?(await r.json()).map((e=>({role:e.info?.role||"unknown",text:(e.parts||[]).filter((e=>"text"===e.type)).map((e=>e.text)).join("\n"),toolCalls:(e.parts||[]).filter((e=>"tool_use"===e.type)).map((e=>({name:e.name,id:e.id}))),timestamp:e.info?.time?.created}))):[]}catch{return[]}}(y,w),C=function(e){return e.reduce(((e,t)=>e+(t.toolCalls?.length||0)),0)}(E),S=function(e){for(let t=e.length-1;t>=0;t--)if("assistant"===e[t].role&&e[t].text)return e[t].text
902
+ return r.ok?(await r.json()).map((e=>({role:e.info?.role||"unknown",text:(e.parts||[]).filter((e=>"text"===e.type)).map((e=>e.text)).join("\n"),toolCalls:(e.parts||[]).filter((e=>"tool_use"===e.type)).map((e=>({name:e.name,id:e.id}))),timestamp:e.info?.time?.created}))):[]}catch{return[]}}(y,w),S=function(e){return e.reduce(((e,t)=>e+(t.toolCalls?.length||0)),0)}(E),C=function(e){for(let t=e.length-1;t>=0;t--)if("assistant"===e[t].role&&e[t].text)return e[t].text
893
903
  return""}(E)
894
- return{success:!0,message:"Prompt completed",data:{sessionId:w,status:I.status,messages:E,toolCallCount:C,elapsedMs:b,finalResponse:S}}}
904
+ return{success:!0,message:"Prompt completed",data:{sessionId:w,status:I.status,messages:E,toolCallCount:S,elapsedMs:b,finalResponse:C}}}
895
905
  const o=t(8148)},4769(e,exports,t){"use strict"
896
906
  function r(e){return(0,o.getOpenCodeServerUrl)(e.projectPath,e.logger)}async function s(e,t,s,o){const n=r(s)
897
907
  if(!n||!t)return!1
@@ -1029,21 +1039,21 @@ let b
1029
1039
  if(u?.length)b=(await Promise.all(u.map((e=>f.get(`/api/projects/${y}/test-processes/${e}`))))).filter((e=>e.success&&e.data)).map((e=>e.data))
1030
1040
  else{const e=await f.get(`/api/projects/${y}/test-processes/active`)
1031
1041
  b=e.success&&e.data?Array.isArray(e.data)?e.data:[e.data]:[]}if(0===b.length)return{success:!1,message:"No test processes configured for this project. Set up testing first.",error:"No test processes"}
1032
- const E=Math.max(1,Math.min(8,b[0]?.config?.poolSize??2)),C=b[0]?.config?.fingerprint||[]
1033
- let S
1034
- try{S=await(0,c.acquireSlot)(v,E)}catch(e){return{success:!1,message:"Could not acquire test worktree slot: "+(0,i.getErrorMessage)(e),error:(0,i.getErrorMessage)(e)}}const k=S.path,T=(0,n.simpleGit)(v)
1042
+ const E=Math.max(1,Math.min(8,b[0]?.config?.poolSize??2)),S=b[0]?.config?.fingerprint||[]
1043
+ let C
1044
+ try{C=await(0,c.acquireSlot)(v,E)}catch(e){return{success:!1,message:"Could not acquire test worktree slot: "+(0,i.getErrorMessage)(e),error:(0,i.getErrorMessage)(e)}}const k=C.path,T=(0,n.simpleGit)(v)
1035
1045
  try{if((0,s.existsSync)(k))try{const e=(0,n.simpleGit)(k)
1036
- await e.raw(["reset","--hard",I]),m.info("Reset pool slot to latest branch HEAD",{worktreePath:k,branchName:I,slotIndex:S.index})}catch(e){m.warn("Could not reset slot, recreating",{error:(0,i.getErrorMessage)(e)})
1046
+ await e.raw(["reset","--hard",I]),m.info("Reset pool slot to latest branch HEAD",{worktreePath:k,branchName:I,slotIndex:C.index})}catch(e){m.warn("Could not reset slot, recreating",{error:(0,i.getErrorMessage)(e)})
1037
1047
  try{await T.raw(["worktree","remove","--force",k])}catch{}}if(!(0,s.existsSync)(k)){(0,s.mkdirSync)((0,o.join)(v,".alchemy_lab","test-worktrees"),{recursive:!0})
1038
1048
  try{if(!(await T.branch()).all.includes(I))return(0,c.releaseSlot)(k),{success:!1,message:`Branch ${I} not found`,error:"Branch not found"}
1039
- await T.raw(["worktree","add","--detach",k,I]),m.info("Created pool slot worktree (detached)",{worktreePath:k,branchName:I,slotIndex:S.index})}catch(e){if(!(e+"").includes("already exists"))return(0,c.releaseSlot)(k),{success:!1,message:"Failed to create pool slot worktree: "+(0,i.getErrorMessage)(e),error:(0,i.getErrorMessage)(e)}
1040
- m.info("Pool slot worktree already exists, using as-is",{worktreePath:k})}}}catch(e){throw(0,c.releaseSlot)(k),e}const _=await(0,c.computeFingerprint)(k,C),j=0===C.length||_!==S.storedFingerprint,A=0===C.length?null:_===S.storedFingerprint
1041
- j||m.info("Pool slot fingerprint matches; skipping setup",{worktreePath:k,slotIndex:S.index,fingerprintFiles:C})
1049
+ await T.raw(["worktree","add","--detach",k,I]),m.info("Created pool slot worktree (detached)",{worktreePath:k,branchName:I,slotIndex:C.index})}catch(e){if(!(e+"").includes("already exists"))return(0,c.releaseSlot)(k),{success:!1,message:"Failed to create pool slot worktree: "+(0,i.getErrorMessage)(e),error:(0,i.getErrorMessage)(e)}
1050
+ m.info("Pool slot worktree already exists, using as-is",{worktreePath:k})}}}catch(e){throw(0,c.releaseSlot)(k),e}const _=await(0,c.computeFingerprint)(k,S),j=0===S.length||_!==C.storedFingerprint,A=0===S.length?null:_===C.storedFingerprint
1051
+ j||m.info("Pool slot fingerprint matches; skipping setup",{worktreePath:k,slotIndex:C.index,fingerprintFiles:S})
1042
1052
  const{execSync:P}=await Promise.resolve().then(t.t.bind(t,5317,23))
1043
1053
  if(j){for(const e of b){const t=e.config?.setup||[]
1044
- if(0!==t.length){m.info("Running setup commands for test process",{processName:e.name,commandCount:t.length,slotIndex:S.index})
1045
- for(const r of t)try{m.info("Setup command",{command:r,worktreePath:k}),P(r,{cwd:k,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"/bin/sh",env:{...process.env,FORCE_COLOR:"0"}})}catch(t){m.warn("Setup command failed",{command:r,processName:e.name,exitCode:t.status,stderr:(t.stderr||"").slice(-500)})}}}C.length>0&&await(0,c.writeSlotFingerprint)(k,_),await(0,c.writeWarmSnapshot)(k)}else{const{removed:e}=await(0,c.restoreToWarmSnapshot)(k)
1046
- e>0&&m.info("Pruned drift from warm slot",{worktreePath:k,slotIndex:S.index,removed:e})}let M
1054
+ if(0!==t.length){m.info("Running setup commands for test process",{processName:e.name,commandCount:t.length,slotIndex:C.index})
1055
+ for(const r of t)try{m.info("Setup command",{command:r,worktreePath:k}),P(r,{cwd:k,timeout:12e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"/bin/sh",env:{...process.env,FORCE_COLOR:"0"}})}catch(t){m.warn("Setup command failed",{command:r,processName:e.name,exitCode:t.status,stderr:(t.stderr||"").slice(-500)})}}}S.length>0&&await(0,c.writeSlotFingerprint)(k,_),await(0,c.writeWarmSnapshot)(k)}else{const{removed:e}=await(0,c.restoreToWarmSnapshot)(k)
1056
+ e>0&&m.info("Pruned drift from warm slot",{worktreePath:k,slotIndex:C.index,removed:e})}let M
1047
1057
  try{const e=(0,n.simpleGit)(k)
1048
1058
  M=(await e.revparse(["HEAD"])).trim()}catch(e){m.warn("Failed to capture worktree HEAD; commit_sha will be NULL on this run",{worktreePath:k,error:(0,i.getErrorMessage)(e)})}const O=[],R=[],D=[]
1049
1059
  let x
@@ -1440,7 +1450,7 @@ e&&e.error&&"retryable"in e.error&&(this.details.retryable=!!e.error.retryable)}
1440
1450
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.spawnPlannerWithDoc=async function(e){const{agent:t,prompt:o,title:n,parentSessionId:i,requestId:a,apiClient:c,logger:l,projectId:d,projectPath:u,trackChildPid:h}=e
1441
1451
  let g=e.planId
1442
1452
  if(!g){const r=`PLAN-${(e.planName||n).replace(/\.md$/i,"")}.md`
1443
- try{const e=await c.post(`/api/projects/${d}/documents`,{filename:r,content:" ",type:"Plan"})
1453
+ try{const e=await c.post(`/api/projects/${d}/documents`,{filename:r,content:" ",type:"Plan",metadata:{isStub:!0}})
1444
1454
  g=e?.data?.id,l.info("spawnPlannerWithDoc: pre-created plan document",{planId:g,filename:r,agent:t})}catch(e){l.warn("spawnPlannerWithDoc: failed to pre-create plan document; planner will fall back to plan_write create",{error:(0,s.getErrorMessage)(e),agent:t})}}const p="quest-planner"===t?"quest":"plan",m=g?`[Session Context]\n- ${p}Id: ${g} \u2014 this is YOUR associated ${p} document. It already exists with a placeholder filename.\n- Use plan_write (update / append / replace) with planId "${g}" to fill it in.${"quest-planner"===t?" For quests, plan_write update also accepts criteria / tickIntervalSeconds / maxInFlight / maxPerDay / minIterations / status.":""}${"quest-planner"===t?"":'\n- On your FIRST plan_write call, include a "name" field with a short descriptive title so the document gets a meaningful filename.'}\n- Do NOT call plan_write "create" \u2014 always modify the document above.\n- Do NOT call plan_read "get-active" \u2014 your associated ${p} is given here, not via the active-${p} slot.\n\n${o}`:o,f=await(0,r.spawnActionAgent)({agent:t,prompt:m,cwd:u,projectPath:u,projectId:d,title:n,requestId:a,parentSessionId:i,apiClient:c,logger:l,trackChildPid:h})
1445
1455
  if(!f.success||!f.sessionId)return{success:!1,error:f.error||"spawnActionAgent returned no sessionId"}
1446
1456
  l.info("spawnPlannerWithDoc: spawn succeeded",{agent:t,sessionId:f.sessionId,pid:f.pid,planId:g})
@@ -1470,11 +1480,11 @@ if("string"==typeof t.body){try{const e=JSON.parse(t.body)
1470
1480
  if(e.error?.message)return e.error.message
1471
1481
  if(e.message)return e.message}catch{}return t.body.substring(0,200)}for(const e of Object.keys(t)){const r=t[e]
1472
1482
  if("string"==typeof r&&r.length>0)return`${e}: ${r}`}return"Unknown error (no readable properties)"}},8955(e,exports){"use strict"
1473
- function t(){return n||s}function r(){return t().map((e=>e.name))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.REQUEST_SCOPED_AGENTS=void 0,exports.initializeAgentRegistry=async function(e,t){return a||(a=(async()=>{try{if(!e)return t.debug("No API client available, using default agents"),n=s,void(i=!0)
1483
+ function t(){return n||s}function r(){return t().map((e=>e.name))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.PERSISTENT_ORCHESTRATOR_AGENTS=exports.REQUEST_SCOPED_AGENTS=void 0,exports.initializeAgentRegistry=async function(e,t){return a||(a=(async()=>{try{if(!e)return t.debug("No API client available, using default agents"),n=s,void(i=!0)
1474
1484
  t.info("Fetching available agents from API")
1475
1485
  const r=await e.proxyGet("/api/agents/templates")
1476
1486
  r&&Array.isArray(r)&&r.length>0?(n=r.map((e=>({id:e.id||e.name,name:e.name,description:e.description,mode:e.mode,builtIn:e.builtIn}))),t.info("Agent registry initialized",{agentCount:n.length})):(t.warn("No agents returned from API, using defaults"),n=s),i=!0}catch(e){t.warn("Failed to fetch agents from API, using defaults",{error:e instanceof Error?e.message:e+""}),n=s,i=!0}})(),a)},exports.getAvailableAgents=t,exports.getAgentNames=r,exports.isValidAgent=function(e){return r().includes(e)},exports.getDefaultAgent=function(){return"work"},exports.formatAgentsForDescription=function(){return t().map((e=>`'${e.name}'${e.description?" - "+e.description:""}`)).join(", ")},exports.isAgentRegistryInitialized=function(){return i},exports.getBuiltInAgentConfig=function(e){const t=s.find((t=>t.name===e))
1477
- return t?{preferredProvider:t.preferredProvider||"inherit",preferredModelTier:t.preferredModelTier||"same",requestContextMode:t.requestContextMode}:null},exports.getAllowedSubagents=function(e){return o[e]||null},exports.resetAgentRegistry=function(){n=null,i=!1,a=null},exports.REQUEST_SCOPED_AGENTS=["coder","tester","test-architect"]
1487
+ return t?{preferredProvider:t.preferredProvider||"inherit",preferredModelTier:t.preferredModelTier||"same",requestContextMode:t.requestContextMode}:null},exports.getAllowedSubagents=function(e){return o[e]||null},exports.resetAgentRegistry=function(){n=null,i=!1,a=null},exports.REQUEST_SCOPED_AGENTS=["coder","tester","test-architect"],exports.PERSISTENT_ORCHESTRATOR_AGENTS=["alchemist","herald"]
1478
1488
  const s=[{id:"coder",name:"coder",description:"Development and implementation agent",builtIn:!0,preferredModelTier:"same",requestContextMode:"required"},{id:"research",name:"research",description:"Codebase research and exploration agent",builtIn:!0,preferredModelTier:"two_down",requestContextMode:"none"},{id:"journal",name:"journal",description:"Journal generation agent",builtIn:!0,preferredModelTier:"one_down"},{id:"planner",name:"planner",description:"Planning and architecture agent",builtIn:!0,preferredModelTier:"same"},{id:"specialist",name:"specialist",description:"Domain specialist for development tasks",builtIn:!0,preferredModelTier:"same"},{id:"auto-planner",name:"auto-planner",description:"Autonomous background planner",builtIn:!0,preferredModelTier:"same"},{id:"alchemist",name:"alchemist",description:"Persistent orchestrator",builtIn:!0,preferredModelTier:"same"}],o={alchemist:["specialist","research","planner"],specialist:["coder","research","auto-planner","planner"],tester:["research"],"auto-tester":["research"]}
1479
1489
  let n=null,i=!1,a=null},8984(e,exports,t){"use strict"
1480
1490
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.MCPClientConfigurer=void 0
@@ -1545,13 +1555,13 @@ if(!i){try{const e=await r.readFile(w,"utf-8"),t=JSON.parse(e)
1545
1555
  t?.openCodeTools?(g=t.openCodeTools,this.logger.info("Found tool settings in project config",{projectConfigTools:g})):v=!0,t?.openCodeModel&&(p=t.openCodeModel)}catch(e){this.logger.debug("No project config found, will create with defaults"),v=!0}try{const e=await r.readFile(h,"utf-8"),t=JSON.parse(e)
1546
1556
  t?.mode?.alchemy?.tools&&(m=t.mode.alchemy.tools,this.logger.info("Found existing tool settings in opencode.json",{existingTools:m})),t?.model&&(f=t.model),t?.mode?.journal&&(y=!0)}catch(e){this.logger.info("No existing opencode.json found, will use defaults")}}const I=i?.openCodeTools||g||m||{glob:!1,grep:!1,ls:!1,list:!1,view:!1,read:!1,write:!1,edit:!1,patch:!1,diagnostics:!0,bash:!0===i?.enableBash,fetch:!1,sourcegraph:!0,agent:!1!==a,todoread:!1,todowrite:!1},b={tools:I},E=i?.openCodeModel||p||f||"anthropic/claude-opus-4-5"
1547
1557
  i?.openCodeModel?b.model=i.openCodeModel:p?b.model=p:f&&(b.model=f)
1548
- const C=c.join(s,".opencode","agent")
1549
- await r.mkdir(C,{recursive:!0})
1550
- const S=E||"anthropic/claude-opus-4-5-20251101"
1558
+ const S=c.join(s,".opencode","agent")
1559
+ await r.mkdir(S,{recursive:!0})
1560
+ const C=E||"anthropic/claude-opus-4-5-20251101"
1551
1561
  let k,T=null,_=null
1552
1562
  if(i?.projectId)if(await this.seedAgentsFromRemote(i.projectId),_=await this.fetchProjectFromRemote(i.projectId),k=_?.metadata?.globalSystemPrompt,k&&this.logger.info("Using global system prompt from project metadata",{projectId:i.projectId,promptLength:k.length}),T=await this.fetchAgentsFromRemote(i.projectId),T&&T.length>0){this.logger.info("Using agents from remote database",{count:T.length})
1553
1563
  for(const e of T){if(!e.enabled)continue
1554
- const t=this.generateAgentMarkdown(e,d,S,k),s=c.join(C,e.name+".md")
1564
+ const t=this.generateAgentMarkdown(e,d,C,k),s=c.join(S,e.name+".md")
1555
1565
  await r.writeFile(s,t,"utf8"),this.logger.info(`Created ${e.name} agent file from remote config`,{agentPath:s,mode:e.mode})}}else this.logger.warn("No agents found - check remote server or enable agents via UI")
1556
1566
  else this.logger.warn("No projectId provided - agents must be configured via database")
1557
1567
  const j={$schema:"https://opencode.ai/config.json",model:E,mcp:{[d]:{type:"local",command:[n,u,s],enabled:!0,timeout:6e5}}}
@@ -1564,7 +1574,7 @@ e.name in r&&(t.bash=!!r[e.name]),t.skill=!1,("subagent"===e.mode||"tester"===e.
1564
1574
  let s=""
1565
1575
  k&&(s+=k.trim()+"\n\n"),e.prompt&&(s+=e.prompt),e.promptAddition&&(s+="\n\n"+e.promptAddition),j.agent[e.name]={tools:t,...s?{prompt:s}:{},...e.description?{description:e.description}:{},mode:"utility"===e.mode?"primary":e.mode||"primary",...e.color?{color:e.color}:{}}}j.agent.general={...j.agent.general,disable:!0},j.agent.explore={...j.agent.explore,tools:{grep:!1,glob:!1,list:!1,read:!1,bash:!1,[d+"_search"]:!0,[d+"_read_files"]:!0,[d+"_view_asset"]:!0,[d+"_query_history"]:!0,webfetch:!0,websearch:!0,codesearch:!0}}
1566
1576
  const e=`---\ndescription: Fast codebase exploration and research subagent\nmode: subagent\n---\n\n${k?k.trim()+"\n\n":""}You are a codebase exploration agent. Your job is to find specific information and return concise, targeted answers.\n\n## Response Guidelines\n\n- **Be concise.** Return only what was asked for. A typical answer is 100-500 words.\n- **Lead with the answer.** State findings first, then supporting details.\n- **Reference specific files and lines.** Use \`file_path:line_number\` format.\n- **Don't exhaustively document everything you find.** Focus on what's relevant to the question.\n- **Use structured output** when listing multiple items (bullet points, not prose).\n\n## Strategy\n\n1. Start with \`search\` to find relevant files by name or content patterns\n2. Use \`read_files\` to read specific sections (use line ranges, don't read entire large files)\n3. Use \`query_history\` for understanding why code changed or tracing decisions\n\n## Anti-patterns to Avoid\n\n- Don't produce multi-thousand-word reports for simple questions\n- Don't read every file in a directory when a targeted search would suffice\n- Don't explain how tools work \u2014 just use them and report findings\n`
1567
- await r.writeFile(c.join(C,"explore.md"),e,"utf8"),this.logger.info("Created explore agent override with research prompt"),this.logger.info("Added agent tools to opencode.json",{agentCount:Object.keys(j.agent).length})}const A=e=>"string"==typeof e&&e.includes(".opencode/plugin/"),P=(await this.fetchPluginManifest())["opencode-claude-auth"],M=j.plugin,O=Array.isArray(M)?M.filter((e=>!A(e))):[]
1577
+ await r.writeFile(c.join(S,"explore.md"),e,"utf8"),this.logger.info("Created explore agent override with research prompt"),this.logger.info("Added agent tools to opencode.json",{agentCount:Object.keys(j.agent).length})}const A=e=>"string"==typeof e&&e.includes(".opencode/plugin/"),P=(await this.fetchPluginManifest())["opencode-claude-auth"],M=j.plugin,O=Array.isArray(M)?M.filter((e=>!A(e))):[]
1568
1578
  P&&this.applyAuthPluginPin(O,P),O.length>0?j.plugin=O:delete j.plugin,await r.writeFile(h,JSON.stringify(j,null,2),"utf8"),this.logger.info("OpenCode configured successfully",{configPath:h})
1569
1579
  try{const e=await Promise.resolve().then(t.t.bind(t,857,23)),s=c.join(e.homedir(),".alchemy_lab","opencode","config"),o=c.join(s,"opencode.json")
1570
1580
  let n=null
@@ -1687,12 +1697,12 @@ if(i.ok){const e=await i.json()
1687
1697
  return e.data?.id||e.id}s.info(`Project registration failed (HTTP ${i.status})`)}catch(e){s.info("Project registration failed",{error:(0,I.getErrorMessage)(e)})}}Object.defineProperty(i,"__esModule",{value:!0})
1688
1698
  const l=e(3444),d=e(9896),u=e(1943),h=e(6928),g=e(5317),p=e(857),m=e(1253),f=e(8984),y=e(2366),v=e(3962),w=e(1187),I=e(8824),b=e(6800),E=e(4139);(async function(){23===parseInt(process.version.replace("v","").split(".")[0],10)&&(console.error(`\n\u274c Node.js ${process.version} is not supported.`),console.error(" AlchemyLab requires Node.js 22 or 24+ (Node 23 has a broken sqlite API)."),console.error("\n Switch with: nvm use 22 or nvm use 24\n"),process.exit(1))
1689
1699
  const i=process.argv.slice(2)
1690
- let C
1691
- const S=i.indexOf("--port");-1!==S&&i[S+1]&&(C=parseInt(i[S+1],10),isNaN(C)&&(console.error("\u274c Invalid port number"),process.exit(1)))
1692
- const k=i.filter(((e,t)=>"--port"!==e&&(-1===S||t!==S+1)))
1700
+ let S
1701
+ const C=i.indexOf("--port");-1!==C&&i[C+1]&&(S=parseInt(i[C+1],10),isNaN(S)&&(console.error("\u274c Invalid port number"),process.exit(1)))
1702
+ const k=i.filter(((e,t)=>"--port"!==e&&(-1===C||t!==C+1)))
1693
1703
  if(0===k.length)return void await async function(r={}){const i=process.cwd(),l=(0,h.join)(i,E.ALCHEMY_DIR_NAME)
1694
1704
  await(0,u.mkdir)(l,{recursive:!0})
1695
- const C=(0,h.join)(l,"server.log"),{createLogger:S}=await Promise.resolve().then(e.t.bind(e,2782,23)),k=S({serviceName:"alchemy-server",console:!1,logToFile:!0,logFilePath:C,baseDir:i}),T=await a(k),_=new m.TokenManager(k,i,{remoteServerUrl:T,allowInteractiveAuth:!1})
1705
+ const S=(0,h.join)(l,"server.log"),{createLogger:C}=await Promise.resolve().then(e.t.bind(e,2782,23)),k=C({serviceName:"alchemy-server",console:!1,logToFile:!0,logFilePath:S,baseDir:i}),T=await a(k),_=new m.TokenManager(k,i,{remoteServerUrl:T,allowInteractiveAuth:!1})
1696
1706
  await _.initialize()
1697
1707
  let j=await _.getToken()
1698
1708
  if(!j?.token){console.log(""),console.log("\u{1f511} Not logged in. Opening browser to authenticate...")
@@ -1741,7 +1751,7 @@ u=setInterval((async()=>{if(!y)try{if(await _.hasValidToken())return
1741
1751
  y=!0,console.log(""),console.log("\u26a0\ufe0f Auth token expired. Opening browser to re-authenticate...")
1742
1752
  const e=await _.startAuthenticationFlow()
1743
1753
  if(console.log("\u{1f310} "+e.authUrl),o(e.authUrl),console.log("\u23f1\ufe0f Waiting for re-authentication..."),await n(_)){const e=await _.getToken()
1744
- e?.token&&(A=e.token,D.updateAuthToken(A)),console.log("\u2705 Re-authenticated successfully.")}else console.log("\u274c Re-authentication timed out. Some features may not work until you restart.")}catch(e){k.warn("Token watchdog check failed",{error:(0,I.getErrorMessage)(e)})}finally{y=!1}}),3e5),await m.start(g)}catch(e){k.error("Failed to start server",{error:(0,I.getErrorMessage)(e)}),console.error("\u274c Failed to start: "+(0,I.getErrorMessage)(e)),process.exit(1)}}({port:C})
1754
+ e?.token&&(A=e.token,D.updateAuthToken(A)),console.log("\u2705 Re-authenticated successfully.")}else console.log("\u274c Re-authentication timed out. Some features may not work until you restart.")}catch(e){k.warn("Token watchdog check failed",{error:(0,I.getErrorMessage)(e)})}finally{y=!1}}),3e5),await m.start(g)}catch(e){k.error("Failed to start server",{error:(0,I.getErrorMessage)(e)}),console.error("\u274c Failed to start: "+(0,I.getErrorMessage)(e)),process.exit(1)}}({port:S})
1745
1755
  const T=k[0].toLowerCase()
1746
1756
  switch("--help"!==T&&"-h"!==T||(r(),process.exit(0)),"--version"!==T&&"-v"!==T||(console.log("alchemy v"+t()),process.exit(0)),T){case"serve":await async function(e={}){const r=process.cwd()
1747
1757
  s(r)||(console.log("\u{1f4c1} Current directory is not an AlchemyLab project."),console.log(""),console.log("\u{1f4a1} Run `alchemy` to initialize this project."),console.log(""),process.exit(1))
@@ -1755,7 +1765,7 @@ const h=e.port||await(0,b.findAvailablePort)(3456),g=new y.AlchemyActionServer(o
1755
1765
  try{await g.start(),console.log(""),console.log("\u2705 Action server running!"),console.log(` Health: http://127.0.0.1:${g.getPort()}/health`),console.log(""),console.log("Press Ctrl+C to stop the server."),console.log("")
1756
1766
  let e=!1
1757
1767
  const t=async()=>{e||(e=!0,console.log(""),console.log("Shutting down action server..."),await g.stop(),process.exit(0))}
1758
- process.on("SIGTERM",t),process.on("SIGINT",t),await new Promise((()=>{}))}catch(e){o.error("Failed to start server",{error:(0,I.getErrorMessage)(e)}),console.error("\u274c Failed to start: "+(0,I.getErrorMessage)(e)),process.exit(1)}}({port:C})
1768
+ process.on("SIGTERM",t),process.on("SIGINT",t),await new Promise((()=>{}))}catch(e){o.error("Failed to start server",{error:(0,I.getErrorMessage)(e)}),console.error("\u274c Failed to start: "+(0,I.getErrorMessage)(e)),process.exit(1)}}({port:S})
1759
1769
  break
1760
1770
  case"logout":await async function(){const e=process.cwd(),t=(0,l.createEnvLogger)({serviceName:"alchemy-cli",console:!1,baseDir:e}),r=await a(t),s=new m.TokenManager(t,e,{remoteServerUrl:r,allowInteractiveAuth:!1})
1761
1771
  await s.initialize(),await s.hasValidToken()?await s.removeToken()?console.log("Logged out successfully."):(console.error("Failed to remove auth token."),process.exit(1)):console.log("Not currently logged in.")}()