ccgauge 1.2.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/app-build-manifest.json +33 -33
- package/.next/standalone/.next/app-path-routes-manifest.json +7 -7
- package/.next/standalone/.next/build-manifest.json +2 -2
- package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/api/blocks/route_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/api/export/usage/route_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/api/pricing/route_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/api/projects/route_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/api/scan/route_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/api/sessions/route_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/api/turns/route_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/api/usage/route_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/models/page.js +1 -1
- package/.next/standalone/.next/server/app/models/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/page.js +1 -1
- package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/projects/[id]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/projects/page.js +1 -1
- package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/sessions/[id]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/sessions/page.js +1 -1
- package/.next/standalone/.next/server/app/sessions/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/settings/page.js +2 -2
- package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/usage/page.js +1 -1
- package/.next/standalone/.next/server/app/usage/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app-paths-manifest.json +7 -7
- package/.next/standalone/.next/server/chunks/697.js +1 -1
- package/.next/standalone/.next/server/functions-config-manifest.json +5 -5
- package/.next/standalone/.next/server/middleware-manifest.json +1 -1
- package/.next/standalone/.next/server/pages/500.html +1 -1
- package/.next/standalone/.next/static/chunks/app/usage/page-8ff1ec4ef6aa86a0.js +1 -0
- package/.next/standalone/package.json +1 -1
- package/CHANGELOG.md +24 -0
- package/dist/mcp/server.mjs +2 -2
- package/package.json +1 -1
- package/.next/standalone/.next/static/chunks/app/usage/page-1ffeadfacd55c9f0.js +0 -1
- /package/.next/standalone/.next/static/{KYCxLofmJUzQwVpdBlibl → OqoHJlqnd6wl-Y-PBHJaU}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{KYCxLofmJUzQwVpdBlibl → OqoHJlqnd6wl-Y-PBHJaU}/_ssgManifest.js +0 -0
package/dist/mcp/server.mjs
CHANGED
|
@@ -39,8 +39,8 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
39
39
|
`:`[${n[c]}\r
|
|
40
40
|
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function Ks(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===k.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??me(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===k.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Bs(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===k.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===k.ZodBranded&&t.keyType._def.type._def.typeName===k.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Hs(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function lm(t,e){if(e.mapStrategy==="record")return Ks(t,e);let r=j(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||me(e),n=j(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||me(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function dm(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function pm(t){return t.target==="openAi"?void 0:{not:me({...t,currentPath:[...t.currentPath,"not"]})}}function fm(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var io={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function hm(t,e){if(e.target==="openApi3")return mm(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in io&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=io[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return mm(t,e)}var mm=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>j(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function gm(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:io[t.innerType._def.typeName],nullable:!0}:{type:[io[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=j(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=j(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function _m(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",xu(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?W(r,"minimum",n.value,n.message,e):W(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),W(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?W(r,"maximum",n.value,n.message,e):W(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),W(r,"maximum",n.value,n.message,e));break;case"multipleOf":W(r,"multipleOf",n.value,n.message,e);break}return r}function ym(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=Sw(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let d=j(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});d!==void 0&&(n.properties[a]=d,u||o.push(a))}o.length&&(n.required=o);let i=$w(t,e);return i!==void 0&&(n.additionalProperties=i),n}function $w(t,e){if(t.catchall._def.typeName!=="ZodNever")return j(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Sw(t){try{return t.isOptional()}catch{return!0}}var vm=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return j(t.innerType._def,e);let r=j(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:me(e)},r]}:me(e)};var bm=(t,e)=>{if(e.pipeStrategy==="input")return j(t.in._def,e);if(e.pipeStrategy==="output")return j(t.out._def,e);let r=j(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=j(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function xm(t,e){return j(t.type._def,e)}function wm(t,e){let n={type:"array",uniqueItems:!0,items:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&W(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&W(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function km(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>j(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:j(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>j(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function $m(t){return{not:me(t)}}function Sm(t){return me(t)}var Tm=(t,e)=>j(t.innerType._def,e);var zm=(t,e,r)=>{switch(e){case k.ZodString:return Bs(t,r);case k.ZodNumber:return _m(t,r);case k.ZodObject:return ym(t,r);case k.ZodBigInt:return tm(t,r);case k.ZodBoolean:return rm();case k.ZodDate:return wu(t,r);case k.ZodUndefined:return $m(r);case k.ZodNull:return fm(r);case k.ZodArray:return em(t,r);case k.ZodUnion:case k.ZodDiscriminatedUnion:return hm(t,r);case k.ZodIntersection:return am(t,r);case k.ZodTuple:return km(t,r);case k.ZodRecord:return Ks(t,r);case k.ZodLiteral:return cm(t,r);case k.ZodEnum:return im(t);case k.ZodNativeEnum:return dm(t);case k.ZodNullable:return gm(t,r);case k.ZodOptional:return vm(t,r);case k.ZodMap:return lm(t,r);case k.ZodSet:return wm(t,r);case k.ZodLazy:return()=>t.getter()._def;case k.ZodPromise:return xm(t,r);case k.ZodNaN:case k.ZodNever:return pm(r);case k.ZodEffects:return sm(t,r);case k.ZodAny:return me(r);case k.ZodUnknown:return Sm(r);case k.ZodDefault:return om(t,r);case k.ZodBranded:return Hs(t,r);case k.ZodReadonly:return Tm(t,r);case k.ZodCatch:return nm(t,r);case k.ZodPipeline:return bm(t,r);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(n=>{})(e)}};function j(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Yf)return a}if(n&&!r){let a=Tw(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=zm(t,t.typeName,e),i=typeof s=="function"?j(s(),e):s;if(i&&zw(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Tw=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Vs(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),me(e)):e.$refStrategy==="seen"?me(e):void 0}},zw=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Su=(t,e)=>{let r=Qf(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,d])=>({...c,[u]:j(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??me(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=j(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??me(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function Rw(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Tu(t,e){return et(t)?Wc(t,{target:Rw(e?.target),io:e?.pipeStrategy??"input"}):Su(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function zu(t){let r=Bt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bs(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ru(t,e){let r=Ht(t,e);if(!r.success)throw r.error;return r.data}var Pw=6e4,Ws=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(zs,r=>{this._oncancel(r)}),this.setNotificationHandler(Ps,r=>{this._onprogress(r)}),this.setRequestHandler(Rs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Es,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(A.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Cs,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,m=new I(l.error.code,l.error.message,l.error.data);d(m)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new I(A.InvalidParams,`Task not found: ${s}`);if(!Wt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Wt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Kt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Os,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new I(A.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ns,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new I(A.InvalidParams,`Task not found: ${r.params.taskId}`);if(Wt(o.status))throw new I(A.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new I(A.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof I?o:new I(A.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),I.fromError(A.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Yn(s)||Df(s)?this._onresponse(s):au(s)?this._onrequest(s,i):Zf(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=I.fromError(A.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Kt]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:A.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):o?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Nf(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};s&&(l.relatedTask={taskId:s}),await this.notification(d,l)},sendRequest:async(d,l,m)=>{if(i.signal.aborted)throw new I(A.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let p=f.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:A.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Yn(e))n(e);else{let i=new I(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Yn(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Yn(e))o(e);else{let i=I.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof I?i:new I(A.InternalError,String(i))}}return}let s;try{let i=await this.request(e,en,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new I(A.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Wt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new I(A.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new I(A.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof I?i:new I(A.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=b=>{d(b)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(b){l(b);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Kt]:c}});let p=b=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(b)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>this._onerror(new Error(`Failed to send cancellation: ${$}`)));let x=b instanceof I?b:new I(A.RequestTimeout,String(b));d(x)};this._responseHandlers.set(m,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return d(b);try{let x=Ht(r,b.result);x.success?u(x.data):d(x.error)}catch(x){d(x)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let h=n?.timeout??Pw,g=()=>p(I.fromError(A.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let b=x=>{let $=this._responseHandlers.get(m);$?$(x):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,b),this._enqueueTaskMessage(_,{type:"request",message:f,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(m),d(x)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(m),d(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Is,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},As,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Uf,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Kt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Kt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Kt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=zu(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Ru(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=zu(e);this._notificationHandlers.set(n,o=>{let s=Ru(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&au(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new I(A.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new I(A.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new I(A.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new I(A.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=ro.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Wt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new I(A.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Wt(a.status))throw new I(A.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=ro.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Wt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Rm(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Pm(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Rm(i)&&Rm(s)?r[o]={...i,...s}:r[o]=s}return r}var b_=Od(md(),1),x_=Od(v_(),1);function CR(){let t=new b_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,x_.default)(t),t}var Pi=class{constructor(e){this._ajv=e??CR()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Ei=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(d=>d.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(d=>d.type==="tool_use");if(i){if(s.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let d=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(s.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(d.size!==l.size||![...d].every(m=>l.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},so,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},nn,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function w_(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function k_(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Ii=class extends Ws{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(oo.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Pi,this.setRequestHandler(lu,n=>this._oninitialize(n)),this.setNotificationHandler(du,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(yu,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=oo.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ei(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Pm(this._capabilities,e)}setRequestHandler(e,r){let o=Bt(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(et(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let d=Ht(rn,c);if(!d.success){let p=d.error instanceof Error?d.error.message:String(d.error);throw new I(A.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=d.data,m=await Promise.resolve(r(c,u));if(l.task){let p=Ht(en,m);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new I(A.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let f=Ht(Us,m);if(!f.success){let p=f.error instanceof Error?f.error.message:String(f.error);throw new I(A.InvalidParams,`Invalid tools/call result: ${p}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){k_(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&w_(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Cf.includes(r)?r:su,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Ts)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(l=>l.type==="tool_use").map(l=>l.id)),d=new Set(o.filter(l=>l.type==="tool_result").map(l=>l.toolUseId));if(u.size!==d.size||![...u].every(l=>d.has(l)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},vu,r):this.request({method:"sampling/createMessage",params:e},so,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},nn,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},nn,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new I(A.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof I?i:new I(A.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},bu,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var S_=Symbol.for("mcp.completable");function wd(t){return!!t&&typeof t=="object"&&S_ in t}function T_(t){return t[S_]?.complete}var $_;(function(t){t.Completable="McpCompletable"})($_||($_={}));var OR=/^[A-Za-z0-9._-]{1,128}$/;function AR(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!OR.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function NR(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function kd(t){let e=AR(t);return NR(t,e.warnings),e.isValid}var Ci=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var Oi=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Ii(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ci(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(nr(Ls)),this.server.assertCanSetRequestHandler(nr(rn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ls,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Xr(r.inputSchema);return o?Tu(o,{strictUnions:!0,pipeStrategy:"input"}):MR})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Xr(r.outputSchema);o&&(n.outputSchema=Tu(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(rn,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new I(A.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new I(A.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new I(A.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new I(A.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof I&&n.code===A.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Xr(e.inputSchema)??e.inputSchema,i=await ys(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=vs(a);throw new I(A.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new I(A.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Xr(e.outputSchema),s=await ys(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=vs(i);throw new I(A.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,d=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(m=>setTimeout(m,d));let l=await n.taskStore.getTask(c);if(!l)throw new I(A.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(nr(Fs)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Fs,async e=>{switch(e.params.ref.type){case"ref/prompt":return Wf(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Gf(e),this.handleResourceCompletion(e,e.params.ref);default:throw new I(A.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new I(A.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new I(A.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return jo;let s=Bt(n.argsSchema)?.[e.params.argument.name];if(!wd(s))return jo;let i=T_(s);if(!i)return jo;let a=await i(e.params.argument.value,e.params.context);return R_(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return jo;throw new I(A.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return jo;let s=await o(e.params.argument.value,e.params.context);return R_(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(nr(Ms)),this.server.assertCanSetRequestHandler(nr(js)),this.server.assertCanSetRequestHandler(nr(Zs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ms,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(js,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Zs,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new I(A.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new I(A.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(nr(Ds)),this.server.assertCanSetRequestHandler(nr(qs)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ds,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?jR(r.argsSchema):void 0}))})),this.server.setRequestHandler(qs,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new I(A.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new I(A.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Xr(n.argsSchema),s=await ys(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=vs(c);throw new I(A.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Pr(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Pr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof De?c._def?.innerType:c;return wd(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){kd(e);let d={title:r,description:n,inputSchema:z_(o),outputSchema:z_(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(typeof l.name=="string"&&kd(l.name),delete this._registeredTools[e],l.name&&(this._registeredTools[l.name]=d)),typeof l.title<"u"&&(d.title=l.title),typeof l.description<"u"&&(d.description=l.description),typeof l.paramsSchema<"u"&&(d.inputSchema=Pr(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=Pr(l.outputSchema)),typeof l.callback<"u"&&(d.handler=l.callback),typeof l.annotations<"u"&&(d.annotations=l.annotations),typeof l._meta<"u"&&(d._meta=l._meta),typeof l.enabled<"u"&&(d.enabled=l.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=d,this.setToolRequestHandlers(),this.sendToolListChanged(),d}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if($d(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!$d(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var MR={type:"object",properties:{}};function P_(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function E_(t){return"_def"in t||"_zod"in t||P_(t)}function $d(t){return typeof t!="object"||t===null||E_(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(P_)}function z_(t){if(t){if($d(t))return Pr(t);if(!E_(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function jR(t){let e=Bt(t);return e?Object.entries(e).map(([r,n])=>{let o=cf(n),s=uf(n);return{name:r,description:o,required:!s}}):[]}function nr(t){let r=Bt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bs(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function R_(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var jo={completion:{values:[],hasMore:!1}};import C_ from"node:process";var Ai=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
41
41
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),ZR(r)}clear(){this._buffer=void 0}};function ZR(t){return qf.parse(JSON.parse(t))}function I_(t){return JSON.stringify(t)+`
|
|
42
|
-
`}var Ni=class{constructor(e=C_.stdin,r=C_.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ai,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=I_(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var DR=/^(\d{4})-(\d{2})-(\d{2})(.*)$/;function Mi(t){let e=new Date(t);return e.setHours(0,0,0,0),e}function Zo(t){let e=new Date(t);return e.setHours(23,59,59,999),e}function ji(t){let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!e)return null;let r=Number(e[1]),n=Number(e[2]),o=Number(e[3]),s=new Date(r,n-1,o);return s.getFullYear()!==r||s.getMonth()!==n-1||s.getDate()!==o?null:s}function O_(t){return ji(t)!==null}function Zi(t,e={}){let r=DR.exec(t);if(r){let o=`${r[1]}-${r[2]}-${r[3]}`,s=ji(o);if(!s)return null;if(r[4]==="")return e.upperBoundDateOnly?Zo(s):s;let i=new Date(t);if(Number.isNaN(i.getTime()))return null;let a=Number(r[1]),c=Number(r[2]),u=Number(r[3]),d=/[zZ]|[+-]\d{2}:?\d{2}$/.test(t),l=d?i.getUTCFullYear():i.getFullYear(),m=(d?i.getUTCMonth():i.getMonth())+1,f=d?i.getUTCDate():i.getDate();return l!==a||m!==c||f!==u?null:i}let n=new Date(t);return Number.isNaN(n.getTime())?null:n}var qR=le.enum(["claude","codex","all"]).default("all"),N_=le.enum(["hour","day","week","month"]).default("day");function LR(t){return Zi(t)!==null}var A_=le.string().refine(LR,{message:"must be a YYYY-MM-DD date or a full ISO 8601 timestamp"}),kn={range:le.enum(["today","yesterday","this_week","last_week","this_month","last_month","7d","30d","90d","all"]).optional().describe('Named time window. Defaults to "all" if no explicit from/to is given.'),from:A_.optional().describe("Inclusive lower bound (ISO date YYYY-MM-DD or full ISO timestamp)."),to:A_.optional().describe("Inclusive upper bound (ISO date YYYY-MM-DD or full ISO timestamp).")},UR=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"],FR=["today","yesterday"],M_=le.string().refine(t=>{let e=t.toLowerCase();return FR.includes(e)||UR.includes(e)?!0:O_(t)},{message:'must be "today", "yesterday", a weekday name (monday..sunday), or YYYY-MM-DD'}),Pt={source:qR.describe("claude | codex | all (default). When all, the response carries combined totals plus a bySource breakdown.")},$n=["claude","codex"];import{promises as Lo,watch as IP}from"node:fs";import cy from"node:path";function VR(t){let e=`${t.source}:`;return t.messageId&&t.requestId?`${e}${t.messageId}::${t.requestId}`:t.messageId?`${e}mid:${t.messageId}`:t.requestId?`${e}req:${t.requestId}`:`${e}uuid:${t.uuid}`}function j_(t){let e=new Map;for(let r of t){let n=VR(r),o=e.get(n);if(!o){e.set(n,r);continue}r.timestamp<o.timestamp&&e.set(n,r)}return Array.from(e.values())}import{promises as kP}from"node:fs";import Di from"node:path";import YR from"node:os";import{createReadStream as HR}from"node:fs";import BR from"node:readline";var Sd=200;async function Z_(t){let e=HR(t,{encoding:"utf8"}),r=BR.createInterface({input:e,crlfDelay:1/0}),n=[],o=[],s=[];for await(let i of r){if(!i.trim())continue;let a;try{a=JSON.parse(i)}catch{continue}if(!(!a||typeof a!="object")){if(a.uuid&&s.push([a.uuid,a.parentUuid??null]),a.type==="assistant"){let c=KR(a,t);c&&n.push(c)}else if(a.type==="user"){let c=WR(a,t);c&&o.push(c)}}}return{assistant:n,user:o,parentLinks:s}}function KR(t,e){let r=t.message;if(!r)return null;let n=r.usage;if(!n)return null;let o=r.model??"";if(!o||o==="<synthetic>")return null;let s=r.id??t.uuid??"";if(!s&&!t.requestId)return null;let i=n.cache_creation,a=Array.isArray(r.content)?r.content:[],c=[],u=!1,d="";for(let l of a)l.type==="tool_use"&&typeof l.name=="string"?c.push(l.name):l.type==="thinking"?u=!0:l.type==="text"&&typeof l.text=="string"&&!d&&(d=l.text.slice(0,Sd));return{type:"assistant",source:"claude",uuid:t.uuid??s,parentUuid:t.parentUuid??null,timestamp:t.timestamp??new Date().toISOString(),sessionId:t.sessionId??"",requestId:t.requestId??"",cwd:t.cwd??"",gitBranch:t.gitBranch,version:t.version,model:o,messageId:s,usage:{input_tokens:Number(n.input_tokens)||0,output_tokens:Number(n.output_tokens)||0,cache_creation_input_tokens:Number(n.cache_creation_input_tokens)||0,cache_read_input_tokens:Number(n.cache_read_input_tokens)||0,cache_creation_5m:Number(i?.ephemeral_5m_input_tokens)||0,cache_creation_1h:Number(i?.ephemeral_1h_input_tokens)||0},toolNames:c,hasThinking:u,textPreview:d,filePath:e,isSidechain:t.isSidechain===!0?!0:void 0}}function WR(t,e){if(!t.uuid)return null;let r=t.message,n="";if(r){let i=r.content;if(typeof i=="string")n=i.slice(0,Sd);else if(Array.isArray(i)){for(let a of i)if(a.type==="text"&&typeof a.text=="string"){n=a.text.slice(0,Sd);break}}}let o=t.isSidechain===!0,s=o||!!n&&GR(n);return{type:"user",source:"claude",uuid:t.uuid,parentUuid:t.parentUuid??null,timestamp:t.timestamp??new Date().toISOString(),sessionId:t.sessionId??"",cwd:t.cwd??"",textPreview:n,isSynthetic:s,isSidechain:o?!0:void 0,filePath:e}}function GR(t){let e=t.trimStart();return!!(e.startsWith("Base directory for this skill:")||e.startsWith("<system-reminder>")||e.startsWith("Caveat: The messages below were generated by")||e.startsWith("<task-notification>"))}var D_={"claude-3-7-sonnet-20250219":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-3-haiku-20240307":{input:.25,output:1.25,cacheCreation5m:.3,cacheCreation1h:.5,cacheRead:.03},"claude-3-opus-20240229":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-4-opus-20250514":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-4-sonnet-20250514":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-fable-5":{input:10,output:50,cacheCreation5m:12.5,cacheCreation1h:20,cacheRead:1},"claude-haiku-4-5":{input:1,output:5,cacheCreation5m:1.25,cacheCreation1h:2,cacheRead:.1},"claude-haiku-4-5-20251001":{input:1,output:5,cacheCreation5m:1.25,cacheCreation1h:2,cacheRead:.1},"claude-opus-4-1":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-opus-4-1-20250805":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-opus-4-20250514":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-opus-4-5":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-5-20251101":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-6":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-6-20260205":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-7":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-7-20260416":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-8":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-sonnet-4-20250514":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-sonnet-4-5":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-sonnet-4-5-20250929":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-sonnet-4-6":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3}},q_={"chatgpt-4o-latest":{input:5,output:15,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"codex-mini-latest":{input:1.5,output:6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.375},"gpt-3.5-turbo":{input:.5,output:1.5,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.05},"gpt-3.5-turbo-0125":{input:.5,output:1.5,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.05},"gpt-3.5-turbo-1106":{input:1,output:2,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.1},"gpt-3.5-turbo-16k":{input:3,output:4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.3},"gpt-4":{input:30,output:60,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-4-0125-preview":{input:10,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1},"gpt-4-0314":{input:30,output:60,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-4-0613":{input:30,output:60,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-4-1106-preview":{input:10,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1},"gpt-4-turbo":{input:10,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1},"gpt-4-turbo-2024-04-09":{input:10,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1},"gpt-4-turbo-preview":{input:10,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1},"gpt-4.1":{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"gpt-4.1-2025-04-14":{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"gpt-4.1-mini":{input:.4,output:1.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.1},"gpt-4.1-mini-2025-04-14":{input:.4,output:1.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.1},"gpt-4.1-nano":{input:.1,output:.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.025},"gpt-4.1-nano-2025-04-14":{input:.1,output:.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.025},"gpt-4o":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.25},"gpt-4o-2024-05-13":{input:5,output:15,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"gpt-4o-2024-08-06":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.25},"gpt-4o-2024-11-20":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.25},"gpt-4o-audio-preview":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-4o-audio-preview-2024-12-17":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-4o-audio-preview-2025-06-03":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-4o-mini":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-4o-mini-2024-07-18":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-4o-mini-audio-preview":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.015},"gpt-4o-mini-audio-preview-2024-12-17":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.015},"gpt-4o-mini-realtime-preview":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.3},"gpt-4o-mini-realtime-preview-2024-12-17":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.3},"gpt-4o-mini-search-preview":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-4o-mini-search-preview-2025-03-11":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-4o-realtime-preview":{input:5,output:20,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.5},"gpt-4o-realtime-preview-2024-12-17":{input:5,output:20,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.5},"gpt-4o-realtime-preview-2025-06-03":{input:5,output:20,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.5},"gpt-4o-search-preview":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.25},"gpt-4o-search-preview-2025-03-11":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.25},"gpt-5":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-2025-08-07":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-chat":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-chat-latest":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-codex":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-mini":{input:.25,output:2,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.025},"gpt-5-mini-2025-08-07":{input:.25,output:2,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.025},"gpt-5-nano":{input:.05,output:.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.005},"gpt-5-nano-2025-08-07":{input:.05,output:.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.005},"gpt-5-pro":{input:15,output:120,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.5},"gpt-5-pro-2025-10-06":{input:15,output:120,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.5},"gpt-5-search-api":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-search-api-2025-10-14":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1-2025-11-13":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1-chat-latest":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1-codex":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1-codex-max":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1-codex-mini":{input:.25,output:2,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.025},"gpt-5.2":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.2-2025-12-11":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.2-chat-latest":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.2-codex":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.2-pro":{input:21,output:168,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.1},"gpt-5.2-pro-2025-12-11":{input:21,output:168,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.1},"gpt-5.3-chat-latest":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.3-codex":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.4":{input:2.5,output:15,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-5.4-2026-03-05":{input:2.5,output:15,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-5.4-mini":{input:.75,output:4.5,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-5.4-mini-2026-03-17":{input:.75,output:4.5,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-5.4-nano":{input:.2,output:1.25,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.02},"gpt-5.4-nano-2026-03-17":{input:.2,output:1.25,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.02},"gpt-5.4-pro":{input:30,output:180,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-5.4-pro-2026-03-05":{input:30,output:180,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-5.5":{input:5,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"gpt-5.5-2026-04-23":{input:5,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"gpt-5.5-pro":{input:30,output:180,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-5.5-pro-2026-04-23":{input:30,output:180,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-audio":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-audio-1.5":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-audio-2025-08-28":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-audio-mini":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},"gpt-audio-mini-2025-10-06":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},"gpt-audio-mini-2025-12-15":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},"gpt-realtime":{input:4,output:16,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.4},"gpt-realtime-1.5":{input:4,output:16,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.4},"gpt-realtime-2":{input:4,output:16,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.4},"gpt-realtime-2025-08-28":{input:4,output:16,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.4},"gpt-realtime-mini":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},"gpt-realtime-mini-2025-10-06":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},"gpt-realtime-mini-2025-12-15":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},o1:{input:15,output:60,cacheCreation5m:0,cacheCreation1h:0,cacheRead:7.5},"o1-2024-12-17":{input:15,output:60,cacheCreation5m:0,cacheCreation1h:0,cacheRead:7.5},"o1-pro":{input:150,output:600,cacheCreation5m:0,cacheCreation1h:0,cacheRead:15},"o1-pro-2025-03-19":{input:150,output:600,cacheCreation5m:0,cacheCreation1h:0,cacheRead:15},o3:{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"o3-2025-04-16":{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"o3-deep-research":{input:10,output:40,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.5},"o3-deep-research-2025-06-26":{input:10,output:40,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.5},"o3-mini":{input:1.1,output:4.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.55},"o3-mini-2025-01-31":{input:1.1,output:4.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.55},"o3-pro":{input:20,output:80,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2},"o3-pro-2025-06-10":{input:20,output:80,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2},"o4-mini":{input:1.1,output:4.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.275},"o4-mini-2025-04-16":{input:1.1,output:4.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.275},"o4-mini-deep-research":{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"o4-mini-deep-research-2025-06-26":{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5}};var JR={"claude-opus-4":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-sonnet-4":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-sonnet-3-7":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-haiku-3-5":{input:.8,output:4,cacheCreation5m:1,cacheCreation1h:1.6,cacheRead:.08},"claude-haiku-3":{input:.25,output:1.25,cacheCreation5m:.3,cacheCreation1h:.5,cacheRead:.03}},_t={...JR,...D_},L_={fable:_t["claude-fable-5"],opus:_t["claude-opus-4-8"],sonnet:_t["claude-sonnet-4-6"],haiku:_t["claude-haiku-4-5"]};function or(t,e){if(!e)return{input:0,output:0,cacheCreation5m:0,cacheCreation1h:0,cacheRead:0,total:0,saved:0};let r=t.input_tokens/1e6*e.input,n=t.output_tokens/1e6*e.output,o=t.cache_creation_5m/1e6*e.cacheCreation5m,s=t.cache_creation_1h/1e6*e.cacheCreation1h;o+s===0&&t.cache_creation_input_tokens>0&&(o=t.cache_creation_input_tokens/1e6*e.cacheCreation5m);let i=t.cache_read_input_tokens/1e6*e.cacheRead,a=r+n+o+s+i,c=t.cache_read_input_tokens/1e6*(e.input-e.cacheRead);return{input:r,output:n,cacheCreation5m:o,cacheCreation1h:s,cacheRead:i,total:a,saved:c}}function U_(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function F_(t){if(!t)return"(unknown)";let e=t.replace(/-(\d{8})$/,"").replace(/^(vertex_ai|bedrock|anthropic)\//,"");e=e.replace(/^claude-/,"");let r=e.split("-");if(r.length>=2){let n=r[0],o=r.slice(1).join(".");return U_(n)+" "+o}return U_(e.replace(/-/g," "))}var XR=/-\d{8}$/,QR=/^(vertex_ai|bedrock|anthropic)\//;function eP(t){if(!t)return{pricing:null,matchType:"none",matchedKey:null};if(_t[t])return{pricing:_t[t],matchType:"exact",matchedKey:t};let e=t.replace(XR,"");if(_t[e])return{pricing:_t[e],matchType:"date-stripped",matchedKey:e};let r=e.replace(QR,"");if(_t[r])return{pricing:_t[r],matchType:"prefix-stripped",matchedKey:r};for(let n of["fable","opus","sonnet","haiku"])if(t.toLowerCase().includes(n))return{pricing:L_[n],matchType:"family-fallback",matchedKey:`claude-${n}-(latest)`};return{pricing:null,matchType:"none",matchedKey:null}}function tP(){let t=YR.homedir(),e=[Di.join(t,".claude","projects"),Di.join(t,".config","claude","projects")];return process.env.CCGAUGE_CONFIG_DIR&&e.push(Di.join(process.env.CCGAUGE_CONFIG_DIR,"projects")),process.env.CLAUDE_CONFIG_DIR&&e.push(Di.join(process.env.CLAUDE_CONFIG_DIR,"projects")),Array.from(new Set(e))}var V_={id:"claude",displayName:{en:"Claude",zh:"Claude"},shortLabel:"C",color:{fg:"#b45309",bg:"#fef3c7"},logoSrc:"/claude-logo.webp",parserVersion:"claude-v5-task-notification-synthetic",capabilities:{hasCacheCreation:!0,hasReasoningTokens:!1,blockWindowMs:300*60*1e3},getDirs:tP,shouldSkipDir:t=>t==="tool-results"||t==="memory",parseFile:async t=>await Z_(t),resolvePricing:eP,shortenModel:F_,costFromUsage:or,costFootnoteKey:null};import qi from"node:path";import bP from"node:os";import{createReadStream as rP,promises as nP}from"node:fs";import oP from"node:readline";var Td=200;async function sP(t){try{let e=await nP.stat(t);return new Date(e.mtimeMs).toISOString()}catch{return new Date().toISOString()}}function Ge(t){return typeof t=="string"?t:""}function sr(t){let e=Number(t);return Number.isFinite(e)?e:0}function zd(t){let e=t.message;if(typeof e=="string")return e;let r=t.content;if(typeof r=="string")return r;if(Array.isArray(r))for(let n of r){let o=n?.type;if((o==="input_text"||o==="output_text"||o==="text")&&typeof n.text=="string")return n.text}return""}async function H_(t){let e=rP(t,{encoding:"utf8"}),r=oP.createInterface({input:e,crlfDelay:1/0}),n=[],o=[],s=[],i="",a,c="",u=0,d=0,l=null,f=await sP(t),p={turnId:null,cwd:"",model:"gpt-unknown",userUuid:null,toolNames:[],hasThinking:!1,pendingTextPreview:""};for await(let h of r){if(!h.trim())continue;let g;try{g=JSON.parse(h)}catch{continue}if(!g||typeof g!="object"||!g.type)continue;let _=g.payload??{},b=Ge(g.timestamp),x=b||f;if(b&&(f=b),g.type==="session_meta"){i=Ge(_.id),c=Ge(_.cwd),a=Ge(_.cli_version)||void 0;let $=Ge(_.timestamp);$&&(f=$),p.cwd||(p.cwd=c);continue}if(g.type==="turn_context"){p.turnId=Ge(_.turn_id)||p.turnId,p.cwd=Ge(_.cwd)||c;let $=Ge(_.model);$&&(p.model=$);let P=Ge(_.effort);P&&(p.effort=P),p.toolNames=[],p.hasThinking=!1,p.pendingTextPreview="";continue}if(g.type==="event_msg"){let $=Ge(_.type);if($==="user_message"){let P=zd(_);if(!P)continue;let ee=`${i}::u${u++}`;o.push({type:"user",source:"codex",uuid:ee,parentUuid:null,timestamp:x,sessionId:i,cwd:p.cwd||c,textPreview:P.slice(0,Td),filePath:t}),s.push([ee,null]),p.userUuid=ee;continue}if($==="agent_message"){let P=zd(_);P&&!p.pendingTextPreview&&(p.pendingTextPreview=P.slice(0,Td));continue}if($==="agent_reasoning"){p.hasThinking=!0;continue}if($==="token_count"){let P=_.info;if(!P)continue;let ee=P.total_token_usage,be=P.last_token_usage,ge=ee?{input:sr(ee.input_tokens),cached:sr(ee.cached_input_tokens),output:sr(ee.output_tokens),reasoning:sr(ee.reasoning_output_tokens)}:null,Je,Oe,Ye,at;if(ge){if(l===null?(Je=ge.input,Oe=ge.cached,Ye=ge.output,at=ge.reasoning):(Je=Math.max(0,ge.input-l.input),Oe=Math.max(0,ge.cached-l.cached),Ye=Math.max(0,ge.output-l.output),at=Math.max(0,ge.reasoning-l.reasoning)),Je===0&&Oe===0&&Ye===0&&at===0)continue;l===null?l={...ge}:l={input:Math.max(l.input,ge.input),cached:Math.max(l.cached,ge.cached),output:Math.max(l.output,ge.output),reasoning:Math.max(l.reasoning,ge.reasoning)}}else if(be){if(Je=sr(be.input_tokens),Oe=sr(be.cached_input_tokens),Ye=sr(be.output_tokens),at=sr(be.reasoning_output_tokens),Je===0&&Oe===0&&Ye===0&&at===0)continue;l===null?l={input:Je,cached:Oe,output:Ye,reasoning:at}:l={input:l.input+Je,cached:l.cached+Oe,output:l.output+Ye,reasoning:l.reasoning+at}}else continue;let Cn=`${i}::a${d++}`,Wo=p.turnId?`${p.turnId}::a${d}`:`${i}::a${d}`;n.push({type:"assistant",source:"codex",uuid:Cn,parentUuid:p.userUuid,timestamp:x,sessionId:i,requestId:Wo,cwd:p.cwd||c,version:a,model:p.model||"gpt-unknown",messageId:Wo,usage:{input_tokens:Math.max(0,Je-Oe),output_tokens:Ye,cache_creation_input_tokens:0,cache_read_input_tokens:Oe,cache_creation_5m:0,cache_creation_1h:0,reasoning_tokens:at},toolNames:[...p.toolNames],hasThinking:p.hasThinking,textPreview:p.pendingTextPreview,filePath:t,effort:p.effort}),s.push([Cn,p.userUuid]),p.toolNames=[],p.hasThinking=!1,p.pendingTextPreview="";continue}continue}if(g.type==="response_item"){let $=Ge(_.type);if($==="function_call"||$==="custom_tool_call"){let P=Ge(_.name);P&&p.toolNames.push(P);continue}if($==="reasoning"){p.hasThinking=!0;continue}if($==="message"){if(Ge(_.role)==="assistant"){let ee=zd(_);ee&&!p.pendingTextPreview&&(p.pendingTextPreview=ee.slice(0,Td))}continue}continue}}return{assistant:n,user:o,parentLinks:s}}var iP={},ir={...iP,...q_},B_={gpt:ir["gpt-5.5"],o:ir.o3},aP=/-\d{8}$/,cP=/^(openai)\//;function K_(t){if(!t)return{pricing:null,matchType:"none",matchedKey:null};if(ir[t])return{pricing:ir[t],matchType:"exact",matchedKey:t};let e=t.replace(aP,"");if(ir[e])return{pricing:ir[e],matchType:"date-stripped",matchedKey:e};let r=e.replace(cP,"");if(ir[r])return{pricing:ir[r],matchType:"prefix-stripped",matchedKey:r};let n=t.toLowerCase();return n.startsWith("gpt-")||n==="gpt"?{pricing:B_.gpt,matchType:"family-fallback",matchedKey:"gpt-(latest)"}:/^o\d/.test(n)?{pricing:B_.o,matchType:"family-fallback",matchedKey:"o-(latest)"}:{pricing:null,matchType:"none",matchedKey:null}}function uP(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}var lP={mini:"Mini",nano:"Nano",pro:"Pro",turbo:"Turbo",preview:"Preview"};function W_(t){if(!t)return"(unknown)";let e=t.replace(/^openai\//,"");return e.toLowerCase().startsWith("gpt-")?"GPT-"+e.slice(4).split("-").map(o=>lP[o.toLowerCase()]??o).join(" "):e.toLowerCase().startsWith("o")?e.toUpperCase():uP(e.replace(/-/g," "))}import{readFileSync as dP}from"node:fs";import pP from"node:os";import G_ from"node:path";var fP={"gpt-5.5":2.5,"gpt-5.4":2,"gpt-5.3-codex":2},mP=2;function hP(t){return t.replace(/^openai\//,"").replace(/-\d{8}$/,"")}function gP(t){for(let e of t.split(/\r?\n/)){let r=(e.split("#")[0]??"").trim(),n=r.indexOf("=");if(n===-1||r.slice(0,n).trim()!=="service_tier")continue;let s=r.slice(n+1).trim().replace(/^['"]+|['"]+$/g,"");if(s==="fast"||s==="priority")return!0}return!1}function _P(){let t=[];return process.env.CODEX_HOME&&t.push(process.env.CODEX_HOME),t.push(G_.join(pP.homedir(),".codex")),Array.from(new Set(t))}function yP(){for(let t of _P())try{let e=dP(G_.join(t,"config.toml"),"utf8");if(gP(e))return!0}catch{}return!1}var Rd;function vP(){return Rd===void 0&&(Rd=yP()),Rd}function J_(t){return vP()?fP[hP(t)]??mP:1}function Y_(t,e){return e===1?t:{input:t.input*e,output:t.output*e,cacheRead:t.cacheRead*e,cacheCreation5m:t.cacheCreation5m*e,cacheCreation1h:t.cacheCreation1h*e}}function xP(){let t=bP.homedir(),e=[qi.join(t,".codex","sessions"),qi.join(t,".codex","archived_sessions")];return process.env.CCGAUGE_CODEX_DIR&&e.push(process.env.CCGAUGE_CODEX_DIR),process.env.CODEX_HOME&&(e.push(qi.join(process.env.CODEX_HOME,"sessions")),e.push(qi.join(process.env.CODEX_HOME,"archived_sessions"))),Array.from(new Set(e))}function wP(t,e,r){return e?or(t,Y_(e,J_(r??""))):or(t,null)}var X_={id:"codex",displayName:{en:"Codex",zh:"Codex"},shortLabel:"X",color:{fg:"#047857",bg:"#d1fae5"},logoSrc:"/codex-logo.webp",parserVersion:"codex-v6-output-excludes-readded-reasoning",capabilities:{hasCacheCreation:!1,hasReasoningTokens:!0,blockWindowMs:300*60*1e3},getDirs:xP,shouldSkipDir:()=>!1,parseFile:H_,resolvePricing:K_,shortenModel:W_,costFromUsage:wP,costFootnoteKey:"cost.footnote.codex"};var Q_={claude:V_,codex:X_},$P=["claude","codex"];function Sn(t){return Q_[t]}function Do(){return $P.map(t=>Q_[t])}async function SP(t){try{return(await kP.stat(t)).isDirectory()}catch{return!1}}async function ey(){let t=[];for(let e of Do())for(let r of e.getDirs())if(await SP(r)){t.push(e.id);break}return t}import{promises as Li}from"node:fs";import Pd from"node:path";import TP from"node:os";var Ui=2,Tn="default";function zP(){return process.env.CCGAUGE_STATE_DIR?process.env.CCGAUGE_STATE_DIR:Pd.join(TP.homedir(),".ccgauge")}function ty(t){let e=t===Tn?`index-v${Ui}.json`:`index-${t}-v${Ui}.json`;return Pd.join(zP(),"cache",e)}async function ry(t=Tn){let e=ty(t);try{let r=await Li.readFile(e,"utf8"),n=JSON.parse(r);return n.schemaVersion!==Ui||!Array.isArray(n.files)?null:n}catch{return null}}async function ny(t,e=Tn){let r=ty(e),n=Pd.dirname(r);await Li.mkdir(n,{recursive:!0});let o={schemaVersion:Ui,savedAt:t.savedAt,files:t.files},s=`${r}.tmp-${process.pid}`;await Li.writeFile(s,JSON.stringify(o)),await Li.rename(s,r)}var oy=/[\\/]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})[\\/]subagents[\\/](?:[^\\/]+[\\/])*agent-[^\\/]+\.jsonl$/i,RP=/[\\/]subagents[\\/]workflows[\\/]/i;function PP(t){let e=oy.exec(t);return e?e[1]:null}function sy(t){return oy.test(t)?RP.test(t)?"workflow":"task":null}function iy({assistantRecords:t,userRecords:e,parentMap:r}){let n=new Map;for(let i of t){if(i.isSidechain||!i.sessionId)continue;let a=n.get(i.sessionId);a||(a=[],n.set(i.sessionId,a)),a.push(i)}for(let i of n.values())i.sort((a,c)=>a.timestamp<c.timestamp?-1:a.timestamp>c.timestamp?1:0);let o=new Map;for(let i of e){if(!i.isSidechain)continue;let a=o.get(i.filePath);(!a||i.timestamp<a.timestamp)&&o.set(i.filePath,i)}let s={subagentFiles:0,relinked:0,orphans:0,alreadyLinked:0};for(let[i,a]of o){let c=PP(i);if(!c)continue;s.subagentFiles+=1;let u=r[a.uuid];if(u!=null){s.alreadyLinked+=1;continue}let d=n.get(c);if(!d||d.length===0){s.orphans+=1;continue}let l=a.timestamp,m;for(let f=d.length-1;f>=0;f-=1)if(d[f].timestamp<=l){m=d[f];break}m||(m=d[0]),r[a.uuid]=m.uuid,s.relinked+=1}return s}import{homedir as EP}from"node:os";function qo(t){let e=EP();if(!e)return t;let r=new Set([e]);process.platform==="win32"&&(r.add(e.replace(/\\/g,"/")),r.add(e.replace(/\\/g,"\\\\")),r.add("\\\\?\\"+e),r.add("\\\\?\\"+e.replace(/\\/g,"/")));let n=t;for(let o of r){let s=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(s,"g"),"~")}return n}var CP=200,OP=100,AP=3e4,NP=2e3,MP=8,Ed=20,Id=class{cacheName;files=new Map;snapshot=null;watchers=new Map;pollTimer=null;snapshotRebuildTimer=null;persistTimer=null;fileDebouncers=new Map;initPromise=null;isIndexing=!1;lastIndexedAt=null;indexDurationMs=null;existingDirs=[];dirToProvider=new Map;errors=[];loadedFromDisk=!1;lastWorkStart=null;rescanPromise=null;mutationTail=Promise.resolve();constructor(e=Tn){this.cacheName=e}runExclusive(e){let r=this.mutationTail.then(e,e);return this.mutationTail=r.then(()=>{},()=>{}),r}init(){return this.initPromise||(this.initPromise=this.doInit()),this.initPromise}async doInit(){let e=Date.now();this.isIndexing=!0,this.lastWorkStart=e;try{await this.detectProviderDirs();let r=await ry(this.cacheName);this.loadedFromDisk=r!==null;let n=new Map;if(r)for(let o of r.files)n.set(o.filePath,o);await this.runExclusive(async()=>{await this.fullScan(n),this.rebuildSnapshotNow(),this.indexDurationMs=Date.now()-e,this.lastIndexedAt=new Date().toISOString(),this.schedulePersist()}),this.syncWatchersToDirs(),this.setupPolling()}finally{this.isIndexing=!1}}async detectProviderDirs(){let e=new Map,r=[];for(let s of Do())for(let i of s.getDirs())await jP(i)&&(e.has(i)||(e.set(i,s),r.push(i)));let n=[],o=[];for(let s of e.keys())this.dirToProvider.has(s)||n.push(s);for(let s of this.dirToProvider.keys())e.has(s)||o.push(s);return this.dirToProvider=e,this.existingDirs=r,{added:n,removed:o}}async fullScan(e){let r=[];for(let[o,s]of this.dirToProvider){let i=await ay(o,s);for(let a of i)r.push({file:a,provider:s})}let n=new Set(r.map(o=>o.file));await Promise.all(r.map(async({file:o,provider:s})=>{try{let i=await Lo.stat(o),a=e.get(o);if(a&&a.source===s.id&&a.parserVersion===s.parserVersion&&a.mtimeMs===i.mtimeMs&&a.size===i.size){this.files.set(o,{source:s.id,parserVersion:s.parserVersion,mtimeMs:i.mtimeMs,size:i.size,assistantRecords:a.assistantRecords,userRecords:a.userRecords,parentLinks:a.parentLinks});return}let c=await s.parseFile(o);this.files.set(o,{source:s.id,parserVersion:s.parserVersion,mtimeMs:i.mtimeMs,size:i.size,assistantRecords:c.assistant,userRecords:c.user,parentLinks:c.parentLinks})}catch(i){this.recordError(`parse ${o}: ${i.message}`)}}));for(let o of Array.from(this.files.keys()))n.has(o)||this.files.delete(o)}syncWatchersToDirs(){for(let[e,r]of this.watchers)if(!this.dirToProvider.has(e)){try{r.close()}catch{}this.watchers.delete(e)}for(let[e,r]of this.dirToProvider)if(!this.watchers.has(e))try{let n=IP(e,{recursive:!0},(o,s)=>{if(!s||typeof s!="string"||!s.endsWith(".jsonl"))return;let i=cy.join(e,s);this.scheduleFileReconcile(i,r)});n.on("error",o=>{this.recordError(`watcher ${e}: ${o.message}`)}),this.watchers.set(e,n)}catch(n){this.recordError(`watch ${e}: ${n.message}`)}}setupPolling(){this.pollTimer&&clearInterval(this.pollTimer);let e=this.cacheName==="mcp",r=process.env.CCGAUGE_POLL_FALLBACK;(r==="1"||r!=="0"&&!e)&&(this.pollTimer=setInterval(()=>{this.pollOnce().catch(o=>this.recordError(`poll: ${o.message}`))},AP),this.pollTimer.unref?.())}async pollOnce(){await this.runExclusive(async()=>{let e=Date.now(),r=await this.detectProviderDirs(),n=r.added.length>0||r.removed.length>0;n&&this.syncWatchersToDirs();let o=[];for(let[i,a]of this.dirToProvider){let c=await ay(i,a);for(let u of c)o.push({file:u,provider:a})}let s=new Set(o.map(i=>i.file));await Promise.all(o.map(async({file:i,provider:a})=>{try{let c=await Lo.stat(i),u=this.files.get(i);if(u&&u.mtimeMs===c.mtimeMs&&u.size===c.size)return;let d=await a.parseFile(i);this.files.set(i,{source:a.id,parserVersion:a.parserVersion,mtimeMs:c.mtimeMs,size:c.size,assistantRecords:d.assistant,userRecords:d.user,parentLinks:d.parentLinks}),n=!0}catch(c){this.recordError(`poll-parse ${i}: ${c.message}`)}}));for(let i of Array.from(this.files.keys()))s.has(i)||(this.files.delete(i),n=!0);n&&(this.lastWorkStart=e,this.scheduleSnapshotRebuild(),this.schedulePersist())})}scheduleFileReconcile(e,r){let n=this.fileDebouncers.get(e);n&&clearTimeout(n);let o=setTimeout(()=>{this.fileDebouncers.delete(e),this.reconcileFile(e,r).catch(s=>this.recordError(`reconcile ${e}: ${s.message}`))},CP);o.unref?.(),this.fileDebouncers.set(e,o)}async reconcileFile(e,r){await this.runExclusive(async()=>{let n=Date.now(),o=null;try{o=await Lo.stat(e)}catch{}if(!o||!o.isFile()){this.files.has(e)&&(this.files.delete(e),this.lastWorkStart=n,this.scheduleSnapshotRebuild(),this.schedulePersist());return}let s=this.files.get(e);if(!(s&&s.mtimeMs===o.mtimeMs&&s.size===o.size))try{let i=await r.parseFile(e);this.files.set(e,{source:r.id,parserVersion:r.parserVersion,mtimeMs:o.mtimeMs,size:o.size,assistantRecords:i.assistant,userRecords:i.user,parentLinks:i.parentLinks}),this.lastWorkStart=n,this.scheduleSnapshotRebuild(),this.schedulePersist()}catch(i){this.recordError(`parse ${e}: ${i.message}`)}})}scheduleSnapshotRebuild(){this.snapshotRebuildTimer&&clearTimeout(this.snapshotRebuildTimer),this.snapshotRebuildTimer=setTimeout(()=>{this.snapshotRebuildTimer=null,this.rebuildSnapshotNow()},OP),this.snapshotRebuildTimer.unref?.()}rebuildSnapshotNow(){let e=Date.now(),r=this.lastWorkStart??e,n=[],o=[],s={},i=0,a={claude:{source:"claude",filesScanned:0,recordsParsed:0,assistantRecords:0,scannedDirs:[]},codex:{source:"codex",filesScanned:0,recordsParsed:0,assistantRecords:0,scannedDirs:[]}};for(let[l,m]of this.dirToProvider)a[m.id].scannedDirs.push(l);for(let l of this.files.values()){n.push(...l.assistantRecords),o.push(...l.userRecords);for(let[m,f]of l.parentLinks)s[m]=f;i+=l.assistantRecords.length+l.userRecords.length,a[l.source].filesScanned+=1,a[l.source].recordsParsed+=l.assistantRecords.length+l.userRecords.length}let c=j_(n).sort((l,m)=>l.timestamp.localeCompare(m.timestamp)),u=ZP(o).sort((l,m)=>l.timestamp.localeCompare(m.timestamp));iy({assistantRecords:c,userRecords:u,parentMap:s});for(let l of c)l.isSidechain&&(l.isWorkflowSubagent=sy(l.filePath)==="workflow");for(let l of c)a[l.source].assistantRecords+=1;let d={filesScanned:this.files.size,recordsParsed:i,assistantRecords:c.length,durationMs:Date.now()-r,scannedDirs:this.existingDirs};this.snapshot={records:c,userRecords:u,parentMap:s,stats:d,bySource:Object.values(a)},this.lastWorkStart=null}getSnapshot(){if(!this.snapshot)throw new Error("Indexer not initialized \u2014 call init() first.");return this.snapshot}async forceRescan(){let e=!this.initPromise;if(await this.init(),e)return this.snapshot;if(this.rescanPromise)return this.rescanPromise;this.rescanPromise=this.runRescan();try{return await this.rescanPromise}finally{this.rescanPromise=null}}async runRescan(){this.isIndexing=!0;try{return await this.runExclusive(async()=>{let e=Date.now();return this.lastWorkStart=e,this.snapshotRebuildTimer&&(clearTimeout(this.snapshotRebuildTimer),this.snapshotRebuildTimer=null),this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.files.clear(),await this.detectProviderDirs(),await this.fullScan(new Map),this.rebuildSnapshotNow(),this.indexDurationMs=Date.now()-e,this.lastIndexedAt=new Date().toISOString(),this.syncWatchersToDirs(),this.schedulePersist(),this.snapshot})}finally{this.isIndexing=!1}}getStatus(){let e=this.snapshot;return{initialized:e!==null,isIndexing:this.isIndexing,lastIndexedAt:this.lastIndexedAt,indexDurationMs:this.indexDurationMs,filesIndexed:this.files.size,recordsIndexed:e?.stats.assistantRecords??0,bySource:e?.bySource??[],watchers:this.watchers.size,errors:this.errors.slice(-Ed),pendingReconciles:this.fileDebouncers.size,loadedFromDisk:this.loadedFromDisk}}schedulePersist(){this.persistTimer&&clearTimeout(this.persistTimer),this.persistTimer=setTimeout(()=>{this.persistTimer=null;let e=[];for(let[r,n]of this.files)e.push({filePath:r,source:n.source,parserVersion:n.parserVersion,mtimeMs:n.mtimeMs,size:n.size,assistantRecords:n.assistantRecords,userRecords:n.userRecords,parentLinks:n.parentLinks});ny({savedAt:new Date().toISOString(),files:e},this.cacheName).catch(r=>this.recordError(`persist: ${r.message}`))},NP),this.persistTimer.unref?.()}recordError(e){let r=`${new Date().toISOString()} ${qo(e)}`;this.errors.push(r),this.errors.length>Ed*2&&this.errors.splice(0,this.errors.length-Ed),process.env.CCGAUGE_DEBUG&&console.error(`[ccgauge:indexer] ${new Date().toISOString()} ${e}`)}disposeWatchers(){for(let e of this.watchers.values())try{e.close()}catch{}this.watchers.clear()}dispose(){this.disposeWatchers(),this.pollTimer&&clearInterval(this.pollTimer),this.snapshotRebuildTimer&&clearTimeout(this.snapshotRebuildTimer),this.persistTimer&&clearTimeout(this.persistTimer);for(let e of this.fileDebouncers.values())clearTimeout(e);this.fileDebouncers.clear()}};async function jP(t){try{return(await Lo.stat(t)).isDirectory()}catch{return!1}}async function ay(t,e){let r=[];async function n(o,s){if(s>MP)return;let i;try{i=await Lo.readdir(o,{withFileTypes:!0})}catch{return}for(let a of i){let c=cy.join(o,a.name);if(a.isDirectory()){if(e.shouldSkipDir(a.name))continue;await n(c,s+1)}else a.isFile()&&a.name.endsWith(".jsonl")&&r.push(c)}}return await n(t,0),r}function ZP(t){let e=new Set;return t.filter(r=>{let n=r.uuid;return n?e.has(n)?!1:(e.add(n),!0):!0})}function DP(){return globalThis.__ccgaugeIndexers||(globalThis.__ccgaugeIndexers=new Map),globalThis.__ccgaugeIndexers}function uy(t=Tn){let e=DP(),r=e.get(t);return r||(r=new Id(t),e.set(t,r)),r}var qP="mcp";async function Ce(){let t=uy(qP);return await t.init(),t}function zn(t){let e=t.from?ly(t.from,"from",!1):void 0,r=t.to?ly(t.to,"to",!0):void 0;if(e||r){let a=e&&r?`${t.from} \u2192 ${t.to}`:e?`from ${t.from}`:`until ${t.to}`;return{from:e,to:r,label:a}}let n=(t.range||"all").toLowerCase(),o=new Date,s=Mi(o),i=Zo(o);switch(n){case"today":return{from:s,to:i,label:"today"};case"yesterday":{let a=new Date(s);a.setDate(a.getDate()-1);let c=Zo(a);return{from:a,to:c,label:"yesterday"}}case"this_week":return{from:dy(o),to:i,label:"this_week"};case"last_week":{let a=dy(o),c=new Date(a);c.setDate(c.getDate()-7);let u=new Date(a);return u.setMilliseconds(u.getMilliseconds()-1),{from:c,to:u,label:"last_week"}}case"this_month":return{from:new Date(o.getFullYear(),o.getMonth(),1),to:i,label:"this_month"};case"last_month":{let a=new Date(o.getFullYear(),o.getMonth()-1,1),c=new Date(o.getFullYear(),o.getMonth(),1);return c.setMilliseconds(c.getMilliseconds()-1),{from:a,to:c,label:"last_month"}}case"all":return{label:"all"};case"7d":case"30d":case"90d":{let a=parseInt(n,10),c=new Date(s);return c.setDate(c.getDate()-(a-1)),{from:c,to:i,label:n}}default:throw new Error(`invalid 'range' argument: ${JSON.stringify(t.range)}. Expected one of: today, yesterday, this_week, last_week, this_month, last_month, 7d, 30d, 90d, all.`)}}function ly(t,e,r){let n=Zi(t,{upperBoundDateOnly:r});if(!n)throw new Error(`invalid '${e}' argument: ${JSON.stringify(t)}. Expected YYYY-MM-DD or a full ISO 8601 timestamp.`);return n}function py(t){let r=Mi(new Date),n=(t??"today").toLowerCase(),o=c=>({start:Mi(c),end:Zo(c)});if(n==="today"){let{start:c,end:u}=o(r);return{from:c,to:u,label:"today"}}if(n==="yesterday"){let c=new Date(r);c.setDate(c.getDate()-1);let{start:u,end:d}=o(c);return{from:u,to:d,label:"yesterday"}}let i=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].indexOf(n);if(i>=0){let c=new Date(r),u=c.getDay()-i;u<0&&(u+=7),c.setDate(c.getDate()-u);let{start:d,end:l}=o(c);return{from:d,to:l,label:n}}let a=ji(t??"");if(a){let{start:c,end:u}=o(a);return{from:c,to:u,label:t??""}}throw new Error(`invalid 'date' argument: ${JSON.stringify(t)}. Expected today | yesterday | monday..sunday | YYYY-MM-DD.`)}function dy(t){let e=t.getDay()||7,r=new Date(t);return r.setDate(r.getDate()-e+1),r.setHours(0,0,0,0),r}function Rn(t){let e=Sn(t.source),{pricing:r}=e.resolvePricing(t.model);return e.costFromUsage(t.usage,r,t.model)}function Uo(t){if(!t)return"(unknown)";let r=t.replace(/[/\\]+$/,"").split(/[/\\]+/);return r[r.length-1]||t}import{readFileSync as LP,statSync as UP}from"node:fs";import{basename as fy}from"node:path";var my=new Map,FP=/^(.+?)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)[/\\]?$/,VP=/^(.+?)[/\\](?:\.git|\.claude)[/\\]worktrees[/\\]([^/\\]+)(?:[/\\].*)?$/;function HP(t){let e=Uo(t);if(!t)return{label:e,isWorktree:!1,mainName:e,worktreeName:"",canonicalCwd:t};let r=VP.exec(t);if(r){let n=r[1],o=r[2],s=fy(n)||n;return{label:`${s} (${o})`,isWorktree:!0,mainName:s,worktreeName:o,canonicalCwd:n}}try{let n=`${t}/.git`;if(!UP(n).isFile())return{label:e,isWorktree:!1,mainName:e,worktreeName:"",canonicalCwd:t};let i=LP(n,"utf8").trim().split(/\r?\n/,1)[0]??"",a=/^gitdir:\s*(.+)$/.exec(i);if(!a)return{label:e,isWorktree:!1,mainName:e,worktreeName:"",canonicalCwd:t};let c=a[1].trim(),u=FP.exec(c);if(!u)return{label:e,isWorktree:!1,mainName:e,worktreeName:"",canonicalCwd:t};let d=u[1],l=u[2],m=fy(d)||d;return{label:`${m} (${l})`,isWorktree:!0,mainName:m,worktreeName:l,canonicalCwd:d}}catch{return{label:e,isWorktree:!1,mainName:e,worktreeName:"",canonicalCwd:t}}}function hy(t){let e=my.get(t);if(e)return e.label;let r=HP(t);return my.set(t,r),r.label}function Fi(t,e){let r=new Date(t),n=r.getFullYear(),o=String(r.getMonth()+1).padStart(2,"0"),s=String(r.getDate()).padStart(2,"0"),i=String(r.getHours()).padStart(2,"0");if(e==="hour")return{key:`${n}-${o}-${s}T${i}`,label:`${o}/${s} ${i}:00`};if(e==="day")return{key:`${n}-${o}-${s}`,label:`${o}/${s}`};if(e==="week"){let a=new Date(r),c=a.getDay()||7;a.setDate(a.getDate()-c+1);let u=String(a.getMonth()+1).padStart(2,"0"),d=String(a.getDate()).padStart(2,"0");return{key:`${a.getFullYear()}-W${u}${d}`,label:`Wk ${u}/${d}`}}return{key:`${n}-${o}`,label:`${n}-${o}`}}function Fo(t){return{source:t.source,fromIso:t.from?.toISOString(),toIso:t.to?.toISOString(),models:t.models&&t.models.length?new Set(t.models):void 0,projects:t.projects&&t.projects.length?new Set(t.projects):void 0}}function Vo(t,e){return!(t.source!==e.source||e.fromIso&&t.timestamp<e.fromIso||e.toIso&&t.timestamp>e.toIso||e.models&&!e.models.has(t.model)||e.projects&&!e.projects.has(t.cwd))}function gy(t,e,r){let n=new Map,o=Fo(r);for(let s of t){if(!Vo(s,o))continue;let{key:i,label:a}=Fi(s.timestamp,e),c=n.get(i);c||(c=BP(i,a),n.set(i,c)),KP(c,s)}return Array.from(n.values()).sort((s,i)=>s.key.localeCompare(i.key))}function BP(t,e){return{key:t,label:e,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,totalTokens:0,cost:0,saved:0,requests:0,models:{}}}function KP(t,e){let r=Rn(e);t.inputTokens+=e.usage.input_tokens,t.outputTokens+=e.usage.output_tokens,t.cacheReadTokens+=e.usage.cache_read_input_tokens,t.cacheCreationTokens+=e.usage.cache_creation_input_tokens,t.totalTokens=t.inputTokens+t.outputTokens+t.cacheReadTokens+t.cacheCreationTokens,t.cost+=r.total,t.saved+=r.saved,t.requests+=1;let n=t.models[e.model]??{tokens:0,cost:0,requests:0};n.tokens+=e.usage.input_tokens+e.usage.output_tokens+e.usage.cache_read_input_tokens+e.usage.cache_creation_input_tokens,n.cost+=r.total,n.requests+=1,t.models[e.model]=n}function _y(t,e){let r=new Map,n=Fo(e);for(let o of t){if(!Vo(o,n))continue;let s=r.get(o.model);if(!s){let{pricing:a,matchType:c}=Sn(o.source).resolvePricing(o.model);s={model:o.model,source:o.source,requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,totalTokens:0,cost:0,saved:0,pricing:a,pricingResolved:c==="exact"||c==="date-stripped"||c==="prefix-stripped"},r.set(o.model,s)}let i=Rn(o);s.requests+=1,s.inputTokens+=o.usage.input_tokens,s.outputTokens+=o.usage.output_tokens,s.cacheReadTokens+=o.usage.cache_read_input_tokens,s.cacheCreationTokens+=o.usage.cache_creation_input_tokens,s.totalTokens=s.inputTokens+s.outputTokens+s.cacheReadTokens+s.cacheCreationTokens,s.cost+=i.total,s.saved+=i.saved}return Array.from(r.values()).sort((o,s)=>s.cost-o.cost)}function yy(t,e){let r=new Map,n=new Map,o=Fo(e);for(let s of t){if(!Vo(s,o))continue;let i=s.cwd||"(unknown)",a=r.get(i);a||(a={source:e.source,cwd:i,projectName:Uo(i),sessions:0,requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,totalTokens:0,cost:0,saved:0,firstActivity:s.timestamp,lastActivity:s.timestamp,models:[]},r.set(i,a),n.set(i,new Set)),n.get(i).add(s.sessionId);let c=Rn(s);a.requests+=1,a.inputTokens+=s.usage.input_tokens,a.outputTokens+=s.usage.output_tokens,a.cacheReadTokens+=s.usage.cache_read_input_tokens,a.cacheCreationTokens+=s.usage.cache_creation_input_tokens,a.totalTokens=a.inputTokens+a.outputTokens+a.cacheReadTokens+a.cacheCreationTokens,a.cost+=c.total,a.saved+=c.saved,s.timestamp<a.firstActivity&&(a.firstActivity=s.timestamp),s.timestamp>a.lastActivity&&(a.lastActivity=s.timestamp),a.models.includes(s.model)||a.models.push(s.model)}for(let[s,i]of n){let a=r.get(s);a.sessions=i.size}return Array.from(r.values()).sort((s,i)=>i.cost-s.cost)}function vy(t,e,r){let n=new Map,o=Fo(r);for(let i of t){if(!Vo(i,o))continue;let a=i.sessionId||i.uuid,c=n.get(a);c||(c={sessionId:a,source:i.source,cwd:i.cwd,projectName:Uo(i.cwd),projectLabel:hy(i.cwd),startTime:i.timestamp,endTime:i.timestamp,durationMs:0,requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,totalTokens:0,cost:0,saved:0,models:[],modelBreakdown:{}},n.set(a,c));let u=Rn(i);c.requests+=1,c.inputTokens+=i.usage.input_tokens,c.outputTokens+=i.usage.output_tokens,c.cacheReadTokens+=i.usage.cache_read_input_tokens,c.cacheCreationTokens+=i.usage.cache_creation_input_tokens,c.totalTokens=c.inputTokens+c.outputTokens+c.cacheReadTokens+c.cacheCreationTokens,c.cost+=u.total,c.saved+=u.saved,i.timestamp<c.startTime&&(c.startTime=i.timestamp),i.timestamp>c.endTime&&(c.endTime=i.timestamp),c.models.includes(i.model)||c.models.push(i.model);let d=c.modelBreakdown[i.model]??{tokens:0,cost:0,requests:0};d.tokens+=i.usage.input_tokens+i.usage.output_tokens+i.usage.cache_read_input_tokens+i.usage.cache_creation_input_tokens,d.cost+=u.total,d.requests+=1,c.modelBreakdown[i.model]=d}let s=new Map;for(let i of e){let a=s.get(i.sessionId);(!a||i.timestamp<a.timestamp)&&s.set(i.sessionId,i)}for(let i of n.values()){i.durationMs=Math.max(0,new Date(i.endTime).getTime()-new Date(i.startTime).getTime());let a=s.get(i.sessionId);a&&a.textPreview&&(i.firstUserMessage=a.textPreview,i.title=a.textPreview.slice(0,80))}return Array.from(n.values()).sort((i,a)=>a.endTime.localeCompare(i.endTime))}function by(t,e){let r=0,n=0,o=0,s=0,i=0,a=0,c=0,u=Fo(e);for(let d of t){if(!Vo(d,u))continue;let l=Rn(d);r+=d.usage.input_tokens,n+=d.usage.output_tokens,o+=d.usage.cache_read_input_tokens,s+=d.usage.cache_creation_input_tokens,i+=l.total,a+=l.saved,c+=1}return{inputTokens:r,outputTokens:n,cacheReadTokens:o,cacheCreationTokens:s,totalTokens:r+n+o+s,cost:i,saved:a,requests:c}}function WP(t,e,r){let n=new Map;for(let a of e)a.isSynthetic||a.textPreview&&a.textPreview.trim()&&n.set(a.uuid,a.textPreview);let o=new Map,s=new Map;function i(a){let c=[],u=a,d=null,l=0,m=new Set;for(;u&&l++<5e3&&!m.has(u);){m.add(u);let f=s.get(u);if(f){d=f;break}if(c.push(u),n.has(u)){d=u;break}u=r[u]??null}d||(d=a);for(let f of c)s.set(f,d);return d}for(let a of t)o.set(a.uuid,i(a.uuid));return o}function Pn(t,e,r){let n=WP(t,e,r),o=new Map;for(let s of t){let i=n.get(s.uuid)??s.uuid,a=o.get(i);(!a||s.timestamp<a.firstTimestamp)&&o.set(i,{turnId:i,firstTimestamp:s.timestamp,firstModel:s.model,cwd:s.cwd,sessionId:s.sessionId,source:s.source})}return o}var En={input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,reasoning_tokens:0,total_tokens:0,cost_usd:0,saved_usd:0,requests:0,turns:0};function Ho(t,e){return t.filter(r=>r.source===e)}function GP(t){let e=0;for(let r of t)e+=r.usage.reasoning_tokens??0;return e}function Vi(t,e){return!(e.from&&t.timestamp<e.from.toISOString()||e.to&&t.timestamp>e.to.toISOString())}function JP(t,e,r,n){let o=Ho(t,e),s=o.filter(a=>Vi(a,r)),i=by(o,{source:e,...r});return{input_tokens:i.inputTokens,output_tokens:i.outputTokens,cache_read_tokens:i.cacheReadTokens,cache_creation_tokens:i.cacheCreationTokens,reasoning_tokens:GP(s),total_tokens:i.totalTokens,cost_usd:i.cost,saved_usd:i.saved,requests:i.requests,turns:Pn(s,n.users,n.parentMap).size}}function xy(t){return t.reduce((e,r)=>({input_tokens:e.input_tokens+r.input_tokens,output_tokens:e.output_tokens+r.output_tokens,cache_read_tokens:e.cache_read_tokens+r.cache_read_tokens,cache_creation_tokens:e.cache_creation_tokens+r.cache_creation_tokens,reasoning_tokens:e.reasoning_tokens+r.reasoning_tokens,total_tokens:e.total_tokens+r.total_tokens,cost_usd:e.cost_usd+r.cost_usd,saved_usd:e.saved_usd+r.saved_usd,requests:e.requests+r.requests,turns:e.turns+r.turns}),{...En})}function Bo(t,e,r,n){let o={claude:{...En},codex:{...En}},s=e==="all"?$n:[e];for(let i of s)o[i]=JP(t,i,r,n);return{totals:xy(s.map(i=>o[i])),bySource:o}}function Hi(t,e,r,n,o){let s=e==="all"?$n:[e],i=new Map;for(let a of s){let c=Ho(t,a),u=gy(c,r,{source:a,...n}),d=new Map,l=n.from?.toISOString(),m=n.to?.toISOString(),f=[];for(let g of c){if(l&&g.timestamp<l||m&&g.timestamp>m)continue;f.push(g);let _=g.usage.reasoning_tokens??0;if(_>0){let{key:b}=Fi(g.timestamp,r);d.set(b,(d.get(b)??0)+_)}}let p=new Map,h=Pn(f,o.users,o.parentMap);for(let g of h.values()){let{key:_}=Fi(g.firstTimestamp,r);p.set(_,(p.get(_)??0)+1)}for(let g of u){let _=i.get(g.key);_||(_={key:g.key,label:g.label,totals:{...En},bySource:{claude:{...En},codex:{...En}}},i.set(g.key,_));let b={input_tokens:g.inputTokens,output_tokens:g.outputTokens,cache_read_tokens:g.cacheReadTokens,cache_creation_tokens:g.cacheCreationTokens,reasoning_tokens:d.get(g.key)??0,total_tokens:g.totalTokens,cost_usd:g.cost,saved_usd:g.saved,requests:g.requests,turns:p.get(g.key)??0};_.bySource[a]=b,_.totals=xy(Object.values(_.bySource))}}return Array.from(i.values()).sort((a,c)=>a.key.localeCompare(c.key))}function Ko(t,e,r,n){let o=e==="all"?$n:[e],s=[];for(let i of o){let a=Ho(t,i),c=a.filter(l=>Vi(l,r)),u=_y(a,{source:i,...r}),d=new Map;for(let l of Pn(c,n.users,n.parentMap).values())d.set(l.firstModel,(d.get(l.firstModel)??0)+1);for(let l of u)s.push({source:i,model:l.model,requests:l.requests,turns:d.get(l.model)??0,input_tokens:l.inputTokens,output_tokens:l.outputTokens,cache_read_tokens:l.cacheReadTokens,cache_creation_tokens:l.cacheCreationTokens,total_tokens:l.totalTokens,cost_usd:l.cost,saved_usd:l.saved,pricing_resolved:l.pricingResolved})}return s.sort((i,a)=>a.cost_usd-i.cost_usd)}function Bi(t,e,r,n){let o=e==="all"?$n:[e],s=[];for(let i of o){let a=Ho(t,i),c=a.filter(l=>Vi(l,r)),u=yy(a,{source:i,...r}),d=new Map;for(let l of Pn(c,n.users,n.parentMap).values()){let m=l.cwd||"(unknown)";d.set(m,(d.get(m)??0)+1)}for(let l of u)s.push({source:i,cwd:l.cwd,project_name:l.projectName,sessions:l.sessions,requests:l.requests,turns:d.get(l.cwd)??0,input_tokens:l.inputTokens,output_tokens:l.outputTokens,cache_read_tokens:l.cacheReadTokens,cache_creation_tokens:l.cacheCreationTokens,total_tokens:l.totalTokens,cost_usd:l.cost,saved_usd:l.saved,models:l.models,first_activity:l.firstActivity,last_activity:l.lastActivity})}return s.sort((i,a)=>a.cost_usd-i.cost_usd)}function In(t,e,r,n,o){let s=r==="all"?$n:[r],i=[];for(let a of s){let c=Ho(t,a),u=e.filter(f=>f.source===a),d=c.filter(f=>Vi(f,n)),l=vy(c,u,{source:a,...n}),m=new Map;for(let f of Pn(d,o.users,o.parentMap).values())m.set(f.sessionId,(m.get(f.sessionId)??0)+1);for(let f of l)i.push({source:a,session_id:f.sessionId,cwd:f.cwd,project_name:f.projectName,title:f.title,first_user_message:f.firstUserMessage,start_time:f.startTime,end_time:f.endTime,duration_ms:f.durationMs,requests:f.requests,turns:m.get(f.sessionId)??0,input_tokens:f.inputTokens,output_tokens:f.outputTokens,cache_read_tokens:f.cacheReadTokens,cache_creation_tokens:f.cacheCreationTokens,total_tokens:f.totalTokens,cost_usd:f.cost,saved_usd:f.saved,models:f.models})}return i.sort((a,c)=>c.end_time.localeCompare(a.end_time))}var YP=process.env.CCGAUGE_MCP_PRETTY==="1";function yt(t){return{content:[{type:"text",text:YP?JSON.stringify(t,null,2):JSON.stringify(t)}]}}function vt(t){return async e=>{try{return await t(e)}catch(r){if(r instanceof Error){let n=qo(r.message);throw n!==r.message&&(r.message=n),r}throw new Error(qo(String(r)))}}}function wy(t){t.registerTool("usage_summary",{title:"Usage summary",description:'Total tokens and dollar-equivalent cost for a date range. When source="all" (default), the response includes a per-source breakdown alongside combined totals so the LLM can answer either provider-specific or combined questions in a single call.',inputSchema:{...kn,...Pt}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=zn(e),i=e.source??"all",a=Bo(n.records,i,{from:s.from,to:s.to},o);return yt({range_label:s.label,from:s.from?.toISOString(),to:s.to?.toISOString(),source:i,...a})})),t.registerTool("usage_by_time",{title:"Usage by time",description:'Time-series of usage and cost, bucketed by hour/day/week/month. Useful for "draw me a trend" or "when does usage spike" questions. Each bucket carries combined totals plus a bySource map (for source="all").',inputSchema:{...kn,...Pt,granularity:N_.describe("hour | day | week | month (default: day)")}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=zn(e),i=e.source??"all",a=e.granularity??"day",c=Hi(n.records,i,a,{from:s.from,to:s.to},o);return yt({range_label:s.label,from:s.from?.toISOString(),to:s.to?.toISOString(),source:i,granularity:a,bucket_count:c.length,buckets:c})})),t.registerTool("usage_by_model",{title:"Usage by model",description:"Per-model usage and cost for a date range. Each entry carries its `source` so you can group by provider client-side. Sorted by cost desc.",inputSchema:{...kn,...Pt,limit:le.number().int().min(1).max(50).default(20).describe("Cap to top N entries by cost. Default 20.")}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=zn(e),i=e.source??"all",a=e.limit??20,c=Ko(n.records,i,{from:s.from,to:s.to},o);return c=c.slice(0,a),yt({range_label:s.label,source:i,count:c.length,models:c})})),t.registerTool("usage_by_project",{title:"Usage by project",description:'Per-project (working directory) usage and cost. Useful for answering "which project is eating my budget" or "what have I worked on this month". Sorted by cost desc.',inputSchema:{...kn,...Pt,limit:le.number().int().min(1).max(100).default(20).describe("Cap to top N projects by cost. Default 20.")}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=zn(e),i=e.source??"all",a=e.limit??20,c=Bi(n.records,i,{from:s.from,to:s.to},o);return c=c.slice(0,a),yt({range_label:s.label,source:i,count:c.length,projects:c})})),t.registerTool("usage_by_session",{title:"Usage by session",description:"Per-session list with each session's first user message (as title), models used, duration, tokens and cost. Default sort is most-recent first; use `sort` to switch.",inputSchema:{...kn,...Pt,sort:le.enum(["recent","cost","tokens","duration"]).default("recent").describe("recent (default) | cost | tokens | duration. Always desc."),limit:le.number().int().min(1).max(200).default(25).describe("Max sessions to return. Default 25.")}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=zn(e),i=e.source??"all",a=e.sort??"recent",c=e.limit??25,u=In(n.records,n.userRecords,i,{from:s.from,to:s.to},o);switch(a){case"cost":u.sort((l,m)=>m.cost_usd-l.cost_usd);break;case"tokens":u.sort((l,m)=>m.total_tokens-l.total_tokens);break;case"duration":u.sort((l,m)=>m.duration_ms-l.duration_ms);break;default:u.sort((l,m)=>m.end_time.localeCompare(l.end_time))}let d=u.length;return u=u.slice(0,c),yt({range_label:s.label,source:i,sort:a,total_count:d,returned_count:u.length,sessions:u})})),t.registerTool("cost_estimator",{title:"Cost estimator",description:"Compute the dollar-equivalent cost of a hypothetical request given token counts. Uses the provider's built-in per-1M-token pricing table; does NOT consult the user's usage history. Useful for \"how much would 5M output tokens of opus 4.8 cost\" / pre-purchase what-ifs. NOTE: reasoning tokens (Codex / OpenAI o-series) are already included in `output_tokens` and billed at the output rate \u2014 don't double-count them.",inputSchema:{source:le.enum(["claude","codex"]).describe("claude | codex \u2014 pick the pricing namespace."),model:le.string().min(1).describe('Exact model id (e.g. "claude-opus-4-8-20260115", "gpt-5.2-codex"). Date suffixes are stripped automatically.'),input_tokens:le.number().int().min(0).default(0),output_tokens:le.number().int().min(0).default(0).describe("Total output tokens. INCLUDES reasoning tokens for Codex / o-series \u2014 those are billed at the output rate, not separately."),cache_read_tokens:le.number().int().min(0).default(0),cache_creation_tokens:le.number().int().min(0).default(0).describe("Sum of 5m + 1h cache writes (Anthropic) or 0 (OpenAI).")}},vt(async e=>{let r=e.source,n=Sn(r),{pricing:o,matchType:s}=n.resolvePricing(e.model),i={input_tokens:e.input_tokens??0,output_tokens:e.output_tokens??0,cache_creation_input_tokens:e.cache_creation_tokens??0,cache_read_input_tokens:e.cache_read_tokens??0,cache_creation_5m:0,cache_creation_1h:0},a=or(i,o);return yt({source:r,model:e.model,pricing_match:s,pricing_resolved:s==="exact"||s==="date-stripped"||s==="prefix-stripped",pricing:o,usage:i,cost_breakdown:{input:a.input,output:a.output,cache_creation:a.cacheCreation5m+a.cacheCreation1h,cache_read:a.cacheRead,total:a.total,saved_vs_full_input:a.saved},total_tokens:i.input_tokens+i.output_tokens+i.cache_read_input_tokens+i.cache_creation_input_tokens})}))}var Cd={input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,reasoning_tokens:0,total_tokens:0,cost_usd:0,saved_usd:0,requests:0,turns:0};function XP(t){let e=new Date,r=e.getDay()||7,n=new Date(e);n.setDate(e.getDate()-r+1+t*7),n.setHours(0,0,0,0);let o=new Date(n);o.setDate(n.getDate()+6),o.setHours(23,59,59,999);let s=i=>`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")}`;return{from:n,to:o,label:`${s(n)} \u2192 ${s(o)}`}}function QP(t){let e=new Map;for(let r of t){let n=r.cwd||"(unknown)",o=e.get(n);o||(o={project:r.project_name,cwd:n,sessions:[]},e.set(n,o)),o.sessions.push(r)}return Array.from(e.values()).sort((r,n)=>n.sessions.reduce((o,s)=>o+s.cost_usd,0)-r.sessions.reduce((o,s)=>o+s.cost_usd,0))}function ky(t,e,r,n=10){let o=e.from.toISOString(),s=e.to.toISOString(),i=new Map;for(let a of t)if(!(r!=="all"&&a.source!==r)&&!(a.timestamp<o)&&!(a.timestamp>s))for(let c of a.toolNames)i.set(c,(i.get(c)??0)+1);return Array.from(i.entries()).sort((a,c)=>c[1]-a[1]).slice(0,n).map(([a,c])=>({tool:a,count:c}))}function $y(t){t.registerTool("daily_summary",{title:"Daily summary \u2014 what was worked on",description:'A "what did I do" report for a single day. Returns totals, sessions grouped by project (with first-user-message titles), models used, and top tool calls. Date defaults to "today" and accepts "yesterday", weekday names ("monday"..), or YYYY-MM-DD.',inputSchema:{date:M_.optional().describe("today | yesterday | monday..sunday | YYYY-MM-DD. Default today."),...Pt}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=py(e.date),i=e.source??"all",a=Bo(n.records,i,s,o),c=In(n.records,n.userRecords,i,s,o),u=Ko(n.records,i,s,o),d=ky(n.records,s,i);return yt({date:s.label,from:s.from.toISOString(),to:s.to.toISOString(),source:i,totals:a.totals,bySource:a.bySource,session_count:c.length,sessions_by_project:QP(c),models:u,top_tools:d})})),t.registerTool("weekly_summary",{title:"Weekly summary",description:"A week-long roll-up: totals, per-day cost trend, top sessions by cost, top projects, and models used. Use `week_offset` to walk back (0=this week, -1=last week, etc.).",inputSchema:{week_offset:le.number().int().min(-52).max(0).default(0).describe("0=this week, -1=last week, ..., -52=one year ago. Default 0."),...Pt,top_session_limit:le.number().int().min(1).max(50).default(10)}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=e.week_offset??0,i=XP(s),a=e.source??"all",c=Bo(n.records,a,i,o),u=Hi(n.records,a,"day",{from:i.from,to:i.to},o),d=new Map(u.map(_=>[_.key,_])),l=[];for(let _=0;_<7;_++){let b=new Date(i.from);b.setDate(b.getDate()+_);let x=`${b.getFullYear()}-${String(b.getMonth()+1).padStart(2,"0")}-${String(b.getDate()).padStart(2,"0")}`,$=d.get(x);$?l.push({date:x,totals:$.totals,bySource:$.bySource}):l.push({date:x,totals:{...Cd},bySource:{claude:{...Cd},codex:{...Cd}}})}let m=In(n.records,n.userRecords,a,i,o),f=m.slice().sort((_,b)=>b.cost_usd-_.cost_usd).slice(0,e.top_session_limit??10),p=Bi(n.records,a,i,o).slice(0,10),h=Ko(n.records,a,i,o),g=ky(n.records,i,a);return yt({week:i.label,from:i.from.toISOString(),to:i.to.toISOString(),source:a,totals:c.totals,bySource:c.bySource,per_day:l,session_count:m.length,top_sessions:f,top_projects:p,models:h,top_tools:g})})),t.registerTool("recent_activity",{title:"Recent activity",description:'The N most recently active sessions across providers. Quick way to answer "what did I just work on" without specifying a date. Defaults to the last 30 days so the response time stays bounded regardless of how long the user has been running ccgauge \u2014 pass `days` to widen.',inputSchema:{limit:le.number().int().min(1).max(50).default(10).describe("Number of sessions to return. Default 10."),days:le.number().int().min(1).max(365).default(30).describe("Look-back window in days. Default 30. Increase if the user has long-running idle sessions you still want surfaced."),...Pt}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=e.source??"all",i=e.limit??10,a=e.days??30,c=new Date,u=new Date(c);u.setDate(u.getDate()-(a-1)),u.setHours(0,0,0,0);let d=new Date(c);d.setHours(23,59,59,999);let l=In(n.records,n.userRecords,s,{from:u,to:d},o).slice().sort((m,f)=>f.end_time.localeCompare(m.end_time)).slice(0,i);return yt({source:s,window_days:a,from:u.toISOString(),to:d.toISOString(),returned_count:l.length,sessions:l})}))}function Sy(t){t.registerResource("providers","ccgauge://providers",{title:"Detected providers",description:"Which AI coding CLIs ccgauge has discovered on this machine, the data directories scanned for each, and a per-source file/record count from the latest snapshot.",mimeType:"application/json"},async e=>{let r=await Ce(),n=r.getSnapshot(),o=r.getStatus(),s=await ey(),i=Do().map(a=>{let c=n.bySource.find(u=>u.source===a.id);return{id:a.id,display_name:a.displayName.en,short_label:a.shortLabel,available:s.includes(a.id),parser_version:a.parserVersion,capabilities:a.capabilities,dirs:a.getDirs(),dirs_with_data:c?.scannedDirs??[],files_indexed:c?.filesScanned??0,assistant_records:c?.assistantRecords??0}});return{contents:[{uri:e.href,mimeType:"application/json",text:JSON.stringify({last_indexed_at:o.lastIndexedAt,index_duration_ms:o.indexDurationMs,loaded_from_disk:o.loadedFromDisk,providers:i},null,2)}]}})}var e1="ccgauge",Ty="1.2.0";function t1(){let t=new Oi({name:e1,version:Ty},{capabilities:{tools:{},resources:{}}});return wy(t),$y(t),Sy(t),t}async function zy(){let t=(...o)=>{process.stderr.write(`[ccgauge-mcp] ${o.map(String).join(" ")}
|
|
43
|
-
`)};Ce().then(o=>{let s=o.getStatus();t(`indexer ready: files=${s.filesIndexed} records=${s.recordsIndexed} loadedFromDisk=${s.loadedFromDisk}`)}).catch(o=>t("indexer init failed:",o.message));let e=t1(),r=new Ni,n=()=>{t("shutting down"),r.close().catch(()=>{}),process.exit(0)};process.on("SIGINT",n),process.on("SIGTERM",n),await e.connect(r),t(`v${Ty} listening on stdio`)}var r1="1.2.
|
|
42
|
+
`}var Ni=class{constructor(e=C_.stdin,r=C_.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ai,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=I_(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var DR=/^(\d{4})-(\d{2})-(\d{2})(.*)$/;function Mi(t){let e=new Date(t);return e.setHours(0,0,0,0),e}function Zo(t){let e=new Date(t);return e.setHours(23,59,59,999),e}function ji(t){let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!e)return null;let r=Number(e[1]),n=Number(e[2]),o=Number(e[3]),s=new Date(r,n-1,o);return s.getFullYear()!==r||s.getMonth()!==n-1||s.getDate()!==o?null:s}function O_(t){return ji(t)!==null}function Zi(t,e={}){let r=DR.exec(t);if(r){let o=`${r[1]}-${r[2]}-${r[3]}`,s=ji(o);if(!s)return null;if(r[4]==="")return e.upperBoundDateOnly?Zo(s):s;let i=new Date(t);if(Number.isNaN(i.getTime()))return null;let a=Number(r[1]),c=Number(r[2]),u=Number(r[3]),d=/[zZ]|[+-]\d{2}:?\d{2}$/.test(t),l=d?i.getUTCFullYear():i.getFullYear(),m=(d?i.getUTCMonth():i.getMonth())+1,f=d?i.getUTCDate():i.getDate();return l!==a||m!==c||f!==u?null:i}let n=new Date(t);return Number.isNaN(n.getTime())?null:n}var qR=le.enum(["claude","codex","all"]).default("all"),N_=le.enum(["hour","day","week","month"]).default("day");function LR(t){return Zi(t)!==null}var A_=le.string().refine(LR,{message:"must be a YYYY-MM-DD date or a full ISO 8601 timestamp"}),kn={range:le.enum(["today","yesterday","this_week","last_week","this_month","last_month","7d","30d","90d","all"]).optional().describe('Named time window. Defaults to "all" if no explicit from/to is given.'),from:A_.optional().describe("Inclusive lower bound (ISO date YYYY-MM-DD or full ISO timestamp)."),to:A_.optional().describe("Inclusive upper bound (ISO date YYYY-MM-DD or full ISO timestamp).")},UR=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"],FR=["today","yesterday"],M_=le.string().refine(t=>{let e=t.toLowerCase();return FR.includes(e)||UR.includes(e)?!0:O_(t)},{message:'must be "today", "yesterday", a weekday name (monday..sunday), or YYYY-MM-DD'}),Pt={source:qR.describe("claude | codex | all (default). When all, the response carries combined totals plus a bySource breakdown.")},$n=["claude","codex"];import{promises as Lo,watch as IP}from"node:fs";import cy from"node:path";function VR(t){let e=`${t.source}:`;return t.messageId&&t.requestId?`${e}${t.messageId}::${t.requestId}`:t.messageId?`${e}mid:${t.messageId}`:t.requestId?`${e}req:${t.requestId}`:`${e}uuid:${t.uuid}`}function j_(t){let e=new Map;for(let r of t){let n=VR(r),o=e.get(n);if(!o){e.set(n,r);continue}r.timestamp<o.timestamp&&e.set(n,r)}return Array.from(e.values())}import{promises as kP}from"node:fs";import Di from"node:path";import YR from"node:os";import{createReadStream as HR}from"node:fs";import BR from"node:readline";var Sd=200;async function Z_(t){let e=HR(t,{encoding:"utf8"}),r=BR.createInterface({input:e,crlfDelay:1/0}),n=[],o=[],s=[];for await(let i of r){if(!i.trim())continue;let a;try{a=JSON.parse(i)}catch{continue}if(!(!a||typeof a!="object")){if(a.uuid&&s.push([a.uuid,a.parentUuid??null]),a.type==="assistant"){let c=KR(a,t);c&&n.push(c)}else if(a.type==="user"){let c=WR(a,t);c&&o.push(c)}}}return{assistant:n,user:o,parentLinks:s}}function KR(t,e){let r=t.message;if(!r)return null;let n=r.usage;if(!n)return null;let o=r.model??"";if(!o||o==="<synthetic>")return null;let s=r.id??t.uuid??"";if(!s&&!t.requestId)return null;let i=n.cache_creation,a=Array.isArray(r.content)?r.content:[],c=[],u=!1,d="";for(let l of a)l.type==="tool_use"&&typeof l.name=="string"?c.push(l.name):l.type==="thinking"?u=!0:l.type==="text"&&typeof l.text=="string"&&!d&&(d=l.text.slice(0,Sd));return{type:"assistant",source:"claude",uuid:t.uuid??s,parentUuid:t.parentUuid??null,timestamp:t.timestamp??new Date().toISOString(),sessionId:t.sessionId??"",requestId:t.requestId??"",cwd:t.cwd??"",gitBranch:t.gitBranch,version:t.version,model:o,messageId:s,usage:{input_tokens:Number(n.input_tokens)||0,output_tokens:Number(n.output_tokens)||0,cache_creation_input_tokens:Number(n.cache_creation_input_tokens)||0,cache_read_input_tokens:Number(n.cache_read_input_tokens)||0,cache_creation_5m:Number(i?.ephemeral_5m_input_tokens)||0,cache_creation_1h:Number(i?.ephemeral_1h_input_tokens)||0},toolNames:c,hasThinking:u,textPreview:d,filePath:e,isSidechain:t.isSidechain===!0?!0:void 0}}function WR(t,e){if(!t.uuid)return null;let r=t.message,n="";if(r){let i=r.content;if(typeof i=="string")n=i.slice(0,Sd);else if(Array.isArray(i)){for(let a of i)if(a.type==="text"&&typeof a.text=="string"){n=a.text.slice(0,Sd);break}}}let o=t.isSidechain===!0,s=o||!!n&&GR(n);return{type:"user",source:"claude",uuid:t.uuid,parentUuid:t.parentUuid??null,timestamp:t.timestamp??new Date().toISOString(),sessionId:t.sessionId??"",cwd:t.cwd??"",textPreview:n,isSynthetic:s,isSidechain:o?!0:void 0,filePath:e}}function GR(t){let e=t.trimStart();return!!(e.startsWith("Base directory for this skill:")||e.startsWith("<system-reminder>")||e.startsWith("Caveat: The messages below were generated by")||e.startsWith("<task-notification>"))}var D_={"claude-3-7-sonnet-20250219":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-3-haiku-20240307":{input:.25,output:1.25,cacheCreation5m:.3,cacheCreation1h:.5,cacheRead:.03},"claude-3-opus-20240229":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-4-opus-20250514":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-4-sonnet-20250514":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-fable-5":{input:10,output:50,cacheCreation5m:12.5,cacheCreation1h:20,cacheRead:1},"claude-haiku-4-5":{input:1,output:5,cacheCreation5m:1.25,cacheCreation1h:2,cacheRead:.1},"claude-haiku-4-5-20251001":{input:1,output:5,cacheCreation5m:1.25,cacheCreation1h:2,cacheRead:.1},"claude-opus-4-1":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-opus-4-1-20250805":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-opus-4-20250514":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-opus-4-5":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-5-20251101":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-6":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-6-20260205":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-7":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-7-20260416":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-opus-4-8":{input:5,output:25,cacheCreation5m:6.25,cacheCreation1h:10,cacheRead:.5},"claude-sonnet-4-20250514":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-sonnet-4-5":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-sonnet-4-5-20250929":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-sonnet-4-6":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3}},q_={"chatgpt-4o-latest":{input:5,output:15,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"codex-mini-latest":{input:1.5,output:6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.375},"gpt-3.5-turbo":{input:.5,output:1.5,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.05},"gpt-3.5-turbo-0125":{input:.5,output:1.5,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.05},"gpt-3.5-turbo-1106":{input:1,output:2,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.1},"gpt-3.5-turbo-16k":{input:3,output:4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.3},"gpt-4":{input:30,output:60,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-4-0125-preview":{input:10,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1},"gpt-4-0314":{input:30,output:60,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-4-0613":{input:30,output:60,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-4-1106-preview":{input:10,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1},"gpt-4-turbo":{input:10,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1},"gpt-4-turbo-2024-04-09":{input:10,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1},"gpt-4-turbo-preview":{input:10,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1},"gpt-4.1":{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"gpt-4.1-2025-04-14":{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"gpt-4.1-mini":{input:.4,output:1.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.1},"gpt-4.1-mini-2025-04-14":{input:.4,output:1.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.1},"gpt-4.1-nano":{input:.1,output:.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.025},"gpt-4.1-nano-2025-04-14":{input:.1,output:.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.025},"gpt-4o":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.25},"gpt-4o-2024-05-13":{input:5,output:15,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"gpt-4o-2024-08-06":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.25},"gpt-4o-2024-11-20":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.25},"gpt-4o-audio-preview":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-4o-audio-preview-2024-12-17":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-4o-audio-preview-2025-06-03":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-4o-mini":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-4o-mini-2024-07-18":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-4o-mini-audio-preview":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.015},"gpt-4o-mini-audio-preview-2024-12-17":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.015},"gpt-4o-mini-realtime-preview":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.3},"gpt-4o-mini-realtime-preview-2024-12-17":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.3},"gpt-4o-mini-search-preview":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-4o-mini-search-preview-2025-03-11":{input:.15,output:.6,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-4o-realtime-preview":{input:5,output:20,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.5},"gpt-4o-realtime-preview-2024-12-17":{input:5,output:20,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.5},"gpt-4o-realtime-preview-2025-06-03":{input:5,output:20,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.5},"gpt-4o-search-preview":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.25},"gpt-4o-search-preview-2025-03-11":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.25},"gpt-5":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-2025-08-07":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-chat":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-chat-latest":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-codex":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-mini":{input:.25,output:2,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.025},"gpt-5-mini-2025-08-07":{input:.25,output:2,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.025},"gpt-5-nano":{input:.05,output:.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.005},"gpt-5-nano-2025-08-07":{input:.05,output:.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.005},"gpt-5-pro":{input:15,output:120,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.5},"gpt-5-pro-2025-10-06":{input:15,output:120,cacheCreation5m:0,cacheCreation1h:0,cacheRead:1.5},"gpt-5-search-api":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5-search-api-2025-10-14":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1-2025-11-13":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1-chat-latest":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1-codex":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1-codex-max":{input:1.25,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.125},"gpt-5.1-codex-mini":{input:.25,output:2,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.025},"gpt-5.2":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.2-2025-12-11":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.2-chat-latest":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.2-codex":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.2-pro":{input:21,output:168,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.1},"gpt-5.2-pro-2025-12-11":{input:21,output:168,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.1},"gpt-5.3-chat-latest":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.3-codex":{input:1.75,output:14,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.175},"gpt-5.4":{input:2.5,output:15,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-5.4-2026-03-05":{input:2.5,output:15,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-5.4-mini":{input:.75,output:4.5,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-5.4-mini-2026-03-17":{input:.75,output:4.5,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.075},"gpt-5.4-nano":{input:.2,output:1.25,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.02},"gpt-5.4-nano-2026-03-17":{input:.2,output:1.25,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.02},"gpt-5.4-pro":{input:30,output:180,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-5.4-pro-2026-03-05":{input:30,output:180,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-5.5":{input:5,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"gpt-5.5-2026-04-23":{input:5,output:30,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"gpt-5.5-pro":{input:30,output:180,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-5.5-pro-2026-04-23":{input:30,output:180,cacheCreation5m:0,cacheCreation1h:0,cacheRead:3},"gpt-audio":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-audio-1.5":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-audio-2025-08-28":{input:2.5,output:10,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.25},"gpt-audio-mini":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},"gpt-audio-mini-2025-10-06":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},"gpt-audio-mini-2025-12-15":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},"gpt-realtime":{input:4,output:16,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.4},"gpt-realtime-1.5":{input:4,output:16,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.4},"gpt-realtime-2":{input:4,output:16,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.4},"gpt-realtime-2025-08-28":{input:4,output:16,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.4},"gpt-realtime-mini":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},"gpt-realtime-mini-2025-10-06":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},"gpt-realtime-mini-2025-12-15":{input:.6,output:2.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.06},o1:{input:15,output:60,cacheCreation5m:0,cacheCreation1h:0,cacheRead:7.5},"o1-2024-12-17":{input:15,output:60,cacheCreation5m:0,cacheCreation1h:0,cacheRead:7.5},"o1-pro":{input:150,output:600,cacheCreation5m:0,cacheCreation1h:0,cacheRead:15},"o1-pro-2025-03-19":{input:150,output:600,cacheCreation5m:0,cacheCreation1h:0,cacheRead:15},o3:{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"o3-2025-04-16":{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"o3-deep-research":{input:10,output:40,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.5},"o3-deep-research-2025-06-26":{input:10,output:40,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2.5},"o3-mini":{input:1.1,output:4.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.55},"o3-mini-2025-01-31":{input:1.1,output:4.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.55},"o3-pro":{input:20,output:80,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2},"o3-pro-2025-06-10":{input:20,output:80,cacheCreation5m:0,cacheCreation1h:0,cacheRead:2},"o4-mini":{input:1.1,output:4.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.275},"o4-mini-2025-04-16":{input:1.1,output:4.4,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.275},"o4-mini-deep-research":{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5},"o4-mini-deep-research-2025-06-26":{input:2,output:8,cacheCreation5m:0,cacheCreation1h:0,cacheRead:.5}};var JR={"claude-opus-4":{input:15,output:75,cacheCreation5m:18.75,cacheCreation1h:30,cacheRead:1.5},"claude-sonnet-4":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-sonnet-3-7":{input:3,output:15,cacheCreation5m:3.75,cacheCreation1h:6,cacheRead:.3},"claude-haiku-3-5":{input:.8,output:4,cacheCreation5m:1,cacheCreation1h:1.6,cacheRead:.08},"claude-haiku-3":{input:.25,output:1.25,cacheCreation5m:.3,cacheCreation1h:.5,cacheRead:.03}},_t={...JR,...D_},L_={fable:_t["claude-fable-5"],opus:_t["claude-opus-4-8"],sonnet:_t["claude-sonnet-4-6"],haiku:_t["claude-haiku-4-5"]};function or(t,e){if(!e)return{input:0,output:0,cacheCreation5m:0,cacheCreation1h:0,cacheRead:0,total:0,saved:0};let r=t.input_tokens/1e6*e.input,n=t.output_tokens/1e6*e.output,o=t.cache_creation_5m/1e6*e.cacheCreation5m,s=t.cache_creation_1h/1e6*e.cacheCreation1h;o+s===0&&t.cache_creation_input_tokens>0&&(o=t.cache_creation_input_tokens/1e6*e.cacheCreation5m);let i=t.cache_read_input_tokens/1e6*e.cacheRead,a=r+n+o+s+i,c=t.cache_read_input_tokens/1e6*(e.input-e.cacheRead);return{input:r,output:n,cacheCreation5m:o,cacheCreation1h:s,cacheRead:i,total:a,saved:c}}function U_(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function F_(t){if(!t)return"(unknown)";let e=t.replace(/-(\d{8})$/,"").replace(/^(vertex_ai|bedrock|anthropic)\//,"");e=e.replace(/^claude-/,"");let r=e.split("-");if(r.length>=2){let n=r[0],o=r.slice(1).join(".");return U_(n)+" "+o}return U_(e.replace(/-/g," "))}var XR=/-\d{8}$/,QR=/^(vertex_ai|bedrock|anthropic)\//;function eP(t){if(!t)return{pricing:null,matchType:"none",matchedKey:null};if(_t[t])return{pricing:_t[t],matchType:"exact",matchedKey:t};let e=t.replace(XR,"");if(_t[e])return{pricing:_t[e],matchType:"date-stripped",matchedKey:e};let r=e.replace(QR,"");if(_t[r])return{pricing:_t[r],matchType:"prefix-stripped",matchedKey:r};for(let n of["fable","opus","sonnet","haiku"])if(t.toLowerCase().includes(n))return{pricing:L_[n],matchType:"family-fallback",matchedKey:`claude-${n}-(latest)`};return{pricing:null,matchType:"none",matchedKey:null}}function tP(){let t=YR.homedir(),e=[Di.join(t,".claude","projects"),Di.join(t,".config","claude","projects")];return process.env.CCGAUGE_CONFIG_DIR&&e.push(Di.join(process.env.CCGAUGE_CONFIG_DIR,"projects")),process.env.CLAUDE_CONFIG_DIR&&e.push(Di.join(process.env.CLAUDE_CONFIG_DIR,"projects")),Array.from(new Set(e))}var V_={id:"claude",displayName:{en:"Claude",zh:"Claude"},shortLabel:"C",color:{fg:"#b45309",bg:"#fef3c7"},logoSrc:"/claude-logo.webp",parserVersion:"claude-v5-task-notification-synthetic",capabilities:{hasCacheCreation:!0,hasReasoningTokens:!1,blockWindowMs:300*60*1e3},getDirs:tP,shouldSkipDir:t=>t==="tool-results"||t==="memory",parseFile:async t=>await Z_(t),resolvePricing:eP,shortenModel:F_,costFromUsage:or,costFootnoteKey:null};import qi from"node:path";import bP from"node:os";import{createReadStream as rP,promises as nP}from"node:fs";import oP from"node:readline";var Td=200;async function sP(t){try{let e=await nP.stat(t);return new Date(e.mtimeMs).toISOString()}catch{return new Date().toISOString()}}function Ge(t){return typeof t=="string"?t:""}function sr(t){let e=Number(t);return Number.isFinite(e)?e:0}function zd(t){let e=t.message;if(typeof e=="string")return e;let r=t.content;if(typeof r=="string")return r;if(Array.isArray(r))for(let n of r){let o=n?.type;if((o==="input_text"||o==="output_text"||o==="text")&&typeof n.text=="string")return n.text}return""}async function H_(t){let e=rP(t,{encoding:"utf8"}),r=oP.createInterface({input:e,crlfDelay:1/0}),n=[],o=[],s=[],i="",a,c="",u=0,d=0,l=null,f=await sP(t),p={turnId:null,cwd:"",model:"gpt-unknown",userUuid:null,toolNames:[],hasThinking:!1,pendingTextPreview:""};for await(let h of r){if(!h.trim())continue;let g;try{g=JSON.parse(h)}catch{continue}if(!g||typeof g!="object"||!g.type)continue;let _=g.payload??{},b=Ge(g.timestamp),x=b||f;if(b&&(f=b),g.type==="session_meta"){i=Ge(_.id),c=Ge(_.cwd),a=Ge(_.cli_version)||void 0;let $=Ge(_.timestamp);$&&(f=$),p.cwd||(p.cwd=c);continue}if(g.type==="turn_context"){p.turnId=Ge(_.turn_id)||p.turnId,p.cwd=Ge(_.cwd)||c;let $=Ge(_.model);$&&(p.model=$);let P=Ge(_.effort);P&&(p.effort=P),p.toolNames=[],p.hasThinking=!1,p.pendingTextPreview="";continue}if(g.type==="event_msg"){let $=Ge(_.type);if($==="user_message"){let P=zd(_);if(!P)continue;let ee=`${i}::u${u++}`;o.push({type:"user",source:"codex",uuid:ee,parentUuid:null,timestamp:x,sessionId:i,cwd:p.cwd||c,textPreview:P.slice(0,Td),filePath:t}),s.push([ee,null]),p.userUuid=ee;continue}if($==="agent_message"){let P=zd(_);P&&!p.pendingTextPreview&&(p.pendingTextPreview=P.slice(0,Td));continue}if($==="agent_reasoning"){p.hasThinking=!0;continue}if($==="token_count"){let P=_.info;if(!P)continue;let ee=P.total_token_usage,be=P.last_token_usage,ge=ee?{input:sr(ee.input_tokens),cached:sr(ee.cached_input_tokens),output:sr(ee.output_tokens),reasoning:sr(ee.reasoning_output_tokens)}:null,Je,Oe,Ye,at;if(ge){if(l===null?(Je=ge.input,Oe=ge.cached,Ye=ge.output,at=ge.reasoning):(Je=Math.max(0,ge.input-l.input),Oe=Math.max(0,ge.cached-l.cached),Ye=Math.max(0,ge.output-l.output),at=Math.max(0,ge.reasoning-l.reasoning)),Je===0&&Oe===0&&Ye===0&&at===0)continue;l===null?l={...ge}:l={input:Math.max(l.input,ge.input),cached:Math.max(l.cached,ge.cached),output:Math.max(l.output,ge.output),reasoning:Math.max(l.reasoning,ge.reasoning)}}else if(be){if(Je=sr(be.input_tokens),Oe=sr(be.cached_input_tokens),Ye=sr(be.output_tokens),at=sr(be.reasoning_output_tokens),Je===0&&Oe===0&&Ye===0&&at===0)continue;l===null?l={input:Je,cached:Oe,output:Ye,reasoning:at}:l={input:l.input+Je,cached:l.cached+Oe,output:l.output+Ye,reasoning:l.reasoning+at}}else continue;let Cn=`${i}::a${d++}`,Wo=p.turnId?`${p.turnId}::a${d}`:`${i}::a${d}`;n.push({type:"assistant",source:"codex",uuid:Cn,parentUuid:p.userUuid,timestamp:x,sessionId:i,requestId:Wo,cwd:p.cwd||c,version:a,model:p.model||"gpt-unknown",messageId:Wo,usage:{input_tokens:Math.max(0,Je-Oe),output_tokens:Ye,cache_creation_input_tokens:0,cache_read_input_tokens:Oe,cache_creation_5m:0,cache_creation_1h:0,reasoning_tokens:at},toolNames:[...p.toolNames],hasThinking:p.hasThinking,textPreview:p.pendingTextPreview,filePath:t,effort:p.effort}),s.push([Cn,p.userUuid]),p.toolNames=[],p.hasThinking=!1,p.pendingTextPreview="";continue}continue}if(g.type==="response_item"){let $=Ge(_.type);if($==="function_call"||$==="custom_tool_call"){let P=Ge(_.name);P&&p.toolNames.push(P);continue}if($==="reasoning"){p.hasThinking=!0;continue}if($==="message"){if(Ge(_.role)==="assistant"){let ee=zd(_);ee&&!p.pendingTextPreview&&(p.pendingTextPreview=ee.slice(0,Td))}continue}continue}}return{assistant:n,user:o,parentLinks:s}}var iP={},ir={...iP,...q_},B_={gpt:ir["gpt-5.5"],o:ir.o3},aP=/-\d{8}$/,cP=/^(openai)\//;function K_(t){if(!t)return{pricing:null,matchType:"none",matchedKey:null};if(ir[t])return{pricing:ir[t],matchType:"exact",matchedKey:t};let e=t.replace(aP,"");if(ir[e])return{pricing:ir[e],matchType:"date-stripped",matchedKey:e};let r=e.replace(cP,"");if(ir[r])return{pricing:ir[r],matchType:"prefix-stripped",matchedKey:r};let n=t.toLowerCase();return n.startsWith("gpt-")||n==="gpt"?{pricing:B_.gpt,matchType:"family-fallback",matchedKey:"gpt-(latest)"}:/^o\d/.test(n)?{pricing:B_.o,matchType:"family-fallback",matchedKey:"o-(latest)"}:{pricing:null,matchType:"none",matchedKey:null}}function uP(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}var lP={mini:"Mini",nano:"Nano",pro:"Pro",turbo:"Turbo",preview:"Preview"};function W_(t){if(!t)return"(unknown)";let e=t.replace(/^openai\//,"");return e.toLowerCase().startsWith("gpt-")?"GPT-"+e.slice(4).split("-").map(o=>lP[o.toLowerCase()]??o).join(" "):e.toLowerCase().startsWith("o")?e.toUpperCase():uP(e.replace(/-/g," "))}import{readFileSync as dP}from"node:fs";import pP from"node:os";import G_ from"node:path";var fP={"gpt-5.5":2.5,"gpt-5.4":2,"gpt-5.3-codex":2},mP=2;function hP(t){return t.replace(/^openai\//,"").replace(/-\d{8}$/,"")}function gP(t){for(let e of t.split(/\r?\n/)){let r=(e.split("#")[0]??"").trim(),n=r.indexOf("=");if(n===-1||r.slice(0,n).trim()!=="service_tier")continue;let s=r.slice(n+1).trim().replace(/^['"]+|['"]+$/g,"");if(s==="fast"||s==="priority")return!0}return!1}function _P(){let t=[];return process.env.CODEX_HOME&&t.push(process.env.CODEX_HOME),t.push(G_.join(pP.homedir(),".codex")),Array.from(new Set(t))}function yP(){for(let t of _P())try{let e=dP(G_.join(t,"config.toml"),"utf8");if(gP(e))return!0}catch{}return!1}var Rd;function vP(){return Rd===void 0&&(Rd=yP()),Rd}function J_(t){return vP()?fP[hP(t)]??mP:1}function Y_(t,e){return e===1?t:{input:t.input*e,output:t.output*e,cacheRead:t.cacheRead*e,cacheCreation5m:t.cacheCreation5m*e,cacheCreation1h:t.cacheCreation1h*e}}function xP(){let t=bP.homedir(),e=[qi.join(t,".codex","sessions"),qi.join(t,".codex","archived_sessions")];return process.env.CCGAUGE_CODEX_DIR&&e.push(process.env.CCGAUGE_CODEX_DIR),process.env.CODEX_HOME&&(e.push(qi.join(process.env.CODEX_HOME,"sessions")),e.push(qi.join(process.env.CODEX_HOME,"archived_sessions"))),Array.from(new Set(e))}function wP(t,e,r){return e?or(t,Y_(e,J_(r??""))):or(t,null)}var X_={id:"codex",displayName:{en:"Codex",zh:"Codex"},shortLabel:"X",color:{fg:"#047857",bg:"#d1fae5"},logoSrc:"/codex-logo.webp",parserVersion:"codex-v6-output-excludes-readded-reasoning",capabilities:{hasCacheCreation:!1,hasReasoningTokens:!0,blockWindowMs:300*60*1e3},getDirs:xP,shouldSkipDir:()=>!1,parseFile:H_,resolvePricing:K_,shortenModel:W_,costFromUsage:wP,costFootnoteKey:"cost.footnote.codex"};var Q_={claude:V_,codex:X_},$P=["claude","codex"];function Sn(t){return Q_[t]}function Do(){return $P.map(t=>Q_[t])}async function SP(t){try{return(await kP.stat(t)).isDirectory()}catch{return!1}}async function ey(){let t=[];for(let e of Do())for(let r of e.getDirs())if(await SP(r)){t.push(e.id);break}return t}import{promises as Li}from"node:fs";import Pd from"node:path";import TP from"node:os";var Ui=2,Tn="default";function zP(){return process.env.CCGAUGE_STATE_DIR?process.env.CCGAUGE_STATE_DIR:Pd.join(TP.homedir(),".ccgauge")}function ty(t){let e=t===Tn?`index-v${Ui}.json`:`index-${t}-v${Ui}.json`;return Pd.join(zP(),"cache",e)}async function ry(t=Tn){let e=ty(t);try{let r=await Li.readFile(e,"utf8"),n=JSON.parse(r);return n.schemaVersion!==Ui||!Array.isArray(n.files)?null:n}catch{return null}}async function ny(t,e=Tn){let r=ty(e),n=Pd.dirname(r);await Li.mkdir(n,{recursive:!0});let o={schemaVersion:Ui,savedAt:t.savedAt,files:t.files},s=`${r}.tmp-${process.pid}`;await Li.writeFile(s,JSON.stringify(o)),await Li.rename(s,r)}var oy=/[\\/]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})[\\/]subagents[\\/](?:[^\\/]+[\\/])*agent-[^\\/]+\.jsonl$/i,RP=/[\\/]subagents[\\/]workflows[\\/]/i;function PP(t){let e=oy.exec(t);return e?e[1]:null}function sy(t){return oy.test(t)?RP.test(t)?"workflow":"task":null}function iy({assistantRecords:t,userRecords:e,parentMap:r}){let n=new Map;for(let i of t){if(i.isSidechain||!i.sessionId)continue;let a=n.get(i.sessionId);a||(a=[],n.set(i.sessionId,a)),a.push(i)}for(let i of n.values())i.sort((a,c)=>a.timestamp<c.timestamp?-1:a.timestamp>c.timestamp?1:0);let o=new Map;for(let i of e){if(!i.isSidechain)continue;let a=o.get(i.filePath);(!a||i.timestamp<a.timestamp)&&o.set(i.filePath,i)}let s={subagentFiles:0,relinked:0,orphans:0,alreadyLinked:0};for(let[i,a]of o){let c=PP(i);if(!c)continue;s.subagentFiles+=1;let u=r[a.uuid];if(u!=null){s.alreadyLinked+=1;continue}let d=n.get(c);if(!d||d.length===0){s.orphans+=1;continue}let l=a.timestamp,m;for(let f=d.length-1;f>=0;f-=1)if(d[f].timestamp<=l){m=d[f];break}m||(m=d[0]),r[a.uuid]=m.uuid,s.relinked+=1}return s}import{homedir as EP}from"node:os";function qo(t){let e=EP();if(!e)return t;let r=new Set([e]);process.platform==="win32"&&(r.add(e.replace(/\\/g,"/")),r.add(e.replace(/\\/g,"\\\\")),r.add("\\\\?\\"+e),r.add("\\\\?\\"+e.replace(/\\/g,"/")));let n=t;for(let o of r){let s=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(s,"g"),"~")}return n}var CP=200,OP=100,AP=3e4,NP=2e3,MP=8,Ed=20,Id=class{cacheName;files=new Map;snapshot=null;watchers=new Map;pollTimer=null;snapshotRebuildTimer=null;persistTimer=null;fileDebouncers=new Map;initPromise=null;isIndexing=!1;lastIndexedAt=null;indexDurationMs=null;existingDirs=[];dirToProvider=new Map;errors=[];loadedFromDisk=!1;lastWorkStart=null;rescanPromise=null;mutationTail=Promise.resolve();constructor(e=Tn){this.cacheName=e}runExclusive(e){let r=this.mutationTail.then(e,e);return this.mutationTail=r.then(()=>{},()=>{}),r}init(){return this.initPromise||(this.initPromise=this.doInit()),this.initPromise}async doInit(){let e=Date.now();this.isIndexing=!0,this.lastWorkStart=e;try{await this.detectProviderDirs();let r=await ry(this.cacheName);this.loadedFromDisk=r!==null;let n=new Map;if(r)for(let o of r.files)n.set(o.filePath,o);await this.runExclusive(async()=>{await this.fullScan(n),this.rebuildSnapshotNow(),this.indexDurationMs=Date.now()-e,this.lastIndexedAt=new Date().toISOString(),this.schedulePersist()}),this.syncWatchersToDirs(),this.setupPolling()}finally{this.isIndexing=!1}}async detectProviderDirs(){let e=new Map,r=[];for(let s of Do())for(let i of s.getDirs())await jP(i)&&(e.has(i)||(e.set(i,s),r.push(i)));let n=[],o=[];for(let s of e.keys())this.dirToProvider.has(s)||n.push(s);for(let s of this.dirToProvider.keys())e.has(s)||o.push(s);return this.dirToProvider=e,this.existingDirs=r,{added:n,removed:o}}async fullScan(e){let r=[];for(let[o,s]of this.dirToProvider){let i=await ay(o,s);for(let a of i)r.push({file:a,provider:s})}let n=new Set(r.map(o=>o.file));await Promise.all(r.map(async({file:o,provider:s})=>{try{let i=await Lo.stat(o),a=e.get(o);if(a&&a.source===s.id&&a.parserVersion===s.parserVersion&&a.mtimeMs===i.mtimeMs&&a.size===i.size){this.files.set(o,{source:s.id,parserVersion:s.parserVersion,mtimeMs:i.mtimeMs,size:i.size,assistantRecords:a.assistantRecords,userRecords:a.userRecords,parentLinks:a.parentLinks});return}let c=await s.parseFile(o);this.files.set(o,{source:s.id,parserVersion:s.parserVersion,mtimeMs:i.mtimeMs,size:i.size,assistantRecords:c.assistant,userRecords:c.user,parentLinks:c.parentLinks})}catch(i){this.recordError(`parse ${o}: ${i.message}`)}}));for(let o of Array.from(this.files.keys()))n.has(o)||this.files.delete(o)}syncWatchersToDirs(){for(let[e,r]of this.watchers)if(!this.dirToProvider.has(e)){try{r.close()}catch{}this.watchers.delete(e)}for(let[e,r]of this.dirToProvider)if(!this.watchers.has(e))try{let n=IP(e,{recursive:!0},(o,s)=>{if(!s||typeof s!="string"||!s.endsWith(".jsonl"))return;let i=cy.join(e,s);this.scheduleFileReconcile(i,r)});n.on("error",o=>{this.recordError(`watcher ${e}: ${o.message}`)}),this.watchers.set(e,n)}catch(n){this.recordError(`watch ${e}: ${n.message}`)}}setupPolling(){this.pollTimer&&clearInterval(this.pollTimer);let e=this.cacheName==="mcp",r=process.env.CCGAUGE_POLL_FALLBACK;(r==="1"||r!=="0"&&!e)&&(this.pollTimer=setInterval(()=>{this.pollOnce().catch(o=>this.recordError(`poll: ${o.message}`))},AP),this.pollTimer.unref?.())}async pollOnce(){await this.runExclusive(async()=>{let e=Date.now(),r=await this.detectProviderDirs(),n=r.added.length>0||r.removed.length>0;n&&this.syncWatchersToDirs();let o=[];for(let[i,a]of this.dirToProvider){let c=await ay(i,a);for(let u of c)o.push({file:u,provider:a})}let s=new Set(o.map(i=>i.file));await Promise.all(o.map(async({file:i,provider:a})=>{try{let c=await Lo.stat(i),u=this.files.get(i);if(u&&u.mtimeMs===c.mtimeMs&&u.size===c.size)return;let d=await a.parseFile(i);this.files.set(i,{source:a.id,parserVersion:a.parserVersion,mtimeMs:c.mtimeMs,size:c.size,assistantRecords:d.assistant,userRecords:d.user,parentLinks:d.parentLinks}),n=!0}catch(c){this.recordError(`poll-parse ${i}: ${c.message}`)}}));for(let i of Array.from(this.files.keys()))s.has(i)||(this.files.delete(i),n=!0);n&&(this.lastWorkStart=e,this.scheduleSnapshotRebuild(),this.schedulePersist())})}scheduleFileReconcile(e,r){let n=this.fileDebouncers.get(e);n&&clearTimeout(n);let o=setTimeout(()=>{this.fileDebouncers.delete(e),this.reconcileFile(e,r).catch(s=>this.recordError(`reconcile ${e}: ${s.message}`))},CP);o.unref?.(),this.fileDebouncers.set(e,o)}async reconcileFile(e,r){await this.runExclusive(async()=>{let n=Date.now(),o=null;try{o=await Lo.stat(e)}catch{}if(!o||!o.isFile()){this.files.has(e)&&(this.files.delete(e),this.lastWorkStart=n,this.scheduleSnapshotRebuild(),this.schedulePersist());return}let s=this.files.get(e);if(!(s&&s.mtimeMs===o.mtimeMs&&s.size===o.size))try{let i=await r.parseFile(e);this.files.set(e,{source:r.id,parserVersion:r.parserVersion,mtimeMs:o.mtimeMs,size:o.size,assistantRecords:i.assistant,userRecords:i.user,parentLinks:i.parentLinks}),this.lastWorkStart=n,this.scheduleSnapshotRebuild(),this.schedulePersist()}catch(i){this.recordError(`parse ${e}: ${i.message}`)}})}scheduleSnapshotRebuild(){this.snapshotRebuildTimer&&clearTimeout(this.snapshotRebuildTimer),this.snapshotRebuildTimer=setTimeout(()=>{this.snapshotRebuildTimer=null,this.rebuildSnapshotNow()},OP),this.snapshotRebuildTimer.unref?.()}rebuildSnapshotNow(){let e=Date.now(),r=this.lastWorkStart??e,n=[],o=[],s={},i=0,a={claude:{source:"claude",filesScanned:0,recordsParsed:0,assistantRecords:0,scannedDirs:[]},codex:{source:"codex",filesScanned:0,recordsParsed:0,assistantRecords:0,scannedDirs:[]}};for(let[l,m]of this.dirToProvider)a[m.id].scannedDirs.push(l);for(let l of this.files.values()){n.push(...l.assistantRecords),o.push(...l.userRecords);for(let[m,f]of l.parentLinks)s[m]=f;i+=l.assistantRecords.length+l.userRecords.length,a[l.source].filesScanned+=1,a[l.source].recordsParsed+=l.assistantRecords.length+l.userRecords.length}let c=j_(n).sort((l,m)=>l.timestamp.localeCompare(m.timestamp)),u=ZP(o).sort((l,m)=>l.timestamp.localeCompare(m.timestamp));iy({assistantRecords:c,userRecords:u,parentMap:s});for(let l of c)l.isSidechain&&(l.isWorkflowSubagent=sy(l.filePath)==="workflow");for(let l of c)a[l.source].assistantRecords+=1;let d={filesScanned:this.files.size,recordsParsed:i,assistantRecords:c.length,durationMs:Date.now()-r,scannedDirs:this.existingDirs};this.snapshot={records:c,userRecords:u,parentMap:s,stats:d,bySource:Object.values(a)},this.lastWorkStart=null}getSnapshot(){if(!this.snapshot)throw new Error("Indexer not initialized \u2014 call init() first.");return this.snapshot}async forceRescan(){let e=!this.initPromise;if(await this.init(),e)return this.snapshot;if(this.rescanPromise)return this.rescanPromise;this.rescanPromise=this.runRescan();try{return await this.rescanPromise}finally{this.rescanPromise=null}}async runRescan(){this.isIndexing=!0;try{return await this.runExclusive(async()=>{let e=Date.now();return this.lastWorkStart=e,this.snapshotRebuildTimer&&(clearTimeout(this.snapshotRebuildTimer),this.snapshotRebuildTimer=null),this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.files.clear(),await this.detectProviderDirs(),await this.fullScan(new Map),this.rebuildSnapshotNow(),this.indexDurationMs=Date.now()-e,this.lastIndexedAt=new Date().toISOString(),this.syncWatchersToDirs(),this.schedulePersist(),this.snapshot})}finally{this.isIndexing=!1}}getStatus(){let e=this.snapshot;return{initialized:e!==null,isIndexing:this.isIndexing,lastIndexedAt:this.lastIndexedAt,indexDurationMs:this.indexDurationMs,filesIndexed:this.files.size,recordsIndexed:e?.stats.assistantRecords??0,bySource:e?.bySource??[],watchers:this.watchers.size,errors:this.errors.slice(-Ed),pendingReconciles:this.fileDebouncers.size,loadedFromDisk:this.loadedFromDisk}}schedulePersist(){this.persistTimer&&clearTimeout(this.persistTimer),this.persistTimer=setTimeout(()=>{this.persistTimer=null;let e=[];for(let[r,n]of this.files)e.push({filePath:r,source:n.source,parserVersion:n.parserVersion,mtimeMs:n.mtimeMs,size:n.size,assistantRecords:n.assistantRecords,userRecords:n.userRecords,parentLinks:n.parentLinks});ny({savedAt:new Date().toISOString(),files:e},this.cacheName).catch(r=>this.recordError(`persist: ${r.message}`))},NP),this.persistTimer.unref?.()}recordError(e){let r=`${new Date().toISOString()} ${qo(e)}`;this.errors.push(r),this.errors.length>Ed*2&&this.errors.splice(0,this.errors.length-Ed),process.env.CCGAUGE_DEBUG&&console.error(`[ccgauge:indexer] ${new Date().toISOString()} ${e}`)}disposeWatchers(){for(let e of this.watchers.values())try{e.close()}catch{}this.watchers.clear()}dispose(){this.disposeWatchers(),this.pollTimer&&clearInterval(this.pollTimer),this.snapshotRebuildTimer&&clearTimeout(this.snapshotRebuildTimer),this.persistTimer&&clearTimeout(this.persistTimer);for(let e of this.fileDebouncers.values())clearTimeout(e);this.fileDebouncers.clear()}};async function jP(t){try{return(await Lo.stat(t)).isDirectory()}catch{return!1}}async function ay(t,e){let r=[];async function n(o,s){if(s>MP)return;let i;try{i=await Lo.readdir(o,{withFileTypes:!0})}catch{return}for(let a of i){let c=cy.join(o,a.name);if(a.isDirectory()){if(e.shouldSkipDir(a.name))continue;await n(c,s+1)}else a.isFile()&&a.name.endsWith(".jsonl")&&r.push(c)}}return await n(t,0),r}function ZP(t){let e=new Set;return t.filter(r=>{let n=r.uuid;return n?e.has(n)?!1:(e.add(n),!0):!0})}function DP(){return globalThis.__ccgaugeIndexers||(globalThis.__ccgaugeIndexers=new Map),globalThis.__ccgaugeIndexers}function uy(t=Tn){let e=DP(),r=e.get(t);return r||(r=new Id(t),e.set(t,r)),r}var qP="mcp";async function Ce(){let t=uy(qP);return await t.init(),t}function zn(t){let e=t.from?ly(t.from,"from",!1):void 0,r=t.to?ly(t.to,"to",!0):void 0;if(e||r){let a=e&&r?`${t.from} \u2192 ${t.to}`:e?`from ${t.from}`:`until ${t.to}`;return{from:e,to:r,label:a}}let n=(t.range||"all").toLowerCase(),o=new Date,s=Mi(o),i=Zo(o);switch(n){case"today":return{from:s,to:i,label:"today"};case"yesterday":{let a=new Date(s);a.setDate(a.getDate()-1);let c=Zo(a);return{from:a,to:c,label:"yesterday"}}case"this_week":return{from:dy(o),to:i,label:"this_week"};case"last_week":{let a=dy(o),c=new Date(a);c.setDate(c.getDate()-7);let u=new Date(a);return u.setMilliseconds(u.getMilliseconds()-1),{from:c,to:u,label:"last_week"}}case"this_month":return{from:new Date(o.getFullYear(),o.getMonth(),1),to:i,label:"this_month"};case"last_month":{let a=new Date(o.getFullYear(),o.getMonth()-1,1),c=new Date(o.getFullYear(),o.getMonth(),1);return c.setMilliseconds(c.getMilliseconds()-1),{from:a,to:c,label:"last_month"}}case"all":return{label:"all"};case"7d":case"30d":case"90d":{let a=parseInt(n,10),c=new Date(s);return c.setDate(c.getDate()-(a-1)),{from:c,to:i,label:n}}default:throw new Error(`invalid 'range' argument: ${JSON.stringify(t.range)}. Expected one of: today, yesterday, this_week, last_week, this_month, last_month, 7d, 30d, 90d, all.`)}}function ly(t,e,r){let n=Zi(t,{upperBoundDateOnly:r});if(!n)throw new Error(`invalid '${e}' argument: ${JSON.stringify(t)}. Expected YYYY-MM-DD or a full ISO 8601 timestamp.`);return n}function py(t){let r=Mi(new Date),n=(t??"today").toLowerCase(),o=c=>({start:Mi(c),end:Zo(c)});if(n==="today"){let{start:c,end:u}=o(r);return{from:c,to:u,label:"today"}}if(n==="yesterday"){let c=new Date(r);c.setDate(c.getDate()-1);let{start:u,end:d}=o(c);return{from:u,to:d,label:"yesterday"}}let i=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].indexOf(n);if(i>=0){let c=new Date(r),u=c.getDay()-i;u<0&&(u+=7),c.setDate(c.getDate()-u);let{start:d,end:l}=o(c);return{from:d,to:l,label:n}}let a=ji(t??"");if(a){let{start:c,end:u}=o(a);return{from:c,to:u,label:t??""}}throw new Error(`invalid 'date' argument: ${JSON.stringify(t)}. Expected today | yesterday | monday..sunday | YYYY-MM-DD.`)}function dy(t){let e=t.getDay()||7,r=new Date(t);return r.setDate(r.getDate()-e+1),r.setHours(0,0,0,0),r}function Rn(t){let e=Sn(t.source),{pricing:r}=e.resolvePricing(t.model);return e.costFromUsage(t.usage,r,t.model)}function Uo(t){if(!t)return"(unknown)";let r=t.replace(/[/\\]+$/,"").split(/[/\\]+/);return r[r.length-1]||t}import{readFileSync as LP,statSync as UP}from"node:fs";import{basename as fy}from"node:path";var my=new Map,FP=/^(.+?)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)[/\\]?$/,VP=/^(.+?)[/\\](?:\.git|\.claude)[/\\]worktrees[/\\]([^/\\]+)(?:[/\\].*)?$/;function HP(t){let e=Uo(t);if(!t)return{label:e,isWorktree:!1,mainName:e,worktreeName:"",canonicalCwd:t};let r=VP.exec(t);if(r){let n=r[1],o=r[2],s=fy(n)||n;return{label:`${s} (${o})`,isWorktree:!0,mainName:s,worktreeName:o,canonicalCwd:n}}try{let n=`${t}/.git`;if(!UP(n).isFile())return{label:e,isWorktree:!1,mainName:e,worktreeName:"",canonicalCwd:t};let i=LP(n,"utf8").trim().split(/\r?\n/,1)[0]??"",a=/^gitdir:\s*(.+)$/.exec(i);if(!a)return{label:e,isWorktree:!1,mainName:e,worktreeName:"",canonicalCwd:t};let c=a[1].trim(),u=FP.exec(c);if(!u)return{label:e,isWorktree:!1,mainName:e,worktreeName:"",canonicalCwd:t};let d=u[1],l=u[2],m=fy(d)||d;return{label:`${m} (${l})`,isWorktree:!0,mainName:m,worktreeName:l,canonicalCwd:d}}catch{return{label:e,isWorktree:!1,mainName:e,worktreeName:"",canonicalCwd:t}}}function hy(t){let e=my.get(t);if(e)return e.label;let r=HP(t);return my.set(t,r),r.label}function Fi(t,e){let r=new Date(t),n=r.getFullYear(),o=String(r.getMonth()+1).padStart(2,"0"),s=String(r.getDate()).padStart(2,"0"),i=String(r.getHours()).padStart(2,"0");if(e==="hour")return{key:`${n}-${o}-${s}T${i}`,label:`${o}/${s} ${i}:00`};if(e==="day")return{key:`${n}-${o}-${s}`,label:`${o}/${s}`};if(e==="week"){let a=new Date(r),c=a.getDay()||7;a.setDate(a.getDate()-c+1);let u=String(a.getMonth()+1).padStart(2,"0"),d=String(a.getDate()).padStart(2,"0");return{key:`${a.getFullYear()}-W${u}${d}`,label:`Wk ${u}/${d}`}}return{key:`${n}-${o}`,label:`${n}-${o}`}}function Fo(t){return{source:t.source,fromIso:t.from?.toISOString(),toIso:t.to?.toISOString(),models:t.models&&t.models.length?new Set(t.models):void 0,projects:t.projects&&t.projects.length?new Set(t.projects):void 0}}function Vo(t,e){return!(t.source!==e.source||e.fromIso&&t.timestamp<e.fromIso||e.toIso&&t.timestamp>e.toIso||e.models&&!e.models.has(t.model)||e.projects&&!e.projects.has(t.cwd))}function gy(t,e,r){let n=new Map,o=Fo(r);for(let s of t){if(!Vo(s,o))continue;let{key:i,label:a}=Fi(s.timestamp,e),c=n.get(i);c||(c=BP(i,a),n.set(i,c)),KP(c,s)}return Array.from(n.values()).sort((s,i)=>s.key.localeCompare(i.key))}function BP(t,e){return{key:t,label:e,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,totalTokens:0,cost:0,saved:0,requests:0,models:{}}}function KP(t,e){let r=Rn(e);t.inputTokens+=e.usage.input_tokens,t.outputTokens+=e.usage.output_tokens,t.cacheReadTokens+=e.usage.cache_read_input_tokens,t.cacheCreationTokens+=e.usage.cache_creation_input_tokens,t.totalTokens=t.inputTokens+t.outputTokens+t.cacheReadTokens+t.cacheCreationTokens,t.cost+=r.total,t.saved+=r.saved,t.requests+=1;let n=t.models[e.model]??{tokens:0,cost:0,requests:0};n.tokens+=e.usage.input_tokens+e.usage.output_tokens+e.usage.cache_read_input_tokens+e.usage.cache_creation_input_tokens,n.cost+=r.total,n.requests+=1,t.models[e.model]=n}function _y(t,e){let r=new Map,n=Fo(e);for(let o of t){if(!Vo(o,n))continue;let s=r.get(o.model);if(!s){let{pricing:a,matchType:c}=Sn(o.source).resolvePricing(o.model);s={model:o.model,source:o.source,requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,totalTokens:0,cost:0,saved:0,pricing:a,pricingResolved:c==="exact"||c==="date-stripped"||c==="prefix-stripped"},r.set(o.model,s)}let i=Rn(o);s.requests+=1,s.inputTokens+=o.usage.input_tokens,s.outputTokens+=o.usage.output_tokens,s.cacheReadTokens+=o.usage.cache_read_input_tokens,s.cacheCreationTokens+=o.usage.cache_creation_input_tokens,s.totalTokens=s.inputTokens+s.outputTokens+s.cacheReadTokens+s.cacheCreationTokens,s.cost+=i.total,s.saved+=i.saved}return Array.from(r.values()).sort((o,s)=>s.cost-o.cost)}function yy(t,e){let r=new Map,n=new Map,o=Fo(e);for(let s of t){if(!Vo(s,o))continue;let i=s.cwd||"(unknown)",a=r.get(i);a||(a={source:e.source,cwd:i,projectName:Uo(i),sessions:0,requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,totalTokens:0,cost:0,saved:0,firstActivity:s.timestamp,lastActivity:s.timestamp,models:[]},r.set(i,a),n.set(i,new Set)),n.get(i).add(s.sessionId);let c=Rn(s);a.requests+=1,a.inputTokens+=s.usage.input_tokens,a.outputTokens+=s.usage.output_tokens,a.cacheReadTokens+=s.usage.cache_read_input_tokens,a.cacheCreationTokens+=s.usage.cache_creation_input_tokens,a.totalTokens=a.inputTokens+a.outputTokens+a.cacheReadTokens+a.cacheCreationTokens,a.cost+=c.total,a.saved+=c.saved,s.timestamp<a.firstActivity&&(a.firstActivity=s.timestamp),s.timestamp>a.lastActivity&&(a.lastActivity=s.timestamp),a.models.includes(s.model)||a.models.push(s.model)}for(let[s,i]of n){let a=r.get(s);a.sessions=i.size}return Array.from(r.values()).sort((s,i)=>i.cost-s.cost)}function vy(t,e,r){let n=new Map,o=Fo(r);for(let i of t){if(!Vo(i,o))continue;let a=i.sessionId||i.uuid,c=n.get(a);c||(c={sessionId:a,source:i.source,cwd:i.cwd,projectName:Uo(i.cwd),projectLabel:hy(i.cwd),startTime:i.timestamp,endTime:i.timestamp,durationMs:0,requests:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,totalTokens:0,cost:0,saved:0,models:[],modelBreakdown:{}},n.set(a,c));let u=Rn(i);c.requests+=1,c.inputTokens+=i.usage.input_tokens,c.outputTokens+=i.usage.output_tokens,c.cacheReadTokens+=i.usage.cache_read_input_tokens,c.cacheCreationTokens+=i.usage.cache_creation_input_tokens,c.totalTokens=c.inputTokens+c.outputTokens+c.cacheReadTokens+c.cacheCreationTokens,c.cost+=u.total,c.saved+=u.saved,i.timestamp<c.startTime&&(c.startTime=i.timestamp),i.timestamp>c.endTime&&(c.endTime=i.timestamp),c.models.includes(i.model)||c.models.push(i.model);let d=c.modelBreakdown[i.model]??{tokens:0,cost:0,requests:0};d.tokens+=i.usage.input_tokens+i.usage.output_tokens+i.usage.cache_read_input_tokens+i.usage.cache_creation_input_tokens,d.cost+=u.total,d.requests+=1,c.modelBreakdown[i.model]=d}let s=new Map;for(let i of e){let a=s.get(i.sessionId);(!a||i.timestamp<a.timestamp)&&s.set(i.sessionId,i)}for(let i of n.values()){i.durationMs=Math.max(0,new Date(i.endTime).getTime()-new Date(i.startTime).getTime());let a=s.get(i.sessionId);a&&a.textPreview&&(i.firstUserMessage=a.textPreview,i.title=a.textPreview.slice(0,80))}return Array.from(n.values()).sort((i,a)=>a.endTime.localeCompare(i.endTime))}function by(t,e){let r=0,n=0,o=0,s=0,i=0,a=0,c=0,u=Fo(e);for(let d of t){if(!Vo(d,u))continue;let l=Rn(d);r+=d.usage.input_tokens,n+=d.usage.output_tokens,o+=d.usage.cache_read_input_tokens,s+=d.usage.cache_creation_input_tokens,i+=l.total,a+=l.saved,c+=1}return{inputTokens:r,outputTokens:n,cacheReadTokens:o,cacheCreationTokens:s,totalTokens:r+n+o+s,cost:i,saved:a,requests:c}}function WP(t,e,r){let n=new Map;for(let a of e)a.isSynthetic||a.textPreview&&a.textPreview.trim()&&n.set(a.uuid,a.textPreview);let o=new Map,s=new Map;function i(a){let c=[],u=a,d=null,l=0,m=new Set;for(;u&&l++<5e3&&!m.has(u);){m.add(u);let f=s.get(u);if(f){d=f;break}if(c.push(u),n.has(u)){d=u;break}u=r[u]??null}d||(d=a);for(let f of c)s.set(f,d);return d}for(let a of t)o.set(a.uuid,i(a.uuid));return o}function Pn(t,e,r){let n=WP(t,e,r),o=new Map;for(let s of t){let i=n.get(s.uuid)??s.uuid,a=o.get(i);(!a||s.timestamp<a.firstTimestamp)&&o.set(i,{turnId:i,firstTimestamp:s.timestamp,firstModel:s.model,cwd:s.cwd,sessionId:s.sessionId,source:s.source})}return o}var En={input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,reasoning_tokens:0,total_tokens:0,cost_usd:0,saved_usd:0,requests:0,turns:0};function Ho(t,e){return t.filter(r=>r.source===e)}function GP(t){let e=0;for(let r of t)e+=r.usage.reasoning_tokens??0;return e}function Vi(t,e){return!(e.from&&t.timestamp<e.from.toISOString()||e.to&&t.timestamp>e.to.toISOString())}function JP(t,e,r,n){let o=Ho(t,e),s=o.filter(a=>Vi(a,r)),i=by(o,{source:e,...r});return{input_tokens:i.inputTokens,output_tokens:i.outputTokens,cache_read_tokens:i.cacheReadTokens,cache_creation_tokens:i.cacheCreationTokens,reasoning_tokens:GP(s),total_tokens:i.totalTokens,cost_usd:i.cost,saved_usd:i.saved,requests:i.requests,turns:Pn(s,n.users,n.parentMap).size}}function xy(t){return t.reduce((e,r)=>({input_tokens:e.input_tokens+r.input_tokens,output_tokens:e.output_tokens+r.output_tokens,cache_read_tokens:e.cache_read_tokens+r.cache_read_tokens,cache_creation_tokens:e.cache_creation_tokens+r.cache_creation_tokens,reasoning_tokens:e.reasoning_tokens+r.reasoning_tokens,total_tokens:e.total_tokens+r.total_tokens,cost_usd:e.cost_usd+r.cost_usd,saved_usd:e.saved_usd+r.saved_usd,requests:e.requests+r.requests,turns:e.turns+r.turns}),{...En})}function Bo(t,e,r,n){let o={claude:{...En},codex:{...En}},s=e==="all"?$n:[e];for(let i of s)o[i]=JP(t,i,r,n);return{totals:xy(s.map(i=>o[i])),bySource:o}}function Hi(t,e,r,n,o){let s=e==="all"?$n:[e],i=new Map;for(let a of s){let c=Ho(t,a),u=gy(c,r,{source:a,...n}),d=new Map,l=n.from?.toISOString(),m=n.to?.toISOString(),f=[];for(let g of c){if(l&&g.timestamp<l||m&&g.timestamp>m)continue;f.push(g);let _=g.usage.reasoning_tokens??0;if(_>0){let{key:b}=Fi(g.timestamp,r);d.set(b,(d.get(b)??0)+_)}}let p=new Map,h=Pn(f,o.users,o.parentMap);for(let g of h.values()){let{key:_}=Fi(g.firstTimestamp,r);p.set(_,(p.get(_)??0)+1)}for(let g of u){let _=i.get(g.key);_||(_={key:g.key,label:g.label,totals:{...En},bySource:{claude:{...En},codex:{...En}}},i.set(g.key,_));let b={input_tokens:g.inputTokens,output_tokens:g.outputTokens,cache_read_tokens:g.cacheReadTokens,cache_creation_tokens:g.cacheCreationTokens,reasoning_tokens:d.get(g.key)??0,total_tokens:g.totalTokens,cost_usd:g.cost,saved_usd:g.saved,requests:g.requests,turns:p.get(g.key)??0};_.bySource[a]=b,_.totals=xy(Object.values(_.bySource))}}return Array.from(i.values()).sort((a,c)=>a.key.localeCompare(c.key))}function Ko(t,e,r,n){let o=e==="all"?$n:[e],s=[];for(let i of o){let a=Ho(t,i),c=a.filter(l=>Vi(l,r)),u=_y(a,{source:i,...r}),d=new Map;for(let l of Pn(c,n.users,n.parentMap).values())d.set(l.firstModel,(d.get(l.firstModel)??0)+1);for(let l of u)s.push({source:i,model:l.model,requests:l.requests,turns:d.get(l.model)??0,input_tokens:l.inputTokens,output_tokens:l.outputTokens,cache_read_tokens:l.cacheReadTokens,cache_creation_tokens:l.cacheCreationTokens,total_tokens:l.totalTokens,cost_usd:l.cost,saved_usd:l.saved,pricing_resolved:l.pricingResolved})}return s.sort((i,a)=>a.cost_usd-i.cost_usd)}function Bi(t,e,r,n){let o=e==="all"?$n:[e],s=[];for(let i of o){let a=Ho(t,i),c=a.filter(l=>Vi(l,r)),u=yy(a,{source:i,...r}),d=new Map;for(let l of Pn(c,n.users,n.parentMap).values()){let m=l.cwd||"(unknown)";d.set(m,(d.get(m)??0)+1)}for(let l of u)s.push({source:i,cwd:l.cwd,project_name:l.projectName,sessions:l.sessions,requests:l.requests,turns:d.get(l.cwd)??0,input_tokens:l.inputTokens,output_tokens:l.outputTokens,cache_read_tokens:l.cacheReadTokens,cache_creation_tokens:l.cacheCreationTokens,total_tokens:l.totalTokens,cost_usd:l.cost,saved_usd:l.saved,models:l.models,first_activity:l.firstActivity,last_activity:l.lastActivity})}return s.sort((i,a)=>a.cost_usd-i.cost_usd)}function In(t,e,r,n,o){let s=r==="all"?$n:[r],i=[];for(let a of s){let c=Ho(t,a),u=e.filter(f=>f.source===a),d=c.filter(f=>Vi(f,n)),l=vy(c,u,{source:a,...n}),m=new Map;for(let f of Pn(d,o.users,o.parentMap).values())m.set(f.sessionId,(m.get(f.sessionId)??0)+1);for(let f of l)i.push({source:a,session_id:f.sessionId,cwd:f.cwd,project_name:f.projectName,title:f.title,first_user_message:f.firstUserMessage,start_time:f.startTime,end_time:f.endTime,duration_ms:f.durationMs,requests:f.requests,turns:m.get(f.sessionId)??0,input_tokens:f.inputTokens,output_tokens:f.outputTokens,cache_read_tokens:f.cacheReadTokens,cache_creation_tokens:f.cacheCreationTokens,total_tokens:f.totalTokens,cost_usd:f.cost,saved_usd:f.saved,models:f.models})}return i.sort((a,c)=>c.end_time.localeCompare(a.end_time))}var YP=process.env.CCGAUGE_MCP_PRETTY==="1";function yt(t){return{content:[{type:"text",text:YP?JSON.stringify(t,null,2):JSON.stringify(t)}]}}function vt(t){return async e=>{try{return await t(e)}catch(r){if(r instanceof Error){let n=qo(r.message);throw n!==r.message&&(r.message=n),r}throw new Error(qo(String(r)))}}}function wy(t){t.registerTool("usage_summary",{title:"Usage summary",description:'Total tokens and dollar-equivalent cost for a date range. When source="all" (default), the response includes a per-source breakdown alongside combined totals so the LLM can answer either provider-specific or combined questions in a single call.',inputSchema:{...kn,...Pt}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=zn(e),i=e.source??"all",a=Bo(n.records,i,{from:s.from,to:s.to},o);return yt({range_label:s.label,from:s.from?.toISOString(),to:s.to?.toISOString(),source:i,...a})})),t.registerTool("usage_by_time",{title:"Usage by time",description:'Time-series of usage and cost, bucketed by hour/day/week/month. Useful for "draw me a trend" or "when does usage spike" questions. Each bucket carries combined totals plus a bySource map (for source="all").',inputSchema:{...kn,...Pt,granularity:N_.describe("hour | day | week | month (default: day)")}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=zn(e),i=e.source??"all",a=e.granularity??"day",c=Hi(n.records,i,a,{from:s.from,to:s.to},o);return yt({range_label:s.label,from:s.from?.toISOString(),to:s.to?.toISOString(),source:i,granularity:a,bucket_count:c.length,buckets:c})})),t.registerTool("usage_by_model",{title:"Usage by model",description:"Per-model usage and cost for a date range. Each entry carries its `source` so you can group by provider client-side. Sorted by cost desc.",inputSchema:{...kn,...Pt,limit:le.number().int().min(1).max(50).default(20).describe("Cap to top N entries by cost. Default 20.")}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=zn(e),i=e.source??"all",a=e.limit??20,c=Ko(n.records,i,{from:s.from,to:s.to},o);return c=c.slice(0,a),yt({range_label:s.label,source:i,count:c.length,models:c})})),t.registerTool("usage_by_project",{title:"Usage by project",description:'Per-project (working directory) usage and cost. Useful for answering "which project is eating my budget" or "what have I worked on this month". Sorted by cost desc.',inputSchema:{...kn,...Pt,limit:le.number().int().min(1).max(100).default(20).describe("Cap to top N projects by cost. Default 20.")}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=zn(e),i=e.source??"all",a=e.limit??20,c=Bi(n.records,i,{from:s.from,to:s.to},o);return c=c.slice(0,a),yt({range_label:s.label,source:i,count:c.length,projects:c})})),t.registerTool("usage_by_session",{title:"Usage by session",description:"Per-session list with each session's first user message (as title), models used, duration, tokens and cost. Default sort is most-recent first; use `sort` to switch.",inputSchema:{...kn,...Pt,sort:le.enum(["recent","cost","tokens","duration"]).default("recent").describe("recent (default) | cost | tokens | duration. Always desc."),limit:le.number().int().min(1).max(200).default(25).describe("Max sessions to return. Default 25.")}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=zn(e),i=e.source??"all",a=e.sort??"recent",c=e.limit??25,u=In(n.records,n.userRecords,i,{from:s.from,to:s.to},o);switch(a){case"cost":u.sort((l,m)=>m.cost_usd-l.cost_usd);break;case"tokens":u.sort((l,m)=>m.total_tokens-l.total_tokens);break;case"duration":u.sort((l,m)=>m.duration_ms-l.duration_ms);break;default:u.sort((l,m)=>m.end_time.localeCompare(l.end_time))}let d=u.length;return u=u.slice(0,c),yt({range_label:s.label,source:i,sort:a,total_count:d,returned_count:u.length,sessions:u})})),t.registerTool("cost_estimator",{title:"Cost estimator",description:"Compute the dollar-equivalent cost of a hypothetical request given token counts. Uses the provider's built-in per-1M-token pricing table; does NOT consult the user's usage history. Useful for \"how much would 5M output tokens of opus 4.8 cost\" / pre-purchase what-ifs. NOTE: reasoning tokens (Codex / OpenAI o-series) are already included in `output_tokens` and billed at the output rate \u2014 don't double-count them.",inputSchema:{source:le.enum(["claude","codex"]).describe("claude | codex \u2014 pick the pricing namespace."),model:le.string().min(1).describe('Exact model id (e.g. "claude-opus-4-8-20260115", "gpt-5.2-codex"). Date suffixes are stripped automatically.'),input_tokens:le.number().int().min(0).default(0),output_tokens:le.number().int().min(0).default(0).describe("Total output tokens. INCLUDES reasoning tokens for Codex / o-series \u2014 those are billed at the output rate, not separately."),cache_read_tokens:le.number().int().min(0).default(0),cache_creation_tokens:le.number().int().min(0).default(0).describe("Sum of 5m + 1h cache writes (Anthropic) or 0 (OpenAI).")}},vt(async e=>{let r=e.source,n=Sn(r),{pricing:o,matchType:s}=n.resolvePricing(e.model),i={input_tokens:e.input_tokens??0,output_tokens:e.output_tokens??0,cache_creation_input_tokens:e.cache_creation_tokens??0,cache_read_input_tokens:e.cache_read_tokens??0,cache_creation_5m:0,cache_creation_1h:0},a=or(i,o);return yt({source:r,model:e.model,pricing_match:s,pricing_resolved:s==="exact"||s==="date-stripped"||s==="prefix-stripped",pricing:o,usage:i,cost_breakdown:{input:a.input,output:a.output,cache_creation:a.cacheCreation5m+a.cacheCreation1h,cache_read:a.cacheRead,total:a.total,saved_vs_full_input:a.saved},total_tokens:i.input_tokens+i.output_tokens+i.cache_read_input_tokens+i.cache_creation_input_tokens})}))}var Cd={input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_creation_tokens:0,reasoning_tokens:0,total_tokens:0,cost_usd:0,saved_usd:0,requests:0,turns:0};function XP(t){let e=new Date,r=e.getDay()||7,n=new Date(e);n.setDate(e.getDate()-r+1+t*7),n.setHours(0,0,0,0);let o=new Date(n);o.setDate(n.getDate()+6),o.setHours(23,59,59,999);let s=i=>`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")}`;return{from:n,to:o,label:`${s(n)} \u2192 ${s(o)}`}}function QP(t){let e=new Map;for(let r of t){let n=r.cwd||"(unknown)",o=e.get(n);o||(o={project:r.project_name,cwd:n,sessions:[]},e.set(n,o)),o.sessions.push(r)}return Array.from(e.values()).sort((r,n)=>n.sessions.reduce((o,s)=>o+s.cost_usd,0)-r.sessions.reduce((o,s)=>o+s.cost_usd,0))}function ky(t,e,r,n=10){let o=e.from.toISOString(),s=e.to.toISOString(),i=new Map;for(let a of t)if(!(r!=="all"&&a.source!==r)&&!(a.timestamp<o)&&!(a.timestamp>s))for(let c of a.toolNames)i.set(c,(i.get(c)??0)+1);return Array.from(i.entries()).sort((a,c)=>c[1]-a[1]).slice(0,n).map(([a,c])=>({tool:a,count:c}))}function $y(t){t.registerTool("daily_summary",{title:"Daily summary \u2014 what was worked on",description:'A "what did I do" report for a single day. Returns totals, sessions grouped by project (with first-user-message titles), models used, and top tool calls. Date defaults to "today" and accepts "yesterday", weekday names ("monday"..), or YYYY-MM-DD.',inputSchema:{date:M_.optional().describe("today | yesterday | monday..sunday | YYYY-MM-DD. Default today."),...Pt}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=py(e.date),i=e.source??"all",a=Bo(n.records,i,s,o),c=In(n.records,n.userRecords,i,s,o),u=Ko(n.records,i,s,o),d=ky(n.records,s,i);return yt({date:s.label,from:s.from.toISOString(),to:s.to.toISOString(),source:i,totals:a.totals,bySource:a.bySource,session_count:c.length,sessions_by_project:QP(c),models:u,top_tools:d})})),t.registerTool("weekly_summary",{title:"Weekly summary",description:"A week-long roll-up: totals, per-day cost trend, top sessions by cost, top projects, and models used. Use `week_offset` to walk back (0=this week, -1=last week, etc.).",inputSchema:{week_offset:le.number().int().min(-52).max(0).default(0).describe("0=this week, -1=last week, ..., -52=one year ago. Default 0."),...Pt,top_session_limit:le.number().int().min(1).max(50).default(10)}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=e.week_offset??0,i=XP(s),a=e.source??"all",c=Bo(n.records,a,i,o),u=Hi(n.records,a,"day",{from:i.from,to:i.to},o),d=new Map(u.map(_=>[_.key,_])),l=[];for(let _=0;_<7;_++){let b=new Date(i.from);b.setDate(b.getDate()+_);let x=`${b.getFullYear()}-${String(b.getMonth()+1).padStart(2,"0")}-${String(b.getDate()).padStart(2,"0")}`,$=d.get(x);$?l.push({date:x,totals:$.totals,bySource:$.bySource}):l.push({date:x,totals:{...Cd},bySource:{claude:{...Cd},codex:{...Cd}}})}let m=In(n.records,n.userRecords,a,i,o),f=m.slice().sort((_,b)=>b.cost_usd-_.cost_usd).slice(0,e.top_session_limit??10),p=Bi(n.records,a,i,o).slice(0,10),h=Ko(n.records,a,i,o),g=ky(n.records,i,a);return yt({week:i.label,from:i.from.toISOString(),to:i.to.toISOString(),source:a,totals:c.totals,bySource:c.bySource,per_day:l,session_count:m.length,top_sessions:f,top_projects:p,models:h,top_tools:g})})),t.registerTool("recent_activity",{title:"Recent activity",description:'The N most recently active sessions across providers. Quick way to answer "what did I just work on" without specifying a date. Defaults to the last 30 days so the response time stays bounded regardless of how long the user has been running ccgauge \u2014 pass `days` to widen.',inputSchema:{limit:le.number().int().min(1).max(50).default(10).describe("Number of sessions to return. Default 10."),days:le.number().int().min(1).max(365).default(30).describe("Look-back window in days. Default 30. Increase if the user has long-running idle sessions you still want surfaced."),...Pt}},vt(async e=>{let n=(await Ce()).getSnapshot(),o={users:n.userRecords,parentMap:n.parentMap},s=e.source??"all",i=e.limit??10,a=e.days??30,c=new Date,u=new Date(c);u.setDate(u.getDate()-(a-1)),u.setHours(0,0,0,0);let d=new Date(c);d.setHours(23,59,59,999);let l=In(n.records,n.userRecords,s,{from:u,to:d},o).slice().sort((m,f)=>f.end_time.localeCompare(m.end_time)).slice(0,i);return yt({source:s,window_days:a,from:u.toISOString(),to:d.toISOString(),returned_count:l.length,sessions:l})}))}function Sy(t){t.registerResource("providers","ccgauge://providers",{title:"Detected providers",description:"Which AI coding CLIs ccgauge has discovered on this machine, the data directories scanned for each, and a per-source file/record count from the latest snapshot.",mimeType:"application/json"},async e=>{let r=await Ce(),n=r.getSnapshot(),o=r.getStatus(),s=await ey(),i=Do().map(a=>{let c=n.bySource.find(u=>u.source===a.id);return{id:a.id,display_name:a.displayName.en,short_label:a.shortLabel,available:s.includes(a.id),parser_version:a.parserVersion,capabilities:a.capabilities,dirs:a.getDirs(),dirs_with_data:c?.scannedDirs??[],files_indexed:c?.filesScanned??0,assistant_records:c?.assistantRecords??0}});return{contents:[{uri:e.href,mimeType:"application/json",text:JSON.stringify({last_indexed_at:o.lastIndexedAt,index_duration_ms:o.indexDurationMs,loaded_from_disk:o.loadedFromDisk,providers:i},null,2)}]}})}var e1="ccgauge",Ty="1.2.1";function t1(){let t=new Oi({name:e1,version:Ty},{capabilities:{tools:{},resources:{}}});return wy(t),$y(t),Sy(t),t}async function zy(){let t=(...o)=>{process.stderr.write(`[ccgauge-mcp] ${o.map(String).join(" ")}
|
|
43
|
+
`)};Ce().then(o=>{let s=o.getStatus();t(`indexer ready: files=${s.filesIndexed} records=${s.recordsIndexed} loadedFromDisk=${s.loadedFromDisk}`)}).catch(o=>t("indexer init failed:",o.message));let e=t1(),r=new Ni,n=()=>{t("shutting down"),r.close().catch(()=>{}),process.exit(0)};process.on("SIGINT",n),process.on("SIGTERM",n),await e.connect(r),t(`v${Ty} listening on stdio`)}var r1="1.2.1";async function n1(){let t=e=>process.stdout.write(`${e}
|
|
44
44
|
`);t(`ccgauge MCP server v${r1}`),t("bundle: OK");try{let r=(await Ce()).getStatus();if(t(`indexer: files=${r.filesIndexed} records=${r.recordsIndexed} loadedFromDisk=${r.loadedFromDisk}`),r.bySource.length===0)t("providers: (none detected \u2014 no Claude Code or Codex data dirs found)");else{t("providers:");for(let n of r.bySource)if(t(` ${n.source.padEnd(8)} ${String(n.filesScanned).padStart(4)} files ${String(n.assistantRecords).padStart(6)} records`),n.scannedDirs.length>0)for(let o of n.scannedDirs)t(` ${o}`)}if(r.errors&&r.errors.length>0){t(`recent errors: ${r.errors.length}`);for(let n of r.errors.slice(-3))t(` - ${n}`)}return 0}catch(e){return process.stderr.write(`[ccgauge-mcp] check failed: ${e.message}
|
|
45
45
|
`),1}}var s1=o1(import.meta.url);process.argv[1]===s1&&zy().catch(t=>{process.stderr.write(`[ccgauge-mcp] fatal: ${t.stack||t}
|
|
46
46
|
`),process.exit(1)});export{n1 as printCheck,zy as runStdioServer};
|