@niwa-labs/ncode 0.1.0 → 0.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/CHANGELOG.zh-CN.md +5 -0
  3. package/README.md +2 -2
  4. package/chunks/{application-A3S2LMBY.js → application-6B6N6MDM.js} +1 -1
  5. package/chunks/{auth-command-QNQ32TBI.js → auth-command-L57HWPOO.js} +1 -1
  6. package/chunks/{chunk-6LDRLO4Y.js → chunk-3LRARE6Z.js} +1 -1
  7. package/chunks/{chunk-5R2PGOIA.js → chunk-3MLT4F77.js} +1 -1
  8. package/chunks/{chunk-NOGL6Y6L.js → chunk-7F3QKGB7.js} +1 -1
  9. package/chunks/{chunk-LFGHL5A2.js → chunk-ALZZ3WAV.js} +1 -1
  10. package/chunks/{chunk-RD7XROJD.js → chunk-CUPCI2YC.js} +1 -1
  11. package/chunks/{chunk-OOBSLGMR.js → chunk-DBSRTVJC.js} +1 -1
  12. package/chunks/{chunk-XSWWOH4F.js → chunk-GS7TCNDK.js} +1 -1
  13. package/chunks/{chunk-36COWQLE.js → chunk-GZPVFWYD.js} +1 -1
  14. package/chunks/{chunk-CAY2BP2G.js → chunk-JEHPL5Z6.js} +1 -1
  15. package/chunks/{chunk-R7NDEPS3.js → chunk-LC7ZI6EV.js} +1 -1
  16. package/chunks/{chunk-ELHMZ5OD.js → chunk-NWMN2FDO.js} +1 -1
  17. package/chunks/{chunk-MVI24MQ2.js → chunk-O5EROATK.js} +664 -664
  18. package/chunks/{chunk-UMGGEC4N.js → chunk-QIYZZJVO.js} +1 -1
  19. package/chunks/{chunk-PBGCNSGZ.js → chunk-QMBFFQPV.js} +1 -1
  20. package/chunks/{chunk-JLFN6WSO.js → chunk-RZDVNG5Z.js} +1 -1
  21. package/chunks/{chunk-MI4YWYJF.js → chunk-UEPKZSE6.js} +1 -1
  22. package/chunks/{chunk-V4IDVAIA.js → chunk-WHBWI5OQ.js} +1 -1
  23. package/chunks/{chunk-ZPIJSTUE.js → chunk-WUORF7YS.js} +1 -1
  24. package/chunks/{chunk-UNEPZJKK.js → chunk-XWNCITOR.js} +5 -5
  25. package/chunks/{data-dir-OKWMOLNQ.js → data-dir-6RWVCAMB.js} +1 -1
  26. package/chunks/{launcher-4QSNU24J.js → launcher-B3C4PQ6Q.js} +3 -3
  27. package/chunks/{lifecycle-ELQ2EYO3.js → lifecycle-56K655PJ.js} +1 -1
  28. package/chunks/main-W3SJ2POE.js +14 -0
  29. package/chunks/{plugin-command-NGTATXBX.js → plugin-command-EBSKJLM3.js} +1 -1
  30. package/chunks/{profile-command-ZHVREBWO.js → profile-command-HIJDJDEL.js} +1 -1
  31. package/chunks/{provider-command-BGKOLCUG.js → provider-command-VCCPLOXR.js} +1 -1
  32. package/chunks/{run-acp-command-2CJQDXHQ.js → run-acp-command-FBV27QBE.js} +13 -13
  33. package/chunks/run-daemon-command-PZ2TU524.js +2 -0
  34. package/chunks/run-exec-command-K7BC2HEI.js +16 -0
  35. package/chunks/src-7ZMHMWLX.js +2 -0
  36. package/chunks/{telemetry-command-6FE4WQ4Q.js → telemetry-command-ZYOF64Y4.js} +1 -1
  37. package/chunks/{update-4VPIX7FP.js → update-ZKUCGIOR.js} +1 -1
  38. package/cli.js +3 -3
  39. package/matrix-mcp-stdio.js +1 -1
  40. package/mcoded.js +1 -1
  41. package/package.json +1 -1
  42. package/release.json +4 -4
  43. package/chunks/main-TXP74KHK.js +0 -14
  44. package/chunks/run-daemon-command-NDOIPTKF.js +0 -2
  45. package/chunks/run-exec-command-VNT4IKOJ.js +0 -16
  46. package/chunks/src-ED5HBSWE.js +0 -2
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
2
- import{a as Kt,b as X,f as Zt,g as en,i as fe,j as he,l as Qe}from"./chunk-MI4YWYJF.js";import{c as bt,i as Wt}from"./chunk-U6RWF7BC.js";import{a as cn}from"./chunk-E25NCIC6.js";import{d as $t,e as zt,f as pe,g as ge,h as Be,i as Ht,l as je,p as Ve,s as Jt,v as Xt,w as Yt}from"./chunk-RD7XROJD.js";import{a as Ue}from"./chunk-ME57CPMB.js";import{a as tn,b as nn,c as We,d as sn,e as rn,f as on,h as an,i as dn}from"./chunk-PBGCNSGZ.js";import{a as Qt}from"./chunk-UMGGEC4N.js";import{a as Vt,b as Ge}from"./chunk-6LDRLO4Y.js";import{e as Tt}from"./chunk-ZPIJSTUE.js";import{e as St}from"./chunk-V4IDVAIA.js";import{J as Fe,M as jt,P as qe,R as Ne,g as wt,h as Mt,i as Pt,j as At,k as kt,n as Rt,q as It,r as Ct,s as xt,t as Et,u as _t,v as te,w as gi,y as Dt,z as Ot}from"./chunk-MVI24MQ2.js";import{a as gt,e as ft,f as ht,g as yt}from"./chunk-TRX2HFTB.js";import{Eb as pt,R as L,S as j,ka as lt,wa as mt}from"./chunk-UNEPZJKK.js";import{a as Lt,c as Ut,d as Ft,e as qt,f as Nt,g as Gt,h as Bt}from"./chunk-AODHXPQF.js";import{a as me}from"./chunk-NOGL6Y6L.js";import{a as vt}from"./chunk-VAARXN34.js";import{e as pi}from"./chunk-FK3SSGJE.js";import{join as fi}from"node:path";import{Writable as hi}from"node:stream";import{formatWithOptions as yi}from"node:util";function Si(e){return fi(e,"v2","observability","logs")}function un(e,t={}){const n=Si(e);const i=t.configureRuntime??wt;const s=t.configureIm??It;const r=t.flushRuntime??Mt;const a=t.flushIm??Ct;const o=t.shutdownRuntime??Pt;const d=t.shutdownIm??xt;const c=t.runtimeLogger??At;const l=t.consoleRef??console;const u=new hi({write(v,P,N){N()}});const h={colorize:false,destination:u};i({dir:n,loggerOptions:h});s({dir:n,loggerOptions:h});const f=["log","info","warn","error","debug","trace"];const g=new Map;const S=new Map;let b=false;const M=()=>{if(!b)return;for(const v of f){const P=g.get(v);if(P&&l[v]===S.get(v)){l[v]=P}}g.clear();S.clear();b=false};const D=()=>{if(b)return;for(const v of f){g.set(v,l[v]);const P=(...N)=>{const A=Ti(v);c[A]({source:"mcode-runtime-console",consoleLevel:v},yi({colors:false,depth:4},...N))};S.set(v,P);l[v]=P}b=true};return{logDirectory:n,async runDuringStartup(v){D();try{return await v()}catch(P){M();throw P}},async flush(){await Promise.allSettled([r(),a()])},async shutdown(){M();await Promise.allSettled([o(),d()])}}}function Ti(e){if(e==="warn")return"warn";if(e==="error")return"error";return"info"}var bi=new Set(["agent","compaction","title"]);var vi=new Set(["waiting","recovered","exhausted","cancelled"]);var wi=new Set(kt);function pn(e){if(!gn(e)||e.schemaVersion!==1)return null;if(!ye(e.sessionId)||!ye(e.turnId))return null;if(!ye(e.callId)||!bi.has(e.scope))return null;if(!vi.has(e.status))return null;if(!ln(e.retryAttempt)||!ln(e.maxRetries))return null;if(!Pi(e.requestAttempt))return null;if(!mn(e.delayMs)||!mn(e.nextRetryAtMs)){return null}const t=Mi(e.error);if(e.error!==void 0&&!t)return null;return{schemaVersion:1,sessionId:e.sessionId,turnId:e.turnId,callId:e.callId,scope:e.scope,status:e.status,retryAttempt:e.retryAttempt,maxRetries:e.maxRetries,requestAttempt:e.requestAttempt,...e.delayMs!==void 0?{delayMs:e.delayMs}:{},...e.nextRetryAtMs!==void 0?{nextRetryAtMs:e.nextRetryAtMs}:{},...t?{error:t}:{}}}function Mi(e){if(e===void 0)return void 0;if(!gn(e)||!wi.has(e.reason))return void 0;if(!ye(e.message))return void 0;if(e.code!==void 0&&(typeof e.code!=="number"||!Number.isFinite(e.code))){return void 0}return{reason:e.reason,message:e.message,...typeof e.code==="number"?{code:e.code}:{}}}function gn(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function ye(e){return typeof e==="string"&&e.length>0}function ln(e){return typeof e==="number"&&Number.isInteger(e)&&e>=0}function Pi(e){return typeof e==="number"&&Number.isInteger(e)&&e>0}function mn(e){return e===void 0||typeof e==="number"&&Number.isFinite(e)&&e>=0}function hn(e){const t=x(e.payload)?e.payload:{};const n=m(t,["sessionId","session_id"]);const i={timestampMs:e.timestamp,source:e.source,...n?{sessionId:n}:{}};if(e.type==="session.start"||e.type==="session.finish"||e.type==="session.error"||e.type==="session.abort"||e.type==="session.active_run.action"){return C({...i,type:e.type,turnId:m(t,["turnId","turn_id"]),taskId:m(t,["taskId","task_id"]),runSource:m(t,["source"]),queueItemIds:yn(t,["queueItemIds","queue_item_ids"])??[],error:m(t,["error"]),errorCode:R(t,["errorCode","error_code"]),errorSource:m(t,["errorSource","error_source"]),errorDetail:m(t,["errorDetail","error_detail"]),errorProviderId:m(t,["errorProviderId","error_provider_id"])})}if(e.type==="turn.prompt_suggestion.generated"){const s=m(t,["suggestion"]);const r=m(t,["turnId","turn_id"]);if(!s||!r||!n)return{...i,type:"unknown",originalType:e.type};const a=m(t,["promptVersion","prompt_version"]);const o=R(t,["elapsedMs","elapsed_ms"]);const d={...i,sessionId:n,type:"turn.prompt_suggestion.generated",turnId:r,suggestion:s,...a!==void 0?{promptVersion:a}:{},...o!==void 0?{elapsedMs:o}:{}};return C(d)}if(e.type==="turn.prompt_suggestion.status"){const s=m(t,["turnId","turn_id"]);const r=m(t,["status"]);const a=m(t,["reason"]);const o=Se(t,["requested"]);if(!s||!r||!n)return{...i,type:"unknown",originalType:e.type};const d={...i,sessionId:n,type:"turn.prompt_suggestion.status",turnId:s,status:r,...a!==void 0?{reason:a}:{},...o!==void 0?{requested:o}:{}};return C(d)}if(e.type==="session.queue.updated"){return C({...i,type:e.type,itemId:m(t,["itemId","item_id"]),status:m(t,["status"]),queuedCount:R(t,["queuedCount","queued_count"]),failedReason:m(t,["failedReason","failed_reason"]),reason:m(t,["reason"]),admissionReason:m(t,["admissionReason","admission_reason"])})}if(e.type==="thread_goal.updated"){const s=ki(t.goal);if(s){return{timestampMs:e.timestamp,source:e.source,type:e.type,sessionId:s.sessionId,goal:s}}}if(e.type==="thread_goal.cleared"){const s=m(t,["goalId","goal_id"]);if(n&&s)return{...i,type:e.type,sessionId:n,goalId:s}}if(e.type==="session.llm_retry"){const s=pn(t);if(s){return{timestampMs:e.timestamp,source:e.source,type:e.type,sessionId:s.sessionId,turnId:s.turnId,callId:s.callId,scope:s.scope,status:s.status,retryAttempt:s.retryAttempt,maxRetries:s.maxRetries,requestAttempt:s.requestAttempt,...s.delayMs!==void 0?{delayMs:s.delayMs}:{},...s.nextRetryAtMs!==void 0?{nextRetryAtMs:s.nextRetryAtMs}:{},...s.error?{error:{reason:s.error.reason,...s.error.code!==void 0?{code:s.error.code}:{}}}:{}}}}if(e.type==="session.created"){const s=m(t,["agentName","agent_name"]);const r=m(t,["sessionType","session_type"]);if(n&&s&&(r==="root"||r==="branch")){return C({...i,type:e.type,agentName:s,sessionType:r,sessionKind:m(t,["sessionKind","session_kind"]),visibility:Ai(t.visibility),title:m(t,["title"]),parentSessionId:m(t,["parentSessionId","parent_session_id"])})}}if(e.type==="session.deleted"){if(n){return C({...i,type:e.type,agentName:m(t,["agentName","agent_name"])})}}if(e.type==="session.title_updated"){const s=m(t,["title"]);if(n&&s!==void 0){return C({...i,type:e.type,title:s,agentName:m(t,["agentName","agent_name"])})}}if(e.type==="session.pinned_updated"){const s=Se(t,["pinned"]);if(n&&s!==void 0){return C({...i,type:e.type,pinned:s,agentName:m(t,["agentName","agent_name"])})}}if(e.type==="session.compaction.progress"){const s=m(t,["progressId"]);const r=m(t,["stage"]);if(n&&s&&(r==="preparing"||r==="installed"||r==="failed")){return{...i,type:e.type,progressId:s,stage:r}}}if(e.type==="session.compaction.started"||e.type==="session.compaction.completed"||e.type==="session.compaction.failed"){const s=m(t,["compactionId","compaction_id"]);if(n&&s){return C({...i,type:e.type,compactionId:s,messagesBefore:R(t,["messagesBefore","messages_before"]),messagesAfter:R(t,["messagesAfter","messages_after"]),tokensBefore:R(t,["tokensBefore","tokens_before"]),tokensAfter:R(t,["tokensAfter","tokens_after"]),tokenUsage:Bi(t.tokenUsage??t.token_usage)})}}if(e.type==="content.retry.exceeded"){const s=m(t,["variant"]);if(n&&(s==="content"||s==="network"||s==="auth")){return C({...i,type:e.type,variant:s,lastUserMsgId:m(t,["lastUserMsgId","last_user_msg_id"])})}}if(e.type==="message.rewind"){if(n){return C({...i,type:e.type,contextReset:Se(t,["contextReset","context_reset"])})}}if(e.type==="session.publish_conflict"){const s=R(t,["durableEntries","durable_entries"]);if(n&&s!==void 0){return C({...i,type:e.type,sessionId:n,preservedTo:m(t,["preservedTo","preserved_to"]),durableEntries:s,publishedEntries:R(t,["publishedEntries","published_entries"])??0})}}if(e.type==="rotation.completed"){const s=m(t,["agentName","agent_name"]);const r=m(t,["oldSessionId","old_session_id"]);const a=m(t,["newSessionId","new_session_id"]);const o=m(t,["reason"]);if(s&&r&&a&&o){return{...i,type:e.type,agentName:s,oldSessionId:r,newSessionId:a,reason:o}}}if(e.type==="questionnaire.ask"){const s=$e(t.request);if(s){return C({...i,type:e.type,request:s,agentName:m(t,["agentName","agent_name"])})}}if(e.type==="questionnaire.dismiss"||e.type==="questionnaire.superseded"){const s=m(t,["requestId","request_id"]);if(s)return{...i,type:e.type,requestId:s}}if(e.type==="permission.ask"){const s=Ni(t);if(s)return{...i,type:e.type,request:s}}if(e.type==="permission.resolved"){const s=m(t,["requestId","request_id"]);if(s){const r=Gi(t.decision);return C({...i,type:e.type,requestId:s,decision:r})}}return{...i,type:"unknown",originalType:e.type}}function Ai(e){return e==="visible"||e==="hidden"?e:void 0}function ki(e){if(!x(e))return void 0;const t=Ci(e.status);if(typeof e.goalId!=="string"||typeof e.sessionId!=="string"||typeof e.objective!=="string"||t===void 0||!W(e.createdAt)||!W(e.updatedAt)||!W(e.tokensUsed)||!W(e.timeUsedSeconds)||!(e.tokenBudget===null||W(e.tokenBudget))||typeof e.hasKickoffAttachments!=="boolean"){return void 0}const n=_i(e.lastVerification);const i=Ii(e.executionWait??e.execution_wait);return{goalId:e.goalId,sessionId:e.sessionId,objective:e.objective,status:t,createdAt:e.createdAt,updatedAt:e.updatedAt,tokensUsed:e.tokensUsed,turnsUsed:W(e.turnsUsed)?e.turnsUsed:0,timeUsedSeconds:e.timeUsedSeconds,tokenBudget:e.tokenBudget,statusReason:Ei(e.statusReason),...i!==void 0?{executionWait:i}:{},...n!==void 0?{lastVerification:n}:{},hasKickoffAttachments:e.hasKickoffAttachments}}var Ri=new Set(["questionnaire","permission","plan","required_background","automation_owner_conflict","dependency_unavailable","verification","unknown"]);function Ii(e){if(e===null||e===void 0)return void 0;if(!x(e))return void 0;const t=m(e,["reason","waitReason","wait_reason"]);const n=R(e,["sinceMs","since_ms","waitSince","wait_since"]);if(!t||!Ri.has(t)||typeof n!=="number"||!Number.isSafeInteger(n)||n<0){return void 0}return{reason:t,sinceMs:n}}function Ci(e){if(typeof e!=="string")return void 0;if(e==="active"||e==="paused"||e==="blocked"||e==="complete"||e==="budget_limited"||e==="usage_limited"){return e}return"paused"}var xi=new Set(["complete(worker_proposal)","complete(verifier_met)","complete(user_requested)","paused(user_requested)","paused(retracted)","paused(infra_retryable)","paused(accounting_unavailable)","paused(verifier_unavailable)","paused(route_unavailable)","paused(verifier_timeout)","paused(verifier_protocol)","paused(verifier_runtime)","paused(verifier_budget)","paused(verifier_capability)","paused(verifier_aborted)","paused(no_progress)","paused(no_progress_after_completion_claim)","blocked(worker_reported)","blocked(safety_policy)","blocked(verifier_impossible)","budget_limited(token)","budget_limited(main_turn)","budget_limited(active_time)","usage_limited(provider_quota)","usage_limited(rate_limit)"]);function Ei(e){return typeof e==="string"&&xi.has(e)?e:null}function _i(e){if(!x(e)||!(e.backend==="evaluator"||e.backend==="subagent")||!(e.verdict==="met"||e.verdict==="not_met"||e.verdict==="impossible"||e.verdict==="inconclusive")||typeof e.reason!=="string"||!Array.isArray(e.missing)||!e.missing.every(t=>typeof t==="string")||!W(e.notMetStreak)||!W(e.at)){return void 0}return{backend:e.backend,verdict:e.verdict,reason:e.reason,missing:e.missing,notMetStreak:e.notMetStreak,at:e.at}}function W(e){return typeof e==="number"&&Number.isFinite(e)}function $e(e){if(!x(e)||typeof e.id!=="string"||!Array.isArray(e.steps)){return void 0}if(["planReview","plan_review","featureKey","feature_key"].some(d=>Object.hasOwn(e,d))){return void 0}const t=e.steps.map(d=>Ui(d));if(t.some(d=>!d))return void 0;const n=qi(e.requester);const i=Fi(e.tool);const s=Li(e.purpose);if(Object.hasOwn(e,"purpose")&&s===void 0)return void 0;const r=Oi(e);if(!r)return void 0;const a=Di(e.presentation);if(r.mode==="plan"&&(e.schemaVersion!==2||a===void 0)){return void 0}const o=x(e.presentation)?e.presentation:{};return{schemaVersion:typeof e.schemaVersion==="number"?e.schemaVersion:1,id:e.id,...typeof e.title==="string"?{title:e.title}:{},...i?{tool:i}:{},...n?{requester:n}:{},...s?{purpose:s}:{},...r.mode?{mode:r.mode}:{},...r.modePayload?{modePayload:r.modePayload}:{},presentation:a??{replaceComposer:typeof o.replaceComposer==="boolean"?o.replaceComposer:true,showProgress:typeof o.showProgress==="boolean"?o.showProgress:true,allowBackNavigation:typeof o.allowBackNavigation==="boolean"?o.allowBackNavigation:true},steps:t,...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{},...typeof e.status==="number"?{status:e.status}:{},...e.createdAt!==void 0?{createdAt:e.createdAt}:{}}}function Di(e){if(!x(e))return void 0;const t=e.replaceComposer??e.replace_composer;const n=e.showProgress??e.show_progress;const i=e.allowBackNavigation??e.allow_back_navigation;return t===true&&n===true&&i===true?{replaceComposer:true,showProgress:true,allowBackNavigation:true}:void 0}function Oi(e){const t=e.modePayload??e.mode_payload;if(t!==void 0&&!x(t))return void 0;const n=x(t)?t:void 0;const i=n?.featureKey??n?.feature_key;const s=n?.planReview??n?.plan_review;if(e.mode===void 0){return n===void 0?{mode:"questionnaire"}:void 0}if(e.mode==="questionnaire")return n===void 0?{mode:e.mode}:void 0;if(e.mode==="feature-enable"){if(s!==void 0||typeof i!=="string"||!i.trim()){return void 0}return{mode:e.mode,modePayload:{featureKey:i}}}if(e.mode!=="plan"||i!==void 0)return void 0;if(s===void 0)return{mode:e.mode};if(!x(s)||typeof s.markdown!=="string"||!s.markdown.trim()||typeof s.path!=="string"||!s.path.trim()){return void 0}return{mode:e.mode,modePayload:{planReview:{markdown:s.markdown,path:s.path}}}}function Li(e){if(e===1||e==="goal")return"goal";if(e===0||e==="general")return"general";return void 0}function Ui(e){if(!x(e)||typeof e.id!=="string"||typeof e.question!=="string"){return void 0}const t=e.selectionMode;if(t!==0&&t!==1&&t!=="single"&&t!=="multiple"){return void 0}if(e.options!==void 0&&!Array.isArray(e.options))return void 0;const n=[];for(const s of e.options??[]){if(!x(s)||typeof s.id!=="string"||typeof s.label!=="string"){return void 0}const r=fn(s.image);n.push({id:s.id,label:s.label,...typeof s.description==="string"?{description:s.description}:{},...r?{image:r}:{},...s.recommended===true?{recommended:true}:{}})}const i=fn(e.image);return{id:e.id,...typeof e.header==="string"?{header:e.header}:{},question:e.question,...typeof e.description==="string"?{description:e.description}:{},...i?{image:i}:{},selectionMode:t,options:n,allowOther:typeof e.allowOther==="boolean"?e.allowOther:false,otherPlaceholder:typeof e.otherPlaceholder==="string"?e.otherPlaceholder:"",required:typeof e.required==="boolean"?e.required:true}}function Fi(e){if(!x(e))return void 0;const t=m(e,["messageId","message_id"]);const n=m(e,["callId","call_id"]);return t&&n?{messageId:t,callId:n}:void 0}function fn(e){if(!x(e))return void 0;const t=m(e,["src"]);if(!t)return void 0;return C({src:t,alt:m(e,["alt"]),caption:m(e,["caption"]),width:R(e,["width"]),height:R(e,["height"])})}function qi(e){if(!x(e)||typeof e.sessionId!=="string")return void 0;return{sessionId:e.sessionId,...typeof e.runId==="string"?{runId:e.runId}:{},...typeof e.toolCallId==="string"?{toolCallId:e.toolCallId}:{},...typeof e.agentName==="string"?{agentName:e.agentName}:{}}}function Ni(e){const t=m(e,["requestId","request_id"]);if(!t)return void 0;const n=m(e,["toolName","tool_name"]);const i=m(e,["toolInput","tool_input"]);const s=ge({toolName:n,input:i});return C({requestId:t,sessionId:m(e,["sessionId","session_id"]),agentName:m(e,["agentName","agent_name"]),toolName:n,toolDescription:m(e,["toolDescription","tool_description"]),reason:m(e,["reason"]),ruleContents:yn(e,["ruleContents","rule_contents"]),toolInput:i,allowAlwaysSupported:typeof e.allowAlwaysSupported==="boolean"?e.allowAlwaysSupported:void 0,createdAt:R(e,["createdAt","created_at"]),structuredPreview:s})}function Gi(e){return e==="allowOnce"||e==="allowAlways"||e==="deny"||e==="denyAlways"?e:void 0}function m(e,t){for(const n of t){if(typeof e[n]==="string")return e[n]}return void 0}function yn(e,t){for(const n of t){const i=e[n];if(Array.isArray(i)&&i.every(s=>typeof s==="string")){return i}}return void 0}function R(e,t){for(const n of t){const i=e[n];if(typeof i==="number"&&Number.isFinite(i))return i}return void 0}function Bi(e){if(!x(e))return void 0;const t=R(e,["inputTokens","input_tokens"]);const n=R(e,["outputTokens","output_tokens"]);const i=R(e,["cacheReadTokens","cache_read_tokens"]);const s=R(e,["cacheWriteTokens","cache_write_tokens"]);const r=R(e,["totalTokens","total_tokens"]);const a=Se(e,["incomplete"]);if(t===void 0||n===void 0||i===void 0||s===void 0||r===void 0||a===void 0||[t,n,i,s,r].some(o=>o<0)||r!==t+n+i+s){return void 0}return{inputTokens:t,outputTokens:n,cacheReadTokens:i,cacheWriteTokens:s,totalTokens:r,incomplete:a}}function Se(e,t){for(const n of t){const i=e[n];if(typeof i==="boolean")return i}return void 0}function x(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function C(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var Te=class{constructor(t,n=X){this.cliService=t;this.observability=n}cliService;observability;async*watch(t){this.observability.recordAccess({operation:"event.watch",source:"process-local"});for await(const n of this.cliService.watchEvents(t)){yield hn(n)}}watchSessionUsageCommits(t){this.observability.recordAccess({operation:"event.watch-session-usage-commits",source:"process-local"});return this.cliService.watchSessionUsageCommits(t)}};var be=class{cliService;observability;constructor(t){this.cliService=t.cliService;this.observability=t.observability??X}service(t="runtime.cli-service"){this.recordAccess(t,"process-local");return this.cliService}recordAccess(t,n){this.observability.recordAccess({operation:t,source:n})}};function ie(e){if(!e.sessionId)throw new Error("Runtime returned a Session without sessionId.");return se({sessionId:e.sessionId,agentName:e.agentName,title:e.title,parentSessionId:e.parentSessionId,sessionType:e.sessionType===1?"root":e.sessionType===0?"branch":void 0,sessionKind:Qi(e.sessionKind),visibility:e.visibility==="hidden"||e.visibility==="visible"?e.visibility:void 0,purpose:e.purpose,archived:e.archived,workspaceDir:e.workspaceDir,createdAt:e.createdAt,updatedAt:e.updatedAt,status:Vi(e.status?.statusType),errorMessage:e.status?.message,errorCode:e.status?.errorCode,errorSource:e.status?.errorSource,errorDetail:e.status?.errorDetail,errorProviderId:e.status?.errorProviderId,interactionMode:e.interactionMode===1?"plan":void 0,model:ji(e.model)})}function ji(e){if(!e)return void 0;const t=e.thinking?.effort?.trim();const n={...e.providerId?{providerId:e.providerId}:{},...e.modelId?{modelId:e.modelId}:{},...e.variant!==void 0?{variant:e.variant}:{},...t?{thinking:{effort:t}}:{}};return Object.keys(n).length>0?n:void 0}function Vi(e){switch(e){case 0:return"idle";case 1:return"started";case 2:return"error";case 3:return"aborted";default:return void 0}}function Qi(e){switch(e){case 0:return"unknown";case 1:return"conversation";case 2:return"task";case 3:return"peek";case 4:return"channel";case 5:return"cron";default:return void 0}}function Tn(e){const t=F(e.selection)??{};const n=F(e.provider)??{};const i=F(e.auth)??{};const s=Array.isArray(e.warnings)?e.warnings.filter(g=>typeof g==="string"):[];const r=w(n,["authMode"]);const a=ne(i,["tokenPresent"]);const o=w(t,["providerId"])??w(n,["id"]);const d=r!==void 0&&r!=="managed-login";const c=e.modelSource==="byok"||d?"byok":e.modelSource==="token-plan"?"token-plan":r==="managed-login"?"token-plan":o||r?"byok":void 0;const l=(c==="token-plan"||c===void 0&&r==="managed-login")&&a!==true;const u=Wi(e.tokenPlanQuota);const h=e.tokenPlanQuotaState==="available"||e.tokenPlanQuotaState==="not-subscribed"||e.tokenPlanQuotaState==="unavailable"?e.tokenPlanQuotaState:void 0;const f=h??(c==="token-plan"?u?"available":"unavailable":void 0);return se({status:l?"needs-login":s.length>0?"warning":r||w(t,["defaultModel"])?"ready":"unknown",defaultModel:w(t,["defaultModel"]),providerId:o,modelId:w(t,["modelId"]),authMode:r,managedTokenPresent:a,modelSource:c,tokenPlanQuotaState:f,tokenPlanQuota:u,profile:e.profile===null||typeof e.profile==="string"?e.profile:void 0,dataDir:typeof e.dataDir==="string"?e.dataDir:void 0,loginEpoch:typeof e.loginEpoch==="string"?e.loginEpoch:void 0,warnings:s})}function Wi(e){const t=F(e);const n=Sn(t?.fiveHour);const i=Sn(t?.weekly);const s=$i(t?.video);return n&&i?{fiveHour:n,weekly:i,...s?{video:s}:{}}:void 0}function $i(e){const t=F(e);if(!t||typeof t.unlimited!=="boolean")return void 0;const n=Y(t,["remainingCount"]);const i=Y(t,["totalCount"]);const s=Y(t,["resetAtMs"]);return se({remainingCount:n===void 0?void 0:Math.round(Math.max(0,n)),totalCount:i===void 0?void 0:Math.round(Math.max(0,i)),resetAtMs:s,unlimited:t.unlimited})}function Sn(e){const t=F(e);if(!t||typeof t.unlimited!=="boolean")return void 0;const n=Y(t,["remainingPercent"]);const i=Y(t,["resetAtMs"]);return se({remainingPercent:n===void 0?void 0:Math.round(Math.min(100,Math.max(0,n))),resetAtMs:i,unlimited:t.unlimited})}function bn(e){const t=F(e.runtimeOwner)??{};const n=F(e.paths)??{};const i=F(e.selection)??{};const s=F(e.provider)??{};const r=F(e.auth)??{};const a=F(e.byok)??{};return se({status:w(e,["status"]),surface:w(e,["surface"]),runtimeMode:w(e,["runtimeMode"]),runtimeOwnerKind:w(t,["kind"]),runtimeOwnerId:w(t,["id"]),dataDir:w(n,["dataDir"]),configPath:w(n,["configPath"]),configPresent:ne(n,["configPresent"]),authCachePresent:ne(n,["authCachePresent"]),defaultModel:w(i,["defaultModel"]),providerId:w(i,["providerId"])??w(s,["id"]),modelId:w(i,["modelId"]),providerBaseUrl:w(s,["baseURL"]),authMode:w(s,["authMode"]),authModeSource:w(s,["authModeSource"]),managedTokenPresent:ne(r,["tokenPresent"]),apiKeyPresent:ne(s,["apiKeyPresent"]),customProviderCount:Y(a,["customProviderCount"]),warnings:Array.isArray(e.warnings)?e.warnings.filter(o=>typeof o==="string"):[]})}function ze(e){const t=new Set;return e.flatMap(n=>{const i=n.path.trim();if(!i||t.has(i))return[];t.add(i);return[{...n,path:i}]})}function vn(e){const t=[];const n=Math.max(0,...e.map(i=>i.length));for(let i=0;i<n;i+=1){for(const s of e){const r=s[i];if(r!==void 0)t.push(r)}}return t}function F(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function w(e,t){for(const n of t){if(typeof e[n]==="string")return e[n]}return void 0}function ne(e,t){for(const n of t){if(typeof e[n]==="boolean")return e[n]}return void 0}function Y(e,t){for(const n of t){const i=e[n];if(typeof i==="number"&&Number.isFinite(i))return i}return void 0}function se(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function wn(e){if(!e)return[];return e.map(t=>{const n=t.userInput;const i=t.assistantResponse;const s=t.fileChangeCount;return{userMessageId:n.msgId,...i?.msgId?{assistantMessageId:i.msgId}:{},...n.contentHead!==void 0?{contentHead:n.contentHead}:{},timestamp:n.timestamp,fileChangeCount:typeof s==="number"&&Number.isFinite(s)&&s>=0?s:0}})}function Mn(e){return{turns:e.turns.map(t=>({turnId:t.turnId,files:t.files.map(n=>({filePath:n.filePath,action:n.action,skipped:n.skipped===true}))}))}}function Pn(e){return{rewound:e.rewound===true,...e.displayRevision!==void 0?{displayRevision:e.displayRevision}:{},...e.historyRevision!==void 0?{historyRevision:e.historyRevision}:{},...e.deletedMessageIds?{deletedMessageIds:[...e.deletedMessageIds]}:{},...e.turnDiffRewind?{turnDiffRewind:{status:e.turnDiffRewind.status,...e.turnDiffRewind.revertedTurnIds?{revertedTurnIds:[...e.turnDiffRewind.revertedTurnIds]}:{},...e.turnDiffRewind.errorCode!==void 0?{errorCode:e.turnDiffRewind.errorCode}:{}}}:{}}}function An(e){return{rewound:e.rewound===true,...e.turnId!==void 0?{turnId:e.turnId}:{},...e.userMessageId!==void 0?{userMessageId:e.userMessageId}:{},...e.displayRevision!==void 0?{displayRevision:e.displayRevision}:{},...e.historyRevision!==void 0?{historyRevision:e.historyRevision}:{},...e.deletedMessageIds?{deletedMessageIds:[...e.deletedMessageIds]}:{}}}var ve=class{constructor(t){this.context=t}context;async getWorkspaceGitMetadata(t){const n=await this.context.service("workspace.git.metadata").getWorkspaceGitMetadata(t);if(!n){return{isGitRepo:false,branch:"",detached:false,isWorktree:false}}const i=n.isGitRepo===true;const s=typeof n.branch==="string"?n.branch.trim():"";const r=n.hasHead===true;const a=s?await this.readReviewLink(t,s):void 0;return{isGitRepo:i,branch:s,detached:i&&r&&s.length===0,isWorktree:n.isWorktree===true,...a?{reviewLink:a}:{}}}async readReviewLink(t,n){try{const i=await this.context.service("workspace.git.review-link").getWorkspaceReviewLink(t,n);return Hi(i)}catch{return void 0}}async listWorkspaceFileTree(t,n,i){const s=await this.context.service("workspace.tree.list").listWorkspaceFileTree({workspaceDir:t,...n?{path:n}:{},...i?{signal:i}:{}});return zi(s)}async searchWorkspaceFiles(t,n,i=20,s){return[...await this.context.service("workspace.search").searchWorkspaceFiles({workspaceDir:t,query:n,limit:i,...s?{signal:s}:{}})]}async listWorkspaceFileTreeCandidates(t,n){const i=ze(t.roots);const s=await Promise.all(i.map(async r=>{const a=await this.listWorkspaceFileTree(r.path,t.path,n);return a.map(o=>({...o,workspaceDir:r.path}))}));return s.flat()}async searchWorkspaceFileCandidates(t,n){const i=ze(t.roots);const s=Math.max(1,Math.floor(t.limit??20));const r=await Promise.all(i.map(async o=>{const d=await this.searchWorkspaceFiles(o.path,t.query,s,n);return d.map(c=>({workspaceDir:o.path,path:c}))}));const a=new Set;return vn(r).flatMap(o=>{const d=`${o.workspaceDir}\0${o.path}`;if(a.has(d))return[];a.add(d);return[o]}).slice(0,s)}};function zi(e){return e.flatMap(t=>{if(!t||typeof t!=="object"||Array.isArray(t))return[];const n=t;if(typeof n.name!=="string"||typeof n.path!=="string"||n.type!=="file"&&n.type!=="directory"){return[]}return[{name:n.name,path:n.path,type:n.type,...typeof n.ignored==="boolean"?{ignored:n.ignored}:{}}]})}function Hi(e){if(!e||typeof e!=="object"||Array.isArray(e))return void 0;const t=e;const{vendor:n,url:i}=t;const s=t.number;if(n!=="github"&&n!=="gitlab")return void 0;if(typeof i!=="string"||!i)return void 0;if(typeof s!=="number"||!Number.isInteger(s)||s<=0){return void 0}return{vendor:n,url:i,number:s}}var we=class{constructor(t,n,i){this.cliService=t;this.defaultAgentName=n;this.onSessionDeleted=i}cliService;defaultAgentName;onSessionDeleted;async createSession(t,n){const i=await this.cliService.createSession({name:this.defaultAgentName,workspaceDir:t.workspaceDir,...t.title?{title:t.title}:{},...t.parentSessionId?{parentSessionId:t.parentSessionId}:{},...t.visibility?{visibility:t.visibility}:{},...t.purpose?{purpose:t.purpose}:{},...n?{model:{providerId:n.providerId,modelId:n.modelId,...n.variant!==void 0?{variant:n.variant}:{},...n.contextLimit!==void 0?{contextLimit:n.contextLimit}:{},...n.thinking?.effort?.trim()?{thinking:{effort:n.thinking.effort.trim()}}:{}}}:{}});const s=He(i.session,i.sessionId);if(t.mcpServers?.length){await this.configureSessionMcpServers(s.sessionId,t.mcpServers)}return s}async configureSessionMcpServers(t,n){await this.cliService.configureSessionMcpServers({sessionId:t,servers:n.map(i=>i.type==="stdio"?{name:i.name,config:{type:i.type,command:i.command,args:[...i.args],...i.env?{env:{...i.env}}:{}}}:{name:i.name,config:{type:i.type,url:i.url,...i.headers?{headers:{...i.headers}}:{}}})})}clearSessionMcpServers(t){return this.cliService.clearSessionMcpServers(t)}async listSessions(t=this.defaultAgentName,n={}){const i=await this.cliService.listSessions({name:t,...n});return(i.sessions??[]).map(ie)}async listSessionPage(t={},n={}){const i=typeof t==="string"?{...n,agentName:t}:t;const{allAgents:s=false,agentName:r,workspaceDir:a,...o}=i;const d=r??this.defaultAgentName;const c=g=>s?this.listSessionTree(d,g):this.listAgentSessions(d,g);if(!a)return kn(await c(o));let l=o.cursor;const u=new Set(l?[l]:[]);const h=o.limit!==void 0&&o.limit>0?o.limit:void 0;const f=[];for(;;){const g=await c({...o,...h?{limit:Math.max(1,h-f.length)}:{},...l?{cursor:l}:{}});const S=kn(g,a);f.push(...S.sessions);const b=h?f.length>=h:f.length>0;if(b||!g.hasMore)return Rn(f,g);if(!g.nextCursor)return{sessions:f,hasMore:false};if(u.has(g.nextCursor))return{sessions:f,hasMore:false};u.add(g.nextCursor);l=g.nextCursor}}async getSession(t){const n=await this.cliService.getSession({id:t});if(!n.session)throw new Error(`Runtime did not return session ${t}.`);return ie(n.session)}async getMessages(t,n=80){return(await this.listMessagePage(t,{limit:n})).messages}async listMessagePage(t,n={}){const i=await this.cliService.getMessages({id:t,...n.limit!==void 0?{limit:n.limit}:{},...n.before?{before:n.before}:{}});return{messages:(i.messages??[]).map(s=>Ht(s)),hasMore:i.hasMore===true,...i.nextCursor?{nextCursor:i.nextCursor}:{}}}async getSessionForkOptions(t,n){return this.cliService.getSessionForkOptions({id:t,...n?{assistantMessageId:n}:{}})}async forkSession(t){const n=await this.cliService.forkSession({id:t.sessionId,...t.assistantMessageId?{assistantMessageId:t.assistantMessageId}:{},clientRequestId:t.clientRequestId,...t.title?{title:t.title}:{},useSuggestedTitle:t.useSuggestedTitle,createIsolatedWorktree:t.createIsolatedWorktree});return{session:He(n.session,void 0),...n.forkOriginMessageId?{forkOriginMessageId:n.forkOriginMessageId}:{},...n.sourceDisplayMessageId?{sourceDisplayMessageId:n.sourceDisplayMessageId}:{},...n.displayRevision?{displayRevision:n.displayRevision}:{},...n.historyRevision?{historyRevision:n.historyRevision}:{}}}async renameSession(t,n){const i=await this.cliService.updateSession({id:t,title:n});return He(i.session,t)}async archiveSession(t,n){await this.cliService.archiveSession({id:t,archived:n})}async deleteSession(t){await this.onSessionDeleted?.(t);await this.cliService.deleteSession({id:t})}async listSessionInputSummaries(t,n={}){let i=n.before;const s=new Set(i?[i]:[]);let r=[];for(;;){const a=await this.cliService.listSessionInputSummaries({id:t,...n.limit!==void 0?{limit:n.limit}:{},...i?{before:i}:{}});const o=wn(a.summaries);r=[...o,...r];if(!a.hasMore||!a.nextCursor||s.has(a.nextCursor)){return r}s.add(a.nextCursor);i=a.nextCursor}}async getSessionRewindPreview(t){const n=await this.cliService.getSessionRewindPreview({id:t.sessionId,userMessageId:t.userMessageId});return Mn(n)}async rewindSession(t){const n=await this.cliService.rewindSession({id:t.sessionId,userMessageId:t.userMessageId,clientRequestId:t.clientRequestId,...t.rewindTurnDiff?{rewindTurnDiff:true}:{}});return Pn(n)}async editSessionMessage(t){const n=await this.cliService.editSessionMessage({id:t.sessionId,userMessageId:t.userMessageId,clientRequestId:t.clientRequestId,content:t.content,...t.attachments?{attachments:t.attachments.map(i=>({meta:{attachmentType:i.type,fileName:i.fileName,mimeType:i.mimeType,...i.sizeBytes!==void 0?{sizeBytes:i.sizeBytes}:{}},local:{...i.filePath?{filePath:i.filePath}:{},...i.assetId?{assetId:i.assetId}:{}}}))}:{},...t.rewindTurnDiff?{rewindTurnDiff:true}:{}});return An(n)}async listAgentSessions(t,n){const i=await this.cliService.listSessions({name:t,...n});return{sessions:i.sessions??[],hasMore:i.hasMore===true,...i.nextCursor?{nextCursor:i.nextCursor}:{}}}async listSessionTree(t,n){const i=await this.cliService.getSessionTree({name:t,...n});return{sessions:(i.sessions??[]).flatMap(s=>{const r=s.session?[s.session]:[];const a=s.session?.sessionId;if(!a)return r;return[...r,...(s.childSessions??[]).map(o=>Ki(o,a))]}),hasMore:i.hasMore===true,...i.nextCursor?{nextCursor:i.nextCursor}:{}}}};function kn(e,t){const n=e.sessions.map(ie).filter(i=>!t||i.workspaceDir===t);return Rn(n,e)}function Rn(e,t){return{sessions:e,hasMore:t.hasMore===true,...t.nextCursor?{nextCursor:t.nextCursor}:{}}}function Ki(e,t){return{...e,sessionType:Et.Branch,parentSessionId:t}}function He(e,t){if(e)return ie(e);if(t)return{sessionId:t};throw new Error("Runtime did not return the created Session.")}function In(e){let t;let n;for(let s=e.messages.length-1;s>=0;s-=1){const r=e.messages[s];if(!r)continue;if(!n)n=Yi(r);if(!t)t=Xi(r.rawJson);if(n&&t)break}const i=Ji(e.model);if(!t){return{status:e.active?"loading":"empty",...i?{model:i}:{},...n?{compaction:n}:{}}}return{status:e.active?"stale":"live",...i?{model:i}:{},contextUsage:t,compaction:n??{state:"never"}}}function Ji(e){if(!e?.providerId||!e.modelId)return void 0;const t=e.contextLimit===void 0?void 0:Number(e.contextLimit);return{provider:e.providerId,id:e.modelId,...t!==void 0&&Number.isFinite(t)&&t>0?{contextWindow:t}:{}}}function Xi(e){if(!e)return void 0;let t;try{const o=JSON.parse(e);if(!Je(o))return void 0;t=o}catch{return void 0}const n=t.contextUsage??t.context_usage;if(!Je(n))return void 0;const i=Ke(n.contextWindowTokens);const s=Ke(n.usedTokens);const r=n.totalCountSource;if(i===void 0||s===void 0||r!=="LOCAL_ESTIMATE"&&r!=="PROVIDER_USAGE_ANCHORED"){return void 0}const a=Array.isArray(n.components)?n.components.flatMap(o=>{if(!Je(o)||!Zi(o.kind))return[];const d=Ke(o.tokens);return d===void 0?[]:[{kind:o.kind,tokens:d}]}):[];return{contextWindowTokens:i,usedTokens:s,totalCountSource:r,components:a}}function Yi(e){const t=e.kind==="compaction_start"?"running":e.kind==="compaction"?"completed":e.kind==="compaction_failed"?"failed":void 0;if(!t)return void 0;return{state:t,...e.timestamp!==void 0&&Number.isFinite(Number(e.timestamp))?{lastCompactedAtMs:Number(e.timestamp)}:{}}}function Ke(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0?e:void 0}function Zi(e){return e==="SYSTEM_PROMPT"||e==="MEMORY"||e==="TOOLS"||e==="SKILLS"||e==="MESSAGES"||e==="OTHER"}function Je(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}var Me=class{constructor(t,n,i){this.context=t;this.defaultAgentName=n;this.workspaceDir=i}context;defaultAgentName;workspaceDir;async getAccountStatus(t,n){return Tn(await this.context.service("runtime.account").getAccountStatus({...t?{sessionId:t}:{},...n?.model?{model:`${n.model.providerId}/${n.model.modelId}`}:{}}))}async getRuntimeDiagnostics(){return bn(await this.context.service("runtime.diagnostics").getRuntimeDiagnostics())}getInstructionSources(t){return this.context.service("runtime.instructions").getInstructionSources({workspaceDir:t})}async getPermissionMode(){return je(await this.context.service("config.permission.read").getPermissionMode())}async setPermissionMode(t){return je(await this.context.service("config.permission.write").setPermissionMode({mode:t}))??t}async getDangerousCommandGateEnabled(){return Ve(await this.context.service("config.permission.read").getDangerousCommandGateEnabled())}async setDangerousCommandGateEnabled(t){return Ve(await this.context.service("config.permission.write").setDangerousCommandGateEnabled({enabled:t}))??t}async getSandboxFilesystemMode(){return Qe(await this.context.service("config.permission.read").getSandboxFilesystemMode())}async setSandboxFilesystemMode(t){return Qe(await this.context.service("config.permission.write").setSandboxFilesystemMode({mode:t}))??t}async listModels(t){const n=this.context.service("model.list");const i={...t?{sessionId:t}:{}};return(await n.listModels(i)).map(es)}async selectModel(t,n){const i=this.context.service("model.select");const s=Cn(t);if(!n)return i.selectModel(s);const r=await i.selectModel(s);if(!r)return false;return this.selectSessionModel(t,n)}setModelFavorite(t,n){return this.context.service("model.favorite").setModelFavorite({providerId:t.providerId,modelId:t.modelId,favorite:n})}selectSessionModel(t,n){return this.context.service("model.select").selectModel({...Cn(t),sessionId:n})}async listUserModelProviders(){const t=await this.context.service("provider.list").listUserModelProviders();return t.filter(n=>!mt(n.providerId,n.baseUrl))}async listProviderPresets(){return await this.context.service("provider.presets").listProviderPresets()}async getCodexOAuthStatus(){return await this.context.service("provider.codex-oauth.status").getCodexOAuthStatus()}async startCodexOAuthLogin(t){return await this.context.service("provider.codex-oauth.start").startCodexOAuthLogin(t)}async cancelCodexOAuthLogin(t){return await this.context.service("provider.codex-oauth.cancel").cancelCodexOAuthLogin(t)}async getMiniMaxApiKeyStatus(){return await this.context.service("provider.minimax.status").getMiniMaxApiKeyStatus()}getMiniMaxModelSource(){return this.context.service("provider.minimax.source").getMiniMaxModelSource()}setMiniMaxModelSource(t){return this.context.service("provider.minimax.source").setMiniMaxModelSource({source:t})}async upsertMiniMaxApiKey(t){await this.context.service("provider.minimax.upsert").upsertMiniMaxApiKey(t)}async createUserModelProvider(t){await this.context.service("provider.create").createUserModelProvider({...t,models:[...t.models]})}discoverUserModelsCandidate(t){return this.context.service("provider.discover").discoverUserModelsCandidate(t)}async saveUserModelProviderCandidate({modelId:t,saveAndUse:n,skipConnectionTest:i,...s}){return await this.context.service("provider.save-candidate").saveUserModelProviderCandidate({candidate:{...s,...s.models?{models:s.models.map(r=>({...r}))}:{}},modelId:t,...i!==void 0?{skipConnectionTest:i}:{},...n!==void 0?{saveAndUse:n}:{}})}async updateUserModelProvider(t){await this.context.service("provider.update").updateUserModelProvider({...t,...t.models?{models:[...t.models]}:{}})}async deleteUserModelProvider(t){await this.context.service("provider.delete").deleteUserModelProvider({providerId:t})}async testUserModelProvider(t){return await this.context.service("provider.test").testUserModelProvider({providerId:t})}async testUserModel(t,n){return await this.context.service("provider.test-model").testUserModel({providerId:t,modelId:n})}async getSessionUsage(t){const n=await this.context.service("session.usage").getSessionUsage({id:t});return{summary:n.summary,rows:n.rows}}async getSessionUsageSummary(t){return await this.context.service("session.usage-summary").getSessionUsageSummary({id:t})}async getSessionCacheWarmingStatus(t){return this.context.service("session.cache-warming-status").getSessionCacheWarmingStatus(t)}async requestCompaction(t,n=this.defaultAgentName,i){const s=await this.context.service("session.compaction").requestCompaction({name:n,id:t,reason:"ui_request",...i?{customInstructions:i}:{}});return{...s,...s.tokensBefore!==void 0?{tokensBefore:Number(s.tokensBefore)}:{},...s.tokensAfter!==void 0?{tokensAfter:Number(s.tokensAfter)}:{}}}async getContextSnapshot(t){const n=this.context.service("session.context-snapshot");const[i,s,r]=await Promise.all([n.getSession({id:t}),n.getMessages({id:t,limit:80}),n.listModels({sessionId:t})]);const a=i.session;if(!a)throw new Error(`Runtime did not return Session ${t}.`);const o=r.find(c=>c.selected===true);const d=o&&(o.providerId!==a.model?.providerId||o.modelId!==a.model?.modelId)?o:a.model??o;return In({messages:s.messages??[],active:a.status?.statusType===1,model:d})}async getActiveRun(t){const n=this.context.service("session.active-run");const i=await n.getSession({id:t});const s=i.session;if(!s)throw new Error(`Runtime did not return Session ${t}.`);const r=s.status?.statusType===1;const[a,o,d]=r?await Promise.all([n.getActiveTurn(t),n.listPendingPermissions({}),n.getPendingQuestionnaire({name:s.agentName??this.defaultAgentName,sessionId:t})]):[void 0,{requests:[]},{}];const c=r&&(d.request!==void 0||(o.requests??[]).some(h=>h.sessionId===t));const l=a?.turnId;const u=r&&!c&&a?.busyReason==="turn"&&a.locallyOwned;return{schemaVersion:1,sessionId:t,state:r?c?"decision-blocked":"running":s.status?.statusType===2||s.status?.statusType===3?"terminal":"idle",...l?{turnId:l}:{},actions:{steer:u}}}async listSkills(t=this.defaultAgentName,n,i=this.workspaceDir){const s=this.context.service("skill.list");const r=await s.listRuntimeSkills({agentName:t,...i?{workspaceDir:i}:{},includePluginSkills:true});const a=n?.trim().toLocaleLowerCase();const o=a?(r.skills??[]).filter(d=>`${d.name} ${d.displayName??""} ${d.description??""}`.toLocaleLowerCase().includes(a)):r.skills??[];return{skills:o,hasMore:false}}inspectProjectMcp(t){return this.context.service("mcp.project.inspect").inspectProjectMcp(t)}async listMcpServers(t,n){const i={...t?{keyword:t}:{},...n?{sessionId:n}:{}};const s=await this.context.service("mcp.list").listMcpServers(i);return s.servers}};function Cn(e){const t=e.thinking?.effort?.trim();return{providerId:e.providerId,modelId:e.modelId,...e.variant!==void 0?{variant:e.variant}:{},...e.contextLimit!==void 0?{contextLimit:e.contextLimit}:{},...t?{thinking:{effort:t}}:{}}}function es(e){const t=e;const n=t.thinkingConfig;if(!n)return t;const{default_value:i,...s}=n;return{...t,thinkingConfig:{...s,...s.defaultValue!==void 0?{defaultValue:s.defaultValue}:i!==void 0?{defaultValue:i}:{}}}}var Pe=class{constructor(t,n){this.createQueueRequestId=t;this.cliService=n}createQueueRequestId;cliService;async listQueuedMessages(t){return[...(await this.getQueueSnapshot(t)).items]}async getQueueSnapshot(t){const n=await this.cliService.listQueueMessages({id:t});const i=(n.items??[]).map(Xe);return{items:i,paused:n.paused===true,pendingCount:n.pendingCount??i.length}}async getTurnStatus(t){const n=await this.cliService.getTurnStatus(t);return is(n)}async continueQueue(t){const n=await this.cliService.resumeSession({id:t,drainQueued:true,continuePausedQueue:true});if(!n.ok)throw new Error(n.body.message);if(Symbol.asyncIterator in n.source){await n.source[Symbol.asyncIterator]().return?.().catch(()=>void 0)}}async steerQueuedMessage(t,n){const i=await this.cliService.steerSession({id:t,queueItemId:n});if(!i.success||!i.queueItemId||!i.turnId){throw new Error("Runtime did not return the steered Queue item and Turn identities.")}return{queueItemId:i.queueItemId,turnId:i.turnId}}async enqueueMessage(t,n,i={}){return this.cliService.enqueueMessage({id:t,content:n,clientRequestId:this.createQueueRequestId(),interactiveSurface:true,...i.clientIntent?{clientIntent:i.clientIntent}:{},...i.reviewRequest?{reviewRequest:i.reviewRequest}:{},...i.model?{model:{...i.model,...i.model.thinking?{thinking:{...i.model.thinking}}:{}}}:{},...i.attachments?.length?{attachments:i.attachments.map(s=>({meta:{attachmentType:s.type,fileName:s.fileName,mimeType:s.mimeType,sizeBytes:s.sizeBytes},local:{...s.filePath?{filePath:s.filePath}:{},...s.assetId?{assetId:s.assetId}:{}}}))}:{}})}async deleteQueuedMessage(t,n){const i=await this.cliService.deleteQueueItem({id:t,itemId:n});return i.item?Xe(i.item):void 0}async updateQueuedMessageContent(t,n,i){const s=await this.cliService.updateQueueItem({id:t,itemId:n,content:i});return s.item?Xe(s.item):void 0}async getPendingQuestionnaire(t,n,i){i?.throwIfAborted();const s=await this.cliService.getPendingQuestionnaire({name:t,sessionId:n});i?.throwIfAborted();return s.request?xn(s.request):void 0}async getLatestPlanReview(t,n,i){i?.throwIfAborted();const s=await this.cliService.getLatestPlanReview({name:t,sessionId:n});i?.throwIfAborted();return s.request?xn(s.request):void 0}async getPlanModeCapabilities(){return this.cliService.getPlanModeCapabilities()}async replyQuestionnaire(t,n,i){const s=await this.cliService.replyQuestionnaire({name:t,requestId:n,schemaVersion:2,answers:i.map(r=>({stepId:r.stepId,selectedOptionIds:r.selectedOptionIds??[],selectedOther:r.selectedOther===true,...r.otherText?{otherText:r.otherText}:{},...r.skipped===true?{skipped:true}:{}})),submittedAt:Date.now()});return s.ok}async dismissQuestionnaire(t,n){const i=await this.cliService.dismissQuestionnaire({name:t,requestId:n});return i.ok}async listPendingPermissions(t){t?.throwIfAborted();const n=await this.cliService.listPendingPermissions({});t?.throwIfAborted();return(n.requests??[]).map(ns)}async replyPermission(t,n,i){const s=await this.cliService.replyPermission({name:t,requestId:n,reply:ts[i]});return s.success===true}};var ts={allowOnce:te.AllowOnce,allowAlways:te.AllowAlways,deny:te.Deny,denyAlways:te.DenyAlways};function ns(e){const t=ge({toolName:e.toolName,input:e.toolInput});return{...e.requestId?{requestId:e.requestId}:{},...e.sessionId?{sessionId:e.sessionId}:{},...e.agentName?{agentName:e.agentName}:{},...e.toolName?{toolName:e.toolName}:{},...e.ruleContents?{ruleContents:[...e.ruleContents]}:{},...e.toolInput!==void 0?{toolInput:e.toolInput}:{},...e.toolDescription!==void 0?{toolDescription:e.toolDescription}:{},...e.reason!==void 0?{reason:e.reason}:{},...e.allowAlwaysSupported!==void 0?{allowAlwaysSupported:e.allowAlwaysSupported}:{},...e.createdAt!==void 0?{createdAt:Number(e.createdAt)}:{},...t?{structuredPreview:t}:{}}}function is(e){return{...e.activeTurn?{activeTurn:{...e.activeTurn}}:{activeTurn:null},...e.latestActivity?{latestActivity:{...e.latestActivity,...e.latestActivity.completedAtMs===void 0?{}:{completedAtMs:e.latestActivity.completedAtMs}}}:{latestActivity:null}}}function Xe(e){return{itemId:e.itemId,sessionId:e.sessionId,status:e.status,...e.source?{source:e.source}:{},...e.reviewRequest?.scope==="local_changes"?{reviewRequest:{scope:"local_changes"}}:{},...e.content!==void 0?{content:e.content}:{},...e.attachments?{attachments:structuredClone(e.attachments)}:{},...e.modelInfo?{modelInfo:{...e.modelInfo}}:{},...e.createdAt!==void 0?{createdAt:e.createdAt}:{},...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{},...e.startedAt!==void 0?{startedAt:e.startedAt}:{},...e.finishedAt!==void 0?{finishedAt:e.finishedAt}:{},...e.failedReason?{failedReason:e.failedReason}:{}}}function xn(e){return $e({...e,...e.expiresAt!==void 0?{expiresAt:Number(e.expiresAt)}:{},...e.createdAt!==void 0?{createdAt:Number(e.createdAt)}:{}})}var ss=200;var rs=20;var os=3;var Ae=class{constructor(t){this.options=t}options;async getSnapshot(t){const n=await this.listAllSessions();const i=$t(n,t).map(s=>zt(s));return{schemaVersion:1,rootSessionId:t,members:i}}async stop(t){const n=new Set;const i=new Set;const s=new Set;const r=await this.abort(t,n,i)==="stopped";const a=await this.getSnapshot(t);let o=a.members.filter(pe);for(let c=0;c<os;c+=1){for(const u of o){if(s.has(u.sessionId))continue;if(await this.abort(u.sessionId,n,i)==="stopped"){s.add(u.sessionId)}}const l=await this.getSnapshot(t);o=l.members.filter(u=>pe(u)&&!s.has(u.sessionId));if(o.length===0)break}const d=await this.getSnapshot(t);return{schemaVersion:1,rootSessionId:t,rootStopped:r,stoppedSessionIds:[...s],activeSessionIds:d.members.filter(pe).filter(({sessionId:c})=>!s.has(c)&&!i.has(c)).map(({sessionId:c})=>c),failedSessionIds:[...n]}}async listAllSessions(){const t=[];let n;for(let i=0;i<rs;i+=1){const s=await this.options.listSessionPage({allAgents:true,includeArchived:true,includeHidden:true,limit:ss,...n?{cursor:n}:{}});t.push(...s.sessions);if(!s.hasMore||!s.nextCursor)break;n=s.nextCursor}return t}async abort(t,n,i){try{if(await this.options.abortSession({id:t,reason:"user_stop"})){i.delete(t);return"stopped"}i.add(t);return"inactive"}catch{n.add(t);return"failed"}}};var ke=class{constructor(t){this.service=t}service;async*sendMessage(t,n,i){n?.throwIfAborted();const s=n?{signal:n}:{};const r={...t,interactiveSurface:true};const a=i?await this.service.sendMessage(r,s,i):await this.service.sendMessage(r,s);if(!a.ok){throw new Ue("runtime",a.body.message,{code:a.body.key,retryable:a.status>=500})}const o=En(a.source)[Symbol.asyncIterator]();const d=()=>void o.return?.(void 0);n?.addEventListener("abort",d,{once:true});try{for await(const c of{[Symbol.asyncIterator]:()=>o}){n?.throwIfAborted();const l=Be(c,t.turnId);if(l)yield l}}finally{n?.removeEventListener("abort",d);await o.return?.(void 0)}}async abortSession(t){return(await this.service.abortSession(t)).success===true}async*resumeSession(t,n,i){i?.throwIfAborted();const s=await this.service.resumeSession(t,i?{signal:i}:{});if(!s.ok){throw new Ue("runtime",s.body.message,{code:s.body.key,retryable:s.status>=500})}const r=En(s.source)[Symbol.asyncIterator]();const a=()=>void r.return?.(void 0);i?.addEventListener("abort",a,{once:true});try{for await(const o of{[Symbol.asyncIterator]:()=>r}){i?.throwIfAborted();const d=Be(o,n);if(d)yield d}}finally{i?.removeEventListener("abort",a);await r.return?.(void 0)}}steer(t){return this.service.steer(t)}};async function*En(e){for await(const t of e)yield t}var _n=200;var Dn=100;var Un=1;var Fn=2;var Re=class{constructor(t){this.cliService=t}cliService;async listInstalledPlugins(t={}){const n=await On(i=>this.cliService.listInstalledPlugins({limit:_n,...i?{cursor:i}:{}}));return n.map(as).filter(i=>i!==void 0&&(t.marketplace===void 0||i.marketplace===t.marketplace))}async listMarketplacePlugins(t){const n=Ln(t.marketplace);const i=await On(s=>this.cliService.listMarketplacePlugins({source:n,limit:_n,...s?{cursor:s}:{}}));return i.flatMap(s=>{const r=ds(s,t.marketplace);return r?[r]:[]})}async mutatePlugin(t){const n={pluginName:t.plugin.name,source:Ln(t.plugin.marketplace)};const i={install:()=>this.cliService.installPlugin(n),remove:()=>this.cliService.uninstallPlugin(n),enable:()=>this.cliService.enablePlugin(n),disable:()=>this.cliService.disablePlugin(n)};const s=await i[t.action]();return{installed:s.installExists,enabled:s.enabled}}async refreshPlugins(){await this.cliService.refreshPlugins()}};async function On(e){const t=[];const n=new Set;let i;for(let s=0;s<Dn;s+=1){const r=await e(i);t.push(...r.plugins);const a=r.nextCursor?.trim();if(!r.hasMore||!a||n.has(a))return t;n.add(a);i=a}throw new Error(`Plugin catalog exceeded ${Dn} pages.`)}function as(e){const t=cs(e.source);if(!t)return void 0;return qn(e,t,true,e.enabled)}function ds(e,t){return qn(e,t,e.installExists,e.enabled)}function qn(e,t,n,i){const s=e.name.trim();if(!s)return void 0;return{pluginId:Rt(s,t),name:s,displayName:e.displayName?.trim()||s,marketplace:t,...e.version?.trim()?{version:e.version.trim()}:{},...e.description?.trim()?{description:e.description.trim()}:{},...e.author?.trim()?{author:e.author.trim()}:{},installed:n,enabled:i,capabilities:{appCount:e.capabilities.appCount,mcpServerCount:e.capabilities.mcpServerCount,skillCount:e.capabilities.skillCount,...e.capabilities.agentCount?{agentCount:e.capabilities.agentCount}:{}}}}function Ln(e){return e==="official"?Un:Fn}function cs(e){if(e===Un)return"official";if(e===Fn)return"local";return void 0}var Ie=class{constructor(t){this.context=t}context;isEnabled(){return this.context.service("goal.enabled").isGoalEnabled()}get(t){return this.context.service("goal.read").getGoal(t)}create(t){return this.context.service("goal.create").createGoal({sessionId:t.sessionId,objective:t.objective,...t.tokenBudget!==void 0?{tokenBudget:t.tokenBudget}:{},...t.attachments?.length?{kickoffAttachments:t.attachments.map(n=>({type:n.type,filePath:n.filePath,fileName:n.fileName,mimeType:n.mimeType}))}:{}})}patch(t,n){return this.context.service("goal.patch").patchGoal(t,n)}clear(t){return this.context.service("goal.clear").clearGoal(t)}};var us="Auth mismatch: the daemon serves a different login than this window; account details come from the daemon only. Re-login or restart the daemon.";var Ce=class{cliService;context;workspaceAccess;sessionAccess;productAccess;interactionAccess;eventAccess;delegationAccess;conversationAccess;pluginAccess;goalAccess;tokenPlanAccountStatusGetter;synchronizeAuth;accountIdentityGetter;authLoginEpochGetter;feedback;dailyCheckin;contextMode;constructor(t,n={}){this.cliService=t;const i=n.defaultAgentName??Jt;this.tokenPlanAccountStatusGetter=n.tokenPlanAccountStatusGetter;this.synchronizeAuth=n.synchronizeAuth;this.accountIdentityGetter=n.accountIdentityGetter;this.authLoginEpochGetter=n.authLoginEpochGetter;this.feedback=n.feedback;this.dailyCheckin=n.dailyCheckin;this.contextMode=n.contextMode??"standard";this.conversationAccess=new ke(t);this.pluginAccess=new Re(t);this.context=new be({cliService:t,...n.observability?{observability:n.observability}:{}});this.goalAccess=new Ie(this.context);this.workspaceAccess=new ve(this.context);this.sessionAccess=new we(t,i,n.onSessionDeleted);this.productAccess=new Me(this.context,i,n.workspaceDir);this.interactionAccess=new Pe(n.createQueueRequestId??ls,t);this.eventAccess=new Te(t,n.observability);this.delegationAccess=new Ae({listSessionPage:s=>this.sessionAccess.listSessionPage(s),abortSession:s=>this.abortSession(s)})}sendMessage(t,n,i){return this.conversationAccess.sendMessage(t,n,i)}abortSession(t){return this.conversationAccess.abortSession(t)}steer(t){return this.conversationAccess.steer(t)}async createSession(t){const n=this.contextMode==="lightweight"&&!t.parentSessionId&&!t.purpose?{...t,purpose:_t}:t;const i=await this.productAccess.listModels().then(r=>r.find(a=>a.selected===true)).catch(()=>void 0);if(!i)return this.sessionAccess.createSession(n);const s=bt(i)?.trim();return this.sessionAccess.createSession(n,{providerId:i.providerId,modelId:i.modelId,...i.variant!==void 0?{variant:i.variant}:{},...i.contextLimit!==void 0?{contextLimit:i.contextLimit}:{},...s?{thinking:{effort:s}}:{}})}configureSessionMcpServers(t,n){return this.sessionAccess.configureSessionMcpServers(t,n)}clearSessionMcpServers(t){return this.sessionAccess.clearSessionMcpServers(t)}listSessions(t,n){return this.sessionAccess.listSessions(t,n)}listSessionPage(t,n){return this.sessionAccess.listSessionPage(t,n)}getSession(t){return this.sessionAccess.getSession(t)}getMessages(t,n){return this.sessionAccess.getMessages(t,n)}listMessagePage(t,n){return this.sessionAccess.listMessagePage(t,n)}getSessionForkOptions(t,n){return this.sessionAccess.getSessionForkOptions(t,n)}forkSession(t){return this.sessionAccess.forkSession(t)}renameSession(t,n){return this.sessionAccess.renameSession(t,n)}archiveSession(t,n){return this.sessionAccess.archiveSession(t,n)}deleteSession(t){return this.sessionAccess.deleteSession(t)}listSessionInputSummaries(t,n){return this.sessionAccess.listSessionInputSummaries(t,n)}getSessionRewindPreview(t){return this.sessionAccess.getSessionRewindPreview(t)}rewindSession(t){return this.sessionAccess.rewindSession(t)}editSessionMessage(t){return this.sessionAccess.editSessionMessage(t)}isGoalEnabled(){return this.goalAccess.isEnabled()}getGoal(t){return this.goalAccess.get(t)}createGoal(t){return this.goalAccess.create(t)}patchGoal(t,n){return this.goalAccess.patch(t,n)}clearGoal(t){return this.goalAccess.clear(t)}getWorkspaceGitMetadata(t){return this.workspaceAccess.getWorkspaceGitMetadata(t)}listWorkspaceFileTree(t,n,i){return this.workspaceAccess.listWorkspaceFileTree(t,n,i)}searchWorkspaceFiles(t,n,i,s){return this.workspaceAccess.searchWorkspaceFiles(t,n,i,s)}listWorkspaceFileTreeCandidates(t,n){return this.workspaceAccess.listWorkspaceFileTreeCandidates(t,n)}searchWorkspaceFileCandidates(t,n){return this.workspaceAccess.searchWorkspaceFileCandidates(t,n)}async getAccountStatus(t,n){let i=await this.productAccess.getAccountStatus(t,n);const s=i.modelSource?i.modelSource==="token-plan":i.authMode==="managed-login";const r=()=>i.loginEpoch!==void 0&&i.loginEpoch!==this.authLoginEpochGetter?.();if(this.synchronizeAuth&&(s||n?.requireManagedAuth||r())){await this.synchronizeAuth();i=await this.productAccess.getAccountStatus(t,n)}const a=i.loginEpoch===void 0||i.loginEpoch===this.authLoginEpochGetter?.();if(!a){return{...i,warnings:[...i.warnings,us]}}const o=i.managedTokenPresent?this.accountIdentityGetter?.():void 0;if(o)i={...i,identity:{email:o.email,name:o.name}};const d=n?.includeMembership!==false;const c=n?.includeMembership===true;if(!d||!c&&(i.modelSource!=="token-plan"||i.managedTokenPresent!==true)||!this.tokenPlanAccountStatusGetter){return i}const l=await(n?.forceRefresh?this.tokenPlanAccountStatusGetter({forceRefresh:true}):this.tokenPlanAccountStatusGetter()).catch(()=>void 0);if(!l)return i;return{...i,...l.quotaState?{tokenPlanQuotaState:l.quotaState}:{},...l.quota?{tokenPlanQuota:l.quota}:{},...c&&l.summary?{tokenPlanSummary:l.summary}:{}}}getRuntimeDiagnostics(){return this.productAccess.getRuntimeDiagnostics()}getInstructionSources(t){return this.productAccess.getInstructionSources(t)}async prepareFeedback(t){if(!this.feedback)throw new Error("MiniMax Code feedback is unavailable.");return this.feedback.prepare(t)}submitFeedback(t,n){if(!this.feedback)return Promise.reject(new Error("MiniMax Code feedback is unavailable."));return this.feedback.submit(t,n)}cancelFeedback(t){if(!this.feedback)return Promise.resolve(false);return Promise.resolve(this.feedback.cancel(t))}runDailyCheckin(){if(!this.dailyCheckin){return Promise.reject(new Error("Daily check-in is unavailable."))}return this.dailyCheckin.run()}getPermissionMode(){return this.productAccess.getPermissionMode()}setPermissionMode(t){return this.productAccess.setPermissionMode(t)}bindSessionPermissionMode(t,n,i){return Ye(()=>this.cliService.bindSessionPermissionMode(t,n,i))}setSessionPermissionMode(t,n){return Ye(()=>this.cliService.setSessionPermissionMode(t,n))}getSessionPermissionMode(t){return Ye(()=>this.cliService.getSessionPermissionMode(t))}getDangerousCommandGateEnabled(){return this.productAccess.getDangerousCommandGateEnabled()}setDangerousCommandGateEnabled(t){return this.productAccess.setDangerousCommandGateEnabled(t)}getSandboxFilesystemMode(){return this.productAccess.getSandboxFilesystemMode()}setSandboxFilesystemMode(t){return this.productAccess.setSandboxFilesystemMode(t)}listModels(t){return this.productAccess.listModels(t)}selectModel(t,n){return this.productAccess.selectModel(t,n)}selectSessionModel(t,n){return this.productAccess.selectSessionModel(t,n)}setModelFavorite(t,n){return this.productAccess.setModelFavorite(t,n)}listUserModelProviders(){return this.productAccess.listUserModelProviders()}listProviderPresets(){return this.productAccess.listProviderPresets()}getCodexOAuthStatus(){return this.productAccess.getCodexOAuthStatus()}startCodexOAuthLogin(t){return this.productAccess.startCodexOAuthLogin(t)}cancelCodexOAuthLogin(t){return this.productAccess.cancelCodexOAuthLogin(t)}getMiniMaxApiKeyStatus(){return this.productAccess.getMiniMaxApiKeyStatus()}getMiniMaxModelSource(){return this.productAccess.getMiniMaxModelSource()}setMiniMaxModelSource(t){return this.productAccess.setMiniMaxModelSource(t)}upsertMiniMaxApiKey(t){return this.productAccess.upsertMiniMaxApiKey(t)}createUserModelProvider(t){return this.productAccess.createUserModelProvider(t)}discoverUserModelsCandidate(t){return this.productAccess.discoverUserModelsCandidate(t)}saveUserModelProviderCandidate(t){return this.productAccess.saveUserModelProviderCandidate(t)}updateUserModelProvider(t){return this.productAccess.updateUserModelProvider(t)}deleteUserModelProvider(t){return this.productAccess.deleteUserModelProvider(t)}testUserModelProvider(t){return this.productAccess.testUserModelProvider(t)}testUserModel(t,n){return this.productAccess.testUserModel(t,n)}getSessionUsage(t){return this.productAccess.getSessionUsage(t)}getSessionUsageSummary(t){return this.productAccess.getSessionUsageSummary(t)}getSessionCacheWarmingStatus(t){return this.productAccess.getSessionCacheWarmingStatus(t)}watchSessionUsageCommits(t){return this.eventAccess.watchSessionUsageCommits(t)}requestCompaction(t,n,i){return this.productAccess.requestCompaction(t,n,i)}getContextSnapshot(t){return this.productAccess.getContextSnapshot(t)}getActiveRun(t){return this.productAccess.getActiveRun(t)}listSkills(t,n,i){return this.productAccess.listSkills(t,n,i)}inspectProjectMcp(t){return this.productAccess.inspectProjectMcp(t)}listMcpServers(t,n){return this.productAccess.listMcpServers(t,n)}listInstalledPlugins(t){return this.pluginAccess.listInstalledPlugins(t)}listMarketplacePlugins(t){return this.pluginAccess.listMarketplacePlugins(t)}mutatePlugin(t){return this.pluginAccess.mutatePlugin(t)}refreshPlugins(){return this.pluginAccess.refreshPlugins()}listQueuedMessages(t){return this.interactionAccess.listQueuedMessages(t)}getQueueSnapshot(t){return this.interactionAccess.getQueueSnapshot(t)}getTurnStatus(t){return this.interactionAccess.getTurnStatus(t)}continueQueue(t){return this.interactionAccess.continueQueue(t)}steerQueuedMessage(t,n){return this.interactionAccess.steerQueuedMessage(t,n)}enqueueMessage(t,n,i){return this.interactionAccess.enqueueMessage(t,n,i)}updateQueuedMessageContent(t,n,i){return this.interactionAccess.updateQueuedMessageContent(t,n,i)}deleteQueuedMessage(t,n){return this.interactionAccess.deleteQueuedMessage(t,n)}getPendingQuestionnaire(t,n,i){return this.interactionAccess.getPendingQuestionnaire(t,n,i)}getLatestPlanReview(t,n,i){return this.interactionAccess.getLatestPlanReview(t,n,i)}getPlanModeCapabilities(){return this.interactionAccess.getPlanModeCapabilities()}replyQuestionnaire(t,n,i){return this.interactionAccess.replyQuestionnaire(t,n,i)}dismissQuestionnaire(t,n){return this.interactionAccess.dismissQuestionnaire(t,n)}listPendingPermissions(t){return this.interactionAccess.listPendingPermissions(t)}replyPermission(t,n,i){return this.interactionAccess.replyPermission(t,n,i)}watchEvents(t){return this.eventAccess.watch(t)}watchSessionTurn(t,n,i,s){return this.conversationAccess.resumeSession({id:t,...s?.afterMsgId?{afterMsgId:s.afterMsgId}:{},...s?.afterCursor?{afterCursor:s.afterCursor}:{}},n,i)}getDelegationSnapshot(t){return this.delegationAccess.getSnapshot(t)}async listBackgroundTasks(t,n){const i=["queued","running","stopping"];const s=["succeeded","failed","canceled","lost"];void n;const r=["bash","workflow","custom","subagent"];const[a,o]=await Promise.all([this.cliService.listBackgroundTasks({ownerSessionId:t,statuses:i,kinds:[...r],limit:100}),this.cliService.listBackgroundTasks({ownerSessionId:t,statuses:s,kinds:[...r],limit:100})]);const d=new Map([...a,...o].map(c=>[c.taskId,c]));return[...d.values()].sort((c,l)=>l.updatedAt-c.updatedAt).map(c=>({taskId:c.taskId,kind:c.kind,status:c.status,ownerSessionId:c.ownerSessionId,...c.description?{description:c.description}:{},...c.kind==="bash"&&typeof c.metadata?.command==="string"?{command:c.metadata.command}:{},createdAtMs:c.createdAt,updatedAtMs:c.updatedAt,...c.startedAt!==void 0?{startedAtMs:c.startedAt}:{},...c.endedAt!==void 0?{endedAtMs:c.endedAt}:{},...c.deliveredAt!==void 0?{deliveredAtMs:c.deliveredAt}:{},...c.lastError?.message?{lastError:c.lastError.message}:{},...c.kind==="bash"&&c.metadata?.executionMode==="managed_foreground"?{foreground:true}:{}}))}stopDelegation(t){return this.delegationAccess.stop(t)}};function ls(){return`minimax-code_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}async function Ye(e){try{return await e()}catch(t){if(typeof t==="object"&&t!==null&&t.code==="METHOD_NOT_ALLOWED"){throw new cn(t)}throw t}}import{performance as Z}from"node:perf_hooks";import{join as tr}from"node:path";import{open as ps,readFile as gs,readdir as fs,stat as hs}from"node:fs/promises";import{join as H}from"node:path";var jn=pi(gi(),1);var Nn={role:["user","assistant","system","tool"],level:["trace","debug","info","warn","error","fatal"],status:["pending","running","completed","failed","cancelled","error","success"],name:["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError"],code:["ECONNRESET","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","EAI_AGAIN","EPIPE"]};var ms=new Set(["manifest.json","messages.jsonl","display.jsonl","ledger.jsonl","snapshot.json","llm-call.json","task-agent-definition.json","session-report-collection.json"]);function Gn(e,t){const n={};let i=0;let s=0;let r=1e5;let a=false;function o(u,h){const f=n[u]??(n[u]={});f[h]=(f[h]??0)+1}function d(u,h){if(r--<=0||h>32){a=true;return}if(!u||typeof u!=="object")return;if(Array.isArray(u)){for(const f of u){if(r<=0){a=true;break}d(f,h+1)}return}for(const[f,g]of Object.entries(u)){if(r<=0){a=true;break}const S=Object.hasOwn(Nn,f)?Nn[f]:void 0;if(typeof g==="string"&&S?.includes(g))o(f,g);if((f==="status"||f==="statusCode")&&typeof g==="number"&&Number.isInteger(g)&&g>=100&&g<=599){o("httpStatus",String(g))}d(g,h+1)}}function c(u){if(!u.trim())return;if(r<=0){a=true;return}try{d(JSON.parse(u),0);i+=1}catch{s+=1}}if(t.endsWith(".json"))c(e);else for(const u of e.split("\n"))c(u);const l=t.split("/").at(-1)??"";return JSON.stringify({schemaVersion:1,redactionPolicy:"diagnostic-counts-v1",sourceKind:ms.has(l)?l:"other",contentOmitted:true,parsedRecords:i,omittedRecords:s,limited:a,counts:n})}var ys=2*24*60*60*1e3;var Ss=64;var Bn=16*1024*1024;var Ze=2*1024*1024;var Ts={cn:{dev:"https://matrix-test.example.invalid",test:"https://matrix-test.example.invalid",staging:"https://matrix-pre.example.invalid",prod:"https://agent.minimaxi.com"},en:{dev:"https://matrix-overseas-test.example.invalid",test:"https://matrix-overseas-test.example.invalid",staging:"https://matrix-overseas-pre.example.invalid",prod:"https://agent.minimax.io"}};async function Vn(e,t){const n=t.fetchImpl??globalThis.fetch;const i=(t.nowMs??Date.now)();await t.flushLogs?.();e.signal.throwIfAborted();const s=[];let r=[];try{r=await ws(e,t)}catch(N){if(e.signal.aborted)throw N;s.push({name:"session",reason:"session_report_unavailable"})}const a=await bs(t.dataDir,i-ys,e.signal);const o=[...r,...a];const d=new jn.default;let c=0;let l=0;let u=0;for(const[N,A]of o.entries()){const de=A.required?"session":A.name.split("/")[0];const Q=`${de}/artifact-${N+1}.json`;const K=A.required?A.sizeBytes:Math.min(A.sizeBytes,Ze);if(l+K>Bn){s.push({name:Q,reason:"diagnostic_bundle_too_large"});continue}l+=K;let G;try{G=await vs(A,e.signal)}catch($){if(e.signal.aborted)throw $;s.push({name:Q,reason:"read_failed"});continue}const V=Buffer.from(Gn(G,A.name),"utf8");if(c+V.byteLength>Bn){s.push({name:Q,reason:"diagnostic_bundle_too_large"});continue}c+=V.byteLength;d.file(Q,V);u+=1}d.file("diagnostic-manifest.json",JSON.stringify({schemaVersion:2,redactionPolicy:"diagnostic-counts-v1",contentOmitted:true,createdAtMs:i,totalFiles:u,totalBytes:c,context:{clientVersion:/^\d{1,5}\.\d{1,5}\.\d{1,5}$/u.test(t.appVersion)?t.appVersion:"unknown"},skipped:s},null,2));const h=await d.generateAsync({type:"nodebuffer",compression:"DEFLATE",compressionOptions:{level:9}});e.signal.throwIfAborted();const f=(t.region??L)();const g=(t.buildEnv??j)();const S=Ts[f][g];const b=await n(`${S}/matrix/api/v1/log/upload`,{method:"POST",headers:{"User-Agent":me("MiniMaxAgent"),Origin:S,Referer:`${S}/`,"Content-Type":"application/json"},body:JSON.stringify({device_id:"0",base_file_name:`mcode-feedback-${ks(i)}.zip`}),signal:e.signal});if(!b.ok){throw new Error(`Feedback diagnostic presign failed with HTTP ${b.status}.`)}const M=await Ms(b);const D=Ps(M.upload_id??M.uploadId);const v=As(M.upload_url??M.uploadUrl);if(!D||!v){throw new Error("Feedback diagnostic upload returned an invalid upload receipt.")}const P=await n(v,{method:"PUT",body:new Uint8Array(h),signal:e.signal});if(!P.ok){throw new Error(`Feedback diagnostic upload failed with HTTP ${P.status}.`)}return{uploadId:D}}async function bs(e,t,n){const i=H(e,"v2","observability");const s=H(i,"logs");const r=[{directory:s,prefix:"runtime/",matches:o=>/^(?:local-runtime|runtime|im-runtime)-.*\.log$/u.test(o)||/^local-proxy-.*\.jsonl$/u.test(o),recursive:true},{directory:H(i,"mcode"),prefix:"mcode/",matches:o=>/^mcode-observability-.*\.jsonl$/u.test(o)},{directory:H(i,"events"),prefix:"runtime-events/",matches:o=>/^runtime-events-\d{4}-\d{2}-\d{2}(?:\.\d+)?\.jsonl$/u.test(o),recursive:true},{directory:H(e,"logs"),prefix:"cli/",matches:o=>o==="cli.log"||/^tui-terminal-.*\.log$/u.test(o)},{directory:H(i,"cli","incidents"),prefix:"cli/incidents/",matches:o=>o.endsWith(".json")}];const a=[];for(const o of r){n.throwIfAborted();await Qn(o,o.directory,"",t,n,a)}return a.sort((o,d)=>d.modifiedAtMs-o.modifiedAtMs||o.name.localeCompare(d.name)).slice(0,Ss)}async function Qn(e,t,n,i,s,r){const a=await fs(t,{withFileTypes:true}).catch(()=>[]);for(const o of a){s.throwIfAborted();const d=n?`${n}/${o.name}`:o.name;const c=H(t,o.name);if(o.isDirectory()&&e.recursive){await Qn(e,c,d,i,s,r);continue}if(!o.isFile()||!e.matches(o.name,d))continue;let l;try{l=await hs(c)}catch(u){if(s.aborted)throw u;continue}if(!l.isFile()||l.mtimeMs<i)continue;r.push({name:`${e.prefix}${d}`,sourcePath:c,modifiedAtMs:l.mtimeMs,sizeBytes:l.size,required:false,wholeFile:Wn(o.name)})}}async function vs(e,t){t.throwIfAborted();if(e.content!==void 0)return e.content;if(!e.sourcePath)throw new Error(`Diagnostic artifact has no source: ${e.name}`);if(e.required)return gs(e.sourcePath,"utf8");if(e.wholeFile&&e.sizeBytes>Ze){throw new Error("diagnostic_single_json_too_large")}const n=Math.min(e.sizeBytes,Ze);const i=e.sizeBytes>n;const s=Buffer.alloc(n);const r=await ps(e.sourcePath,"r");try{const a=await r.read(s,0,n,Math.max(0,e.sizeBytes-n));t.throwIfAborted();const o=s.subarray(0,a.bytesRead).toString("utf8");if(!i)return o;const d=o.indexOf("\n");return d>=0?o.slice(d+1):o}finally{await r.close()}}async function ws(e,t){if(!e.sessionId)return[];if(!t.collectSessionReport){throw new Error("session_report_capability_unavailable")}const n=await t.collectSessionReport(e.sessionId);return n.artifacts.map(i=>({name:i.name,...i.path?{sourcePath:i.path}:{},...i.content!==void 0?{content:i.content}:{},modifiedAtMs:0,sizeBytes:i.bytes,required:true,wholeFile:Wn(i.name)}))}function Wn(e){return e.endsWith(".json")&&!e.endsWith(".jsonl")}async function Ms(e){try{const t=JSON.parse(await e.text());return t!==null&&typeof t==="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Ps(e){if(typeof e==="number")return Number.isSafeInteger(e)&&e>0?String(e):void 0;return typeof e==="string"&&e.trim()?e.trim():void 0}function As(e){if(typeof e!=="string")return void 0;try{const t=new URL(e);return t.protocol==="https:"?t.toString():void 0}catch{return void 0}}function ks(e){const t=new Date(e);return[t.getUTCFullYear(),String(t.getUTCMonth()+1).padStart(2,"0"),String(t.getUTCDate()).padStart(2,"0"),String(t.getUTCHours()).padStart(2,"0"),String(t.getUTCMinutes()).padStart(2,"0"),String(t.getUTCSeconds()).padStart(2,"0")].join("")}import{randomUUID as ti}from"node:crypto";import{release as Ds}from"node:os";import{createHash as Rs}from"node:crypto";var Is={cn:{dev:"https://matrix-test.example.invalid",test:"https://matrix-test.example.invalid",staging:"https://matrix-pre.example.invalid",prod:"https://agent.minimaxi.com"},en:{dev:"https://matrix-overseas-test.example.invalid",test:"https://matrix-overseas-test.example.invalid",staging:"https://matrix-overseas-pre.example.invalid",prod:"https://agent.minimax.io"}};function xe(e){const t=(e.region??L)();const n=(e.buildEnv??j)();return Is[t][n]}function re(e){const t=new URL(e.endpoint);const n=e.region==="cn"?"zh":"en";t.search=new URLSearchParams({...e.query,device_platform:"web",biz_id:"3",app_id:"3001",version_code:"22201",is_desktop:"1",desktop_version:e.appVersion.trim(),unix:String(e.nowMs),timezone_offset:String(new Date().getTimezoneOffset()*-60),sys_language:n,lang:n,device_id:"0",os_name:process.platform,browser_name:"mcode",user_id:e.realUserID.trim(),client:"mcode"}).toString();const i=e.body??"";const s=e.body??"{}";const r=Math.floor(e.nowMs/1e3);const a=`${t.pathname}${t.search}`;return{url:t,...e.body===void 0?{}:{body:e.body},headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":me("MiniMaxCode"),Authorization:`Bearer ${e.token}`,yy:et(`${encodeURIComponent(a)}_${s}${et(String(e.nowMs))}ooui`),"x-timestamp":String(r),"x-signature":et(`${r}I*7Cf%WZ#S&%1RlZJ&C2${i}`)}}}function et(e){return Rs("md5").update(e).digest("hex")}var Cs=1;function nt(e){if(e.endpoint)return e.endpoint;return`${xe(e)}/minimax-cloud/api/v1/feedback/ticket`}function $n(e,t){return{description:e.description,contact:"",task_context:{...e.sessionId?{session_id:e.sessionId}:{},client_type:Cs,client_version:k(t),os:k(e.platform.platform),os_version:k(e.platform.osVersion)},screenshots:[],upload_diagnostic_log:Boolean(e.diagnosticUploadId),...e.diagnosticUploadId?{diagnostic_log:{upload_id:e.diagnosticUploadId}}:{}}}function zn(e){const t=JSON.stringify(e.payload);const n=re({endpoint:e.endpoint,token:e.token,realUserID:e.realUserID,appVersion:k(e.appVersion),region:e.region,nowMs:e.nowMs,body:t});return{...n,body:t}}function Hn(e){return re({endpoint:e.endpoint,token:e.token,realUserID:e.realUserID,appVersion:k(e.appVersion),region:e.region,nowMs:e.nowMs,query:{limit:String(e.limit)}})}async function Kn(e){const t=await Zn(e);const n=E(t.data);const i=E(t.statusInfo)??E(t.status_info)??E(n?.statusInfo)??E(n?.status_info);const s=E(t.base_resp)??E(n?.base_resp);if(typeof i?.code==="number"&&i.code!==0||typeof s?.status_code==="number"&&s.status_code!==0){throw new Error(_s(e.status,t,i,s))}const r=oe(t.ticket_id)??oe(n?.ticket_id);const a=t.status??n?.status;const o=tt(t.created_at)??tt(n?.created_at);return{schemaVersion:1,...r?{ticketId:r}:{},status:a===1||a==="processing"?"processing":a===2||a==="resolved"?"resolved":"unknown",...o!==void 0?{createdAtMs:o}:{}}}async function Jn(e){const t=await e.text().catch(()=>"");const n=["x-request-id","x-trace-id","trace-id"].flatMap(i=>{const s=e.headers.get(i)?.trim();return s?[`${i}=${k(s)}`]:[]}).join("; ");return[`Feedback POST returned HTTP ${e.status}${e.statusText?` ${k(e.statusText)}`:""}.`,...n?[`Trace: ${n}.`]:[],`Response body: ${ei(t||"<empty>")}.`].join(" ")}async function Xn(e,t){if(!e.ok)return void 0;const n=await Zn(e);const i=E(n.data);if(xs(n,i))return void 0;const s=Array.isArray(n.tickets)?n.tickets:Array.isArray(i?.tickets)?i.tickets:[];const r=t.submittedAtMs-5e3;const a=t.nowMs+3e4;for(const o of s){const d=E(o);if(!d||oe(d.description)!==t.description)continue;const c=oe(d.ticket_id);const l=tt(d.created_at);if(!c||l===void 0||l<r||l>a){continue}return{schemaVersion:1,ticketId:c,status:Es(d.status),createdAtMs:l}}return void 0}function k(e){return Wt(e.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu,"")).trim()}function Yn(e){if(typeof e==="number")return Number.isSafeInteger(e)&&e>0?String(e):void 0;return oe(e)}async function Zn(e){try{const t=await e.text();return t?E(JSON.parse(t))??{}:{}}catch{return{}}}function E(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function oe(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function tt(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function xs(e,t){const n=E(e.statusInfo)??E(e.status_info)??E(t?.statusInfo)??E(t?.status_info);if(typeof n?.code==="number"&&n.code!==0)return true;const i=E(e.base_resp)??E(t?.base_resp);return typeof i?.status_code==="number"&&i.status_code!==0}function Es(e){if(e===1||e==="processing")return"processing";if(e===2||e==="resolved")return"resolved";return"unknown"}function _s(e,t,n,i){const s=[`HTTP ${e}`,...n?.code!==void 0?[`statusInfo.code=${String(n.code)}`]:[],...n?.message!==void 0?[`statusInfo.message=${k(String(n.message))}`]:[],...i?.status_code!==void 0?[`base_resp.status_code=${String(i.status_code)}`]:[],...i?.status_msg!==void 0?[`base_resp.status_msg=${k(String(i.status_msg))}`]:[]];return`Feedback POST business rejection: ${s.join("; ")}. Response body: ${ei(JSON.stringify(t))}.`}function ei(e){const t=k(e.replace(/("(?:api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)"\s*:\s*)"[^"]*"/giu,'$1"[redacted]"'));const n=Array.from(t);return n.length<=4e3?t:`${n.slice(0,4e3).join("")}\u2026 [truncated]`}var Ee=class extends Error{constructor(n,i,s,r){super(n);this.code=i;this.statusCode=s;this.retryable=r}code;statusCode;retryable;name="TuiFeedbackError"};var Os=18e4;var Ls=15*6e4;var Us=32;var Fs=20;var _e=class{constructor(t){this.options=t;this.fetchImpl=t.fetchImpl??globalThis.fetch;this.nowMs=t.nowMs??Date.now;this.createDraftId=t.createDraftId??(()=>`feedback_${ti()}`);this.timeoutMs=ni(t.timeoutMs,Os);this.draftTtlMs=ni(t.draftTtlMs,Ls);this.platform=t.platform??(()=>({platform:process.platform,arch:process.arch,nodeVersion:process.versions.node,osVersion:Ds()}))}options;drafts=new Map;fetchImpl;nowMs;createDraftId;timeoutMs;draftTtlMs;platform;prepare(t){this.pruneExpiredDrafts();const n=qs(t.description);const i=Ns(t.sessionId);const s=this.platform();const r=this.nowMs();const a=this.uniqueDraftId();const o={schemaVersion:1,draftId:a,description:n,diagnostics:[{label:"Client",value:`mcode ${k(this.options.appVersion)}`},{label:"Runtime",value:"clean \xB7 cli"},{label:"Platform",value:`${k(s.platform)} ${k(s.arch)} \xB7 Node ${k(s.nodeVersion)}`},{label:"OS",value:k(s.osVersion)},{label:"Session",value:i??"not included"}],diagnosticBundleIncluded:Boolean(this.options.diagnosticLogUploader),included:["reviewed feedback description with recognized credentials redacted","bounded client, Runtime, platform, and optional Session metadata",...this.options.diagnosticLogUploader?["diagnostic counts from the selected Session subtree (including messages, snapshots, and report artifacts); original contents and filenames are omitted","bounded diagnostic counts from Runtime, CLI, and terminal logs and events from the last 2 days","only known roles, states, error types/codes, HTTP statuses, and parse/omission counts are retained"]:[]],excluded:["stored credentials and authentication files","raw attachments, prompts, conversation text, tool arguments/results, local paths, file contents, and free-text errors",...this.options.diagnosticLogUploader?["unrelated sessions, workspace files, and config files"]:["canonical full conversation and tool-call history (messages.jsonl)","file contents and diagnostic log bodies","workspace and config file contents"]],expiresAtMs:r+this.draftTtlMs};this.makeDraftCapacity();this.drafts.set(a,{preview:o,...i?{sessionId:i}:{},platform:s,cancelled:false});return structuredClone(o)}async submit(t,n={}){const i=this.requireDraft(t);if(i.receipt)return structuredClone(i.receipt);if(i.activeController)throw _("Feedback upload is already in progress.","feedback_upload_failed",409,true);ae(n,"preparing");const s=n.signal;let r=this.options.authContextGetter();let a=r?.accessToken?.trim();if(!a)throw _("MiniMax Code sign-in is required. Run /login, then retry.","feedback_login_required",401,true);const o=new AbortController;i.activeController=o;i.cancelled=false;let d=false;const c=setTimeout(()=>{d=true;o.abort(new DOMException("Feedback upload timed out.","TimeoutError"))},this.timeoutMs);c.unref?.();const l=()=>o.abort(s?.reason);if(s?.aborted)l();else s?.addEventListener("abort",l,{once:true});let u;let h;let f;try{if(!r?.realUserID?.trim()&&this.options.authContextResolver){r=await this.options.authContextResolver({forceRefresh:false,signal:o.signal});a=r?.accessToken?.trim()}const g=r?.realUserID?.trim();if(!a)throw _("MiniMax Code sign-in is required. Run /login, then retry.","feedback_login_required",401,true);if(!g)throw _("MiniMax Code account identity is not ready. Check the connection, then retry.","feedback_upload_failed",503,true);h=a;f=g;if(this.options.diagnosticLogUploader){ae(n,"uploading-diagnostics")}await this.uploadDiagnostics(i,o.signal);ae(n,"creating-ticket");const S=$n({description:i.preview.description,...i.sessionId?{sessionId:i.sessionId}:{},platform:i.platform,...i.diagnosticUploadId?{diagnosticUploadId:i.diagnosticUploadId}:{}},this.options.appVersion);u=this.nowMs();let b=await this.submitTicket(S,a,g,o.signal);if(b.status===401&&this.options.authContextResolver){const D=await this.options.authContextResolver({forceRefresh:true,signal:o.signal});const v=D?.accessToken?.trim();const P=D?.realUserID?.trim();if(v&&P){h=v;f=P;b=await this.submitTicket(S,v,P,o.signal)}}if(!b.ok){throw await Gs(b)}const M=await Kn(b);i.receipt={...M,...i.diagnosticUploadId?{uploadId:i.diagnosticUploadId}:{}};ae(n,"completed");return structuredClone(i.receipt)}catch(g){const S=Bs(g);if(u!==void 0&&h&&f&&!d&&!i.cancelled&&!s?.aborted){const b=await this.confirmSubmittedTicket(i,u,h,f,o.signal);if(b){i.receipt={...b,...i.diagnosticUploadId?{uploadId:i.diagnosticUploadId}:{}};ae(n,"completed");return structuredClone(i.receipt)}}if(g instanceof Ee)throw g;if(d)throw _("Feedback upload timed out. Press Enter to retry.","feedback_timeout",504,true);if(i.cancelled||s?.aborted)throw _("Feedback upload was cancelled.","feedback_cancelled",499,false);if(g instanceof TypeError)throw _(`Feedback POST network error: ${S}`,"feedback_offline",503,true);throw _(S||"Feedback upload failed without an error detail.","feedback_upload_failed",502,true)}finally{clearTimeout(c);s?.removeEventListener("abort",l);i.activeController=void 0}}async submitTicket(t,n,i,s){const r=zn({endpoint:nt(this.options),payload:t,token:n,realUserID:i,appVersion:this.options.appVersion,region:(this.options.region??L)(),nowMs:this.nowMs()});return this.fetchImpl(r.url,{method:"POST",headers:r.headers,body:r.body,signal:s})}async confirmSubmittedTicket(t,n,i,s,r){try{const a=this.nowMs();const o=Hn({endpoint:nt(this.options),token:i,realUserID:s,appVersion:this.options.appVersion,region:(this.options.region??L)(),nowMs:a,limit:Fs});const d=await this.fetchImpl(o.url,{method:"GET",headers:o.headers,signal:r});return Xn(d,{description:t.preview.description,submittedAtMs:n,nowMs:a})}catch{return void 0}}cancel(t){const n=this.drafts.get(t);if(!n)return false;n.cancelled=true;n.activeController?.abort(new DOMException("Feedback upload cancelled.","AbortError"));this.drafts.delete(t);return true}async uploadDiagnostics(t,n){if(!this.options.diagnosticLogUploader||t.diagnosticUploadId)return;try{const i=await this.options.diagnosticLogUploader({description:t.preview.description,...t.sessionId?{sessionId:t.sessionId}:{},signal:n});const s=Yn(i.uploadId);if(!s)throw new Error("Feedback diagnostic upload returned an invalid receipt.");t.diagnosticUploadId=s}catch(i){if(n.aborted)throw i}}requireDraft(t){this.pruneExpiredDrafts();const n=this.drafts.get(t);if(!n)throw _("Feedback draft was not found or has expired.","feedback_not_found",404,false);return n}uniqueDraftId(){for(let t=0;t<4;t+=1){const n=this.createDraftId();if(n&&!this.drafts.has(n))return n}return`feedback_${ti()}`}pruneExpiredDrafts(){const t=this.nowMs();for(const[n,i]of this.drafts){if(i.preview.expiresAtMs>t)continue;this.cancel(n)}}makeDraftCapacity(){while(this.drafts.size>=Us){const t=this.drafts.keys().next().value;if(!t)return;this.cancel(t)}}};function qs(e){const t=k(e.trim());if(!t)throw _("Feedback description is required.","feedback_invalid_request",400,false);if(Array.from(t).length>4e3)throw _("Feedback description must be 4000 characters or fewer.","feedback_invalid_request",400,false);return t}function Ns(e){const t=e===void 0?void 0:k(e.trim());if(!t)return void 0;if(Array.from(t).length>256)throw _("Feedback session id is too long.","feedback_invalid_request",400,false);return t}async function Gs(e){const t=e.status;const n=await Jn(e);if(t===401)return _(`${n} Run /login, then retry.`,"feedback_login_required",t,true);if(t===403)return _(`${n} Feedback submission is not available for this account or environment.`,"feedback_upload_failed",t,false);if(t===408||t===504)return _(`${n} Feedback upload timed out.`,"feedback_timeout",t,true);return _(n,"feedback_upload_failed",t,t===429||t>=500)}function Bs(e){return k(e instanceof Error?e.message:String(e))}function _(e,t,n,i){return new Ee(e,t,n,i)}function ni(e,t){return e!==void 0&&Number.isFinite(e)&&e>0?Math.floor(e):t}function ae(e,t){try{e.onPhase?.(t)}catch{}}function js(e,t,n=process.env){if(t.beta?.browserUseTooling!==true)return void 0;const i=n.MCODE_CHROME_PATH?.trim()||t.browser?.chromePath?.trim();return{dataDir:e,...i?{chromePath:i}:{}}}function ii(e,t,n=process.env,i=s=>new Dt(s)){const s=js(e,t,n);return s?i(s):void 0}function si(e,t){return Ot({dataDir:e},t)}var De=class{constructor(t){this.gateway=t}gateway;pending;run(){if(this.pending)return this.pending;const t=this.runOnce().finally(()=>{if(this.pending===t)this.pending=void 0});this.pending=t;return t}async runOnce(){const t=fe(await this.gateway.getSigninPanel());if(en(t)){return{status:"already-claimed",panel:t}}if(!Zt(t)){return{status:"unavailable",panel:t}}const n=he(await this.gateway.claimSignin());if(n.claim_result===2){return{status:"already-claimed",panel:n.panel}}return{status:"claimed",dayNo:n.day_no,points:n.points,expireAtMs:n.expire_at_ms,panel:n.panel}}};var Vs="/minimax-cloud/api/v1/signin/status";var Qs="/minimax-cloud/api/v1/signin/claim";var Oe=class{constructor(t){this.options=t;this.fetchImpl=t.fetchImpl??globalThis.fetch;this.nowMs=t.nowMs??Date.now;this.timeoutMs=t.timeoutMs??3e4}options;fetchImpl;nowMs;timeoutMs;statusAccountKey;async getSigninPanel(){const{data:t,accountKey:n}=await this.request(Vs,"GET");this.statusAccountKey=n;return fe(t)}async claimSignin(){const t=await this.request(Qs,"POST",this.statusAccountKey);this.statusAccountKey=void 0;return he(t.data)}async request(t,n,i){const s=new AbortController;const r=setTimeout(()=>s.abort(),this.timeoutMs);r.unref?.();try{let a=await this.resolveAuth(false,s.signal);ri(a,i);let o=await this.fetch(t,n,a,s.signal);if(o.status===401&&this.options.authContextResolver){a=await this.resolveAuth(true,s.signal);ri(a,i);o=await this.fetch(t,n,a,s.signal)}if(!o.ok){throw new Error(`Daily check-in request failed with HTTP ${o.status}.`)}const d=await o.json();this.assertCurrentAccount(a);const c=d.base_resp?.status_code;if(typeof c==="number"&&c!==0){throw new Error(d.base_resp?.status_msg||"Daily check-in request failed.")}if(d.data===null||d.data===void 0){throw new Error("Daily check-in response data is missing.")}return{data:d.data,accountKey:oi(a)}}finally{clearTimeout(r)}}async resolveAuth(t,n){let i=t?void 0:this.options.authContextGetter();if((t||!i?.realUserID?.trim())&&this.options.authContextResolver){i=await this.options.authContextResolver({forceRefresh:t,signal:n})}const s=i?.accessToken?.trim();const r=i?.realUserID?.trim();if(!s||!r){throw new Error("MiniMax Code sign-in is required. Run /login, then retry /checkin.")}return{accessToken:s,realUserID:r}}fetch(t,n,i,s){const r=(this.options.region??L)();const a=this.options.origin??xe({region:()=>r,buildEnv:this.options.buildEnv??j});const o=n==="POST"?"{}":void 0;const d=re({endpoint:`${a}${t}`,token:i.accessToken,realUserID:i.realUserID,appVersion:this.options.appVersion,region:r,nowMs:this.nowMs(),...o?{body:o}:{}});return this.fetchImpl(d.url,{method:n,headers:d.headers,...d.body?{body:d.body}:{},signal:s})}assertCurrentAccount(t){const n=this.options.authContextGetter();if(!n?.accessToken?.trim()||n.realUserID?.trim()!==t.realUserID){throw new Error("MiniMax account changed during daily check-in. Retry /checkin.")}}};function oi(e){return e.realUserID}function ri(e,t){if(t&&oi(e)!==t){throw new Error("MiniMax account changed during daily check-in. Retry /checkin.")}}import{chmod as Ws,mkdtemp as $s,rm as zs}from"node:fs/promises";import{tmpdir as Hs}from"node:os";import di from"node:path";var Ks=async()=>void 0;var Js=()=>void 0;async function ci(e,t={}){const n=Xs(e.buildEnv);if(!e.requested)return ai(false,"disabled",n);const i=e.logger??{info:()=>void 0,warn:()=>void 0};const s=e.environment??process.env;const r=t.removeRuntimeDir??Zs;let a;let o;let d;try{const c=(t.validateResource??Nt)({resourceDir:Ft(e.entryUrl,s),expectedBuildEnv:n});a=await(t.createRuntimeDir??Ys)();o=await(t.startBroker??Ut)({dataDir:a,session:e.session,logger:i});const l=di.join(e.dataDir,"integrations","mcode-tools",e.region);await Gt(l);d=(t.activateEnvironment??Lt)(s,{runtimeExecutable:process.execPath,brokerEndpoint:o.endpoint,brokerCapabilityFile:o.capabilityFile,configDir:l,region:e.region,commandBinDir:qt(e.entryUrl),...e.bedrockLane?{bedrockLane:e.bedrockLane}:{}});const u=er({buildEnv:n,resource:c,broker:o,runtimeDir:a,removeRuntimeDir:r,activation:d});i.info(`mcode-tools readiness category=${u.category} buildEnv=${n} region=${e.region} version=${c.manifest.version}`);return u}catch(c){d?.restore();await o?.dispose().catch(()=>void 0);if(a)await r(a).catch(()=>void 0);const l=Bt(c);i.warn(`mcode-tools readiness category=${l} buildEnv=${n} region=${e.region}`);return ai(true,l,n)}}function Xs(e){return e==="dev"?"test":e}async function Ys(){const e=process.platform==="win32"?Hs():"/tmp";const t=await $s(di.join(e,`mcode-tools-tui-${process.pid}-`));if(process.platform!=="win32")await Ws(t,448);return t}function Zs(e){return zs(e,{recursive:true,force:true})}function er(e){let t=false;return{requested:true,ready:true,category:"ready",buildEnv:e.buildEnv,version:e.resource.manifest.version,ensureCommandPath:e.activation.ensureCommandPath,async dispose(){if(t)return;t=true;e.activation.restore();const n=[];try{await e.broker.dispose()}catch(i){n.push(i)}try{await e.removeRuntimeDir(e.runtimeDir)}catch(i){n.push(i)}if(n.length===1)throw n[0];if(n.length>1)throw new AggregateError(n,"mcode-tools TUI cleanup failed")}}}function ai(e,t,n){return{requested:e,ready:false,category:t,buildEnv:n,ensureCommandPath:Js,dispose:Ks}}var nr=6e4;var ui=vt("mcode:tui-lifecycle");async function Ta(e,t={}){const n=Ne({profile:e.profile,dataDir:e.dataDir,env:process.env});const i=e.noDaemon===true?"off":Yt();if(e.noDaemon===true){const p=process.env["MCODE_SERVER_MODE"]?.trim();if(p!==void 0&&p!==""&&p!=="off"){ui.warn("--no-daemon overrides MCODE_SERVER_MODE for this invocation",{env:p})}}{const p=qe(n.controlRoot);if(p&&Fe(p.pid)){const T=[];if(p.region!==void 0&&p.region!==L()){T.push(`region (daemon: ${p.region}, this process: ${L()})`)}if(p.buildEnv!==void 0&&p.buildEnv!==j()){T.push(`buildEnv (daemon: ${p.buildEnv}, this process: ${j()})`)}if(T.length>0){const y=`Daemon env mismatch on control root ${n.controlRoot}: ${T.join("; ")}. Restart this process with the daemon's env (e.g. MAVIS_REGION=${p.region}) or stop the daemon first: mcode daemon stop.`;if(i==="off"&&e.managementSurface!==true){ui.warn("daemon env mismatch ignored in no-daemon mode",{controlRoot:n.controlRoot,mismatches:T})}else{throw new Error(y)}}}}const s=t.getConfig??lt;const r=e.configPath??tr(e.dataDir,"config.yaml");const a=ir(r,t.readExplicitBetaFeature??pt);const o=()=>{const p=s();return{...p,beta:{...p.beta,browserUseTooling:a}}};const d=o().beta?.mcodeTools===true;const c=t.readAuthContext??rn;const l=t.importSharedAuthContext??dn;const u={region:L(),buildEnv:j()};const h=Tt(e.lane,u.buildEnv);const f=h?{bedrockLane:h}:void 0;const g=Boolean(t.sharedAuthCore)||!sr(t);let S;let b=0;let M=0;let D;let v;let P;let N=()=>void 0;let A;let de;const Q=g?()=>S:()=>c(e.dataDir,u);const K=p=>{const T=p?.accessToken?.trim();if(!T||p?.realUserID?.trim())return p;const y=(t.readVerifiedIdentity??nn)(e.dataDir,u,T);if(!y)return p;const{verifiedAtMs:U,...O}=y;void U;return{...p,...O}};const G=()=>K(Q());const V=new Vt({authContextGetter:G,...f?{routingContextGetter:()=>f}:{},region:u.region,buildEnv:u.buildEnv,...t.fetchImpl?{fetchImpl:t.fetchImpl}:{}});let $;if(g){const p=t.sharedAuthCore??tn({dataDir:e.dataDir,region:u.region,buildEnv:u.buildEnv,oauthEndpoints:ft(process.env,u)});$=p;const T=async(y,U=6e4)=>{const O=++M;const I=await rr(p,U);if(O!==M)return;if(!I){S=void 0;return}if(S?.realUserID?.trim()&&S.accessToken===I.accessToken&&b===I.generation)return;const q={accessToken:I.accessToken,loginEpoch:I.loginEpoch};S=q;b=I.generation;try{const ee=await it(V,q,u,t,y)??q;if(O===M&&b===I.generation&&S?.accessToken===I.accessToken){S={...ee,loginEpoch:I.loginEpoch}}}catch{}};A=(y,U)=>{const O=T(y,U);D=O;return O};de=async(y,U)=>{if(U.aborted)throw U.reason;if(y){const O=b;const I=S?.loginEpoch;M+=1;S=void 0;const q=await p.handleUnauthorized({generation:O,loginEpoch:I});if(q!=="retry")return void 0}await A?.(U);return S};await A().catch(()=>void 0);N=p.watch(y=>{if(!or(y)){M+=1;S=void 0;b=y.generation;return}if(y.status!=="authenticated")return;if(S&&b===y.generation)return;void A?.(void 0,0).catch(()=>void 0)})}else{const p=G()??K(l(e.dataDir,u,void 0));if(p?.accessToken){const T=await li(e.dataDir,p,u,V,t);if(!T){const y=K(l(e.dataDir,u,p.accessToken));if(y?.accessToken){await li(e.dataDir,y,u,V,t)}}}}let ce=ar(d,u.buildEnv);if(g&&$){ce=await(t.prepareMcodeToolsIntegration??ci)({requested:d,dataDir:e.dataDir,buildEnv:u.buildEnv,region:u.region,session:jt($),entryUrl:__mavis_tuiPackageEntryUrl,...h?{bedrockLane:h}:{}})}const rt=ce.ready;let ot=false;const at=async()=>{if(ot)return;ot=true;N();await ce.dispose()};const dt=p=>{if(g){const T=de;return T?T(p.forceRefresh,p.signal):Promise.resolve(void 0)}return dr(e.dataDir,u,Q,V,t,p.forceRefresh,p.signal)};const ue=e.observability===void 0;const z=e.observability??(t.createObservability??Kt)(e.dataDir,{surface:e.surface??"inspection"});const J=(t.createLogging??un)(e.dataDir);const mi={dataDir:e.dataDir,defaultWorkspaceDir:e.workspaceDir,appVersion:e.version,...e.promptMode?{promptMode:e.promptMode}:{},...e.systemPromptOverrides?{systemPromptOverrides:e.systemPromptOverrides}:{},configGetter:()=>{const p=o();return{...p,dataDir:e.dataDir,...e.permissionMode?{permissionMode:e.permissionMode}:{},beta:{...p.beta,mcodeTools:rt}}},configSource:t.configSource,authContextGetter:G,...f?{routingContextGetter:()=>f}:{},authContextInvalidator:async(p,T)=>{if(!g){st(e.dataDir,u,Q(),t);return}const y=p?.trim();const U=S?.accessToken?.trim();if(y&&U&&U!==y){return}if(!$||!A)return;while(v){const O=v;const I=P;await O;if(!y||I===y)return;const q=S?.accessToken?.trim();if(!q||q!==y)return}if(!v){const O=b;const I=T??S?.loginEpoch;if(!I||I!==S?.loginEpoch)return;M+=1;S=void 0;const q=(async()=>{try{const ee=await $.handleUnauthorized({generation:O,loginEpoch:I});if(ee!=="retry")return;await A()}catch(ee){if(ee instanceof ht)await A()}})().finally(()=>{if(v===q){v=void 0;P=void 0}});P=y;v=q}await v},capabilities:{questionnaireReply:e.surface!=="headless",permissionPrompt:e.surface!=="headless",elicitation:e.surface!=="headless"},...e.managementSurface||e.surface==="headless"||e.surface==="acp"||(t.getDataEnvironment??St)()==="test"?{startupExecutionPolicy:"quarantined"}:{}};const ct=Z.now();if(ue){z.recordStartup({phase:"runtime.initialize",outcome:"started"})}let B;const ut=e.managementSurface?qe(Ne({dataDir:e.dataDir,...e.profile?{profile:e.profile}:{}}).controlRoot):void 0;const le=e.managementSurface?ut&&Fe(ut.pid)?"required":"off":i;try{if(le==="off"){B=(t.createBrowserProvider??ii)(e.dataDir,o())}const p=await J.runDuringStartup(()=>le==="off"?Qt({...mi,...B?{browserAdapter:B}:{},productCapabilities:{mcodeTools:rt}},t.factory):Xt({dataDir:e.dataDir,daemonTargets:n,...e.managementSurface?{autoSpawn:false}:{},...e.profile?{profile:e.profile}:{},...e.promptMode!==void 0?{promptMode:e.promptMode}:{},clientKind:e.surface==="headless"?"exec":e.surface==="acp"?"acp":"tui"}));if(le!=="off"){await J.runDuringStartup(()=>p.ready)}ce.ensureCommandPath();if(ue){z.recordStartup({phase:"runtime.initialize",outcome:"succeeded",durationMs:Z.now()-ct})}return{host:p,adapter:new Ce(p.cliService,{workspaceDir:e.workspaceDir,observability:z,...e.contextMode?{contextMode:e.contextMode}:{},onSessionDeleted:B?.disposeSession?B.disposeSession.bind(B):T=>si(e.dataDir,T),...g?{synchronizeAuth:()=>A?.()??Promise.resolve()}:{},authLoginEpochGetter:()=>G()?.loginEpoch,tokenPlanAccountStatusGetter:T=>V.getTokenPlanAccountStatus(void 0,T),accountIdentityGetter:()=>{const T=G();return T?.accessToken?{email:T.userEmail,name:T.userName??T.subUserName}:void 0},dailyCheckin:new De(new Oe({appVersion:e.version,authContextGetter:G,authContextResolver:dt,...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},region:()=>u.region,buildEnv:()=>u.buildEnv})),feedback:new _e({appVersion:e.version,authContextGetter:G,authContextResolver:dt,...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},region:()=>u.region,buildEnv:()=>u.buildEnv,diagnosticLogUploader:T=>Vn(T,{dataDir:e.dataDir,appVersion:e.version,...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},region:()=>u.region,buildEnv:()=>u.buildEnv,flushLogs:async()=>{await Promise.allSettled([z.flush(),J.flush()])},collectSessionReport:y=>{return p.cliService.collectSessionReport(y)}})})}),...B?{browserProvider:B}:{},...le!=="off"?{connection:{state:()=>p.connectionState(),onChange:T=>p.onConnectionStateChange(T)}}:{},logDirectory:J.logDirectory,observability:z,synchronizeAuthContext:async T=>{if(!g)return;if(T==="logged_out"){M+=1;S=void 0;return}let y=A?.();do{await y;if(y===D)break;y=D}while(y)},shutdownAuth:at,shutdownLogging:()=>J.shutdown()}}catch(p){if(ue){z.recordStartup({phase:"runtime.initialize",outcome:"failed",durationMs:Z.now()-ct,errorKind:cr(p)})}const T=[];try{await at()}catch(y){T.push(y)}if(B){try{await B.close()}catch(y){T.push(y)}}try{await J.shutdown()}catch(y){T.push(y)}if(ue){try{await z.flush()}catch(y){T.push(y)}}if(T.length>0){throw new AggregateError([p,...T],"Minimax Code Runtime startup cleanup failed.")}throw p}}function ir(e,t){try{return t(e,"browserUseTooling")!==false}catch{return false}}function sr(e){return Boolean(e.readAuthContext||e.importSharedAuthContext||e.renewAccessToken||e.writeAuthContext||e.invalidateAuthContext)}async function rr(e,t){try{return await e.getAccessToken({requiredScopes:[...gt],minValidityMs:t})}catch(n){if(yt(n))return void 0;throw n}}function or(e){return e.status==="authenticated"||e.status==="expired"||e.status==="refreshing"}function ar(e,t){return{requested:e,ready:false,category:e?"host_unavailable":"disabled",buildEnv:t==="dev"?"test":t,ensureCommandPath:()=>void 0,dispose:async()=>void 0}}async function li(e,t,n,i,s){let r=t;try{const a=await(s.renewAccessToken??(c=>c.renewAccessToken()))(i);r=a?{...t,accessToken:a}:t;if(a&&a!==t.accessToken){Le(e,r,n,t,s)}const o=await it(i,r,n,s,void 0,Boolean(r.realUserID?.trim()));const d=o?.accessToken?.trim();if(o?.realUserID&&d){Le(e,o,n,t,s);(s.writeVerifiedIdentity??We)(e,n,d,o)}return true}catch(a){if(!(a instanceof Ge))return true;st(e,n,r,s);return false}}async function dr(e,t,n,i,s,r,a){const o=n();const d=o?.accessToken?.trim();if(!d)return void 0;let c={...o,accessToken:d};const l=c;try{if(r){const f=await(s.renewAccessToken??(g=>g.renewAccessToken(a)))(i);if(f&&f!==d){c={...o,accessToken:f};Le(e,c,t,l,s)}}const u=await it(i,c,t,s,a);if(!u?.realUserID)return c;const h=u.accessToken?.trim();if(!h)return void 0;Le(e,u,t,l,s);(s.writeVerifiedIdentity??We)(e,t,h,u);return u}catch(u){if(!(u instanceof Ge))throw u;st(e,t,c,s);return void 0}}function Le(e,t,n,i,s){if(s.writeAuthContext){s.writeAuthContext(e,t,n);return}on(e,t,n,{expectedSharedAuth:i})}async function it(e,t,n,i,s,r=false){if(i.resolveAuthContext){return i.resolveAuthContext(e,t,s)}if(i.resolveRealUserID){const a=await i.resolveRealUserID(e,t);return a?{...t,realUserID:a}:t}if(i.completeAuthContext){return i.completeAuthContext(t,n)}if(r&&t.realUserID?.trim())return t;return e.getAuthContextForAuth(t,s)}function st(e,t,n,i){const s=n?.accessToken?.trim();if(s){(i.writeRejectedIdentity??sn)(e,t,s)}(i.invalidateAuthContext??an)(e,t)}async function ba(e,t={}){const n=e.observability??X;const i=Z.now();n.recordStartup({phase:"runtime.shutdown",outcome:"started"});const s=t.reportFailure??((u,h)=>{const f=h instanceof Error?h.message:String(h);process.stderr.write(`[minimax-code] ${u} cleanup failed: ${f}
2
+ import{a as Kt,b as X,f as Zt,g as en,i as fe,j as he,l as Qe}from"./chunk-UEPKZSE6.js";import{c as bt,i as Wt}from"./chunk-U6RWF7BC.js";import{a as cn}from"./chunk-E25NCIC6.js";import{d as $t,e as zt,f as pe,g as ge,h as Be,i as Ht,l as je,p as Ve,s as Jt,v as Xt,w as Yt}from"./chunk-CUPCI2YC.js";import{a as Ue}from"./chunk-ME57CPMB.js";import{a as tn,b as nn,c as We,d as sn,e as rn,f as on,h as an,i as dn}from"./chunk-QMBFFQPV.js";import{a as Qt}from"./chunk-QIYZZJVO.js";import{a as Vt,b as Ge}from"./chunk-3LRARE6Z.js";import{e as Tt}from"./chunk-WUORF7YS.js";import{e as St}from"./chunk-WHBWI5OQ.js";import{J as Fe,M as jt,P as qe,R as Ne,g as wt,h as Mt,i as Pt,j as At,k as kt,n as Rt,q as It,r as Ct,s as xt,t as Et,u as _t,v as te,w as gi,y as Dt,z as Ot}from"./chunk-O5EROATK.js";import{a as gt,e as ft,f as ht,g as yt}from"./chunk-TRX2HFTB.js";import{Aa as mt,Ib as pt,V as L,W as j,oa as lt}from"./chunk-XWNCITOR.js";import{a as Lt,c as Ut,d as Ft,e as qt,f as Nt,g as Gt,h as Bt}from"./chunk-AODHXPQF.js";import{a as me}from"./chunk-7F3QKGB7.js";import{a as vt}from"./chunk-VAARXN34.js";import{e as pi}from"./chunk-FK3SSGJE.js";import{join as fi}from"node:path";import{Writable as hi}from"node:stream";import{formatWithOptions as yi}from"node:util";function Si(e){return fi(e,"v2","observability","logs")}function un(e,t={}){const n=Si(e);const i=t.configureRuntime??wt;const s=t.configureIm??It;const r=t.flushRuntime??Mt;const a=t.flushIm??Ct;const o=t.shutdownRuntime??Pt;const d=t.shutdownIm??xt;const c=t.runtimeLogger??At;const l=t.consoleRef??console;const u=new hi({write(v,P,N){N()}});const h={colorize:false,destination:u};i({dir:n,loggerOptions:h});s({dir:n,loggerOptions:h});const f=["log","info","warn","error","debug","trace"];const g=new Map;const S=new Map;let b=false;const M=()=>{if(!b)return;for(const v of f){const P=g.get(v);if(P&&l[v]===S.get(v)){l[v]=P}}g.clear();S.clear();b=false};const D=()=>{if(b)return;for(const v of f){g.set(v,l[v]);const P=(...N)=>{const A=Ti(v);c[A]({source:"mcode-runtime-console",consoleLevel:v},yi({colors:false,depth:4},...N))};S.set(v,P);l[v]=P}b=true};return{logDirectory:n,async runDuringStartup(v){D();try{return await v()}catch(P){M();throw P}},async flush(){await Promise.allSettled([r(),a()])},async shutdown(){M();await Promise.allSettled([o(),d()])}}}function Ti(e){if(e==="warn")return"warn";if(e==="error")return"error";return"info"}var bi=new Set(["agent","compaction","title"]);var vi=new Set(["waiting","recovered","exhausted","cancelled"]);var wi=new Set(kt);function pn(e){if(!gn(e)||e.schemaVersion!==1)return null;if(!ye(e.sessionId)||!ye(e.turnId))return null;if(!ye(e.callId)||!bi.has(e.scope))return null;if(!vi.has(e.status))return null;if(!ln(e.retryAttempt)||!ln(e.maxRetries))return null;if(!Pi(e.requestAttempt))return null;if(!mn(e.delayMs)||!mn(e.nextRetryAtMs)){return null}const t=Mi(e.error);if(e.error!==void 0&&!t)return null;return{schemaVersion:1,sessionId:e.sessionId,turnId:e.turnId,callId:e.callId,scope:e.scope,status:e.status,retryAttempt:e.retryAttempt,maxRetries:e.maxRetries,requestAttempt:e.requestAttempt,...e.delayMs!==void 0?{delayMs:e.delayMs}:{},...e.nextRetryAtMs!==void 0?{nextRetryAtMs:e.nextRetryAtMs}:{},...t?{error:t}:{}}}function Mi(e){if(e===void 0)return void 0;if(!gn(e)||!wi.has(e.reason))return void 0;if(!ye(e.message))return void 0;if(e.code!==void 0&&(typeof e.code!=="number"||!Number.isFinite(e.code))){return void 0}return{reason:e.reason,message:e.message,...typeof e.code==="number"?{code:e.code}:{}}}function gn(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function ye(e){return typeof e==="string"&&e.length>0}function ln(e){return typeof e==="number"&&Number.isInteger(e)&&e>=0}function Pi(e){return typeof e==="number"&&Number.isInteger(e)&&e>0}function mn(e){return e===void 0||typeof e==="number"&&Number.isFinite(e)&&e>=0}function hn(e){const t=x(e.payload)?e.payload:{};const n=m(t,["sessionId","session_id"]);const i={timestampMs:e.timestamp,source:e.source,...n?{sessionId:n}:{}};if(e.type==="session.start"||e.type==="session.finish"||e.type==="session.error"||e.type==="session.abort"||e.type==="session.active_run.action"){return C({...i,type:e.type,turnId:m(t,["turnId","turn_id"]),taskId:m(t,["taskId","task_id"]),runSource:m(t,["source"]),queueItemIds:yn(t,["queueItemIds","queue_item_ids"])??[],error:m(t,["error"]),errorCode:R(t,["errorCode","error_code"]),errorSource:m(t,["errorSource","error_source"]),errorDetail:m(t,["errorDetail","error_detail"]),errorProviderId:m(t,["errorProviderId","error_provider_id"])})}if(e.type==="turn.prompt_suggestion.generated"){const s=m(t,["suggestion"]);const r=m(t,["turnId","turn_id"]);if(!s||!r||!n)return{...i,type:"unknown",originalType:e.type};const a=m(t,["promptVersion","prompt_version"]);const o=R(t,["elapsedMs","elapsed_ms"]);const d={...i,sessionId:n,type:"turn.prompt_suggestion.generated",turnId:r,suggestion:s,...a!==void 0?{promptVersion:a}:{},...o!==void 0?{elapsedMs:o}:{}};return C(d)}if(e.type==="turn.prompt_suggestion.status"){const s=m(t,["turnId","turn_id"]);const r=m(t,["status"]);const a=m(t,["reason"]);const o=Se(t,["requested"]);if(!s||!r||!n)return{...i,type:"unknown",originalType:e.type};const d={...i,sessionId:n,type:"turn.prompt_suggestion.status",turnId:s,status:r,...a!==void 0?{reason:a}:{},...o!==void 0?{requested:o}:{}};return C(d)}if(e.type==="session.queue.updated"){return C({...i,type:e.type,itemId:m(t,["itemId","item_id"]),status:m(t,["status"]),queuedCount:R(t,["queuedCount","queued_count"]),failedReason:m(t,["failedReason","failed_reason"]),reason:m(t,["reason"]),admissionReason:m(t,["admissionReason","admission_reason"])})}if(e.type==="thread_goal.updated"){const s=ki(t.goal);if(s){return{timestampMs:e.timestamp,source:e.source,type:e.type,sessionId:s.sessionId,goal:s}}}if(e.type==="thread_goal.cleared"){const s=m(t,["goalId","goal_id"]);if(n&&s)return{...i,type:e.type,sessionId:n,goalId:s}}if(e.type==="session.llm_retry"){const s=pn(t);if(s){return{timestampMs:e.timestamp,source:e.source,type:e.type,sessionId:s.sessionId,turnId:s.turnId,callId:s.callId,scope:s.scope,status:s.status,retryAttempt:s.retryAttempt,maxRetries:s.maxRetries,requestAttempt:s.requestAttempt,...s.delayMs!==void 0?{delayMs:s.delayMs}:{},...s.nextRetryAtMs!==void 0?{nextRetryAtMs:s.nextRetryAtMs}:{},...s.error?{error:{reason:s.error.reason,...s.error.code!==void 0?{code:s.error.code}:{}}}:{}}}}if(e.type==="session.created"){const s=m(t,["agentName","agent_name"]);const r=m(t,["sessionType","session_type"]);if(n&&s&&(r==="root"||r==="branch")){return C({...i,type:e.type,agentName:s,sessionType:r,sessionKind:m(t,["sessionKind","session_kind"]),visibility:Ai(t.visibility),title:m(t,["title"]),parentSessionId:m(t,["parentSessionId","parent_session_id"])})}}if(e.type==="session.deleted"){if(n){return C({...i,type:e.type,agentName:m(t,["agentName","agent_name"])})}}if(e.type==="session.title_updated"){const s=m(t,["title"]);if(n&&s!==void 0){return C({...i,type:e.type,title:s,agentName:m(t,["agentName","agent_name"])})}}if(e.type==="session.pinned_updated"){const s=Se(t,["pinned"]);if(n&&s!==void 0){return C({...i,type:e.type,pinned:s,agentName:m(t,["agentName","agent_name"])})}}if(e.type==="session.compaction.progress"){const s=m(t,["progressId"]);const r=m(t,["stage"]);if(n&&s&&(r==="preparing"||r==="installed"||r==="failed")){return{...i,type:e.type,progressId:s,stage:r}}}if(e.type==="session.compaction.started"||e.type==="session.compaction.completed"||e.type==="session.compaction.failed"){const s=m(t,["compactionId","compaction_id"]);if(n&&s){return C({...i,type:e.type,compactionId:s,messagesBefore:R(t,["messagesBefore","messages_before"]),messagesAfter:R(t,["messagesAfter","messages_after"]),tokensBefore:R(t,["tokensBefore","tokens_before"]),tokensAfter:R(t,["tokensAfter","tokens_after"]),tokenUsage:Bi(t.tokenUsage??t.token_usage)})}}if(e.type==="content.retry.exceeded"){const s=m(t,["variant"]);if(n&&(s==="content"||s==="network"||s==="auth")){return C({...i,type:e.type,variant:s,lastUserMsgId:m(t,["lastUserMsgId","last_user_msg_id"])})}}if(e.type==="message.rewind"){if(n){return C({...i,type:e.type,contextReset:Se(t,["contextReset","context_reset"])})}}if(e.type==="session.publish_conflict"){const s=R(t,["durableEntries","durable_entries"]);if(n&&s!==void 0){return C({...i,type:e.type,sessionId:n,preservedTo:m(t,["preservedTo","preserved_to"]),durableEntries:s,publishedEntries:R(t,["publishedEntries","published_entries"])??0})}}if(e.type==="rotation.completed"){const s=m(t,["agentName","agent_name"]);const r=m(t,["oldSessionId","old_session_id"]);const a=m(t,["newSessionId","new_session_id"]);const o=m(t,["reason"]);if(s&&r&&a&&o){return{...i,type:e.type,agentName:s,oldSessionId:r,newSessionId:a,reason:o}}}if(e.type==="questionnaire.ask"){const s=$e(t.request);if(s){return C({...i,type:e.type,request:s,agentName:m(t,["agentName","agent_name"])})}}if(e.type==="questionnaire.dismiss"||e.type==="questionnaire.superseded"){const s=m(t,["requestId","request_id"]);if(s)return{...i,type:e.type,requestId:s}}if(e.type==="permission.ask"){const s=Ni(t);if(s)return{...i,type:e.type,request:s}}if(e.type==="permission.resolved"){const s=m(t,["requestId","request_id"]);if(s){const r=Gi(t.decision);return C({...i,type:e.type,requestId:s,decision:r})}}return{...i,type:"unknown",originalType:e.type}}function Ai(e){return e==="visible"||e==="hidden"?e:void 0}function ki(e){if(!x(e))return void 0;const t=Ci(e.status);if(typeof e.goalId!=="string"||typeof e.sessionId!=="string"||typeof e.objective!=="string"||t===void 0||!W(e.createdAt)||!W(e.updatedAt)||!W(e.tokensUsed)||!W(e.timeUsedSeconds)||!(e.tokenBudget===null||W(e.tokenBudget))||typeof e.hasKickoffAttachments!=="boolean"){return void 0}const n=_i(e.lastVerification);const i=Ii(e.executionWait??e.execution_wait);return{goalId:e.goalId,sessionId:e.sessionId,objective:e.objective,status:t,createdAt:e.createdAt,updatedAt:e.updatedAt,tokensUsed:e.tokensUsed,turnsUsed:W(e.turnsUsed)?e.turnsUsed:0,timeUsedSeconds:e.timeUsedSeconds,tokenBudget:e.tokenBudget,statusReason:Ei(e.statusReason),...i!==void 0?{executionWait:i}:{},...n!==void 0?{lastVerification:n}:{},hasKickoffAttachments:e.hasKickoffAttachments}}var Ri=new Set(["questionnaire","permission","plan","required_background","automation_owner_conflict","dependency_unavailable","verification","unknown"]);function Ii(e){if(e===null||e===void 0)return void 0;if(!x(e))return void 0;const t=m(e,["reason","waitReason","wait_reason"]);const n=R(e,["sinceMs","since_ms","waitSince","wait_since"]);if(!t||!Ri.has(t)||typeof n!=="number"||!Number.isSafeInteger(n)||n<0){return void 0}return{reason:t,sinceMs:n}}function Ci(e){if(typeof e!=="string")return void 0;if(e==="active"||e==="paused"||e==="blocked"||e==="complete"||e==="budget_limited"||e==="usage_limited"){return e}return"paused"}var xi=new Set(["complete(worker_proposal)","complete(verifier_met)","complete(user_requested)","paused(user_requested)","paused(retracted)","paused(infra_retryable)","paused(accounting_unavailable)","paused(verifier_unavailable)","paused(route_unavailable)","paused(verifier_timeout)","paused(verifier_protocol)","paused(verifier_runtime)","paused(verifier_budget)","paused(verifier_capability)","paused(verifier_aborted)","paused(no_progress)","paused(no_progress_after_completion_claim)","blocked(worker_reported)","blocked(safety_policy)","blocked(verifier_impossible)","budget_limited(token)","budget_limited(main_turn)","budget_limited(active_time)","usage_limited(provider_quota)","usage_limited(rate_limit)"]);function Ei(e){return typeof e==="string"&&xi.has(e)?e:null}function _i(e){if(!x(e)||!(e.backend==="evaluator"||e.backend==="subagent")||!(e.verdict==="met"||e.verdict==="not_met"||e.verdict==="impossible"||e.verdict==="inconclusive")||typeof e.reason!=="string"||!Array.isArray(e.missing)||!e.missing.every(t=>typeof t==="string")||!W(e.notMetStreak)||!W(e.at)){return void 0}return{backend:e.backend,verdict:e.verdict,reason:e.reason,missing:e.missing,notMetStreak:e.notMetStreak,at:e.at}}function W(e){return typeof e==="number"&&Number.isFinite(e)}function $e(e){if(!x(e)||typeof e.id!=="string"||!Array.isArray(e.steps)){return void 0}if(["planReview","plan_review","featureKey","feature_key"].some(d=>Object.hasOwn(e,d))){return void 0}const t=e.steps.map(d=>Ui(d));if(t.some(d=>!d))return void 0;const n=qi(e.requester);const i=Fi(e.tool);const s=Li(e.purpose);if(Object.hasOwn(e,"purpose")&&s===void 0)return void 0;const r=Oi(e);if(!r)return void 0;const a=Di(e.presentation);if(r.mode==="plan"&&(e.schemaVersion!==2||a===void 0)){return void 0}const o=x(e.presentation)?e.presentation:{};return{schemaVersion:typeof e.schemaVersion==="number"?e.schemaVersion:1,id:e.id,...typeof e.title==="string"?{title:e.title}:{},...i?{tool:i}:{},...n?{requester:n}:{},...s?{purpose:s}:{},...r.mode?{mode:r.mode}:{},...r.modePayload?{modePayload:r.modePayload}:{},presentation:a??{replaceComposer:typeof o.replaceComposer==="boolean"?o.replaceComposer:true,showProgress:typeof o.showProgress==="boolean"?o.showProgress:true,allowBackNavigation:typeof o.allowBackNavigation==="boolean"?o.allowBackNavigation:true},steps:t,...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{},...typeof e.status==="number"?{status:e.status}:{},...e.createdAt!==void 0?{createdAt:e.createdAt}:{}}}function Di(e){if(!x(e))return void 0;const t=e.replaceComposer??e.replace_composer;const n=e.showProgress??e.show_progress;const i=e.allowBackNavigation??e.allow_back_navigation;return t===true&&n===true&&i===true?{replaceComposer:true,showProgress:true,allowBackNavigation:true}:void 0}function Oi(e){const t=e.modePayload??e.mode_payload;if(t!==void 0&&!x(t))return void 0;const n=x(t)?t:void 0;const i=n?.featureKey??n?.feature_key;const s=n?.planReview??n?.plan_review;if(e.mode===void 0){return n===void 0?{mode:"questionnaire"}:void 0}if(e.mode==="questionnaire")return n===void 0?{mode:e.mode}:void 0;if(e.mode==="feature-enable"){if(s!==void 0||typeof i!=="string"||!i.trim()){return void 0}return{mode:e.mode,modePayload:{featureKey:i}}}if(e.mode!=="plan"||i!==void 0)return void 0;if(s===void 0)return{mode:e.mode};if(!x(s)||typeof s.markdown!=="string"||!s.markdown.trim()||typeof s.path!=="string"||!s.path.trim()){return void 0}return{mode:e.mode,modePayload:{planReview:{markdown:s.markdown,path:s.path}}}}function Li(e){if(e===1||e==="goal")return"goal";if(e===0||e==="general")return"general";return void 0}function Ui(e){if(!x(e)||typeof e.id!=="string"||typeof e.question!=="string"){return void 0}const t=e.selectionMode;if(t!==0&&t!==1&&t!=="single"&&t!=="multiple"){return void 0}if(e.options!==void 0&&!Array.isArray(e.options))return void 0;const n=[];for(const s of e.options??[]){if(!x(s)||typeof s.id!=="string"||typeof s.label!=="string"){return void 0}const r=fn(s.image);n.push({id:s.id,label:s.label,...typeof s.description==="string"?{description:s.description}:{},...r?{image:r}:{},...s.recommended===true?{recommended:true}:{}})}const i=fn(e.image);return{id:e.id,...typeof e.header==="string"?{header:e.header}:{},question:e.question,...typeof e.description==="string"?{description:e.description}:{},...i?{image:i}:{},selectionMode:t,options:n,allowOther:typeof e.allowOther==="boolean"?e.allowOther:false,otherPlaceholder:typeof e.otherPlaceholder==="string"?e.otherPlaceholder:"",required:typeof e.required==="boolean"?e.required:true}}function Fi(e){if(!x(e))return void 0;const t=m(e,["messageId","message_id"]);const n=m(e,["callId","call_id"]);return t&&n?{messageId:t,callId:n}:void 0}function fn(e){if(!x(e))return void 0;const t=m(e,["src"]);if(!t)return void 0;return C({src:t,alt:m(e,["alt"]),caption:m(e,["caption"]),width:R(e,["width"]),height:R(e,["height"])})}function qi(e){if(!x(e)||typeof e.sessionId!=="string")return void 0;return{sessionId:e.sessionId,...typeof e.runId==="string"?{runId:e.runId}:{},...typeof e.toolCallId==="string"?{toolCallId:e.toolCallId}:{},...typeof e.agentName==="string"?{agentName:e.agentName}:{}}}function Ni(e){const t=m(e,["requestId","request_id"]);if(!t)return void 0;const n=m(e,["toolName","tool_name"]);const i=m(e,["toolInput","tool_input"]);const s=ge({toolName:n,input:i});return C({requestId:t,sessionId:m(e,["sessionId","session_id"]),agentName:m(e,["agentName","agent_name"]),toolName:n,toolDescription:m(e,["toolDescription","tool_description"]),reason:m(e,["reason"]),ruleContents:yn(e,["ruleContents","rule_contents"]),toolInput:i,allowAlwaysSupported:typeof e.allowAlwaysSupported==="boolean"?e.allowAlwaysSupported:void 0,createdAt:R(e,["createdAt","created_at"]),structuredPreview:s})}function Gi(e){return e==="allowOnce"||e==="allowAlways"||e==="deny"||e==="denyAlways"?e:void 0}function m(e,t){for(const n of t){if(typeof e[n]==="string")return e[n]}return void 0}function yn(e,t){for(const n of t){const i=e[n];if(Array.isArray(i)&&i.every(s=>typeof s==="string")){return i}}return void 0}function R(e,t){for(const n of t){const i=e[n];if(typeof i==="number"&&Number.isFinite(i))return i}return void 0}function Bi(e){if(!x(e))return void 0;const t=R(e,["inputTokens","input_tokens"]);const n=R(e,["outputTokens","output_tokens"]);const i=R(e,["cacheReadTokens","cache_read_tokens"]);const s=R(e,["cacheWriteTokens","cache_write_tokens"]);const r=R(e,["totalTokens","total_tokens"]);const a=Se(e,["incomplete"]);if(t===void 0||n===void 0||i===void 0||s===void 0||r===void 0||a===void 0||[t,n,i,s,r].some(o=>o<0)||r!==t+n+i+s){return void 0}return{inputTokens:t,outputTokens:n,cacheReadTokens:i,cacheWriteTokens:s,totalTokens:r,incomplete:a}}function Se(e,t){for(const n of t){const i=e[n];if(typeof i==="boolean")return i}return void 0}function x(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function C(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var Te=class{constructor(t,n=X){this.cliService=t;this.observability=n}cliService;observability;async*watch(t){this.observability.recordAccess({operation:"event.watch",source:"process-local"});for await(const n of this.cliService.watchEvents(t)){yield hn(n)}}watchSessionUsageCommits(t){this.observability.recordAccess({operation:"event.watch-session-usage-commits",source:"process-local"});return this.cliService.watchSessionUsageCommits(t)}};var be=class{cliService;observability;constructor(t){this.cliService=t.cliService;this.observability=t.observability??X}service(t="runtime.cli-service"){this.recordAccess(t,"process-local");return this.cliService}recordAccess(t,n){this.observability.recordAccess({operation:t,source:n})}};function ie(e){if(!e.sessionId)throw new Error("Runtime returned a Session without sessionId.");return se({sessionId:e.sessionId,agentName:e.agentName,title:e.title,parentSessionId:e.parentSessionId,sessionType:e.sessionType===1?"root":e.sessionType===0?"branch":void 0,sessionKind:Qi(e.sessionKind),visibility:e.visibility==="hidden"||e.visibility==="visible"?e.visibility:void 0,purpose:e.purpose,archived:e.archived,workspaceDir:e.workspaceDir,createdAt:e.createdAt,updatedAt:e.updatedAt,status:Vi(e.status?.statusType),errorMessage:e.status?.message,errorCode:e.status?.errorCode,errorSource:e.status?.errorSource,errorDetail:e.status?.errorDetail,errorProviderId:e.status?.errorProviderId,interactionMode:e.interactionMode===1?"plan":void 0,model:ji(e.model)})}function ji(e){if(!e)return void 0;const t=e.thinking?.effort?.trim();const n={...e.providerId?{providerId:e.providerId}:{},...e.modelId?{modelId:e.modelId}:{},...e.variant!==void 0?{variant:e.variant}:{},...t?{thinking:{effort:t}}:{}};return Object.keys(n).length>0?n:void 0}function Vi(e){switch(e){case 0:return"idle";case 1:return"started";case 2:return"error";case 3:return"aborted";default:return void 0}}function Qi(e){switch(e){case 0:return"unknown";case 1:return"conversation";case 2:return"task";case 3:return"peek";case 4:return"channel";case 5:return"cron";default:return void 0}}function Tn(e){const t=F(e.selection)??{};const n=F(e.provider)??{};const i=F(e.auth)??{};const s=Array.isArray(e.warnings)?e.warnings.filter(g=>typeof g==="string"):[];const r=w(n,["authMode"]);const a=ne(i,["tokenPresent"]);const o=w(t,["providerId"])??w(n,["id"]);const d=r!==void 0&&r!=="managed-login";const c=e.modelSource==="byok"||d?"byok":e.modelSource==="token-plan"?"token-plan":r==="managed-login"?"token-plan":o||r?"byok":void 0;const l=(c==="token-plan"||c===void 0&&r==="managed-login")&&a!==true;const u=Wi(e.tokenPlanQuota);const h=e.tokenPlanQuotaState==="available"||e.tokenPlanQuotaState==="not-subscribed"||e.tokenPlanQuotaState==="unavailable"?e.tokenPlanQuotaState:void 0;const f=h??(c==="token-plan"?u?"available":"unavailable":void 0);return se({status:l?"needs-login":s.length>0?"warning":r||w(t,["defaultModel"])?"ready":"unknown",defaultModel:w(t,["defaultModel"]),providerId:o,modelId:w(t,["modelId"]),authMode:r,managedTokenPresent:a,modelSource:c,tokenPlanQuotaState:f,tokenPlanQuota:u,profile:e.profile===null||typeof e.profile==="string"?e.profile:void 0,dataDir:typeof e.dataDir==="string"?e.dataDir:void 0,loginEpoch:typeof e.loginEpoch==="string"?e.loginEpoch:void 0,warnings:s})}function Wi(e){const t=F(e);const n=Sn(t?.fiveHour);const i=Sn(t?.weekly);const s=$i(t?.video);return n&&i?{fiveHour:n,weekly:i,...s?{video:s}:{}}:void 0}function $i(e){const t=F(e);if(!t||typeof t.unlimited!=="boolean")return void 0;const n=Y(t,["remainingCount"]);const i=Y(t,["totalCount"]);const s=Y(t,["resetAtMs"]);return se({remainingCount:n===void 0?void 0:Math.round(Math.max(0,n)),totalCount:i===void 0?void 0:Math.round(Math.max(0,i)),resetAtMs:s,unlimited:t.unlimited})}function Sn(e){const t=F(e);if(!t||typeof t.unlimited!=="boolean")return void 0;const n=Y(t,["remainingPercent"]);const i=Y(t,["resetAtMs"]);return se({remainingPercent:n===void 0?void 0:Math.round(Math.min(100,Math.max(0,n))),resetAtMs:i,unlimited:t.unlimited})}function bn(e){const t=F(e.runtimeOwner)??{};const n=F(e.paths)??{};const i=F(e.selection)??{};const s=F(e.provider)??{};const r=F(e.auth)??{};const a=F(e.byok)??{};return se({status:w(e,["status"]),surface:w(e,["surface"]),runtimeMode:w(e,["runtimeMode"]),runtimeOwnerKind:w(t,["kind"]),runtimeOwnerId:w(t,["id"]),dataDir:w(n,["dataDir"]),configPath:w(n,["configPath"]),configPresent:ne(n,["configPresent"]),authCachePresent:ne(n,["authCachePresent"]),defaultModel:w(i,["defaultModel"]),providerId:w(i,["providerId"])??w(s,["id"]),modelId:w(i,["modelId"]),providerBaseUrl:w(s,["baseURL"]),authMode:w(s,["authMode"]),authModeSource:w(s,["authModeSource"]),managedTokenPresent:ne(r,["tokenPresent"]),apiKeyPresent:ne(s,["apiKeyPresent"]),customProviderCount:Y(a,["customProviderCount"]),warnings:Array.isArray(e.warnings)?e.warnings.filter(o=>typeof o==="string"):[]})}function ze(e){const t=new Set;return e.flatMap(n=>{const i=n.path.trim();if(!i||t.has(i))return[];t.add(i);return[{...n,path:i}]})}function vn(e){const t=[];const n=Math.max(0,...e.map(i=>i.length));for(let i=0;i<n;i+=1){for(const s of e){const r=s[i];if(r!==void 0)t.push(r)}}return t}function F(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function w(e,t){for(const n of t){if(typeof e[n]==="string")return e[n]}return void 0}function ne(e,t){for(const n of t){if(typeof e[n]==="boolean")return e[n]}return void 0}function Y(e,t){for(const n of t){const i=e[n];if(typeof i==="number"&&Number.isFinite(i))return i}return void 0}function se(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function wn(e){if(!e)return[];return e.map(t=>{const n=t.userInput;const i=t.assistantResponse;const s=t.fileChangeCount;return{userMessageId:n.msgId,...i?.msgId?{assistantMessageId:i.msgId}:{},...n.contentHead!==void 0?{contentHead:n.contentHead}:{},timestamp:n.timestamp,fileChangeCount:typeof s==="number"&&Number.isFinite(s)&&s>=0?s:0}})}function Mn(e){return{turns:e.turns.map(t=>({turnId:t.turnId,files:t.files.map(n=>({filePath:n.filePath,action:n.action,skipped:n.skipped===true}))}))}}function Pn(e){return{rewound:e.rewound===true,...e.displayRevision!==void 0?{displayRevision:e.displayRevision}:{},...e.historyRevision!==void 0?{historyRevision:e.historyRevision}:{},...e.deletedMessageIds?{deletedMessageIds:[...e.deletedMessageIds]}:{},...e.turnDiffRewind?{turnDiffRewind:{status:e.turnDiffRewind.status,...e.turnDiffRewind.revertedTurnIds?{revertedTurnIds:[...e.turnDiffRewind.revertedTurnIds]}:{},...e.turnDiffRewind.errorCode!==void 0?{errorCode:e.turnDiffRewind.errorCode}:{}}}:{}}}function An(e){return{rewound:e.rewound===true,...e.turnId!==void 0?{turnId:e.turnId}:{},...e.userMessageId!==void 0?{userMessageId:e.userMessageId}:{},...e.displayRevision!==void 0?{displayRevision:e.displayRevision}:{},...e.historyRevision!==void 0?{historyRevision:e.historyRevision}:{},...e.deletedMessageIds?{deletedMessageIds:[...e.deletedMessageIds]}:{}}}var ve=class{constructor(t){this.context=t}context;async getWorkspaceGitMetadata(t){const n=await this.context.service("workspace.git.metadata").getWorkspaceGitMetadata(t);if(!n){return{isGitRepo:false,branch:"",detached:false,isWorktree:false}}const i=n.isGitRepo===true;const s=typeof n.branch==="string"?n.branch.trim():"";const r=n.hasHead===true;const a=s?await this.readReviewLink(t,s):void 0;return{isGitRepo:i,branch:s,detached:i&&r&&s.length===0,isWorktree:n.isWorktree===true,...a?{reviewLink:a}:{}}}async readReviewLink(t,n){try{const i=await this.context.service("workspace.git.review-link").getWorkspaceReviewLink(t,n);return Hi(i)}catch{return void 0}}async listWorkspaceFileTree(t,n,i){const s=await this.context.service("workspace.tree.list").listWorkspaceFileTree({workspaceDir:t,...n?{path:n}:{},...i?{signal:i}:{}});return zi(s)}async searchWorkspaceFiles(t,n,i=20,s){return[...await this.context.service("workspace.search").searchWorkspaceFiles({workspaceDir:t,query:n,limit:i,...s?{signal:s}:{}})]}async listWorkspaceFileTreeCandidates(t,n){const i=ze(t.roots);const s=await Promise.all(i.map(async r=>{const a=await this.listWorkspaceFileTree(r.path,t.path,n);return a.map(o=>({...o,workspaceDir:r.path}))}));return s.flat()}async searchWorkspaceFileCandidates(t,n){const i=ze(t.roots);const s=Math.max(1,Math.floor(t.limit??20));const r=await Promise.all(i.map(async o=>{const d=await this.searchWorkspaceFiles(o.path,t.query,s,n);return d.map(c=>({workspaceDir:o.path,path:c}))}));const a=new Set;return vn(r).flatMap(o=>{const d=`${o.workspaceDir}\0${o.path}`;if(a.has(d))return[];a.add(d);return[o]}).slice(0,s)}};function zi(e){return e.flatMap(t=>{if(!t||typeof t!=="object"||Array.isArray(t))return[];const n=t;if(typeof n.name!=="string"||typeof n.path!=="string"||n.type!=="file"&&n.type!=="directory"){return[]}return[{name:n.name,path:n.path,type:n.type,...typeof n.ignored==="boolean"?{ignored:n.ignored}:{}}]})}function Hi(e){if(!e||typeof e!=="object"||Array.isArray(e))return void 0;const t=e;const{vendor:n,url:i}=t;const s=t.number;if(n!=="github"&&n!=="gitlab")return void 0;if(typeof i!=="string"||!i)return void 0;if(typeof s!=="number"||!Number.isInteger(s)||s<=0){return void 0}return{vendor:n,url:i,number:s}}var we=class{constructor(t,n,i){this.cliService=t;this.defaultAgentName=n;this.onSessionDeleted=i}cliService;defaultAgentName;onSessionDeleted;async createSession(t,n){const i=await this.cliService.createSession({name:this.defaultAgentName,workspaceDir:t.workspaceDir,...t.title?{title:t.title}:{},...t.parentSessionId?{parentSessionId:t.parentSessionId}:{},...t.visibility?{visibility:t.visibility}:{},...t.purpose?{purpose:t.purpose}:{},...n?{model:{providerId:n.providerId,modelId:n.modelId,...n.variant!==void 0?{variant:n.variant}:{},...n.contextLimit!==void 0?{contextLimit:n.contextLimit}:{},...n.thinking?.effort?.trim()?{thinking:{effort:n.thinking.effort.trim()}}:{}}}:{}});const s=He(i.session,i.sessionId);if(t.mcpServers?.length){await this.configureSessionMcpServers(s.sessionId,t.mcpServers)}return s}async configureSessionMcpServers(t,n){await this.cliService.configureSessionMcpServers({sessionId:t,servers:n.map(i=>i.type==="stdio"?{name:i.name,config:{type:i.type,command:i.command,args:[...i.args],...i.env?{env:{...i.env}}:{}}}:{name:i.name,config:{type:i.type,url:i.url,...i.headers?{headers:{...i.headers}}:{}}})})}clearSessionMcpServers(t){return this.cliService.clearSessionMcpServers(t)}async listSessions(t=this.defaultAgentName,n={}){const i=await this.cliService.listSessions({name:t,...n});return(i.sessions??[]).map(ie)}async listSessionPage(t={},n={}){const i=typeof t==="string"?{...n,agentName:t}:t;const{allAgents:s=false,agentName:r,workspaceDir:a,...o}=i;const d=r??this.defaultAgentName;const c=g=>s?this.listSessionTree(d,g):this.listAgentSessions(d,g);if(!a)return kn(await c(o));let l=o.cursor;const u=new Set(l?[l]:[]);const h=o.limit!==void 0&&o.limit>0?o.limit:void 0;const f=[];for(;;){const g=await c({...o,...h?{limit:Math.max(1,h-f.length)}:{},...l?{cursor:l}:{}});const S=kn(g,a);f.push(...S.sessions);const b=h?f.length>=h:f.length>0;if(b||!g.hasMore)return Rn(f,g);if(!g.nextCursor)return{sessions:f,hasMore:false};if(u.has(g.nextCursor))return{sessions:f,hasMore:false};u.add(g.nextCursor);l=g.nextCursor}}async getSession(t){const n=await this.cliService.getSession({id:t});if(!n.session)throw new Error(`Runtime did not return session ${t}.`);return ie(n.session)}async getMessages(t,n=80){return(await this.listMessagePage(t,{limit:n})).messages}async listMessagePage(t,n={}){const i=await this.cliService.getMessages({id:t,...n.limit!==void 0?{limit:n.limit}:{},...n.before?{before:n.before}:{}});return{messages:(i.messages??[]).map(s=>Ht(s)),hasMore:i.hasMore===true,...i.nextCursor?{nextCursor:i.nextCursor}:{}}}async getSessionForkOptions(t,n){return this.cliService.getSessionForkOptions({id:t,...n?{assistantMessageId:n}:{}})}async forkSession(t){const n=await this.cliService.forkSession({id:t.sessionId,...t.assistantMessageId?{assistantMessageId:t.assistantMessageId}:{},clientRequestId:t.clientRequestId,...t.title?{title:t.title}:{},useSuggestedTitle:t.useSuggestedTitle,createIsolatedWorktree:t.createIsolatedWorktree});return{session:He(n.session,void 0),...n.forkOriginMessageId?{forkOriginMessageId:n.forkOriginMessageId}:{},...n.sourceDisplayMessageId?{sourceDisplayMessageId:n.sourceDisplayMessageId}:{},...n.displayRevision?{displayRevision:n.displayRevision}:{},...n.historyRevision?{historyRevision:n.historyRevision}:{}}}async renameSession(t,n){const i=await this.cliService.updateSession({id:t,title:n});return He(i.session,t)}async archiveSession(t,n){await this.cliService.archiveSession({id:t,archived:n})}async deleteSession(t){await this.onSessionDeleted?.(t);await this.cliService.deleteSession({id:t})}async listSessionInputSummaries(t,n={}){let i=n.before;const s=new Set(i?[i]:[]);let r=[];for(;;){const a=await this.cliService.listSessionInputSummaries({id:t,...n.limit!==void 0?{limit:n.limit}:{},...i?{before:i}:{}});const o=wn(a.summaries);r=[...o,...r];if(!a.hasMore||!a.nextCursor||s.has(a.nextCursor)){return r}s.add(a.nextCursor);i=a.nextCursor}}async getSessionRewindPreview(t){const n=await this.cliService.getSessionRewindPreview({id:t.sessionId,userMessageId:t.userMessageId});return Mn(n)}async rewindSession(t){const n=await this.cliService.rewindSession({id:t.sessionId,userMessageId:t.userMessageId,clientRequestId:t.clientRequestId,...t.rewindTurnDiff?{rewindTurnDiff:true}:{}});return Pn(n)}async editSessionMessage(t){const n=await this.cliService.editSessionMessage({id:t.sessionId,userMessageId:t.userMessageId,clientRequestId:t.clientRequestId,content:t.content,...t.attachments?{attachments:t.attachments.map(i=>({meta:{attachmentType:i.type,fileName:i.fileName,mimeType:i.mimeType,...i.sizeBytes!==void 0?{sizeBytes:i.sizeBytes}:{}},local:{...i.filePath?{filePath:i.filePath}:{},...i.assetId?{assetId:i.assetId}:{}}}))}:{},...t.rewindTurnDiff?{rewindTurnDiff:true}:{}});return An(n)}async listAgentSessions(t,n){const i=await this.cliService.listSessions({name:t,...n});return{sessions:i.sessions??[],hasMore:i.hasMore===true,...i.nextCursor?{nextCursor:i.nextCursor}:{}}}async listSessionTree(t,n){const i=await this.cliService.getSessionTree({name:t,...n});return{sessions:(i.sessions??[]).flatMap(s=>{const r=s.session?[s.session]:[];const a=s.session?.sessionId;if(!a)return r;return[...r,...(s.childSessions??[]).map(o=>Ki(o,a))]}),hasMore:i.hasMore===true,...i.nextCursor?{nextCursor:i.nextCursor}:{}}}};function kn(e,t){const n=e.sessions.map(ie).filter(i=>!t||i.workspaceDir===t);return Rn(n,e)}function Rn(e,t){return{sessions:e,hasMore:t.hasMore===true,...t.nextCursor?{nextCursor:t.nextCursor}:{}}}function Ki(e,t){return{...e,sessionType:Et.Branch,parentSessionId:t}}function He(e,t){if(e)return ie(e);if(t)return{sessionId:t};throw new Error("Runtime did not return the created Session.")}function In(e){let t;let n;for(let s=e.messages.length-1;s>=0;s-=1){const r=e.messages[s];if(!r)continue;if(!n)n=Yi(r);if(!t)t=Xi(r.rawJson);if(n&&t)break}const i=Ji(e.model);if(!t){return{status:e.active?"loading":"empty",...i?{model:i}:{},...n?{compaction:n}:{}}}return{status:e.active?"stale":"live",...i?{model:i}:{},contextUsage:t,compaction:n??{state:"never"}}}function Ji(e){if(!e?.providerId||!e.modelId)return void 0;const t=e.contextLimit===void 0?void 0:Number(e.contextLimit);return{provider:e.providerId,id:e.modelId,...t!==void 0&&Number.isFinite(t)&&t>0?{contextWindow:t}:{}}}function Xi(e){if(!e)return void 0;let t;try{const o=JSON.parse(e);if(!Je(o))return void 0;t=o}catch{return void 0}const n=t.contextUsage??t.context_usage;if(!Je(n))return void 0;const i=Ke(n.contextWindowTokens);const s=Ke(n.usedTokens);const r=n.totalCountSource;if(i===void 0||s===void 0||r!=="LOCAL_ESTIMATE"&&r!=="PROVIDER_USAGE_ANCHORED"){return void 0}const a=Array.isArray(n.components)?n.components.flatMap(o=>{if(!Je(o)||!Zi(o.kind))return[];const d=Ke(o.tokens);return d===void 0?[]:[{kind:o.kind,tokens:d}]}):[];return{contextWindowTokens:i,usedTokens:s,totalCountSource:r,components:a}}function Yi(e){const t=e.kind==="compaction_start"?"running":e.kind==="compaction"?"completed":e.kind==="compaction_failed"?"failed":void 0;if(!t)return void 0;return{state:t,...e.timestamp!==void 0&&Number.isFinite(Number(e.timestamp))?{lastCompactedAtMs:Number(e.timestamp)}:{}}}function Ke(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0?e:void 0}function Zi(e){return e==="SYSTEM_PROMPT"||e==="MEMORY"||e==="TOOLS"||e==="SKILLS"||e==="MESSAGES"||e==="OTHER"}function Je(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}var Me=class{constructor(t,n,i){this.context=t;this.defaultAgentName=n;this.workspaceDir=i}context;defaultAgentName;workspaceDir;async getAccountStatus(t,n){return Tn(await this.context.service("runtime.account").getAccountStatus({...t?{sessionId:t}:{},...n?.model?{model:`${n.model.providerId}/${n.model.modelId}`}:{}}))}async getRuntimeDiagnostics(){return bn(await this.context.service("runtime.diagnostics").getRuntimeDiagnostics())}getInstructionSources(t){return this.context.service("runtime.instructions").getInstructionSources({workspaceDir:t})}async getPermissionMode(){return je(await this.context.service("config.permission.read").getPermissionMode())}async setPermissionMode(t){return je(await this.context.service("config.permission.write").setPermissionMode({mode:t}))??t}async getDangerousCommandGateEnabled(){return Ve(await this.context.service("config.permission.read").getDangerousCommandGateEnabled())}async setDangerousCommandGateEnabled(t){return Ve(await this.context.service("config.permission.write").setDangerousCommandGateEnabled({enabled:t}))??t}async getSandboxFilesystemMode(){return Qe(await this.context.service("config.permission.read").getSandboxFilesystemMode())}async setSandboxFilesystemMode(t){return Qe(await this.context.service("config.permission.write").setSandboxFilesystemMode({mode:t}))??t}async listModels(t){const n=this.context.service("model.list");const i={...t?{sessionId:t}:{}};return(await n.listModels(i)).map(es)}async selectModel(t,n){const i=this.context.service("model.select");const s=Cn(t);if(!n)return i.selectModel(s);const r=await i.selectModel(s);if(!r)return false;return this.selectSessionModel(t,n)}setModelFavorite(t,n){return this.context.service("model.favorite").setModelFavorite({providerId:t.providerId,modelId:t.modelId,favorite:n})}selectSessionModel(t,n){return this.context.service("model.select").selectModel({...Cn(t),sessionId:n})}async listUserModelProviders(){const t=await this.context.service("provider.list").listUserModelProviders();return t.filter(n=>!mt(n.providerId,n.baseUrl))}async listProviderPresets(){return await this.context.service("provider.presets").listProviderPresets()}async getCodexOAuthStatus(){return await this.context.service("provider.codex-oauth.status").getCodexOAuthStatus()}async startCodexOAuthLogin(t){return await this.context.service("provider.codex-oauth.start").startCodexOAuthLogin(t)}async cancelCodexOAuthLogin(t){return await this.context.service("provider.codex-oauth.cancel").cancelCodexOAuthLogin(t)}async getMiniMaxApiKeyStatus(){return await this.context.service("provider.minimax.status").getMiniMaxApiKeyStatus()}getMiniMaxModelSource(){return this.context.service("provider.minimax.source").getMiniMaxModelSource()}setMiniMaxModelSource(t){return this.context.service("provider.minimax.source").setMiniMaxModelSource({source:t})}async upsertMiniMaxApiKey(t){await this.context.service("provider.minimax.upsert").upsertMiniMaxApiKey(t)}async createUserModelProvider(t){await this.context.service("provider.create").createUserModelProvider({...t,models:[...t.models]})}discoverUserModelsCandidate(t){return this.context.service("provider.discover").discoverUserModelsCandidate(t)}async saveUserModelProviderCandidate({modelId:t,saveAndUse:n,skipConnectionTest:i,...s}){return await this.context.service("provider.save-candidate").saveUserModelProviderCandidate({candidate:{...s,...s.models?{models:s.models.map(r=>({...r}))}:{}},modelId:t,...i!==void 0?{skipConnectionTest:i}:{},...n!==void 0?{saveAndUse:n}:{}})}async updateUserModelProvider(t){await this.context.service("provider.update").updateUserModelProvider({...t,...t.models?{models:[...t.models]}:{}})}async deleteUserModelProvider(t){await this.context.service("provider.delete").deleteUserModelProvider({providerId:t})}async testUserModelProvider(t){return await this.context.service("provider.test").testUserModelProvider({providerId:t})}async testUserModel(t,n){return await this.context.service("provider.test-model").testUserModel({providerId:t,modelId:n})}async getSessionUsage(t){const n=await this.context.service("session.usage").getSessionUsage({id:t});return{summary:n.summary,rows:n.rows}}async getSessionUsageSummary(t){return await this.context.service("session.usage-summary").getSessionUsageSummary({id:t})}async getSessionCacheWarmingStatus(t){return this.context.service("session.cache-warming-status").getSessionCacheWarmingStatus(t)}async requestCompaction(t,n=this.defaultAgentName,i){const s=await this.context.service("session.compaction").requestCompaction({name:n,id:t,reason:"ui_request",...i?{customInstructions:i}:{}});return{...s,...s.tokensBefore!==void 0?{tokensBefore:Number(s.tokensBefore)}:{},...s.tokensAfter!==void 0?{tokensAfter:Number(s.tokensAfter)}:{}}}async getContextSnapshot(t){const n=this.context.service("session.context-snapshot");const[i,s,r]=await Promise.all([n.getSession({id:t}),n.getMessages({id:t,limit:80}),n.listModels({sessionId:t})]);const a=i.session;if(!a)throw new Error(`Runtime did not return Session ${t}.`);const o=r.find(c=>c.selected===true);const d=o&&(o.providerId!==a.model?.providerId||o.modelId!==a.model?.modelId)?o:a.model??o;return In({messages:s.messages??[],active:a.status?.statusType===1,model:d})}async getActiveRun(t){const n=this.context.service("session.active-run");const i=await n.getSession({id:t});const s=i.session;if(!s)throw new Error(`Runtime did not return Session ${t}.`);const r=s.status?.statusType===1;const[a,o,d]=r?await Promise.all([n.getActiveTurn(t),n.listPendingPermissions({}),n.getPendingQuestionnaire({name:s.agentName??this.defaultAgentName,sessionId:t})]):[void 0,{requests:[]},{}];const c=r&&(d.request!==void 0||(o.requests??[]).some(h=>h.sessionId===t));const l=a?.turnId;const u=r&&!c&&a?.busyReason==="turn"&&a.locallyOwned;return{schemaVersion:1,sessionId:t,state:r?c?"decision-blocked":"running":s.status?.statusType===2||s.status?.statusType===3?"terminal":"idle",...l?{turnId:l}:{},actions:{steer:u}}}async listSkills(t=this.defaultAgentName,n,i=this.workspaceDir){const s=this.context.service("skill.list");const r=await s.listRuntimeSkills({agentName:t,...i?{workspaceDir:i}:{},includePluginSkills:true});const a=n?.trim().toLocaleLowerCase();const o=a?(r.skills??[]).filter(d=>`${d.name} ${d.displayName??""} ${d.description??""}`.toLocaleLowerCase().includes(a)):r.skills??[];return{skills:o,hasMore:false}}inspectProjectMcp(t){return this.context.service("mcp.project.inspect").inspectProjectMcp(t)}async listMcpServers(t,n){const i={...t?{keyword:t}:{},...n?{sessionId:n}:{}};const s=await this.context.service("mcp.list").listMcpServers(i);return s.servers}};function Cn(e){const t=e.thinking?.effort?.trim();return{providerId:e.providerId,modelId:e.modelId,...e.variant!==void 0?{variant:e.variant}:{},...e.contextLimit!==void 0?{contextLimit:e.contextLimit}:{},...t?{thinking:{effort:t}}:{}}}function es(e){const t=e;const n=t.thinkingConfig;if(!n)return t;const{default_value:i,...s}=n;return{...t,thinkingConfig:{...s,...s.defaultValue!==void 0?{defaultValue:s.defaultValue}:i!==void 0?{defaultValue:i}:{}}}}var Pe=class{constructor(t,n){this.createQueueRequestId=t;this.cliService=n}createQueueRequestId;cliService;async listQueuedMessages(t){return[...(await this.getQueueSnapshot(t)).items]}async getQueueSnapshot(t){const n=await this.cliService.listQueueMessages({id:t});const i=(n.items??[]).map(Xe);return{items:i,paused:n.paused===true,pendingCount:n.pendingCount??i.length}}async getTurnStatus(t){const n=await this.cliService.getTurnStatus(t);return is(n)}async continueQueue(t){const n=await this.cliService.resumeSession({id:t,drainQueued:true,continuePausedQueue:true});if(!n.ok)throw new Error(n.body.message);if(Symbol.asyncIterator in n.source){await n.source[Symbol.asyncIterator]().return?.().catch(()=>void 0)}}async steerQueuedMessage(t,n){const i=await this.cliService.steerSession({id:t,queueItemId:n});if(!i.success||!i.queueItemId||!i.turnId){throw new Error("Runtime did not return the steered Queue item and Turn identities.")}return{queueItemId:i.queueItemId,turnId:i.turnId}}async enqueueMessage(t,n,i={}){return this.cliService.enqueueMessage({id:t,content:n,clientRequestId:this.createQueueRequestId(),interactiveSurface:true,...i.clientIntent?{clientIntent:i.clientIntent}:{},...i.reviewRequest?{reviewRequest:i.reviewRequest}:{},...i.model?{model:{...i.model,...i.model.thinking?{thinking:{...i.model.thinking}}:{}}}:{},...i.attachments?.length?{attachments:i.attachments.map(s=>({meta:{attachmentType:s.type,fileName:s.fileName,mimeType:s.mimeType,sizeBytes:s.sizeBytes},local:{...s.filePath?{filePath:s.filePath}:{},...s.assetId?{assetId:s.assetId}:{}}}))}:{}})}async deleteQueuedMessage(t,n){const i=await this.cliService.deleteQueueItem({id:t,itemId:n});return i.item?Xe(i.item):void 0}async updateQueuedMessageContent(t,n,i){const s=await this.cliService.updateQueueItem({id:t,itemId:n,content:i});return s.item?Xe(s.item):void 0}async getPendingQuestionnaire(t,n,i){i?.throwIfAborted();const s=await this.cliService.getPendingQuestionnaire({name:t,sessionId:n});i?.throwIfAborted();return s.request?xn(s.request):void 0}async getLatestPlanReview(t,n,i){i?.throwIfAborted();const s=await this.cliService.getLatestPlanReview({name:t,sessionId:n});i?.throwIfAborted();return s.request?xn(s.request):void 0}async getPlanModeCapabilities(){return this.cliService.getPlanModeCapabilities()}async replyQuestionnaire(t,n,i){const s=await this.cliService.replyQuestionnaire({name:t,requestId:n,schemaVersion:2,answers:i.map(r=>({stepId:r.stepId,selectedOptionIds:r.selectedOptionIds??[],selectedOther:r.selectedOther===true,...r.otherText?{otherText:r.otherText}:{},...r.skipped===true?{skipped:true}:{}})),submittedAt:Date.now()});return s.ok}async dismissQuestionnaire(t,n){const i=await this.cliService.dismissQuestionnaire({name:t,requestId:n});return i.ok}async listPendingPermissions(t){t?.throwIfAborted();const n=await this.cliService.listPendingPermissions({});t?.throwIfAborted();return(n.requests??[]).map(ns)}async replyPermission(t,n,i){const s=await this.cliService.replyPermission({name:t,requestId:n,reply:ts[i]});return s.success===true}};var ts={allowOnce:te.AllowOnce,allowAlways:te.AllowAlways,deny:te.Deny,denyAlways:te.DenyAlways};function ns(e){const t=ge({toolName:e.toolName,input:e.toolInput});return{...e.requestId?{requestId:e.requestId}:{},...e.sessionId?{sessionId:e.sessionId}:{},...e.agentName?{agentName:e.agentName}:{},...e.toolName?{toolName:e.toolName}:{},...e.ruleContents?{ruleContents:[...e.ruleContents]}:{},...e.toolInput!==void 0?{toolInput:e.toolInput}:{},...e.toolDescription!==void 0?{toolDescription:e.toolDescription}:{},...e.reason!==void 0?{reason:e.reason}:{},...e.allowAlwaysSupported!==void 0?{allowAlwaysSupported:e.allowAlwaysSupported}:{},...e.createdAt!==void 0?{createdAt:Number(e.createdAt)}:{},...t?{structuredPreview:t}:{}}}function is(e){return{...e.activeTurn?{activeTurn:{...e.activeTurn}}:{activeTurn:null},...e.latestActivity?{latestActivity:{...e.latestActivity,...e.latestActivity.completedAtMs===void 0?{}:{completedAtMs:e.latestActivity.completedAtMs}}}:{latestActivity:null}}}function Xe(e){return{itemId:e.itemId,sessionId:e.sessionId,status:e.status,...e.source?{source:e.source}:{},...e.reviewRequest?.scope==="local_changes"?{reviewRequest:{scope:"local_changes"}}:{},...e.content!==void 0?{content:e.content}:{},...e.attachments?{attachments:structuredClone(e.attachments)}:{},...e.modelInfo?{modelInfo:{...e.modelInfo}}:{},...e.createdAt!==void 0?{createdAt:e.createdAt}:{},...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{},...e.startedAt!==void 0?{startedAt:e.startedAt}:{},...e.finishedAt!==void 0?{finishedAt:e.finishedAt}:{},...e.failedReason?{failedReason:e.failedReason}:{}}}function xn(e){return $e({...e,...e.expiresAt!==void 0?{expiresAt:Number(e.expiresAt)}:{},...e.createdAt!==void 0?{createdAt:Number(e.createdAt)}:{}})}var ss=200;var rs=20;var os=3;var Ae=class{constructor(t){this.options=t}options;async getSnapshot(t){const n=await this.listAllSessions();const i=$t(n,t).map(s=>zt(s));return{schemaVersion:1,rootSessionId:t,members:i}}async stop(t){const n=new Set;const i=new Set;const s=new Set;const r=await this.abort(t,n,i)==="stopped";const a=await this.getSnapshot(t);let o=a.members.filter(pe);for(let c=0;c<os;c+=1){for(const u of o){if(s.has(u.sessionId))continue;if(await this.abort(u.sessionId,n,i)==="stopped"){s.add(u.sessionId)}}const l=await this.getSnapshot(t);o=l.members.filter(u=>pe(u)&&!s.has(u.sessionId));if(o.length===0)break}const d=await this.getSnapshot(t);return{schemaVersion:1,rootSessionId:t,rootStopped:r,stoppedSessionIds:[...s],activeSessionIds:d.members.filter(pe).filter(({sessionId:c})=>!s.has(c)&&!i.has(c)).map(({sessionId:c})=>c),failedSessionIds:[...n]}}async listAllSessions(){const t=[];let n;for(let i=0;i<rs;i+=1){const s=await this.options.listSessionPage({allAgents:true,includeArchived:true,includeHidden:true,limit:ss,...n?{cursor:n}:{}});t.push(...s.sessions);if(!s.hasMore||!s.nextCursor)break;n=s.nextCursor}return t}async abort(t,n,i){try{if(await this.options.abortSession({id:t,reason:"user_stop"})){i.delete(t);return"stopped"}i.add(t);return"inactive"}catch{n.add(t);return"failed"}}};var ke=class{constructor(t){this.service=t}service;async*sendMessage(t,n,i){n?.throwIfAborted();const s=n?{signal:n}:{};const r={...t,interactiveSurface:true};const a=i?await this.service.sendMessage(r,s,i):await this.service.sendMessage(r,s);if(!a.ok){throw new Ue("runtime",a.body.message,{code:a.body.key,retryable:a.status>=500})}const o=En(a.source)[Symbol.asyncIterator]();const d=()=>void o.return?.(void 0);n?.addEventListener("abort",d,{once:true});try{for await(const c of{[Symbol.asyncIterator]:()=>o}){n?.throwIfAborted();const l=Be(c,t.turnId);if(l)yield l}}finally{n?.removeEventListener("abort",d);await o.return?.(void 0)}}async abortSession(t){return(await this.service.abortSession(t)).success===true}async*resumeSession(t,n,i){i?.throwIfAborted();const s=await this.service.resumeSession(t,i?{signal:i}:{});if(!s.ok){throw new Ue("runtime",s.body.message,{code:s.body.key,retryable:s.status>=500})}const r=En(s.source)[Symbol.asyncIterator]();const a=()=>void r.return?.(void 0);i?.addEventListener("abort",a,{once:true});try{for await(const o of{[Symbol.asyncIterator]:()=>r}){i?.throwIfAborted();const d=Be(o,n);if(d)yield d}}finally{i?.removeEventListener("abort",a);await r.return?.(void 0)}}steer(t){return this.service.steer(t)}};async function*En(e){for await(const t of e)yield t}var _n=200;var Dn=100;var Un=1;var Fn=2;var Re=class{constructor(t){this.cliService=t}cliService;async listInstalledPlugins(t={}){const n=await On(i=>this.cliService.listInstalledPlugins({limit:_n,...i?{cursor:i}:{}}));return n.map(as).filter(i=>i!==void 0&&(t.marketplace===void 0||i.marketplace===t.marketplace))}async listMarketplacePlugins(t){const n=Ln(t.marketplace);const i=await On(s=>this.cliService.listMarketplacePlugins({source:n,limit:_n,...s?{cursor:s}:{}}));return i.flatMap(s=>{const r=ds(s,t.marketplace);return r?[r]:[]})}async mutatePlugin(t){const n={pluginName:t.plugin.name,source:Ln(t.plugin.marketplace)};const i={install:()=>this.cliService.installPlugin(n),remove:()=>this.cliService.uninstallPlugin(n),enable:()=>this.cliService.enablePlugin(n),disable:()=>this.cliService.disablePlugin(n)};const s=await i[t.action]();return{installed:s.installExists,enabled:s.enabled}}async refreshPlugins(){await this.cliService.refreshPlugins()}};async function On(e){const t=[];const n=new Set;let i;for(let s=0;s<Dn;s+=1){const r=await e(i);t.push(...r.plugins);const a=r.nextCursor?.trim();if(!r.hasMore||!a||n.has(a))return t;n.add(a);i=a}throw new Error(`Plugin catalog exceeded ${Dn} pages.`)}function as(e){const t=cs(e.source);if(!t)return void 0;return qn(e,t,true,e.enabled)}function ds(e,t){return qn(e,t,e.installExists,e.enabled)}function qn(e,t,n,i){const s=e.name.trim();if(!s)return void 0;return{pluginId:Rt(s,t),name:s,displayName:e.displayName?.trim()||s,marketplace:t,...e.version?.trim()?{version:e.version.trim()}:{},...e.description?.trim()?{description:e.description.trim()}:{},...e.author?.trim()?{author:e.author.trim()}:{},installed:n,enabled:i,capabilities:{appCount:e.capabilities.appCount,mcpServerCount:e.capabilities.mcpServerCount,skillCount:e.capabilities.skillCount,...e.capabilities.agentCount?{agentCount:e.capabilities.agentCount}:{}}}}function Ln(e){return e==="official"?Un:Fn}function cs(e){if(e===Un)return"official";if(e===Fn)return"local";return void 0}var Ie=class{constructor(t){this.context=t}context;isEnabled(){return this.context.service("goal.enabled").isGoalEnabled()}get(t){return this.context.service("goal.read").getGoal(t)}create(t){return this.context.service("goal.create").createGoal({sessionId:t.sessionId,objective:t.objective,...t.tokenBudget!==void 0?{tokenBudget:t.tokenBudget}:{},...t.attachments?.length?{kickoffAttachments:t.attachments.map(n=>({type:n.type,filePath:n.filePath,fileName:n.fileName,mimeType:n.mimeType}))}:{}})}patch(t,n){return this.context.service("goal.patch").patchGoal(t,n)}clear(t){return this.context.service("goal.clear").clearGoal(t)}};var us="Auth mismatch: the daemon serves a different login than this window; account details come from the daemon only. Re-login or restart the daemon.";var Ce=class{cliService;context;workspaceAccess;sessionAccess;productAccess;interactionAccess;eventAccess;delegationAccess;conversationAccess;pluginAccess;goalAccess;tokenPlanAccountStatusGetter;synchronizeAuth;accountIdentityGetter;authLoginEpochGetter;feedback;dailyCheckin;contextMode;constructor(t,n={}){this.cliService=t;const i=n.defaultAgentName??Jt;this.tokenPlanAccountStatusGetter=n.tokenPlanAccountStatusGetter;this.synchronizeAuth=n.synchronizeAuth;this.accountIdentityGetter=n.accountIdentityGetter;this.authLoginEpochGetter=n.authLoginEpochGetter;this.feedback=n.feedback;this.dailyCheckin=n.dailyCheckin;this.contextMode=n.contextMode??"standard";this.conversationAccess=new ke(t);this.pluginAccess=new Re(t);this.context=new be({cliService:t,...n.observability?{observability:n.observability}:{}});this.goalAccess=new Ie(this.context);this.workspaceAccess=new ve(this.context);this.sessionAccess=new we(t,i,n.onSessionDeleted);this.productAccess=new Me(this.context,i,n.workspaceDir);this.interactionAccess=new Pe(n.createQueueRequestId??ls,t);this.eventAccess=new Te(t,n.observability);this.delegationAccess=new Ae({listSessionPage:s=>this.sessionAccess.listSessionPage(s),abortSession:s=>this.abortSession(s)})}sendMessage(t,n,i){return this.conversationAccess.sendMessage(t,n,i)}abortSession(t){return this.conversationAccess.abortSession(t)}steer(t){return this.conversationAccess.steer(t)}async createSession(t){const n=this.contextMode==="lightweight"&&!t.parentSessionId&&!t.purpose?{...t,purpose:_t}:t;const i=await this.productAccess.listModels().then(r=>r.find(a=>a.selected===true)).catch(()=>void 0);if(!i)return this.sessionAccess.createSession(n);const s=bt(i)?.trim();return this.sessionAccess.createSession(n,{providerId:i.providerId,modelId:i.modelId,...i.variant!==void 0?{variant:i.variant}:{},...i.contextLimit!==void 0?{contextLimit:i.contextLimit}:{},...s?{thinking:{effort:s}}:{}})}configureSessionMcpServers(t,n){return this.sessionAccess.configureSessionMcpServers(t,n)}clearSessionMcpServers(t){return this.sessionAccess.clearSessionMcpServers(t)}listSessions(t,n){return this.sessionAccess.listSessions(t,n)}listSessionPage(t,n){return this.sessionAccess.listSessionPage(t,n)}getSession(t){return this.sessionAccess.getSession(t)}getMessages(t,n){return this.sessionAccess.getMessages(t,n)}listMessagePage(t,n){return this.sessionAccess.listMessagePage(t,n)}getSessionForkOptions(t,n){return this.sessionAccess.getSessionForkOptions(t,n)}forkSession(t){return this.sessionAccess.forkSession(t)}renameSession(t,n){return this.sessionAccess.renameSession(t,n)}archiveSession(t,n){return this.sessionAccess.archiveSession(t,n)}deleteSession(t){return this.sessionAccess.deleteSession(t)}listSessionInputSummaries(t,n){return this.sessionAccess.listSessionInputSummaries(t,n)}getSessionRewindPreview(t){return this.sessionAccess.getSessionRewindPreview(t)}rewindSession(t){return this.sessionAccess.rewindSession(t)}editSessionMessage(t){return this.sessionAccess.editSessionMessage(t)}isGoalEnabled(){return this.goalAccess.isEnabled()}getGoal(t){return this.goalAccess.get(t)}createGoal(t){return this.goalAccess.create(t)}patchGoal(t,n){return this.goalAccess.patch(t,n)}clearGoal(t){return this.goalAccess.clear(t)}getWorkspaceGitMetadata(t){return this.workspaceAccess.getWorkspaceGitMetadata(t)}listWorkspaceFileTree(t,n,i){return this.workspaceAccess.listWorkspaceFileTree(t,n,i)}searchWorkspaceFiles(t,n,i,s){return this.workspaceAccess.searchWorkspaceFiles(t,n,i,s)}listWorkspaceFileTreeCandidates(t,n){return this.workspaceAccess.listWorkspaceFileTreeCandidates(t,n)}searchWorkspaceFileCandidates(t,n){return this.workspaceAccess.searchWorkspaceFileCandidates(t,n)}async getAccountStatus(t,n){let i=await this.productAccess.getAccountStatus(t,n);const s=i.modelSource?i.modelSource==="token-plan":i.authMode==="managed-login";const r=()=>i.loginEpoch!==void 0&&i.loginEpoch!==this.authLoginEpochGetter?.();if(this.synchronizeAuth&&(s||n?.requireManagedAuth||r())){await this.synchronizeAuth();i=await this.productAccess.getAccountStatus(t,n)}const a=i.loginEpoch===void 0||i.loginEpoch===this.authLoginEpochGetter?.();if(!a){return{...i,warnings:[...i.warnings,us]}}const o=i.managedTokenPresent?this.accountIdentityGetter?.():void 0;if(o)i={...i,identity:{email:o.email,name:o.name}};const d=n?.includeMembership!==false;const c=n?.includeMembership===true;if(!d||!c&&(i.modelSource!=="token-plan"||i.managedTokenPresent!==true)||!this.tokenPlanAccountStatusGetter){return i}const l=await(n?.forceRefresh?this.tokenPlanAccountStatusGetter({forceRefresh:true}):this.tokenPlanAccountStatusGetter()).catch(()=>void 0);if(!l)return i;return{...i,...l.quotaState?{tokenPlanQuotaState:l.quotaState}:{},...l.quota?{tokenPlanQuota:l.quota}:{},...c&&l.summary?{tokenPlanSummary:l.summary}:{}}}getRuntimeDiagnostics(){return this.productAccess.getRuntimeDiagnostics()}getInstructionSources(t){return this.productAccess.getInstructionSources(t)}async prepareFeedback(t){if(!this.feedback)throw new Error("MiniMax Code feedback is unavailable.");return this.feedback.prepare(t)}submitFeedback(t,n){if(!this.feedback)return Promise.reject(new Error("MiniMax Code feedback is unavailable."));return this.feedback.submit(t,n)}cancelFeedback(t){if(!this.feedback)return Promise.resolve(false);return Promise.resolve(this.feedback.cancel(t))}runDailyCheckin(){if(!this.dailyCheckin){return Promise.reject(new Error("Daily check-in is unavailable."))}return this.dailyCheckin.run()}getPermissionMode(){return this.productAccess.getPermissionMode()}setPermissionMode(t){return this.productAccess.setPermissionMode(t)}bindSessionPermissionMode(t,n,i){return Ye(()=>this.cliService.bindSessionPermissionMode(t,n,i))}setSessionPermissionMode(t,n){return Ye(()=>this.cliService.setSessionPermissionMode(t,n))}getSessionPermissionMode(t){return Ye(()=>this.cliService.getSessionPermissionMode(t))}getDangerousCommandGateEnabled(){return this.productAccess.getDangerousCommandGateEnabled()}setDangerousCommandGateEnabled(t){return this.productAccess.setDangerousCommandGateEnabled(t)}getSandboxFilesystemMode(){return this.productAccess.getSandboxFilesystemMode()}setSandboxFilesystemMode(t){return this.productAccess.setSandboxFilesystemMode(t)}listModels(t){return this.productAccess.listModels(t)}selectModel(t,n){return this.productAccess.selectModel(t,n)}selectSessionModel(t,n){return this.productAccess.selectSessionModel(t,n)}setModelFavorite(t,n){return this.productAccess.setModelFavorite(t,n)}listUserModelProviders(){return this.productAccess.listUserModelProviders()}listProviderPresets(){return this.productAccess.listProviderPresets()}getCodexOAuthStatus(){return this.productAccess.getCodexOAuthStatus()}startCodexOAuthLogin(t){return this.productAccess.startCodexOAuthLogin(t)}cancelCodexOAuthLogin(t){return this.productAccess.cancelCodexOAuthLogin(t)}getMiniMaxApiKeyStatus(){return this.productAccess.getMiniMaxApiKeyStatus()}getMiniMaxModelSource(){return this.productAccess.getMiniMaxModelSource()}setMiniMaxModelSource(t){return this.productAccess.setMiniMaxModelSource(t)}upsertMiniMaxApiKey(t){return this.productAccess.upsertMiniMaxApiKey(t)}createUserModelProvider(t){return this.productAccess.createUserModelProvider(t)}discoverUserModelsCandidate(t){return this.productAccess.discoverUserModelsCandidate(t)}saveUserModelProviderCandidate(t){return this.productAccess.saveUserModelProviderCandidate(t)}updateUserModelProvider(t){return this.productAccess.updateUserModelProvider(t)}deleteUserModelProvider(t){return this.productAccess.deleteUserModelProvider(t)}testUserModelProvider(t){return this.productAccess.testUserModelProvider(t)}testUserModel(t,n){return this.productAccess.testUserModel(t,n)}getSessionUsage(t){return this.productAccess.getSessionUsage(t)}getSessionUsageSummary(t){return this.productAccess.getSessionUsageSummary(t)}getSessionCacheWarmingStatus(t){return this.productAccess.getSessionCacheWarmingStatus(t)}watchSessionUsageCommits(t){return this.eventAccess.watchSessionUsageCommits(t)}requestCompaction(t,n,i){return this.productAccess.requestCompaction(t,n,i)}getContextSnapshot(t){return this.productAccess.getContextSnapshot(t)}getActiveRun(t){return this.productAccess.getActiveRun(t)}listSkills(t,n,i){return this.productAccess.listSkills(t,n,i)}inspectProjectMcp(t){return this.productAccess.inspectProjectMcp(t)}listMcpServers(t,n){return this.productAccess.listMcpServers(t,n)}listInstalledPlugins(t){return this.pluginAccess.listInstalledPlugins(t)}listMarketplacePlugins(t){return this.pluginAccess.listMarketplacePlugins(t)}mutatePlugin(t){return this.pluginAccess.mutatePlugin(t)}refreshPlugins(){return this.pluginAccess.refreshPlugins()}listQueuedMessages(t){return this.interactionAccess.listQueuedMessages(t)}getQueueSnapshot(t){return this.interactionAccess.getQueueSnapshot(t)}getTurnStatus(t){return this.interactionAccess.getTurnStatus(t)}continueQueue(t){return this.interactionAccess.continueQueue(t)}steerQueuedMessage(t,n){return this.interactionAccess.steerQueuedMessage(t,n)}enqueueMessage(t,n,i){return this.interactionAccess.enqueueMessage(t,n,i)}updateQueuedMessageContent(t,n,i){return this.interactionAccess.updateQueuedMessageContent(t,n,i)}deleteQueuedMessage(t,n){return this.interactionAccess.deleteQueuedMessage(t,n)}getPendingQuestionnaire(t,n,i){return this.interactionAccess.getPendingQuestionnaire(t,n,i)}getLatestPlanReview(t,n,i){return this.interactionAccess.getLatestPlanReview(t,n,i)}getPlanModeCapabilities(){return this.interactionAccess.getPlanModeCapabilities()}replyQuestionnaire(t,n,i){return this.interactionAccess.replyQuestionnaire(t,n,i)}dismissQuestionnaire(t,n){return this.interactionAccess.dismissQuestionnaire(t,n)}listPendingPermissions(t){return this.interactionAccess.listPendingPermissions(t)}replyPermission(t,n,i){return this.interactionAccess.replyPermission(t,n,i)}watchEvents(t){return this.eventAccess.watch(t)}watchSessionTurn(t,n,i,s){return this.conversationAccess.resumeSession({id:t,...s?.afterMsgId?{afterMsgId:s.afterMsgId}:{},...s?.afterCursor?{afterCursor:s.afterCursor}:{}},n,i)}getDelegationSnapshot(t){return this.delegationAccess.getSnapshot(t)}async listBackgroundTasks(t,n){const i=["queued","running","stopping"];const s=["succeeded","failed","canceled","lost"];void n;const r=["bash","workflow","custom","subagent"];const[a,o]=await Promise.all([this.cliService.listBackgroundTasks({ownerSessionId:t,statuses:i,kinds:[...r],limit:100}),this.cliService.listBackgroundTasks({ownerSessionId:t,statuses:s,kinds:[...r],limit:100})]);const d=new Map([...a,...o].map(c=>[c.taskId,c]));return[...d.values()].sort((c,l)=>l.updatedAt-c.updatedAt).map(c=>({taskId:c.taskId,kind:c.kind,status:c.status,ownerSessionId:c.ownerSessionId,...c.description?{description:c.description}:{},...c.kind==="bash"&&typeof c.metadata?.command==="string"?{command:c.metadata.command}:{},createdAtMs:c.createdAt,updatedAtMs:c.updatedAt,...c.startedAt!==void 0?{startedAtMs:c.startedAt}:{},...c.endedAt!==void 0?{endedAtMs:c.endedAt}:{},...c.deliveredAt!==void 0?{deliveredAtMs:c.deliveredAt}:{},...c.lastError?.message?{lastError:c.lastError.message}:{},...c.kind==="bash"&&c.metadata?.executionMode==="managed_foreground"?{foreground:true}:{}}))}stopDelegation(t){return this.delegationAccess.stop(t)}};function ls(){return`minimax-code_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}async function Ye(e){try{return await e()}catch(t){if(typeof t==="object"&&t!==null&&t.code==="METHOD_NOT_ALLOWED"){throw new cn(t)}throw t}}import{performance as Z}from"node:perf_hooks";import{join as tr}from"node:path";import{open as ps,readFile as gs,readdir as fs,stat as hs}from"node:fs/promises";import{join as H}from"node:path";var jn=pi(gi(),1);var Nn={role:["user","assistant","system","tool"],level:["trace","debug","info","warn","error","fatal"],status:["pending","running","completed","failed","cancelled","error","success"],name:["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError"],code:["ECONNRESET","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","EAI_AGAIN","EPIPE"]};var ms=new Set(["manifest.json","messages.jsonl","display.jsonl","ledger.jsonl","snapshot.json","llm-call.json","task-agent-definition.json","session-report-collection.json"]);function Gn(e,t){const n={};let i=0;let s=0;let r=1e5;let a=false;function o(u,h){const f=n[u]??(n[u]={});f[h]=(f[h]??0)+1}function d(u,h){if(r--<=0||h>32){a=true;return}if(!u||typeof u!=="object")return;if(Array.isArray(u)){for(const f of u){if(r<=0){a=true;break}d(f,h+1)}return}for(const[f,g]of Object.entries(u)){if(r<=0){a=true;break}const S=Object.hasOwn(Nn,f)?Nn[f]:void 0;if(typeof g==="string"&&S?.includes(g))o(f,g);if((f==="status"||f==="statusCode")&&typeof g==="number"&&Number.isInteger(g)&&g>=100&&g<=599){o("httpStatus",String(g))}d(g,h+1)}}function c(u){if(!u.trim())return;if(r<=0){a=true;return}try{d(JSON.parse(u),0);i+=1}catch{s+=1}}if(t.endsWith(".json"))c(e);else for(const u of e.split("\n"))c(u);const l=t.split("/").at(-1)??"";return JSON.stringify({schemaVersion:1,redactionPolicy:"diagnostic-counts-v1",sourceKind:ms.has(l)?l:"other",contentOmitted:true,parsedRecords:i,omittedRecords:s,limited:a,counts:n})}var ys=2*24*60*60*1e3;var Ss=64;var Bn=16*1024*1024;var Ze=2*1024*1024;var Ts={cn:{dev:"https://matrix-test.example.invalid",test:"https://matrix-test.example.invalid",staging:"https://matrix-pre.example.invalid",prod:"https://agent.minimaxi.com"},en:{dev:"https://matrix-overseas-test.example.invalid",test:"https://matrix-overseas-test.example.invalid",staging:"https://matrix-overseas-pre.example.invalid",prod:"https://agent.minimax.io"}};async function Vn(e,t){const n=t.fetchImpl??globalThis.fetch;const i=(t.nowMs??Date.now)();await t.flushLogs?.();e.signal.throwIfAborted();const s=[];let r=[];try{r=await ws(e,t)}catch(N){if(e.signal.aborted)throw N;s.push({name:"session",reason:"session_report_unavailable"})}const a=await bs(t.dataDir,i-ys,e.signal);const o=[...r,...a];const d=new jn.default;let c=0;let l=0;let u=0;for(const[N,A]of o.entries()){const de=A.required?"session":A.name.split("/")[0];const Q=`${de}/artifact-${N+1}.json`;const K=A.required?A.sizeBytes:Math.min(A.sizeBytes,Ze);if(l+K>Bn){s.push({name:Q,reason:"diagnostic_bundle_too_large"});continue}l+=K;let G;try{G=await vs(A,e.signal)}catch($){if(e.signal.aborted)throw $;s.push({name:Q,reason:"read_failed"});continue}const V=Buffer.from(Gn(G,A.name),"utf8");if(c+V.byteLength>Bn){s.push({name:Q,reason:"diagnostic_bundle_too_large"});continue}c+=V.byteLength;d.file(Q,V);u+=1}d.file("diagnostic-manifest.json",JSON.stringify({schemaVersion:2,redactionPolicy:"diagnostic-counts-v1",contentOmitted:true,createdAtMs:i,totalFiles:u,totalBytes:c,context:{clientVersion:/^\d{1,5}\.\d{1,5}\.\d{1,5}$/u.test(t.appVersion)?t.appVersion:"unknown"},skipped:s},null,2));const h=await d.generateAsync({type:"nodebuffer",compression:"DEFLATE",compressionOptions:{level:9}});e.signal.throwIfAborted();const f=(t.region??L)();const g=(t.buildEnv??j)();const S=Ts[f][g];const b=await n(`${S}/matrix/api/v1/log/upload`,{method:"POST",headers:{"User-Agent":me("MiniMaxAgent"),Origin:S,Referer:`${S}/`,"Content-Type":"application/json"},body:JSON.stringify({device_id:"0",base_file_name:`mcode-feedback-${ks(i)}.zip`}),signal:e.signal});if(!b.ok){throw new Error(`Feedback diagnostic presign failed with HTTP ${b.status}.`)}const M=await Ms(b);const D=Ps(M.upload_id??M.uploadId);const v=As(M.upload_url??M.uploadUrl);if(!D||!v){throw new Error("Feedback diagnostic upload returned an invalid upload receipt.")}const P=await n(v,{method:"PUT",body:new Uint8Array(h),signal:e.signal});if(!P.ok){throw new Error(`Feedback diagnostic upload failed with HTTP ${P.status}.`)}return{uploadId:D}}async function bs(e,t,n){const i=H(e,"v2","observability");const s=H(i,"logs");const r=[{directory:s,prefix:"runtime/",matches:o=>/^(?:local-runtime|runtime|im-runtime)-.*\.log$/u.test(o)||/^local-proxy-.*\.jsonl$/u.test(o),recursive:true},{directory:H(i,"mcode"),prefix:"mcode/",matches:o=>/^mcode-observability-.*\.jsonl$/u.test(o)},{directory:H(i,"events"),prefix:"runtime-events/",matches:o=>/^runtime-events-\d{4}-\d{2}-\d{2}(?:\.\d+)?\.jsonl$/u.test(o),recursive:true},{directory:H(e,"logs"),prefix:"cli/",matches:o=>o==="cli.log"||/^tui-terminal-.*\.log$/u.test(o)},{directory:H(i,"cli","incidents"),prefix:"cli/incidents/",matches:o=>o.endsWith(".json")}];const a=[];for(const o of r){n.throwIfAborted();await Qn(o,o.directory,"",t,n,a)}return a.sort((o,d)=>d.modifiedAtMs-o.modifiedAtMs||o.name.localeCompare(d.name)).slice(0,Ss)}async function Qn(e,t,n,i,s,r){const a=await fs(t,{withFileTypes:true}).catch(()=>[]);for(const o of a){s.throwIfAborted();const d=n?`${n}/${o.name}`:o.name;const c=H(t,o.name);if(o.isDirectory()&&e.recursive){await Qn(e,c,d,i,s,r);continue}if(!o.isFile()||!e.matches(o.name,d))continue;let l;try{l=await hs(c)}catch(u){if(s.aborted)throw u;continue}if(!l.isFile()||l.mtimeMs<i)continue;r.push({name:`${e.prefix}${d}`,sourcePath:c,modifiedAtMs:l.mtimeMs,sizeBytes:l.size,required:false,wholeFile:Wn(o.name)})}}async function vs(e,t){t.throwIfAborted();if(e.content!==void 0)return e.content;if(!e.sourcePath)throw new Error(`Diagnostic artifact has no source: ${e.name}`);if(e.required)return gs(e.sourcePath,"utf8");if(e.wholeFile&&e.sizeBytes>Ze){throw new Error("diagnostic_single_json_too_large")}const n=Math.min(e.sizeBytes,Ze);const i=e.sizeBytes>n;const s=Buffer.alloc(n);const r=await ps(e.sourcePath,"r");try{const a=await r.read(s,0,n,Math.max(0,e.sizeBytes-n));t.throwIfAborted();const o=s.subarray(0,a.bytesRead).toString("utf8");if(!i)return o;const d=o.indexOf("\n");return d>=0?o.slice(d+1):o}finally{await r.close()}}async function ws(e,t){if(!e.sessionId)return[];if(!t.collectSessionReport){throw new Error("session_report_capability_unavailable")}const n=await t.collectSessionReport(e.sessionId);return n.artifacts.map(i=>({name:i.name,...i.path?{sourcePath:i.path}:{},...i.content!==void 0?{content:i.content}:{},modifiedAtMs:0,sizeBytes:i.bytes,required:true,wholeFile:Wn(i.name)}))}function Wn(e){return e.endsWith(".json")&&!e.endsWith(".jsonl")}async function Ms(e){try{const t=JSON.parse(await e.text());return t!==null&&typeof t==="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Ps(e){if(typeof e==="number")return Number.isSafeInteger(e)&&e>0?String(e):void 0;return typeof e==="string"&&e.trim()?e.trim():void 0}function As(e){if(typeof e!=="string")return void 0;try{const t=new URL(e);return t.protocol==="https:"?t.toString():void 0}catch{return void 0}}function ks(e){const t=new Date(e);return[t.getUTCFullYear(),String(t.getUTCMonth()+1).padStart(2,"0"),String(t.getUTCDate()).padStart(2,"0"),String(t.getUTCHours()).padStart(2,"0"),String(t.getUTCMinutes()).padStart(2,"0"),String(t.getUTCSeconds()).padStart(2,"0")].join("")}import{randomUUID as ti}from"node:crypto";import{release as Ds}from"node:os";import{createHash as Rs}from"node:crypto";var Is={cn:{dev:"https://matrix-test.example.invalid",test:"https://matrix-test.example.invalid",staging:"https://matrix-pre.example.invalid",prod:"https://agent.minimaxi.com"},en:{dev:"https://matrix-overseas-test.example.invalid",test:"https://matrix-overseas-test.example.invalid",staging:"https://matrix-overseas-pre.example.invalid",prod:"https://agent.minimax.io"}};function xe(e){const t=(e.region??L)();const n=(e.buildEnv??j)();return Is[t][n]}function re(e){const t=new URL(e.endpoint);const n=e.region==="cn"?"zh":"en";t.search=new URLSearchParams({...e.query,device_platform:"web",biz_id:"3",app_id:"3001",version_code:"22201",is_desktop:"1",desktop_version:e.appVersion.trim(),unix:String(e.nowMs),timezone_offset:String(new Date().getTimezoneOffset()*-60),sys_language:n,lang:n,device_id:"0",os_name:process.platform,browser_name:"mcode",user_id:e.realUserID.trim(),client:"mcode"}).toString();const i=e.body??"";const s=e.body??"{}";const r=Math.floor(e.nowMs/1e3);const a=`${t.pathname}${t.search}`;return{url:t,...e.body===void 0?{}:{body:e.body},headers:{Accept:"application/json","Content-Type":"application/json","User-Agent":me("MiniMaxCode"),Authorization:`Bearer ${e.token}`,yy:et(`${encodeURIComponent(a)}_${s}${et(String(e.nowMs))}ooui`),"x-timestamp":String(r),"x-signature":et(`${r}I*7Cf%WZ#S&%1RlZJ&C2${i}`)}}}function et(e){return Rs("md5").update(e).digest("hex")}var Cs=1;function nt(e){if(e.endpoint)return e.endpoint;return`${xe(e)}/minimax-cloud/api/v1/feedback/ticket`}function $n(e,t){return{description:e.description,contact:"",task_context:{...e.sessionId?{session_id:e.sessionId}:{},client_type:Cs,client_version:k(t),os:k(e.platform.platform),os_version:k(e.platform.osVersion)},screenshots:[],upload_diagnostic_log:Boolean(e.diagnosticUploadId),...e.diagnosticUploadId?{diagnostic_log:{upload_id:e.diagnosticUploadId}}:{}}}function zn(e){const t=JSON.stringify(e.payload);const n=re({endpoint:e.endpoint,token:e.token,realUserID:e.realUserID,appVersion:k(e.appVersion),region:e.region,nowMs:e.nowMs,body:t});return{...n,body:t}}function Hn(e){return re({endpoint:e.endpoint,token:e.token,realUserID:e.realUserID,appVersion:k(e.appVersion),region:e.region,nowMs:e.nowMs,query:{limit:String(e.limit)}})}async function Kn(e){const t=await Zn(e);const n=E(t.data);const i=E(t.statusInfo)??E(t.status_info)??E(n?.statusInfo)??E(n?.status_info);const s=E(t.base_resp)??E(n?.base_resp);if(typeof i?.code==="number"&&i.code!==0||typeof s?.status_code==="number"&&s.status_code!==0){throw new Error(_s(e.status,t,i,s))}const r=oe(t.ticket_id)??oe(n?.ticket_id);const a=t.status??n?.status;const o=tt(t.created_at)??tt(n?.created_at);return{schemaVersion:1,...r?{ticketId:r}:{},status:a===1||a==="processing"?"processing":a===2||a==="resolved"?"resolved":"unknown",...o!==void 0?{createdAtMs:o}:{}}}async function Jn(e){const t=await e.text().catch(()=>"");const n=["x-request-id","x-trace-id","trace-id"].flatMap(i=>{const s=e.headers.get(i)?.trim();return s?[`${i}=${k(s)}`]:[]}).join("; ");return[`Feedback POST returned HTTP ${e.status}${e.statusText?` ${k(e.statusText)}`:""}.`,...n?[`Trace: ${n}.`]:[],`Response body: ${ei(t||"<empty>")}.`].join(" ")}async function Xn(e,t){if(!e.ok)return void 0;const n=await Zn(e);const i=E(n.data);if(xs(n,i))return void 0;const s=Array.isArray(n.tickets)?n.tickets:Array.isArray(i?.tickets)?i.tickets:[];const r=t.submittedAtMs-5e3;const a=t.nowMs+3e4;for(const o of s){const d=E(o);if(!d||oe(d.description)!==t.description)continue;const c=oe(d.ticket_id);const l=tt(d.created_at);if(!c||l===void 0||l<r||l>a){continue}return{schemaVersion:1,ticketId:c,status:Es(d.status),createdAtMs:l}}return void 0}function k(e){return Wt(e.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu,"")).trim()}function Yn(e){if(typeof e==="number")return Number.isSafeInteger(e)&&e>0?String(e):void 0;return oe(e)}async function Zn(e){try{const t=await e.text();return t?E(JSON.parse(t))??{}:{}}catch{return{}}}function E(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)?e:void 0}function oe(e){return typeof e==="string"&&e.trim()?e.trim():void 0}function tt(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function xs(e,t){const n=E(e.statusInfo)??E(e.status_info)??E(t?.statusInfo)??E(t?.status_info);if(typeof n?.code==="number"&&n.code!==0)return true;const i=E(e.base_resp)??E(t?.base_resp);return typeof i?.status_code==="number"&&i.status_code!==0}function Es(e){if(e===1||e==="processing")return"processing";if(e===2||e==="resolved")return"resolved";return"unknown"}function _s(e,t,n,i){const s=[`HTTP ${e}`,...n?.code!==void 0?[`statusInfo.code=${String(n.code)}`]:[],...n?.message!==void 0?[`statusInfo.message=${k(String(n.message))}`]:[],...i?.status_code!==void 0?[`base_resp.status_code=${String(i.status_code)}`]:[],...i?.status_msg!==void 0?[`base_resp.status_msg=${k(String(i.status_msg))}`]:[]];return`Feedback POST business rejection: ${s.join("; ")}. Response body: ${ei(JSON.stringify(t))}.`}function ei(e){const t=k(e.replace(/("(?:api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|token|password|secret)"\s*:\s*)"[^"]*"/giu,'$1"[redacted]"'));const n=Array.from(t);return n.length<=4e3?t:`${n.slice(0,4e3).join("")}\u2026 [truncated]`}var Ee=class extends Error{constructor(n,i,s,r){super(n);this.code=i;this.statusCode=s;this.retryable=r}code;statusCode;retryable;name="TuiFeedbackError"};var Os=18e4;var Ls=15*6e4;var Us=32;var Fs=20;var _e=class{constructor(t){this.options=t;this.fetchImpl=t.fetchImpl??globalThis.fetch;this.nowMs=t.nowMs??Date.now;this.createDraftId=t.createDraftId??(()=>`feedback_${ti()}`);this.timeoutMs=ni(t.timeoutMs,Os);this.draftTtlMs=ni(t.draftTtlMs,Ls);this.platform=t.platform??(()=>({platform:process.platform,arch:process.arch,nodeVersion:process.versions.node,osVersion:Ds()}))}options;drafts=new Map;fetchImpl;nowMs;createDraftId;timeoutMs;draftTtlMs;platform;prepare(t){this.pruneExpiredDrafts();const n=qs(t.description);const i=Ns(t.sessionId);const s=this.platform();const r=this.nowMs();const a=this.uniqueDraftId();const o={schemaVersion:1,draftId:a,description:n,diagnostics:[{label:"Client",value:`mcode ${k(this.options.appVersion)}`},{label:"Runtime",value:"clean \xB7 cli"},{label:"Platform",value:`${k(s.platform)} ${k(s.arch)} \xB7 Node ${k(s.nodeVersion)}`},{label:"OS",value:k(s.osVersion)},{label:"Session",value:i??"not included"}],diagnosticBundleIncluded:Boolean(this.options.diagnosticLogUploader),included:["reviewed feedback description with recognized credentials redacted","bounded client, Runtime, platform, and optional Session metadata",...this.options.diagnosticLogUploader?["diagnostic counts from the selected Session subtree (including messages, snapshots, and report artifacts); original contents and filenames are omitted","bounded diagnostic counts from Runtime, CLI, and terminal logs and events from the last 2 days","only known roles, states, error types/codes, HTTP statuses, and parse/omission counts are retained"]:[]],excluded:["stored credentials and authentication files","raw attachments, prompts, conversation text, tool arguments/results, local paths, file contents, and free-text errors",...this.options.diagnosticLogUploader?["unrelated sessions, workspace files, and config files"]:["canonical full conversation and tool-call history (messages.jsonl)","file contents and diagnostic log bodies","workspace and config file contents"]],expiresAtMs:r+this.draftTtlMs};this.makeDraftCapacity();this.drafts.set(a,{preview:o,...i?{sessionId:i}:{},platform:s,cancelled:false});return structuredClone(o)}async submit(t,n={}){const i=this.requireDraft(t);if(i.receipt)return structuredClone(i.receipt);if(i.activeController)throw _("Feedback upload is already in progress.","feedback_upload_failed",409,true);ae(n,"preparing");const s=n.signal;let r=this.options.authContextGetter();let a=r?.accessToken?.trim();if(!a)throw _("MiniMax Code sign-in is required. Run /login, then retry.","feedback_login_required",401,true);const o=new AbortController;i.activeController=o;i.cancelled=false;let d=false;const c=setTimeout(()=>{d=true;o.abort(new DOMException("Feedback upload timed out.","TimeoutError"))},this.timeoutMs);c.unref?.();const l=()=>o.abort(s?.reason);if(s?.aborted)l();else s?.addEventListener("abort",l,{once:true});let u;let h;let f;try{if(!r?.realUserID?.trim()&&this.options.authContextResolver){r=await this.options.authContextResolver({forceRefresh:false,signal:o.signal});a=r?.accessToken?.trim()}const g=r?.realUserID?.trim();if(!a)throw _("MiniMax Code sign-in is required. Run /login, then retry.","feedback_login_required",401,true);if(!g)throw _("MiniMax Code account identity is not ready. Check the connection, then retry.","feedback_upload_failed",503,true);h=a;f=g;if(this.options.diagnosticLogUploader){ae(n,"uploading-diagnostics")}await this.uploadDiagnostics(i,o.signal);ae(n,"creating-ticket");const S=$n({description:i.preview.description,...i.sessionId?{sessionId:i.sessionId}:{},platform:i.platform,...i.diagnosticUploadId?{diagnosticUploadId:i.diagnosticUploadId}:{}},this.options.appVersion);u=this.nowMs();let b=await this.submitTicket(S,a,g,o.signal);if(b.status===401&&this.options.authContextResolver){const D=await this.options.authContextResolver({forceRefresh:true,signal:o.signal});const v=D?.accessToken?.trim();const P=D?.realUserID?.trim();if(v&&P){h=v;f=P;b=await this.submitTicket(S,v,P,o.signal)}}if(!b.ok){throw await Gs(b)}const M=await Kn(b);i.receipt={...M,...i.diagnosticUploadId?{uploadId:i.diagnosticUploadId}:{}};ae(n,"completed");return structuredClone(i.receipt)}catch(g){const S=Bs(g);if(u!==void 0&&h&&f&&!d&&!i.cancelled&&!s?.aborted){const b=await this.confirmSubmittedTicket(i,u,h,f,o.signal);if(b){i.receipt={...b,...i.diagnosticUploadId?{uploadId:i.diagnosticUploadId}:{}};ae(n,"completed");return structuredClone(i.receipt)}}if(g instanceof Ee)throw g;if(d)throw _("Feedback upload timed out. Press Enter to retry.","feedback_timeout",504,true);if(i.cancelled||s?.aborted)throw _("Feedback upload was cancelled.","feedback_cancelled",499,false);if(g instanceof TypeError)throw _(`Feedback POST network error: ${S}`,"feedback_offline",503,true);throw _(S||"Feedback upload failed without an error detail.","feedback_upload_failed",502,true)}finally{clearTimeout(c);s?.removeEventListener("abort",l);i.activeController=void 0}}async submitTicket(t,n,i,s){const r=zn({endpoint:nt(this.options),payload:t,token:n,realUserID:i,appVersion:this.options.appVersion,region:(this.options.region??L)(),nowMs:this.nowMs()});return this.fetchImpl(r.url,{method:"POST",headers:r.headers,body:r.body,signal:s})}async confirmSubmittedTicket(t,n,i,s,r){try{const a=this.nowMs();const o=Hn({endpoint:nt(this.options),token:i,realUserID:s,appVersion:this.options.appVersion,region:(this.options.region??L)(),nowMs:a,limit:Fs});const d=await this.fetchImpl(o.url,{method:"GET",headers:o.headers,signal:r});return Xn(d,{description:t.preview.description,submittedAtMs:n,nowMs:a})}catch{return void 0}}cancel(t){const n=this.drafts.get(t);if(!n)return false;n.cancelled=true;n.activeController?.abort(new DOMException("Feedback upload cancelled.","AbortError"));this.drafts.delete(t);return true}async uploadDiagnostics(t,n){if(!this.options.diagnosticLogUploader||t.diagnosticUploadId)return;try{const i=await this.options.diagnosticLogUploader({description:t.preview.description,...t.sessionId?{sessionId:t.sessionId}:{},signal:n});const s=Yn(i.uploadId);if(!s)throw new Error("Feedback diagnostic upload returned an invalid receipt.");t.diagnosticUploadId=s}catch(i){if(n.aborted)throw i}}requireDraft(t){this.pruneExpiredDrafts();const n=this.drafts.get(t);if(!n)throw _("Feedback draft was not found or has expired.","feedback_not_found",404,false);return n}uniqueDraftId(){for(let t=0;t<4;t+=1){const n=this.createDraftId();if(n&&!this.drafts.has(n))return n}return`feedback_${ti()}`}pruneExpiredDrafts(){const t=this.nowMs();for(const[n,i]of this.drafts){if(i.preview.expiresAtMs>t)continue;this.cancel(n)}}makeDraftCapacity(){while(this.drafts.size>=Us){const t=this.drafts.keys().next().value;if(!t)return;this.cancel(t)}}};function qs(e){const t=k(e.trim());if(!t)throw _("Feedback description is required.","feedback_invalid_request",400,false);if(Array.from(t).length>4e3)throw _("Feedback description must be 4000 characters or fewer.","feedback_invalid_request",400,false);return t}function Ns(e){const t=e===void 0?void 0:k(e.trim());if(!t)return void 0;if(Array.from(t).length>256)throw _("Feedback session id is too long.","feedback_invalid_request",400,false);return t}async function Gs(e){const t=e.status;const n=await Jn(e);if(t===401)return _(`${n} Run /login, then retry.`,"feedback_login_required",t,true);if(t===403)return _(`${n} Feedback submission is not available for this account or environment.`,"feedback_upload_failed",t,false);if(t===408||t===504)return _(`${n} Feedback upload timed out.`,"feedback_timeout",t,true);return _(n,"feedback_upload_failed",t,t===429||t>=500)}function Bs(e){return k(e instanceof Error?e.message:String(e))}function _(e,t,n,i){return new Ee(e,t,n,i)}function ni(e,t){return e!==void 0&&Number.isFinite(e)&&e>0?Math.floor(e):t}function ae(e,t){try{e.onPhase?.(t)}catch{}}function js(e,t,n=process.env){if(t.beta?.browserUseTooling!==true)return void 0;const i=n.MCODE_CHROME_PATH?.trim()||t.browser?.chromePath?.trim();return{dataDir:e,...i?{chromePath:i}:{}}}function ii(e,t,n=process.env,i=s=>new Dt(s)){const s=js(e,t,n);return s?i(s):void 0}function si(e,t){return Ot({dataDir:e},t)}var De=class{constructor(t){this.gateway=t}gateway;pending;run(){if(this.pending)return this.pending;const t=this.runOnce().finally(()=>{if(this.pending===t)this.pending=void 0});this.pending=t;return t}async runOnce(){const t=fe(await this.gateway.getSigninPanel());if(en(t)){return{status:"already-claimed",panel:t}}if(!Zt(t)){return{status:"unavailable",panel:t}}const n=he(await this.gateway.claimSignin());if(n.claim_result===2){return{status:"already-claimed",panel:n.panel}}return{status:"claimed",dayNo:n.day_no,points:n.points,expireAtMs:n.expire_at_ms,panel:n.panel}}};var Vs="/minimax-cloud/api/v1/signin/status";var Qs="/minimax-cloud/api/v1/signin/claim";var Oe=class{constructor(t){this.options=t;this.fetchImpl=t.fetchImpl??globalThis.fetch;this.nowMs=t.nowMs??Date.now;this.timeoutMs=t.timeoutMs??3e4}options;fetchImpl;nowMs;timeoutMs;statusAccountKey;async getSigninPanel(){const{data:t,accountKey:n}=await this.request(Vs,"GET");this.statusAccountKey=n;return fe(t)}async claimSignin(){const t=await this.request(Qs,"POST",this.statusAccountKey);this.statusAccountKey=void 0;return he(t.data)}async request(t,n,i){const s=new AbortController;const r=setTimeout(()=>s.abort(),this.timeoutMs);r.unref?.();try{let a=await this.resolveAuth(false,s.signal);ri(a,i);let o=await this.fetch(t,n,a,s.signal);if(o.status===401&&this.options.authContextResolver){a=await this.resolveAuth(true,s.signal);ri(a,i);o=await this.fetch(t,n,a,s.signal)}if(!o.ok){throw new Error(`Daily check-in request failed with HTTP ${o.status}.`)}const d=await o.json();this.assertCurrentAccount(a);const c=d.base_resp?.status_code;if(typeof c==="number"&&c!==0){throw new Error(d.base_resp?.status_msg||"Daily check-in request failed.")}if(d.data===null||d.data===void 0){throw new Error("Daily check-in response data is missing.")}return{data:d.data,accountKey:oi(a)}}finally{clearTimeout(r)}}async resolveAuth(t,n){let i=t?void 0:this.options.authContextGetter();if((t||!i?.realUserID?.trim())&&this.options.authContextResolver){i=await this.options.authContextResolver({forceRefresh:t,signal:n})}const s=i?.accessToken?.trim();const r=i?.realUserID?.trim();if(!s||!r){throw new Error("MiniMax Code sign-in is required. Run /login, then retry /checkin.")}return{accessToken:s,realUserID:r}}fetch(t,n,i,s){const r=(this.options.region??L)();const a=this.options.origin??xe({region:()=>r,buildEnv:this.options.buildEnv??j});const o=n==="POST"?"{}":void 0;const d=re({endpoint:`${a}${t}`,token:i.accessToken,realUserID:i.realUserID,appVersion:this.options.appVersion,region:r,nowMs:this.nowMs(),...o?{body:o}:{}});return this.fetchImpl(d.url,{method:n,headers:d.headers,...d.body?{body:d.body}:{},signal:s})}assertCurrentAccount(t){const n=this.options.authContextGetter();if(!n?.accessToken?.trim()||n.realUserID?.trim()!==t.realUserID){throw new Error("MiniMax account changed during daily check-in. Retry /checkin.")}}};function oi(e){return e.realUserID}function ri(e,t){if(t&&oi(e)!==t){throw new Error("MiniMax account changed during daily check-in. Retry /checkin.")}}import{chmod as Ws,mkdtemp as $s,rm as zs}from"node:fs/promises";import{tmpdir as Hs}from"node:os";import di from"node:path";var Ks=async()=>void 0;var Js=()=>void 0;async function ci(e,t={}){const n=Xs(e.buildEnv);if(!e.requested)return ai(false,"disabled",n);const i=e.logger??{info:()=>void 0,warn:()=>void 0};const s=e.environment??process.env;const r=t.removeRuntimeDir??Zs;let a;let o;let d;try{const c=(t.validateResource??Nt)({resourceDir:Ft(e.entryUrl,s),expectedBuildEnv:n});a=await(t.createRuntimeDir??Ys)();o=await(t.startBroker??Ut)({dataDir:a,session:e.session,logger:i});const l=di.join(e.dataDir,"integrations","mcode-tools",e.region);await Gt(l);d=(t.activateEnvironment??Lt)(s,{runtimeExecutable:process.execPath,brokerEndpoint:o.endpoint,brokerCapabilityFile:o.capabilityFile,configDir:l,region:e.region,commandBinDir:qt(e.entryUrl),...e.bedrockLane?{bedrockLane:e.bedrockLane}:{}});const u=er({buildEnv:n,resource:c,broker:o,runtimeDir:a,removeRuntimeDir:r,activation:d});i.info(`mcode-tools readiness category=${u.category} buildEnv=${n} region=${e.region} version=${c.manifest.version}`);return u}catch(c){d?.restore();await o?.dispose().catch(()=>void 0);if(a)await r(a).catch(()=>void 0);const l=Bt(c);i.warn(`mcode-tools readiness category=${l} buildEnv=${n} region=${e.region}`);return ai(true,l,n)}}function Xs(e){return e==="dev"?"test":e}async function Ys(){const e=process.platform==="win32"?Hs():"/tmp";const t=await $s(di.join(e,`mcode-tools-tui-${process.pid}-`));if(process.platform!=="win32")await Ws(t,448);return t}function Zs(e){return zs(e,{recursive:true,force:true})}function er(e){let t=false;return{requested:true,ready:true,category:"ready",buildEnv:e.buildEnv,version:e.resource.manifest.version,ensureCommandPath:e.activation.ensureCommandPath,async dispose(){if(t)return;t=true;e.activation.restore();const n=[];try{await e.broker.dispose()}catch(i){n.push(i)}try{await e.removeRuntimeDir(e.runtimeDir)}catch(i){n.push(i)}if(n.length===1)throw n[0];if(n.length>1)throw new AggregateError(n,"mcode-tools TUI cleanup failed")}}}function ai(e,t,n){return{requested:e,ready:false,category:t,buildEnv:n,ensureCommandPath:Js,dispose:Ks}}var nr=6e4;var ui=vt("mcode:tui-lifecycle");async function Ta(e,t={}){const n=Ne({profile:e.profile,dataDir:e.dataDir,env:process.env});const i=e.noDaemon===true?"off":Yt();if(e.noDaemon===true){const p=process.env["MCODE_SERVER_MODE"]?.trim();if(p!==void 0&&p!==""&&p!=="off"){ui.warn("--no-daemon overrides MCODE_SERVER_MODE for this invocation",{env:p})}}{const p=qe(n.controlRoot);if(p&&Fe(p.pid)){const T=[];if(p.region!==void 0&&p.region!==L()){T.push(`region (daemon: ${p.region}, this process: ${L()})`)}if(p.buildEnv!==void 0&&p.buildEnv!==j()){T.push(`buildEnv (daemon: ${p.buildEnv}, this process: ${j()})`)}if(T.length>0){const y=`Daemon env mismatch on control root ${n.controlRoot}: ${T.join("; ")}. Restart this process with the daemon's env (e.g. MAVIS_REGION=${p.region}) or stop the daemon first: mcode daemon stop.`;if(i==="off"&&e.managementSurface!==true){ui.warn("daemon env mismatch ignored in no-daemon mode",{controlRoot:n.controlRoot,mismatches:T})}else{throw new Error(y)}}}}const s=t.getConfig??lt;const r=e.configPath??tr(e.dataDir,"config.yaml");const a=ir(r,t.readExplicitBetaFeature??pt);const o=()=>{const p=s();return{...p,beta:{...p.beta,browserUseTooling:a}}};const d=o().beta?.mcodeTools===true;const c=t.readAuthContext??rn;const l=t.importSharedAuthContext??dn;const u={region:L(),buildEnv:j()};const h=Tt(e.lane,u.buildEnv);const f=h?{bedrockLane:h}:void 0;const g=Boolean(t.sharedAuthCore)||!sr(t);let S;let b=0;let M=0;let D;let v;let P;let N=()=>void 0;let A;let de;const Q=g?()=>S:()=>c(e.dataDir,u);const K=p=>{const T=p?.accessToken?.trim();if(!T||p?.realUserID?.trim())return p;const y=(t.readVerifiedIdentity??nn)(e.dataDir,u,T);if(!y)return p;const{verifiedAtMs:U,...O}=y;void U;return{...p,...O}};const G=()=>K(Q());const V=new Vt({authContextGetter:G,...f?{routingContextGetter:()=>f}:{},region:u.region,buildEnv:u.buildEnv,...t.fetchImpl?{fetchImpl:t.fetchImpl}:{}});let $;if(g){const p=t.sharedAuthCore??tn({dataDir:e.dataDir,region:u.region,buildEnv:u.buildEnv,oauthEndpoints:ft(process.env,u)});$=p;const T=async(y,U=6e4)=>{const O=++M;const I=await rr(p,U);if(O!==M)return;if(!I){S=void 0;return}if(S?.realUserID?.trim()&&S.accessToken===I.accessToken&&b===I.generation)return;const q={accessToken:I.accessToken,loginEpoch:I.loginEpoch};S=q;b=I.generation;try{const ee=await it(V,q,u,t,y)??q;if(O===M&&b===I.generation&&S?.accessToken===I.accessToken){S={...ee,loginEpoch:I.loginEpoch}}}catch{}};A=(y,U)=>{const O=T(y,U);D=O;return O};de=async(y,U)=>{if(U.aborted)throw U.reason;if(y){const O=b;const I=S?.loginEpoch;M+=1;S=void 0;const q=await p.handleUnauthorized({generation:O,loginEpoch:I});if(q!=="retry")return void 0}await A?.(U);return S};await A().catch(()=>void 0);N=p.watch(y=>{if(!or(y)){M+=1;S=void 0;b=y.generation;return}if(y.status!=="authenticated")return;if(S&&b===y.generation)return;void A?.(void 0,0).catch(()=>void 0)})}else{const p=G()??K(l(e.dataDir,u,void 0));if(p?.accessToken){const T=await li(e.dataDir,p,u,V,t);if(!T){const y=K(l(e.dataDir,u,p.accessToken));if(y?.accessToken){await li(e.dataDir,y,u,V,t)}}}}let ce=ar(d,u.buildEnv);if(g&&$){ce=await(t.prepareMcodeToolsIntegration??ci)({requested:d,dataDir:e.dataDir,buildEnv:u.buildEnv,region:u.region,session:jt($),entryUrl:__mavis_tuiPackageEntryUrl,...h?{bedrockLane:h}:{}})}const rt=ce.ready;let ot=false;const at=async()=>{if(ot)return;ot=true;N();await ce.dispose()};const dt=p=>{if(g){const T=de;return T?T(p.forceRefresh,p.signal):Promise.resolve(void 0)}return dr(e.dataDir,u,Q,V,t,p.forceRefresh,p.signal)};const ue=e.observability===void 0;const z=e.observability??(t.createObservability??Kt)(e.dataDir,{surface:e.surface??"inspection"});const J=(t.createLogging??un)(e.dataDir);const mi={dataDir:e.dataDir,defaultWorkspaceDir:e.workspaceDir,appVersion:e.version,...e.promptMode?{promptMode:e.promptMode}:{},...e.systemPromptOverrides?{systemPromptOverrides:e.systemPromptOverrides}:{},configGetter:()=>{const p=o();return{...p,dataDir:e.dataDir,...e.permissionMode?{permissionMode:e.permissionMode}:{},beta:{...p.beta,mcodeTools:rt}}},configSource:t.configSource,authContextGetter:G,...f?{routingContextGetter:()=>f}:{},authContextInvalidator:async(p,T)=>{if(!g){st(e.dataDir,u,Q(),t);return}const y=p?.trim();const U=S?.accessToken?.trim();if(y&&U&&U!==y){return}if(!$||!A)return;while(v){const O=v;const I=P;await O;if(!y||I===y)return;const q=S?.accessToken?.trim();if(!q||q!==y)return}if(!v){const O=b;const I=T??S?.loginEpoch;if(!I||I!==S?.loginEpoch)return;M+=1;S=void 0;const q=(async()=>{try{const ee=await $.handleUnauthorized({generation:O,loginEpoch:I});if(ee!=="retry")return;await A()}catch(ee){if(ee instanceof ht)await A()}})().finally(()=>{if(v===q){v=void 0;P=void 0}});P=y;v=q}await v},capabilities:{questionnaireReply:e.surface!=="headless",permissionPrompt:e.surface!=="headless",elicitation:e.surface!=="headless"},...e.managementSurface||e.surface==="headless"||e.surface==="acp"||(t.getDataEnvironment??St)()==="test"?{startupExecutionPolicy:"quarantined"}:{}};const ct=Z.now();if(ue){z.recordStartup({phase:"runtime.initialize",outcome:"started"})}let B;const ut=e.managementSurface?qe(Ne({dataDir:e.dataDir,...e.profile?{profile:e.profile}:{}}).controlRoot):void 0;const le=e.managementSurface?ut&&Fe(ut.pid)?"required":"off":i;try{if(le==="off"){B=(t.createBrowserProvider??ii)(e.dataDir,o())}const p=await J.runDuringStartup(()=>le==="off"?Qt({...mi,...B?{browserAdapter:B}:{},productCapabilities:{mcodeTools:rt}},t.factory):Xt({dataDir:e.dataDir,daemonTargets:n,...e.managementSurface?{autoSpawn:false}:{},...e.profile?{profile:e.profile}:{},...e.promptMode!==void 0?{promptMode:e.promptMode}:{},clientKind:e.surface==="headless"?"exec":e.surface==="acp"?"acp":"tui"}));if(le!=="off"){await J.runDuringStartup(()=>p.ready)}ce.ensureCommandPath();if(ue){z.recordStartup({phase:"runtime.initialize",outcome:"succeeded",durationMs:Z.now()-ct})}return{host:p,adapter:new Ce(p.cliService,{workspaceDir:e.workspaceDir,observability:z,...e.contextMode?{contextMode:e.contextMode}:{},onSessionDeleted:B?.disposeSession?B.disposeSession.bind(B):T=>si(e.dataDir,T),...g?{synchronizeAuth:()=>A?.()??Promise.resolve()}:{},authLoginEpochGetter:()=>G()?.loginEpoch,tokenPlanAccountStatusGetter:T=>V.getTokenPlanAccountStatus(void 0,T),accountIdentityGetter:()=>{const T=G();return T?.accessToken?{email:T.userEmail,name:T.userName??T.subUserName}:void 0},dailyCheckin:new De(new Oe({appVersion:e.version,authContextGetter:G,authContextResolver:dt,...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},region:()=>u.region,buildEnv:()=>u.buildEnv})),feedback:new _e({appVersion:e.version,authContextGetter:G,authContextResolver:dt,...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},region:()=>u.region,buildEnv:()=>u.buildEnv,diagnosticLogUploader:T=>Vn(T,{dataDir:e.dataDir,appVersion:e.version,...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},region:()=>u.region,buildEnv:()=>u.buildEnv,flushLogs:async()=>{await Promise.allSettled([z.flush(),J.flush()])},collectSessionReport:y=>{return p.cliService.collectSessionReport(y)}})})}),...B?{browserProvider:B}:{},...le!=="off"?{connection:{state:()=>p.connectionState(),onChange:T=>p.onConnectionStateChange(T)}}:{},logDirectory:J.logDirectory,observability:z,synchronizeAuthContext:async T=>{if(!g)return;if(T==="logged_out"){M+=1;S=void 0;return}let y=A?.();do{await y;if(y===D)break;y=D}while(y)},shutdownAuth:at,shutdownLogging:()=>J.shutdown()}}catch(p){if(ue){z.recordStartup({phase:"runtime.initialize",outcome:"failed",durationMs:Z.now()-ct,errorKind:cr(p)})}const T=[];try{await at()}catch(y){T.push(y)}if(B){try{await B.close()}catch(y){T.push(y)}}try{await J.shutdown()}catch(y){T.push(y)}if(ue){try{await z.flush()}catch(y){T.push(y)}}if(T.length>0){throw new AggregateError([p,...T],"Minimax Code Runtime startup cleanup failed.")}throw p}}function ir(e,t){try{return t(e,"browserUseTooling")!==false}catch{return false}}function sr(e){return Boolean(e.readAuthContext||e.importSharedAuthContext||e.renewAccessToken||e.writeAuthContext||e.invalidateAuthContext)}async function rr(e,t){try{return await e.getAccessToken({requiredScopes:[...gt],minValidityMs:t})}catch(n){if(yt(n))return void 0;throw n}}function or(e){return e.status==="authenticated"||e.status==="expired"||e.status==="refreshing"}function ar(e,t){return{requested:e,ready:false,category:e?"host_unavailable":"disabled",buildEnv:t==="dev"?"test":t,ensureCommandPath:()=>void 0,dispose:async()=>void 0}}async function li(e,t,n,i,s){let r=t;try{const a=await(s.renewAccessToken??(c=>c.renewAccessToken()))(i);r=a?{...t,accessToken:a}:t;if(a&&a!==t.accessToken){Le(e,r,n,t,s)}const o=await it(i,r,n,s,void 0,Boolean(r.realUserID?.trim()));const d=o?.accessToken?.trim();if(o?.realUserID&&d){Le(e,o,n,t,s);(s.writeVerifiedIdentity??We)(e,n,d,o)}return true}catch(a){if(!(a instanceof Ge))return true;st(e,n,r,s);return false}}async function dr(e,t,n,i,s,r,a){const o=n();const d=o?.accessToken?.trim();if(!d)return void 0;let c={...o,accessToken:d};const l=c;try{if(r){const f=await(s.renewAccessToken??(g=>g.renewAccessToken(a)))(i);if(f&&f!==d){c={...o,accessToken:f};Le(e,c,t,l,s)}}const u=await it(i,c,t,s,a);if(!u?.realUserID)return c;const h=u.accessToken?.trim();if(!h)return void 0;Le(e,u,t,l,s);(s.writeVerifiedIdentity??We)(e,t,h,u);return u}catch(u){if(!(u instanceof Ge))throw u;st(e,t,c,s);return void 0}}function Le(e,t,n,i,s){if(s.writeAuthContext){s.writeAuthContext(e,t,n);return}on(e,t,n,{expectedSharedAuth:i})}async function it(e,t,n,i,s,r=false){if(i.resolveAuthContext){return i.resolveAuthContext(e,t,s)}if(i.resolveRealUserID){const a=await i.resolveRealUserID(e,t);return a?{...t,realUserID:a}:t}if(i.completeAuthContext){return i.completeAuthContext(t,n)}if(r&&t.realUserID?.trim())return t;return e.getAuthContextForAuth(t,s)}function st(e,t,n,i){const s=n?.accessToken?.trim();if(s){(i.writeRejectedIdentity??sn)(e,t,s)}(i.invalidateAuthContext??an)(e,t)}async function ba(e,t={}){const n=e.observability??X;const i=Z.now();n.recordStartup({phase:"runtime.shutdown",outcome:"started"});const s=t.reportFailure??((u,h)=>{const f=h instanceof Error?h.message:String(h);process.stderr.write(`[minimax-code] ${u} cleanup failed: ${f}
3
3
  `)});const r=ur(t.shutdownTimeoutMs);const a=i+r;const o=Symbol("shutdown timeout");let d=false;const c=async(u,h)=>{let f;try{const g=Promise.resolve(h());void g.catch(()=>void 0);const S=Math.max(0,a-Z.now());const b=S>0?new Promise(D=>{f=setTimeout(()=>D(o),S)}):Promise.resolve(o);const M=await Promise.race([g,b]);if(M===o){d=true;l(u,r)}}catch(g){d=true;try{s(u,g)}catch{}}finally{if(f)clearTimeout(f)}};await c("embedded Runtime",()=>e.host.apiHost.close());await c("shared OAuth watch",()=>e.shutdownAuth?.());await c("Browser provider",()=>e.browserProvider?.close());await c("runtime logging",()=>e.shutdownLogging());n.recordStartup({phase:"runtime.shutdown",outcome:d?"failed":"succeeded",durationMs:Z.now()-i});await c("runtime observability",()=>n.flush());return d;function l(u,h){try{s(u,new Error(`Runtime shutdown deadline exceeded after ${h}ms`))}catch{}}}function cr(e){if(e instanceof Error&&e.name)return e.name;return typeof e}function ur(e){if(e===void 0||!Number.isFinite(e)){return nr}return Math.max(0,e)}export{Ta as a,ba as b};