@makaio/framework 1.0.0-dev-1783973359164 → 1.0.0-dev-1783977266352
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.makaio-build.json +2 -2
- package/dist/{account-identity-BYfeWLe-.mjs → account-identity-CP4DC0DL.mjs} +1 -1
- package/dist/{adapter-nl_xz9dz.mjs → adapter-B9vVBwli.mjs} +1 -1
- package/dist/adapters/node.mjs +1 -1
- package/dist/bus/index.mjs +1 -1
- package/dist/{client-BkpLM8Fx.mjs → client-CzPCSeyE.mjs} +1 -1
- package/dist/contracts/adapter/index.mjs +1 -1
- package/dist/contracts/artifact/index.d.mts +1 -1
- package/dist/contracts/client/index.d.mts +1 -1
- package/dist/contracts/client/index.mjs +1 -1
- package/dist/contracts/extension/index.d.mts +2 -2
- package/dist/contracts/extension/index.mjs +1 -1
- package/dist/contracts/facet/index.d.mts +1 -1
- package/dist/contracts/harness/index.d.mts +1 -1
- package/dist/contracts/index.d.mts +61 -61
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/materialization/index.d.mts +3 -3
- package/dist/contracts/native-session-supervisor/index.mjs +1 -1
- package/dist/contracts/session/index.d.mts +2 -2
- package/dist/contracts/session/index.mjs +1 -1
- package/dist/contracts/workflow/index.d.mts +2 -2
- package/dist/{definition-Bj9Vr16H.d.mts → definition-D7qCBmtc.d.mts} +1 -1
- package/dist/{extension-D4iKUUMG.mjs → extension-Cgg45Xk1.mjs} +1 -1
- package/dist/git/index.mjs +8 -8
- package/dist/{index-DHGW7dFf.d.mts → index-2PsDAhPN.d.mts} +8 -8
- package/dist/{index-CtjLeK1F.d.mts → index-BXWTilGs.d.mts} +1 -1
- package/dist/{index-DNkR5yTY.d.mts → index-BrAp9ntB.d.mts} +47 -47
- package/dist/{index-C2C1qH1Y.d.mts → index-CHjKP5G0.d.mts} +8 -8
- package/dist/{index-CVs0Qxks.d.mts → index-CSxfU0tB.d.mts} +4 -4
- package/dist/{index-Lp0T_V1W.d.mts → index-CidblQAY.d.mts} +6 -6
- package/dist/{index-BKZAAWo2.d.mts → index-Cq6rXKae.d.mts} +88 -88
- package/dist/{index-9g0agW_p.d.mts → index-D3Eek6kd.d.mts} +22 -22
- package/dist/{index-x2gFj3BK.d.mts → index-DMQlLz2W.d.mts} +9 -9
- package/dist/{index-COC9jCdc.d.mts → index-DmuGKvE2.d.mts} +4 -4
- package/dist/{index-BDr2Ba122.d.mts → index-MTvmxwiu2.d.mts} +1 -1
- package/dist/{index-ButbwvVY.d.mts → index-kqxUXYe7.d.mts} +6 -6
- package/dist/kernel/extension/index.d.mts +1 -1
- package/dist/kernel/index.d.mts +2 -2
- package/dist/kernel/observability/index.d.mts +1 -1
- package/dist/{lib-DymjnkAP.mjs → lib-DktBDEoY.mjs} +1 -1
- package/dist/{namespace-B0uZIZYT.d.mts → namespace-TLkZRkcU.d.mts} +20 -20
- package/dist/{namespace-CCZXyxSe.d.mts → namespace-dgNmx9g3.d.mts} +27 -27
- package/dist/{native-session-supervisor-CdtVGWA9.mjs → native-session-supervisor-Bgz-Q1WH.mjs} +1 -1
- package/dist/package.json +1 -1
- package/dist/{profile-D2m94ZYD.mjs → profile-BRi6K6am.mjs} +1 -1
- package/dist/runtime-node/index.mjs +1 -1
- package/dist/{schema-aOwmHxaF.d.mts → schema-CxN7d_MU.d.mts} +1 -1
- package/dist/{schemas-CoJCTFod2.d.mts → schemas-CIO03KSD2.d.mts} +8 -8
- package/dist/{schemas-BolSW7pQ.d.mts → schemas-DlCdlCEF.d.mts} +4 -4
- package/dist/{schemas-n9Ff6_RX.mjs → schemas-DyJHJ8Pm.mjs} +1 -1
- package/dist/semver-D3Y7uMEb.mjs +1 -0
- package/dist/services/context-rules/index.d.mts +3 -3
- package/dist/services/execution-target/index.d.mts +1 -1
- package/dist/services/filesystem/namespace.d.mts +6 -6
- package/dist/services/filesystem/schemas.d.mts +3 -3
- package/dist/services/harness/index.d.mts +3 -3
- package/dist/services/index.d.mts +16 -16
- package/dist/services/session/index.d.mts +4 -4
- package/dist/services/session/session-events/namespace.d.mts +1 -1
- package/dist/services/session/storage/namespace.d.mts +1 -1
- package/dist/services/session/storage/schema.d.mts +1 -1
- package/dist/services/settings/namespace.d.mts +8 -8
- package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
- package/dist/services/subagent-template/index.d.mts +1 -1
- package/dist/services/subagent-template/schemas.d.mts +1 -1
- package/dist/{session-lRd8HZNZ.mjs → session-BxWogVkD.mjs} +1 -1
- package/dist/{transition-CwUIm1hJ.d.mts → transition-DjipYcC3.d.mts} +1 -1
- package/dist/{types-BaDYigzD.d.mts → types-DQsYUZwa.d.mts} +34 -34
- package/dist/{version-C1-VD-XL.mjs → version-BbWrAPld.mjs} +1 -1
- package/dist/workflow-engine/index.d.mts +46 -46
- package/package.json +2 -2
- package/dist/semver-BccS1s9R.mjs +0 -1
package/dist/.makaio-build.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 1,
|
|
3
|
-
"fingerprint": "
|
|
4
|
-
"builtAt": "2026-07-
|
|
3
|
+
"fingerprint": "b6189826f75da850f68fce0192c8c6c5824de636747420c2725bf1999b0accb0",
|
|
4
|
+
"builtAt": "2026-07-13T21:15:29.728Z"
|
|
5
5
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./json-value-DmU8ibo_.mjs";import"./shared-RP_KARKF.mjs";import{g as t,h as n,m as r}from"./profile-
|
|
1
|
+
import{t as e}from"./json-value-DmU8ibo_.mjs";import"./shared-RP_KARKF.mjs";import{g as t,h as n,m as r}from"./profile-BRi6K6am.mjs";import{n as i}from"./version-BbWrAPld.mjs";import{z as a}from"zod";const o=a.enum([`strong`,`alias`]),s=a.object({scheme:t,value:t,strength:o}),c=a.object({key:t,label:a.string(),usedPercentage:a.number().finite().min(0).max(100),resetsAt:n.optional()}),l=a.object({windows:a.array(c)}),u=a.record(a.string(),a.unknown()).optional(),d=a.object({clientId:t,found:a.boolean(),binaryPath:r.optional(),version:a.string().optional(),warningMessage:a.string().optional()}),f=a.object({clientId:t,binaryName:t,supportedVersions:i.optional()}),p=a.object({clientAccountId:t,clientId:t,observedAt:n,source:t,displayLabel:a.string().optional(),usage:l,metadata:u}),m=a.discriminatedUnion(`kind`,[a.object({kind:a.literal(`session`),sessionId:t}),a.object({kind:a.literal(`adapter-session`),adapterSessionId:t}),a.object({kind:a.literal(`both`),sessionId:t,adapterSessionId:t})]),h=a.object({clientId:a.string(),source:a.string(),kind:a.string(),observedAt:n,payload:e}),g={request:a.object({clientId:t,observedAt:n.optional(),displayLabel:a.string().optional(),identifiers:a.array(s).min(1),metadata:u}),response:a.object({clientAccountId:t,displayLabel:a.string().optional()})},_={request:h.extend({locator:m}),response:a.object({handled:a.boolean(),sessionId:t.nullable(),clientAccountId:t.nullable(),changed:a.boolean()})},v={request:a.object({clientId:t,observedAt:n,source:t,account:a.object({displayLabel:a.string().optional(),identifiers:a.array(s).min(1)}),usage:l,metadata:u}),response:a.object({clientAccountId:t,snapshot:p})};export{u as a,_ as c,p as d,c as f,h as i,m as l,g as n,d as o,l as p,o as r,f as s,s as t,v as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e,b as t,c as n,d as r,f as i,g as a,h as o,ht as s,l as c,m as l,o as u,p as d,s as f,t as p,u as m,v as h,y as g}from"./schemas-
|
|
1
|
+
import{_ as e,b as t,c as n,d as r,f as i,g as a,h as o,ht as s,l as c,m as l,o as u,p as d,s as f,t as p,u as m,v as h,y as g}from"./schemas-DyJHJ8Pm.mjs";import"./compression-CZ_6fYq8.mjs";import"./provider-context-DOsjOjiR.mjs";import"./contracts/adapter/schemas/session-lineage.mjs";import{createBusNamespace as _}from"@makaio/framework/core";const v={getCapabilities:s,startAgent:t,infer:g,listAgents:h,getAgent:e,stopAgent:a,rehydrateAgent:o,getConfigSchema:l,"agent.created":d,"session.created":i,"session.discovered":p,"session.usage":r,"session.closed":m,log:c,error:n,initialized:f,quota:u},y=_(`adapter`,v),b=y.subjects;export{b as n,v as r,y as t};
|
package/dist/adapters/node.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{o as e,t}from"../chunk-DTipWd-i.mjs";import{i as n,r}from"../cursor-storage-Bw-7ROzx.mjs";import{t as i}from"../globby-CisClzat.mjs";import*as a from"node:fs/promises";import*as o from"node:path";import{MakaioBus as s}from"@makaio/framework/bus";import{AdapterSubjects as c,ClientSubjects as l,SessionStorageSubjects as u,SessionSubjects as d}from"@makaio/framework/contracts";const f=65536;async function p(e){let{filePath:t,startOffset:n=0}=e,r=[],i=[],o=n,s;try{s=await a.open(t,`r`);let e=await s.stat();if(n>=e.size)return{records:r,bytesRead:n,errors:i};let c=Buffer.alloc(f),l=``,u=n,d=0;for(n>0&&(d=await v(s,n));u<e.size;){let{bytesRead:e}=await s.read(c,0,f,u);if(e===0)break;l+=c.toString(`utf8`,0,e),u+=e;let t=l.split(`
|
|
2
2
|
`),n=t.pop();for(let e of t){if(d++,e.trim()===``){o+=Buffer.byteLength(e,`utf8`)+1;continue}let t=g(e,d);t.success?r.push(t.record):i.push(t.error),o+=Buffer.byteLength(e,`utf8`)+1}l=n??``}return{records:r,bytesRead:o,errors:i}}finally{s&&await s.close()}}async function m(e,t){let n=[],r;try{r=await a.open(e,`r`);let i=Buffer.alloc(f),o=``,s=0;for(;n.length<t;){let{bytesRead:e}=await r.read(i,0,f,s);if(e===0)break;o+=i.toString(`utf8`,0,e),s+=e;let a=o.split(`
|
|
3
3
|
`);o=a.pop()??``;for(let e of a){if(n.length>=t)break;let r=e.trim();if(r!==``)try{n.push(JSON.parse(r))}catch{}}}return n}finally{r&&await r.close()}}async function h(e,t){let n;try{n=await a.open(e,`r`);let r=Buffer.alloc(f),i=``,o=0;for(;;){let{bytesRead:e}=await n.read(r,0,f,o);if(e===0)break;i+=r.toString(`utf8`,0,e),o+=e;let a=i.split(`
|
|
4
|
-
`);i=a.pop()??``;for(let e of a){let n=e.trim();if(n!==``)try{if(t(JSON.parse(n)))return!0}catch{}}}return!1}finally{n&&await n.close()}}function g(e,t){try{return{success:!0,record:JSON.parse(e)}}catch(n){return{success:!1,error:{line:t,error:n instanceof Error?n.message:String(n),content:_(e)}}}}function _(e){return e.length<=200?e:e.slice(0,200)+`...`}async function v(e,t){let n=0,r=Buffer.alloc(f),i=0;for(;i<t;){let a=Math.min(f,t-i),{bytesRead:o}=await e.read(r,0,a,i);if(o===0)break;for(let e=0;e<o;e++)r[e]===10&&n++;i+=o}return n}var y=e(t(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)}))(),1),b=class e extends Error{name=`TimeoutError`;constructor(t,n){super(t,n),Error.captureStackTrace?.(this,e)}};const x=e=>e.reason??new DOMException(`This operation was aborted.`,`AbortError`);function S(e,t){let{milliseconds:n,fallback:r,message:i,customTimers:a={setTimeout,clearTimeout},signal:o}=t,s,c,l=new Promise((t,l)=>{if(typeof n!=`number`||Math.sign(n)!==1)throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(o?.aborted){l(x(o));return}if(o&&(c=()=>{l(x(o))},o.addEventListener(`abort`,c,{once:!0})),e.then(t,l),n===1/0)return;let u=new b;s=a.setTimeout.call(void 0,()=>{if(r){try{t(r())}catch(e){l(e)}return}typeof e.cancel==`function`&&e.cancel(),i===!1?t():i instanceof Error?l(i):(u.message=i??`Promise timed out after ${n} milliseconds`,l(u))},n)}).finally(()=>{l.clear(),c&&o&&o.removeEventListener(`abort`,c)});return l.clear=()=>{a.clearTimeout.call(void 0,s),s=void 0},l}function C(e,t,n){let r=0,i=e.length;for(;i>0;){let a=Math.trunc(i/2),o=r+a;n(e[o],t)<=0?(r=++o,i-=a+1):i=a}return r}var w=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:r}=t??{},{size:i}=this,a={priority:n,id:r,run:e};if(i===0){this.#e.length=0,this.#t=0,this.#e.push(a);return}if(this.#e.at(-1).priority>=n){this.#e.push(a);return}this.#n();let o=C(this.#e,a,(e,t)=>t.priority-e.priority);this.#e.splice(o,0,a)}setPriority(e,t){let n=this.#e.findIndex((t,n)=>n>=this.#t&&t.id===e);if(n===-1)throw ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[r]=this.#e.splice(n,1);this.enqueue(r.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((t,n)=>n<this.#t?!1:typeof e==`string`?t.id===e:t.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>100&&this.#t>this.#e.length/2&&this.#n(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let r=this.#e[n];r.priority===e.priority&&t.push(r.run)}return t}get size(){return this.#e.length-this.#t}#n(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}},T=class extends y.default{#e;#t;#n=0;#r;#i=!1;#a=!1;#o;#s=0;#c=0;#l;#u;#d;#f=[];#p=0;#m;#h;#g=0;#_;#v;#y=1n;#b=new Map;#x=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:w,strict:!1,...e},!(typeof e.intervalCap==`number`&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??``}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??``}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===1/0)throw TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===1/0||e.interval===0,this.#r=e.intervalCap,this.#o=e.interval,this.#d=e.strict,this.#m=new e.queueClass,this.#h=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#v=e.autoStart===!1,this.#z()}#S(e){for(;this.#p<this.#f.length;){let t=this.#f[this.#p];if(t!==void 0&&e-t>=this.#o)this.#p++;else break}(this.#p>100&&this.#p>this.#f.length/2||this.#p===this.#f.length)&&(this.#f=this.#f.slice(this.#p),this.#p=0)}#C(e){this.#d?this.#f.push(e):this.#n++}#w(){this.#d?this.#f.length>this.#p&&this.#f.pop():this.#n>0&&this.#n--}#T(){return this.#f.length-this.#p}get#E(){return this.#t?!0:this.#d?this.#T()<this.#r:this.#n<this.#r}get#D(){return this.#g<this.#_}#O(){this.#g--,this.#g===0&&this.emit(`pendingZero`),this.#P(),this.emit(`next`)}#k(){this.#u=void 0,this.#I(),this.#F()}#A(e){if(this.#d){if(this.#S(e),this.#T()>=this.#r){let t=this.#f[this.#p],n=this.#o-(e-t);return this.#j(n),!0}return!1}if(this.#l===void 0){let t=this.#s-e;if(t<0){if(this.#c>0){let t=e-this.#c;if(t<this.#o)return this.#j(this.#o-t),!0}this.#n=this.#e?this.#g:0}else return this.#j(t),!0}return!1}#j(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#k()},e))}#M(){this.#l&&=(clearInterval(this.#l),void 0)}#N(){this.#u&&=(clearTimeout(this.#u),void 0)}#P(){if(this.#m.size===0){if(this.#M(),this.emit(`empty`),this.#g===0){if(this.#N(),this.#d&&this.#p>0){let e=Date.now();this.#S(e)}this.emit(`idle`)}return!1}let e=!1;if(!this.#v){let t=Date.now(),n=!this.#A(t);if(this.#E&&this.#D){let r=this.#m.dequeue();this.#t||(this.#C(t),this.#B()),this.emit(`active`),r(),n&&this.#F(),e=!0}}return e}#F(){this.#t||this.#l!==void 0||this.#d||(this.#l=setInterval(()=>{this.#I()},this.#o),this.#s=Date.now()+this.#o)}#I(){this.#d||(this.#n===0&&this.#g===0&&this.#l&&this.#M(),this.#n=this.#e?this.#g:0),this.#L(),this.#B()}#L(){for(;this.#P(););}get concurrency(){return this.#_}set concurrency(e){if(!(typeof e==`number`&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#_=e,this.#L()}setPriority(e,t){if(typeof t!=`number`||!Number.isFinite(t))throw TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#m.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#y++).toString()},new Promise((n,r)=>{let i=Symbol(`task-${t.id}`),a=()=>void 0,o=async()=>{a(),this.#g++,this.#b.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let o;try{try{t.signal?.throwIfAborted()}catch(e){throw this.#V(),this.#b.delete(i),e}this.#c=Date.now();let r=e({signal:t.signal});if(t.timeout&&(r=S(Promise.resolve(r),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#g} running, ${this.#m.size} waiting)`})),t.signal){let{signal:e}=t;r=Promise.race([r,new Promise((t,n)=>{o=()=>{n(e.reason)},e.addEventListener(`abort`,o,{once:!0})})])}let a=await r;n(a),this.emit(`completed`,a)}catch(e){r(e),this.emit(`error`,e)}finally{o&&t.signal?.removeEventListener(`abort`,o),this.#b.delete(i),queueMicrotask(()=>{this.#O()})}};this.#m.enqueue(o,t);let s=()=>{if(this.#m instanceof w){this.#m.remove(o);return}this.#m.remove?.(t.id)};if(t.signal){let{signal:e}=t,n=()=>{a(),s(),r(e.reason),this.#P(),this.emit(`next`)};if(a=()=>{e.removeEventListener(`abort`,n),this.#x.delete(a)},e.aborted){n();return}e.addEventListener(`abort`,n,{once:!0}),this.#x.add(a)}this.emit(`add`),this.#P()})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this.#v?(this.#v=!1,this.#L(),this):this}pause(){this.#v=!0}clear(){for(let e of this.#x)e();this.#m=new this.#h,this.#M(),this.#H(),this.emit(`empty`),this.#g===0&&(this.#N(),this.emit(`idle`)),this.emit(`next`)}async onEmpty(){this.#m.size!==0&&await this.#R(`empty`)}async onSizeLessThan(e){this.#m.size<e||await this.#R(`next`,()=>this.#m.size<e)}async onIdle(){this.#g===0&&this.#m.size===0||await this.#R(`idle`)}async onPendingZero(){this.#g!==0&&await this.#R(`pendingZero`)}async onRateLimit(){this.isRateLimited||await this.#R(`rateLimit`)}async onRateLimitCleared(){this.isRateLimited&&await this.#R(`rateLimitCleared`)}onError(){return new Promise((e,t)=>{let n=e=>{this.off(`error`,n),t(e)};this.on(`error`,n)})}async#R(e,t){return new Promise(n=>{let r=()=>{t&&!t()||(this.off(e,r),n())};this.on(e,r)})}get size(){return this.#m.size}sizeBy(e){return this.#m.filter(e).length}get pending(){return this.#g}get isPaused(){return this.#v}#z(){this.#t||(this.on(`add`,()=>{this.#m.size>0&&this.#B()}),this.on(`next`,()=>{this.#B()}))}#B(){this.#t||this.#a||(this.#a=!0,queueMicrotask(()=>{this.#a=!1,this.#H()}))}#V(){this.#t||(this.#w(),this.#B())}#H(){let e=this.#i;if(this.#t||this.#m.size===0){e&&(this.#i=!1,this.emit(`rateLimitCleared`));return}let t;if(this.#d){let e=Date.now();this.#S(e),t=this.#T()}else t=this.#n;let n=t>=this.#r;n!==e&&(this.#i=n,this.emit(n?`rateLimit`:`rateLimitCleared`))}get isRateLimited(){return this.#i}get isSaturated(){return this.#g===this.#_&&this.#m.size>0||this.isRateLimited&&this.#m.size>0}get runningTasks(){return[...this.#b.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}},E=class{eventQueue;cursorQueue;onEventEmitted;constructor(e){this.onEventEmitted=e.onEventEmitted,this.eventQueue=new T({concurrency:1,interval:1e3,intervalCap:e.eventsPerSecond}),this.cursorQueue=new T({concurrency:1})}queueEvent(e){return this.eventQueue.add(async()=>{await s.emit(e.subject,e.payload),this.onEventEmitted()})}queueAfterEvents(e,t=[]){let n=Promise.all(t);return n.catch(()=>void 0),this.cursorQueue.add(async()=>{await n,await e()})}async drain(){await Promise.all([this.eventQueue.onIdle(),this.cursorQueue.onIdle()])}async onIdle(){await this.drain()}},D=class{options;emittery=new n;trackedFiles=new Map;pollTimer;isPolling=!1;isDisposed=!1;inFlightChecks=new Map;constructor(e){if(!o.isAbsolute(e.directory))throw Error(`Directory must be an absolute path: ${e.directory}`);this.options={directory:e.directory,pattern:e.pattern,pollIntervalMs:e.pollIntervalMs??1e4}}on(e,t){return this.emittery.on(e,t)}once(e,t){return this.emittery.once(e,t)}async start(){this.isDisposed||this.pollTimer===void 0&&(await this.poll(),this.pollTimer=setInterval(()=>{this.poll()},this.options.pollIntervalMs))}stop(){this.pollTimer!==void 0&&(clearInterval(this.pollTimer),this.pollTimer=void 0)}dispose(){this.isDisposed=!0,this.stop(),this.emittery.clearListeners(),this.trackedFiles.clear(),this.inFlightChecks.clear()}isRunning(){return this.pollTimer!==void 0}getTrackedFiles(){return this.trackedFiles}seedFromCursors(e){for(let t of e)this.trackedFiles.set(t.filePath,{size:t.bytesRead,mtimeMs:new Date(t.lastModified).getTime()})}async poll(){if(!this.isDisposed&&!this.isPolling){this.isPolling=!0;try{let e=await this.discoverFiles(),t=new Set(e);for(let e of this.trackedFiles.keys())if(!t.has(e)){if(this.isDisposed)return;this.trackedFiles.delete(e),await this.emittery.emit(`deleted`,{filePath:e})}for(let t of e)try{await this.runFileCheck(t)}catch(e){await this.emitWatcherError(e,t)}if(this.isDisposed)return;await this.emittery.emit(`polled`,{trackedFilePaths:new Set(this.trackedFiles.keys())})}catch(e){await this.emitWatcherError(e)}finally{this.isPolling=!1}}}async discoverFiles(){return i(this.options.pattern,{cwd:this.options.directory,absolute:!0,onlyFiles:!0})}async checkFile(e){if(this.isDisposed)return;let t=await a.stat(e);if(this.isDisposed)return;let n={size:t.size,mtimeMs:t.mtimeMs},r=this.trackedFiles.get(e);if(!r){if(this.trackedFiles.set(e,n),this.isDisposed){this.trackedFiles.delete(e);return}await this.emittery.emit(`change`,{filePath:e,stat:{size:t.size,mtime:t.mtime},changeType:`created`});return}if(n.mtimeMs!==r.mtimeMs){let i=n.size<r.size?`rotated`:`modified`;if(this.trackedFiles.set(e,n),this.isDisposed)return;await this.emittery.emit(`change`,{filePath:e,stat:{size:t.size,mtime:t.mtime},changeType:i})}}clearTrackedFile(e){return this.trackedFiles.delete(e)}clearAllTrackedFiles(){this.trackedFiles.clear()}triggerImmediatePoll(e){this.runFileCheck(e).catch(t=>{this.emitWatcherError(t,e)})}async runFileCheck(e){if(this.isDisposed)return;let t=this.inFlightChecks.get(e);if(t){await t;return}let n=(async()=>{try{await this.checkFile(e)}finally{this.inFlightChecks.delete(e)}})();this.inFlightChecks.set(e,n),await n}async emitWatcherError(e,t){let n=e instanceof Error?e:Error(String(e));try{await this.emittery.emit(`error`,{error:n,filePath:t})}catch(e){console.error(`[LogFileWatcher] Error listener failed:`,e instanceof Error?e.message:String(e))}}},O=class{watcher;constructor(e){this.watcher=new D(e)}isRunning(){return this.watcher.isRunning()}async start(){await this.watcher.start()}stop(){this.watcher.stop()}dispose(){this.watcher.dispose()}onChange(e){return this.watcher.on(`change`,e)}onError(e){return this.watcher.on(`error`,e)}onDeleted(e){return this.watcher.on(`deleted`,e)}onPolled(e){return this.watcher.on(`polled`,({trackedFilePaths:t})=>e(t))}getTrackedFileMtimeMs(e){return this.watcher.getTrackedFiles().get(e)?.mtimeMs}triggerImmediatePoll(e){this.watcher.triggerImmediatePoll(e)}seedFromCursors(e){this.watcher.seedFromCursors(e)}},k=class{filesProcessed=0;eventsEmitted=0;sessionsImported=new Set;sessionsSkipped=new Set;lastLoggedEventCount=0;lastLoggedSnapshot=``;reset(){this.filesProcessed=0,this.eventsEmitted=0,this.sessionsImported.clear(),this.sessionsSkipped.clear(),this.lastLoggedEventCount=0,this.lastLoggedSnapshot=``}recordFileProcessed(){this.filesProcessed++}recordEventEmitted(e){this.eventsEmitted++,!(this.eventsEmitted-this.lastLoggedEventCount<1e3)&&(console.info(`${e} Imported ${this.eventsEmitted} events (${this.sessionsImported.size} sessions)...`),this.lastLoggedEventCount=this.eventsEmitted)}recordSessionImported(e){this.sessionsImported.add(e)}recordSessionSkipped(e){this.sessionsSkipped.add(e)}hasActivity(){return this.eventsEmitted>0||this.filesProcessed>0}stoppedMessage(e){return`${e} Stopped - ${this.eventsEmitted} events from ${this.sessionsImported.size} sessions (${this.sessionsSkipped.size} skipped)`}logProgress(e){if(!this.hasActivity())return;let t=JSON.stringify({eventsEmitted:this.eventsEmitted,filesProcessed:this.filesProcessed,sessionsImported:this.sessionsImported.size,sessionsSkipped:this.sessionsSkipped.size});t!==this.lastLoggedSnapshot&&(this.lastLoggedSnapshot=t,console.info(`${e} Progress: ${this.eventsEmitted} events, ${this.sessionsImported.size} sessions, ${this.filesProcessed} files, ${this.sessionsSkipped.size} skipped`))}};function A(e){return async t=>{try{if(e!==void 0)try{let n=await s.requestOptional(l.runtime.isAdapterManaged,{adapterSessionId:t,clientId:e});if(n.handled&&n.data.managed)return!0}catch{}let n=await s.request(d.getByAdapterSessionId,{adapterSessionId:t});return n.session!==null&&!n.session.isImported}catch{return!1}}}var j=class{checkedSessions=new Map;inFlight=new Map;generations=new Map;async isSkipped(e,t,n){for(;;){let r=this.checkedSessions.get(e);if(r!==void 0)return r;let i=this.generations.get(e)??0,a=this.inFlight.get(e),o;if(a&&a.generation===i?o=a.promise:(o=t(e).then(t=>((this.generations.get(e)??0)===i&&(this.checkedSessions.set(e,t),t&&n(e)),t)).finally(()=>{let t=this.inFlight.get(e);t&&t.generation===i&&this.inFlight.delete(e)}),this.inFlight.set(e,{generation:i,promise:o})),await o,(this.generations.get(e)??0)===i){let t=this.checkedSessions.get(e);if(t!==void 0)return t;continue}}}invalidate(e){this.checkedSessions.delete(e),this.inFlight.delete(e),this.generations.set(e,(this.generations.get(e)??0)+1)}clear(){this.checkedSessions.clear(),this.inFlight.clear(),this.generations.clear()}};function M(e,t,n,r){return!n||!e||r===`rotated`?!1:new Date(e)>=t}function N(e,t,n){for(let r of n??[]){let n=r.line===void 0?``:` at line ${r.line}`;console.warn(`${e} Parse error in ${t}${n}: ${r.error}`)}}async function P(e,t,n,i){let{cursor:a}=await s.request(r.get,{filePath:e});return a&&a.bytesRead>0&&!a.sessionContext&&!t?(await s.request(r.delete,{filePath:e}).catch(()=>{}),i(n),`retry`):a}async function F(e,t,n,r,i,a){let o=await a.parseFile(e,0);N(i,e,o.errors);let s=a.validateRecords(o.records);s.length>0&&await a.handleFirstRead(e,s,o.bytesRead??0,t,n,0,r)}function I(e,t,n,r,i){let a=[];n&&(a.push(i(t.sessionEvent)),a.push(i(t.startedEvent)));let o=r(e,t);for(let e of o)a.push(i(e));return a}function L(e,t){let n=[];for(let r of e)n.push(t(r));return n}function R(e){return typeof e==`object`&&!!e&&`compactionDetected`in e&&e.compactionDetected===!0}function z(e,t,n){return{...e,state:n(t)}}var B=class{tasks=new Set;track(e){this.tasks.add(e),e.finally(()=>{this.tasks.delete(e)})}async drain(){for(;this.tasks.size>0;)await Promise.allSettled([...this.tasks])}},V=class{config;watcher;eventQueue;importer;managedSessionCache=new j;unsubscribeChange;unsubscribeError;unsubscribeDeleted;unsubscribeRuntimeStarted;stats=new k;watcherTasks=new B;progressTimer;constructor(e,t){this.importer=t;let n=e.directory??t.getLogDirectory();this.config={enabled:e.enabled,directory:e.directory,pollIntervalMs:e.pollIntervalMs??1e4,eventsPerSecond:e.eventsPerSecond??100,adapterId:e.adapterId,adapterName:e.adapterName,checkMakaioManaged:e.checkMakaioManaged,clientId:e.clientId,machineId:e.machineId},this.watcher=new O({directory:n,pattern:this.getLogFilePattern(),pollIntervalMs:this.config.pollIntervalMs}),this.eventQueue=new E({eventsPerSecond:this.config.eventsPerSecond,onEventEmitted:()=>{this.stats.recordEventEmitted(this.logPrefix)}})}shouldSkipFile(e){return!1}validateRecords(e){return e}getMaxRecords(){}buildCursorSessionContext(e){let{adapterSessionId:t,sessionEvent:n,startedEvent:r,state:i,...a}=e;return{...a,adapterSessionId:t,sessionEvent:n,startedEvent:r,state:this.importer.serializeState(i)}}usesJsonFormat(){let e=this.getLogFilePattern();return e.includes(`.json`)&&!e.includes(`.jsonl`)}isEnabled(){return this.config.enabled}isRunning(){return this.watcher.isRunning()}async start(){if(!this.config.enabled||this.isRunning())return;let e=this.config.directory??this.importer.getLogDirectory();console.info(`${this.logPrefix} Starting - watching ${e}`),this.stats.reset(),this.managedSessionCache.clear(),this.progressTimer=setInterval(()=>this.stats.logProgress(this.logPrefix),1e4),this.unsubscribeChange=this.watcher.onChange(e=>{this.trackFileChange(e)}),this.unsubscribeError=this.watcher.onError(({error:e,filePath:t})=>{console.warn(`${this.logPrefix} Error${t?` for ${t}`:``}: ${e.message}`)}),this.unsubscribeDeleted=this.watcher.onDeleted(({filePath:e})=>{this.watcherTasks.track(s.request(r.delete,{filePath:e}).then(()=>void 0).catch(()=>{}))}),this.unsubscribeRuntimeStarted=s.on(l.runtime.started,e=>{e.payload.source.layer===`adapter`&&e.payload.adapterSessionId!==void 0&&this.managedSessionCache.invalidate(e.payload.adapterSessionId)}),await this.watcher.start()}async stop(){this.progressTimer&&=(clearInterval(this.progressTimer),void 0),this.unsubscribeChange?.(),this.unsubscribeError?.(),this.unsubscribeDeleted?.(),this.unsubscribeRuntimeStarted?.(),this.unsubscribeChange=void 0,this.unsubscribeError=void 0,this.unsubscribeDeleted=void 0,this.unsubscribeRuntimeStarted=void 0,this.watcher.stop(),await this.watcherTasks.drain(),await this.eventQueue.drain(),this.stats.hasActivity()&&console.info(this.stats.stoppedMessage(this.logPrefix))}async dispose(){await this.stop(),this.watcher.dispose(),this.managedSessionCache.clear()}static createDefaultCheckMakaioManaged(e){return A(e)}async updateCursor(e,t,n,i){await s.request(r.set,{filePath:e,bytesRead:t,lastModified:n.toISOString(),sessionContext:i})}async handleFileChange(e){let{filePath:t,changeType:n,stat:i}=e;if(this.shouldSkipFile(t))return;let a=this.usesJsonFormat();n===`rotated`&&await s.request(r.delete,{filePath:t}).catch(()=>{});let o=await P(t,a,e,e=>this.trackFileChange(e));if(o===`retry`)return;let c=o?.sessionContext!==void 0,l=c?o?.bytesRead??0:0;if(M(o?.lastModified,i.mtime,a,n))return;let u=await this.parseFile(t,a?0:l,this.getMaxRecords());N(this.logPrefix,t,u.errors),this.stats.recordFileProcessed();let d=this.validateRecords(u.records),f=u.bytesRead??0;if(d.length===0){await this.maybeUpdateCursor(t,f,l,i.mtime,a,o?.sessionContext);return}c&&o?.sessionContext?await this.handleIncrementalRead(t,d,o.sessionContext,f,i.mtime,a,l):await this.handleFirstRead(t,d,f,i.mtime,a,l)}trackFileChange(e){let t=this.handleFileChange(e).catch(e=>{console.error(`${this.logPrefix} Error handling file change:`,e instanceof Error?e.message:String(e))});this.watcherTasks.track(t)}async handleFirstRead(e,t,n,r,i,a,o=!0){let s=this.importer.extractSessionContext(t);if(await this.isSessionSkipped(s.adapterSessionId)){await this.maybeUpdateCursor(e,n,a,r,i,this.buildCursorSessionContext(s));return}let c=I(t,s,o,(e,t)=>this.importer.processRecords(e,t),e=>this.queueEvent(e));this.trackImportedSession(s.adapterSessionId),await this.queueCursorUpdate(e,n,a,r,i,this.buildCursorSessionContext(s),c)}trackImportedSession(e){this.stats.recordSessionImported(e)}async handleIncrementalRead(e,t,n,i,a,o,c){if(await this.isSessionSkipped(n.adapterSessionId)){await this.maybeUpdateCursor(e,i,c,a,o,n);return}let l;try{l=this.importer.deserializeState(n.state)}catch(t){console.warn(`${this.logPrefix} Corrupted cursor state for ${e}, deleting cursor and re-importing.`,t instanceof Error?t.message:String(t)),await s.request(r.delete,{filePath:e}).catch(t=>{console.warn(`${this.logPrefix} Failed to delete corrupted cursor for ${e}.`,t instanceof Error?t.message:String(t))}),await F(e,a,o,!0,this.logPrefix,{parseFile:(e,t)=>this.parseFile(e,t),validateRecords:e=>this.validateRecords(e),handleFirstRead:(e,t,n,r,i,a,o)=>this.handleFirstRead(e,t,n,r,i,a,o)});return}let u={adapterSessionId:n.adapterSessionId,model:n.model,cwd:n.cwd,sessionEvent:n.sessionEvent,startedEvent:n.startedEvent,state:l},d=this.importer.processRecords(t,u);if(R(u.state)){await F(e,a,o,!1,this.logPrefix,{parseFile:(e,t)=>this.parseFile(e,t),validateRecords:e=>this.validateRecords(e),handleFirstRead:(e,t,n,r,i,a,o)=>this.handleFirstRead(e,t,n,r,i,a,o)});return}let f=L(d,e=>this.queueEvent(e)),p=z(n,u.state,e=>this.importer.serializeState(e));await this.queueCursorUpdate(e,i,c,a,o,p,f)}async maybeUpdateCursor(e,t,n,r,i,a){(t>n||i)&&await this.updateCursor(e,t,r,a)}async isSessionSkipped(e){return this.managedSessionCache.isSkipped(e,e=>this.importer.isMakaioManaged(e),e=>this.stats.recordSessionSkipped(e))}queueEvent(e){return this.eventQueue.queueEvent(e)}queueCursorUpdate(e,t,n,r,i,a,o=[]){return this.eventQueue.queueAfterEvents(()=>this.maybeUpdateCursor(e,t,n,r,i,a),o)}},H=class extends V{trackingFilePaths=new Set;trackingInactiveCount=new Map;lastSeenMtimeMs=new Map;unsubscribePolled;constructor(e,t){super(e,t)}clearTrackingState(e){this.trackingFilePaths.delete(e),this.trackingInactiveCount.delete(e),this.lastSeenMtimeMs.delete(e)}async persistImportedStatus(e){let{session:t}=await s.request(u.getByLogFilePath,{logFilePath:e});return!t||t.importStatus!==`tracking`||(await s.request(u.updateImportStatus,{sessionId:t.sessionId,importStatus:`imported`})).success?!0:(console.warn(`${this.logPrefix} Failed to persist imported status for ${e}`),!1)}async start(){!this.isEnabled()||this.isRunning()||(await super.start(),this.unsubscribePolled=this.watcher.onPolled(e=>{this.onPollCycle(e).catch(e=>{console.error(`${this.logPrefix} Error handling poll cycle:`,e instanceof Error?e.message:String(e))})}),await this.restorePersistedTrackingState())}async stop(){this.unsubscribePolled?.(),this.unsubscribePolled=void 0,await super.stop()}async dispose(){this.trackingFilePaths.clear(),this.trackingInactiveCount.clear(),this.lastSeenMtimeMs.clear(),await super.dispose()}async handleFileChange(e){let{filePath:t,changeType:n,stat:i}=e;if(this.shouldSkipFile(t))return;let{cursor:a}=await s.request(r.get,{filePath:t});if(!a){await this.discoverNewFile(e);return}n===`modified`&&await this.handleModifiedImportedFile(t,e,i.mtime)}async restorePersistedTrackingState(){this.trackingFilePaths.clear(),this.trackingInactiveCount.clear(),this.lastSeenMtimeMs.clear();try{let{sessions:e}=await s.request(u.listImported,{source:this.config.adapterName,importStatus:`tracking`});for(let t of e){if(t.source!==this.config.adapterName)continue;if(!t.logFilePath){(await s.request(u.updateImportStatus,{sessionId:t.sessionId,importStatus:`imported`})).success||console.warn(`${this.logPrefix} Failed to reset tracking status for session ${t.sessionId}`);continue}let e=this.watcher.getTrackedFileMtimeMs(t.logFilePath);if(e===void 0){(await s.request(u.updateImportStatus,{sessionId:t.sessionId,importStatus:`imported`})).success||console.warn(`${this.logPrefix} Failed to reset tracking status for ${t.logFilePath}`);continue}this.trackingFilePaths.add(t.logFilePath),this.trackingInactiveCount.set(t.logFilePath,0),this.lastSeenMtimeMs.set(t.logFilePath,e)}}catch(e){console.warn(`[DiscoveryOrchestrator] Failed to restore persisted tracking state:`,e instanceof Error?e.message:String(e))}}async discoverNewFile(e){let{filePath:t,stat:n}=e,r=await this.importer.extractDiscoveryMetadata(t);if(!(r.hasMessages??!1)){await this.updateCursor(t,0,n.mtime);return}if(await this.isSessionSkipped(r.adapterSessionId)){await this.updateCursor(t,0,n.mtime);return}let i=this.queueEvent({subject:c.session.discovered,payload:{adapterId:this.config.adapterId,adapterName:this.config.adapterName,adapterSessionId:r.adapterSessionId,model:r.model??null,cwd:r.cwd??null,title:r.title,parentAdapterSessionId:r.parentAdapterSessionId??null,forkPointMessageId:r.forkPointMessageId??null,kind:r.kind??`root`,startedAt:r.startedAt,logFilePath:t}});await this.eventQueue.queueAfterEvents(()=>this.updateCursor(t,0,n.mtime),[i])}async handleModifiedImportedFile(e,t,n){let{session:r}=await s.request(u.getByLogFilePath,{logFilePath:e});if(!r){await this.discoverNewFile(t);return}if(r.source===this.config.adapterName&&!(r.importStatus!==`imported`&&r.importStatus!==`tracking`)){if(await super.handleFileChange(t),r.importStatus===`imported`&&!(await s.request(u.updateImportStatus,{sessionId:r.sessionId,importStatus:`tracking`})).success){console.warn(`${this.logPrefix} Failed to persist tracking status for ${e}`);return}this.trackingFilePaths.add(e),this.lastSeenMtimeMs.set(e,n.getTime()),this.trackingInactiveCount.delete(e),this.watcher.triggerImmediatePoll(e)}}async onPollCycle(e){for(let t of[...this.trackingFilePaths]){if(!e.has(t)){await this.persistImportedStatus(t)&&this.clearTrackingState(t);continue}let n=this.watcher.getTrackedFileMtimeMs(t),r=this.lastSeenMtimeMs.get(t);if(!(n===void 0||r===void 0))try{if(n===r){let e=(this.trackingInactiveCount.get(t)??0)+1;e>=3?await this.persistImportedStatus(t)&&this.clearTrackingState(t):this.trackingInactiveCount.set(t,e)}else this.lastSeenMtimeMs.set(t,n),this.trackingInactiveCount.delete(t)}catch(e){console.warn(`${this.logPrefix} Failed to process tracked file ${t}:`,e instanceof Error?e.message:String(e))}}}};export{V as BaseLogOrchestrator,H as DiscoveryOrchestrator,p as parseJsonlFile,m as readFirstJsonlRecords,h as someJsonlRecord};
|
|
4
|
+
`);i=a.pop()??``;for(let e of a){let n=e.trim();if(n!==``)try{if(t(JSON.parse(n)))return!0}catch{}}}return!1}finally{n&&await n.close()}}function g(e,t){try{return{success:!0,record:JSON.parse(e)}}catch(n){return{success:!1,error:{line:t,error:n instanceof Error?n.message:String(n),content:_(e)}}}}function _(e){return e.length<=200?e:e.slice(0,200)+`...`}async function v(e,t){let n=0,r=Buffer.alloc(f),i=0;for(;i<t;){let a=Math.min(f,t-i),{bytesRead:o}=await e.read(r,0,a,i);if(o===0)break;for(let e=0;e<o;e++)r[e]===10&&n++;i+=o}return n}var y=e(t(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)}))(),1),b=class e extends Error{name=`TimeoutError`;constructor(t,n){super(t,n),Error.captureStackTrace?.(this,e)}};const x=e=>e.reason??new DOMException(`This operation was aborted.`,`AbortError`);function S(e,t){let{milliseconds:n,fallback:r,message:i,customTimers:a={setTimeout,clearTimeout},signal:o}=t,s,c,l=new Promise((t,l)=>{if(typeof n!=`number`||Math.sign(n)!==1)throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(o?.aborted){l(x(o));return}if(o&&(c=()=>{l(x(o))},o.addEventListener(`abort`,c,{once:!0})),e.then(t,l),n===1/0)return;let u=new b;s=a.setTimeout.call(void 0,()=>{if(r){try{t(r())}catch(e){l(e)}return}typeof e.cancel==`function`&&e.cancel(),i===!1?t():i instanceof Error?l(i):(u.message=i??`Promise timed out after ${n} milliseconds`,l(u))},n)}).finally(()=>{l.clear(),c&&o&&o.removeEventListener(`abort`,c)});return l.clear=()=>{a.clearTimeout.call(void 0,s),s=void 0},l}function C(e,t,n){let r=0,i=e.length;for(;i>0;){let a=Math.trunc(i/2),o=r+a;n(e[o],t)<=0?(r=++o,i-=a+1):i=a}return r}var w=class{#e=[];#t=0;enqueue(e,t){let{priority:n=0,id:r}=t??{},{size:i}=this,a={priority:n,id:r,run:e};if(i===0){this.#e.length=0,this.#t=0,this.#e.push(a);return}if(this.#e.at(-1).priority>=n){this.#e.push(a);return}this.#n();let o=C(this.#e,a,(e,t)=>t.priority-e.priority);this.#e.splice(o,0,a)}setPriority(e,t){let n=this.#e.findIndex((t,n)=>n>=this.#t&&t.id===e);if(n===-1)throw ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[r]=this.#e.splice(n,1);this.enqueue(r.run,{priority:t,id:e})}remove(e){let t=this.#e.findIndex((t,n)=>n<this.#t?!1:typeof e==`string`?t.id===e:t.run===e);t!==-1&&this.#e.splice(t,1)}dequeue(){if(this.#t===this.#e.length)return;let e=this.#e[this.#t];return this.#t++,this.#t===this.#e.length?(this.#e.length=0,this.#t=0):this.#t>100&&this.#t>this.#e.length/2&&this.#n(),e?.run}filter(e){let t=[];for(let n=this.#t;n<this.#e.length;n++){let r=this.#e[n];r.priority===e.priority&&t.push(r.run)}return t}get size(){return this.#e.length-this.#t}#n(){this.#t!==0&&(this.#e.splice(0,this.#t),this.#t=0)}},T=class extends y.default{#e;#t;#n=0;#r;#i=!1;#a=!1;#o;#s=0;#c=0;#l;#u;#d;#f=[];#p=0;#m;#h;#g=0;#_;#v;#y=1n;#b=new Map;#x=new Set;timeout;constructor(e){if(super(),e={carryoverIntervalCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:w,strict:!1,...e},!(typeof e.intervalCap==`number`&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??``}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??``}\` (${typeof e.interval})`);if(e.strict&&e.interval===0)throw TypeError("The `strict` option requires a non-zero `interval`");if(e.strict&&e.intervalCap===1/0)throw TypeError("The `strict` option requires a finite `intervalCap`");if(this.#e=e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1,this.#t=e.intervalCap===1/0||e.interval===0,this.#r=e.intervalCap,this.#o=e.interval,this.#d=e.strict,this.#m=new e.queueClass,this.#h=e.queueClass,this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,this.#v=e.autoStart===!1,this.#z()}#S(e){for(;this.#p<this.#f.length;){let t=this.#f[this.#p];if(t!==void 0&&e-t>=this.#o)this.#p++;else break}(this.#p>100&&this.#p>this.#f.length/2||this.#p===this.#f.length)&&(this.#f=this.#f.slice(this.#p),this.#p=0)}#C(e){this.#d?this.#f.push(e):this.#n++}#w(){this.#d?this.#f.length>this.#p&&this.#f.pop():this.#n>0&&this.#n--}#T(){return this.#f.length-this.#p}get#E(){return this.#t?!0:this.#d?this.#T()<this.#r:this.#n<this.#r}get#D(){return this.#g<this.#_}#O(){this.#g--,this.#g===0&&this.emit(`pendingZero`),this.#P(),this.emit(`next`)}#k(){this.#u=void 0,this.#I(),this.#F()}#A(e){if(this.#d){if(this.#S(e),this.#T()>=this.#r){let t=this.#f[this.#p],n=this.#o-(e-t);return this.#j(n),!0}return!1}if(this.#l===void 0){let t=this.#s-e;if(t<0){if(this.#c>0){let t=e-this.#c;if(t<this.#o)return this.#j(this.#o-t),!0}this.#n=this.#e?this.#g:0}else return this.#j(t),!0}return!1}#j(e){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#k()},e))}#M(){this.#l&&=(clearInterval(this.#l),void 0)}#N(){this.#u&&=(clearTimeout(this.#u),void 0)}#P(){if(this.#m.size===0){if(this.#M(),this.emit(`empty`),this.#g===0){if(this.#N(),this.#d&&this.#p>0){let e=Date.now();this.#S(e)}this.emit(`idle`)}return!1}let e=!1;if(!this.#v){let t=Date.now(),n=!this.#A(t);if(this.#E&&this.#D){let r=this.#m.dequeue();this.#t||(this.#C(t),this.#B()),this.emit(`active`),r(),n&&this.#F(),e=!0}}return e}#F(){this.#t||this.#l!==void 0||this.#d||(this.#l=setInterval(()=>{this.#I()},this.#o),this.#s=Date.now()+this.#o)}#I(){this.#d||(this.#n===0&&this.#g===0&&this.#l&&this.#M(),this.#n=this.#e?this.#g:0),this.#L(),this.#B()}#L(){for(;this.#P(););}get concurrency(){return this.#_}set concurrency(e){if(!(typeof e==`number`&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#_=e,this.#L()}setPriority(e,t){if(typeof t!=`number`||!Number.isFinite(t))throw TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);this.#m.setPriority(e,t)}async add(e,t={}){return t={timeout:this.timeout,...t,id:t.id??(this.#y++).toString()},new Promise((n,r)=>{let i=Symbol(`task-${t.id}`),a=()=>void 0,o=async()=>{a(),this.#g++,this.#b.set(i,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});let o;try{try{t.signal?.throwIfAborted()}catch(e){throw this.#V(),this.#b.delete(i),e}this.#c=Date.now();let r=e({signal:t.signal});if(t.timeout&&(r=S(Promise.resolve(r),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${this.#g} running, ${this.#m.size} waiting)`})),t.signal){let{signal:e}=t;r=Promise.race([r,new Promise((t,n)=>{o=()=>{n(e.reason)},e.addEventListener(`abort`,o,{once:!0})})])}let a=await r;n(a),this.emit(`completed`,a)}catch(e){r(e),this.emit(`error`,e)}finally{o&&t.signal?.removeEventListener(`abort`,o),this.#b.delete(i),queueMicrotask(()=>{this.#O()})}};this.#m.enqueue(o,t);let s=()=>{if(this.#m instanceof w){this.#m.remove(o);return}this.#m.remove?.(t.id)};if(t.signal){let{signal:e}=t,n=()=>{a(),s(),r(e.reason),this.#P(),this.emit(`next`)};if(a=()=>{e.removeEventListener(`abort`,n),this.#x.delete(a)},e.aborted){n();return}e.addEventListener(`abort`,n,{once:!0}),this.#x.add(a)}this.emit(`add`),this.#P()})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this.#v?(this.#v=!1,this.#L(),this):this}pause(){this.#v=!0}clear(){for(let e of this.#x)e();this.#m=new this.#h,this.#M(),this.#H(),this.emit(`empty`),this.#g===0&&(this.#N(),this.emit(`idle`)),this.emit(`next`)}async onEmpty(){this.#m.size!==0&&await this.#R(`empty`)}async onSizeLessThan(e){this.#m.size<e||await this.#R([`next`,`active`],()=>this.#m.size<e)}async onIdle(){this.#g===0&&this.#m.size===0||await this.#R(`idle`)}async onPendingZero(){this.#g!==0&&await this.#R(`pendingZero`)}async onRateLimit(){this.isRateLimited||await this.#R(`rateLimit`)}async onRateLimitCleared(){this.isRateLimited&&await this.#R(`rateLimitCleared`)}onError(){return new Promise((e,t)=>{let n=e=>{this.off(`error`,n),t(e)};this.on(`error`,n)})}async#R(e,t){let n=Array.isArray(e)?e:[e];return new Promise(e=>{let r=()=>{if(!(t&&!t())){for(let e of n)this.off(e,r);e()}};for(let e of n)this.on(e,r)})}get size(){return this.#m.size}sizeBy(e){return this.#m.filter(e).length}get pending(){return this.#g}get isPaused(){return this.#v}#z(){this.#t||(this.on(`add`,()=>{this.#m.size>0&&this.#B()}),this.on(`next`,()=>{this.#B()}))}#B(){this.#t||this.#a||(this.#a=!0,queueMicrotask(()=>{this.#a=!1,this.#H()}))}#V(){this.#t||(this.#w(),this.#B())}#H(){let e=this.#i;if(this.#t||this.#m.size===0){e&&(this.#i=!1,this.emit(`rateLimitCleared`));return}let t;if(this.#d){let e=Date.now();this.#S(e),t=this.#T()}else t=this.#n;let n=t>=this.#r;n!==e&&(this.#i=n,this.emit(n?`rateLimit`:`rateLimitCleared`))}get isRateLimited(){return this.#i}get isSaturated(){return this.#g===this.#_&&this.#m.size>0||this.isRateLimited&&this.#m.size>0}get runningTasks(){return[...this.#b.values()].map(e=>({...e,timeoutRemaining:e.timeout?Math.max(0,e.startTime+e.timeout-Date.now()):void 0}))}},E=class{eventQueue;cursorQueue;onEventEmitted;constructor(e){this.onEventEmitted=e.onEventEmitted,this.eventQueue=new T({concurrency:1,interval:1e3,intervalCap:e.eventsPerSecond}),this.cursorQueue=new T({concurrency:1})}queueEvent(e){return this.eventQueue.add(async()=>{await s.emit(e.subject,e.payload),this.onEventEmitted()})}queueAfterEvents(e,t=[]){let n=Promise.all(t);return n.catch(()=>void 0),this.cursorQueue.add(async()=>{await n,await e()})}async drain(){await Promise.all([this.eventQueue.onIdle(),this.cursorQueue.onIdle()])}async onIdle(){await this.drain()}},D=class{options;emittery=new n;trackedFiles=new Map;pollTimer;isPolling=!1;isDisposed=!1;inFlightChecks=new Map;constructor(e){if(!o.isAbsolute(e.directory))throw Error(`Directory must be an absolute path: ${e.directory}`);this.options={directory:e.directory,pattern:e.pattern,pollIntervalMs:e.pollIntervalMs??1e4}}on(e,t){return this.emittery.on(e,t)}once(e,t){return this.emittery.once(e,t)}async start(){this.isDisposed||this.pollTimer===void 0&&(await this.poll(),this.pollTimer=setInterval(()=>{this.poll()},this.options.pollIntervalMs))}stop(){this.pollTimer!==void 0&&(clearInterval(this.pollTimer),this.pollTimer=void 0)}dispose(){this.isDisposed=!0,this.stop(),this.emittery.clearListeners(),this.trackedFiles.clear(),this.inFlightChecks.clear()}isRunning(){return this.pollTimer!==void 0}getTrackedFiles(){return this.trackedFiles}seedFromCursors(e){for(let t of e)this.trackedFiles.set(t.filePath,{size:t.bytesRead,mtimeMs:new Date(t.lastModified).getTime()})}async poll(){if(!this.isDisposed&&!this.isPolling){this.isPolling=!0;try{let e=await this.discoverFiles(),t=new Set(e);for(let e of this.trackedFiles.keys())if(!t.has(e)){if(this.isDisposed)return;this.trackedFiles.delete(e),await this.emittery.emit(`deleted`,{filePath:e})}for(let t of e)try{await this.runFileCheck(t)}catch(e){await this.emitWatcherError(e,t)}if(this.isDisposed)return;await this.emittery.emit(`polled`,{trackedFilePaths:new Set(this.trackedFiles.keys())})}catch(e){await this.emitWatcherError(e)}finally{this.isPolling=!1}}}async discoverFiles(){return i(this.options.pattern,{cwd:this.options.directory,absolute:!0,onlyFiles:!0})}async checkFile(e){if(this.isDisposed)return;let t=await a.stat(e);if(this.isDisposed)return;let n={size:t.size,mtimeMs:t.mtimeMs},r=this.trackedFiles.get(e);if(!r){if(this.trackedFiles.set(e,n),this.isDisposed){this.trackedFiles.delete(e);return}await this.emittery.emit(`change`,{filePath:e,stat:{size:t.size,mtime:t.mtime},changeType:`created`});return}if(n.mtimeMs!==r.mtimeMs){let i=n.size<r.size?`rotated`:`modified`;if(this.trackedFiles.set(e,n),this.isDisposed)return;await this.emittery.emit(`change`,{filePath:e,stat:{size:t.size,mtime:t.mtime},changeType:i})}}clearTrackedFile(e){return this.trackedFiles.delete(e)}clearAllTrackedFiles(){this.trackedFiles.clear()}triggerImmediatePoll(e){this.runFileCheck(e).catch(t=>{this.emitWatcherError(t,e)})}async runFileCheck(e){if(this.isDisposed)return;let t=this.inFlightChecks.get(e);if(t){await t;return}let n=(async()=>{try{await this.checkFile(e)}finally{this.inFlightChecks.delete(e)}})();this.inFlightChecks.set(e,n),await n}async emitWatcherError(e,t){let n=e instanceof Error?e:Error(String(e));try{await this.emittery.emit(`error`,{error:n,filePath:t})}catch(e){console.error(`[LogFileWatcher] Error listener failed:`,e instanceof Error?e.message:String(e))}}},O=class{watcher;constructor(e){this.watcher=new D(e)}isRunning(){return this.watcher.isRunning()}async start(){await this.watcher.start()}stop(){this.watcher.stop()}dispose(){this.watcher.dispose()}onChange(e){return this.watcher.on(`change`,e)}onError(e){return this.watcher.on(`error`,e)}onDeleted(e){return this.watcher.on(`deleted`,e)}onPolled(e){return this.watcher.on(`polled`,({trackedFilePaths:t})=>e(t))}getTrackedFileMtimeMs(e){return this.watcher.getTrackedFiles().get(e)?.mtimeMs}triggerImmediatePoll(e){this.watcher.triggerImmediatePoll(e)}seedFromCursors(e){this.watcher.seedFromCursors(e)}},k=class{filesProcessed=0;eventsEmitted=0;sessionsImported=new Set;sessionsSkipped=new Set;lastLoggedEventCount=0;lastLoggedSnapshot=``;reset(){this.filesProcessed=0,this.eventsEmitted=0,this.sessionsImported.clear(),this.sessionsSkipped.clear(),this.lastLoggedEventCount=0,this.lastLoggedSnapshot=``}recordFileProcessed(){this.filesProcessed++}recordEventEmitted(e){this.eventsEmitted++,!(this.eventsEmitted-this.lastLoggedEventCount<1e3)&&(console.info(`${e} Imported ${this.eventsEmitted} events (${this.sessionsImported.size} sessions)...`),this.lastLoggedEventCount=this.eventsEmitted)}recordSessionImported(e){this.sessionsImported.add(e)}recordSessionSkipped(e){this.sessionsSkipped.add(e)}hasActivity(){return this.eventsEmitted>0||this.filesProcessed>0}stoppedMessage(e){return`${e} Stopped - ${this.eventsEmitted} events from ${this.sessionsImported.size} sessions (${this.sessionsSkipped.size} skipped)`}logProgress(e){if(!this.hasActivity())return;let t=JSON.stringify({eventsEmitted:this.eventsEmitted,filesProcessed:this.filesProcessed,sessionsImported:this.sessionsImported.size,sessionsSkipped:this.sessionsSkipped.size});t!==this.lastLoggedSnapshot&&(this.lastLoggedSnapshot=t,console.info(`${e} Progress: ${this.eventsEmitted} events, ${this.sessionsImported.size} sessions, ${this.filesProcessed} files, ${this.sessionsSkipped.size} skipped`))}};function A(e){return async t=>{try{if(e!==void 0)try{let n=await s.requestOptional(l.runtime.isAdapterManaged,{adapterSessionId:t,clientId:e});if(n.handled&&n.data.managed)return!0}catch{}let n=await s.request(d.getByAdapterSessionId,{adapterSessionId:t});return n.session!==null&&!n.session.isImported}catch{return!1}}}var j=class{checkedSessions=new Map;inFlight=new Map;generations=new Map;async isSkipped(e,t,n){for(;;){let r=this.checkedSessions.get(e);if(r!==void 0)return r;let i=this.generations.get(e)??0,a=this.inFlight.get(e),o;if(a&&a.generation===i?o=a.promise:(o=t(e).then(t=>((this.generations.get(e)??0)===i&&(this.checkedSessions.set(e,t),t&&n(e)),t)).finally(()=>{let t=this.inFlight.get(e);t&&t.generation===i&&this.inFlight.delete(e)}),this.inFlight.set(e,{generation:i,promise:o})),await o,(this.generations.get(e)??0)===i){let t=this.checkedSessions.get(e);if(t!==void 0)return t;continue}}}invalidate(e){this.checkedSessions.delete(e),this.inFlight.delete(e),this.generations.set(e,(this.generations.get(e)??0)+1)}clear(){this.checkedSessions.clear(),this.inFlight.clear(),this.generations.clear()}};function M(e,t,n,r){return!n||!e||r===`rotated`?!1:new Date(e)>=t}function N(e,t,n){for(let r of n??[]){let n=r.line===void 0?``:` at line ${r.line}`;console.warn(`${e} Parse error in ${t}${n}: ${r.error}`)}}async function P(e,t,n,i){let{cursor:a}=await s.request(r.get,{filePath:e});return a&&a.bytesRead>0&&!a.sessionContext&&!t?(await s.request(r.delete,{filePath:e}).catch(()=>{}),i(n),`retry`):a}async function F(e,t,n,r,i,a){let o=await a.parseFile(e,0);N(i,e,o.errors);let s=a.validateRecords(o.records);s.length>0&&await a.handleFirstRead(e,s,o.bytesRead??0,t,n,0,r)}function I(e,t,n,r,i){let a=[];n&&(a.push(i(t.sessionEvent)),a.push(i(t.startedEvent)));let o=r(e,t);for(let e of o)a.push(i(e));return a}function L(e,t){let n=[];for(let r of e)n.push(t(r));return n}function R(e){return typeof e==`object`&&!!e&&`compactionDetected`in e&&e.compactionDetected===!0}function z(e,t,n){return{...e,state:n(t)}}var B=class{tasks=new Set;track(e){this.tasks.add(e),e.finally(()=>{this.tasks.delete(e)})}async drain(){for(;this.tasks.size>0;)await Promise.allSettled([...this.tasks])}},V=class{config;watcher;eventQueue;importer;managedSessionCache=new j;unsubscribeChange;unsubscribeError;unsubscribeDeleted;unsubscribeRuntimeStarted;stats=new k;watcherTasks=new B;progressTimer;constructor(e,t){this.importer=t;let n=e.directory??t.getLogDirectory();this.config={enabled:e.enabled,directory:e.directory,pollIntervalMs:e.pollIntervalMs??1e4,eventsPerSecond:e.eventsPerSecond??100,adapterId:e.adapterId,adapterName:e.adapterName,checkMakaioManaged:e.checkMakaioManaged,clientId:e.clientId,machineId:e.machineId},this.watcher=new O({directory:n,pattern:this.getLogFilePattern(),pollIntervalMs:this.config.pollIntervalMs}),this.eventQueue=new E({eventsPerSecond:this.config.eventsPerSecond,onEventEmitted:()=>{this.stats.recordEventEmitted(this.logPrefix)}})}shouldSkipFile(e){return!1}validateRecords(e){return e}getMaxRecords(){}buildCursorSessionContext(e){let{adapterSessionId:t,sessionEvent:n,startedEvent:r,state:i,...a}=e;return{...a,adapterSessionId:t,sessionEvent:n,startedEvent:r,state:this.importer.serializeState(i)}}usesJsonFormat(){let e=this.getLogFilePattern();return e.includes(`.json`)&&!e.includes(`.jsonl`)}isEnabled(){return this.config.enabled}isRunning(){return this.watcher.isRunning()}async start(){if(!this.config.enabled||this.isRunning())return;let e=this.config.directory??this.importer.getLogDirectory();console.info(`${this.logPrefix} Starting - watching ${e}`),this.stats.reset(),this.managedSessionCache.clear(),this.progressTimer=setInterval(()=>this.stats.logProgress(this.logPrefix),1e4),this.unsubscribeChange=this.watcher.onChange(e=>{this.trackFileChange(e)}),this.unsubscribeError=this.watcher.onError(({error:e,filePath:t})=>{console.warn(`${this.logPrefix} Error${t?` for ${t}`:``}: ${e.message}`)}),this.unsubscribeDeleted=this.watcher.onDeleted(({filePath:e})=>{this.watcherTasks.track(s.request(r.delete,{filePath:e}).then(()=>void 0).catch(()=>{}))}),this.unsubscribeRuntimeStarted=s.on(l.runtime.started,e=>{e.payload.source.layer===`adapter`&&e.payload.adapterSessionId!==void 0&&this.managedSessionCache.invalidate(e.payload.adapterSessionId)}),await this.watcher.start()}async stop(){this.progressTimer&&=(clearInterval(this.progressTimer),void 0),this.unsubscribeChange?.(),this.unsubscribeError?.(),this.unsubscribeDeleted?.(),this.unsubscribeRuntimeStarted?.(),this.unsubscribeChange=void 0,this.unsubscribeError=void 0,this.unsubscribeDeleted=void 0,this.unsubscribeRuntimeStarted=void 0,this.watcher.stop(),await this.watcherTasks.drain(),await this.eventQueue.drain(),this.stats.hasActivity()&&console.info(this.stats.stoppedMessage(this.logPrefix))}async dispose(){await this.stop(),this.watcher.dispose(),this.managedSessionCache.clear()}static createDefaultCheckMakaioManaged(e){return A(e)}async updateCursor(e,t,n,i){await s.request(r.set,{filePath:e,bytesRead:t,lastModified:n.toISOString(),sessionContext:i})}async handleFileChange(e){let{filePath:t,changeType:n,stat:i}=e;if(this.shouldSkipFile(t))return;let a=this.usesJsonFormat();n===`rotated`&&await s.request(r.delete,{filePath:t}).catch(()=>{});let o=await P(t,a,e,e=>this.trackFileChange(e));if(o===`retry`)return;let c=o?.sessionContext!==void 0,l=c?o?.bytesRead??0:0;if(M(o?.lastModified,i.mtime,a,n))return;let u=await this.parseFile(t,a?0:l,this.getMaxRecords());N(this.logPrefix,t,u.errors),this.stats.recordFileProcessed();let d=this.validateRecords(u.records),f=u.bytesRead??0;if(d.length===0){await this.maybeUpdateCursor(t,f,l,i.mtime,a,o?.sessionContext);return}c&&o?.sessionContext?await this.handleIncrementalRead(t,d,o.sessionContext,f,i.mtime,a,l):await this.handleFirstRead(t,d,f,i.mtime,a,l)}trackFileChange(e){let t=this.handleFileChange(e).catch(e=>{console.error(`${this.logPrefix} Error handling file change:`,e instanceof Error?e.message:String(e))});this.watcherTasks.track(t)}async handleFirstRead(e,t,n,r,i,a,o=!0){let s=this.importer.extractSessionContext(t);if(await this.isSessionSkipped(s.adapterSessionId)){await this.maybeUpdateCursor(e,n,a,r,i,this.buildCursorSessionContext(s));return}let c=I(t,s,o,(e,t)=>this.importer.processRecords(e,t),e=>this.queueEvent(e));this.trackImportedSession(s.adapterSessionId),await this.queueCursorUpdate(e,n,a,r,i,this.buildCursorSessionContext(s),c)}trackImportedSession(e){this.stats.recordSessionImported(e)}async handleIncrementalRead(e,t,n,i,a,o,c){if(await this.isSessionSkipped(n.adapterSessionId)){await this.maybeUpdateCursor(e,i,c,a,o,n);return}let l;try{l=this.importer.deserializeState(n.state)}catch(t){console.warn(`${this.logPrefix} Corrupted cursor state for ${e}, deleting cursor and re-importing.`,t instanceof Error?t.message:String(t)),await s.request(r.delete,{filePath:e}).catch(t=>{console.warn(`${this.logPrefix} Failed to delete corrupted cursor for ${e}.`,t instanceof Error?t.message:String(t))}),await F(e,a,o,!0,this.logPrefix,{parseFile:(e,t)=>this.parseFile(e,t),validateRecords:e=>this.validateRecords(e),handleFirstRead:(e,t,n,r,i,a,o)=>this.handleFirstRead(e,t,n,r,i,a,o)});return}let u={adapterSessionId:n.adapterSessionId,model:n.model,cwd:n.cwd,sessionEvent:n.sessionEvent,startedEvent:n.startedEvent,state:l},d=this.importer.processRecords(t,u);if(R(u.state)){await F(e,a,o,!1,this.logPrefix,{parseFile:(e,t)=>this.parseFile(e,t),validateRecords:e=>this.validateRecords(e),handleFirstRead:(e,t,n,r,i,a,o)=>this.handleFirstRead(e,t,n,r,i,a,o)});return}let f=L(d,e=>this.queueEvent(e)),p=z(n,u.state,e=>this.importer.serializeState(e));await this.queueCursorUpdate(e,i,c,a,o,p,f)}async maybeUpdateCursor(e,t,n,r,i,a){(t>n||i)&&await this.updateCursor(e,t,r,a)}async isSessionSkipped(e){return this.managedSessionCache.isSkipped(e,e=>this.importer.isMakaioManaged(e),e=>this.stats.recordSessionSkipped(e))}queueEvent(e){return this.eventQueue.queueEvent(e)}queueCursorUpdate(e,t,n,r,i,a,o=[]){return this.eventQueue.queueAfterEvents(()=>this.maybeUpdateCursor(e,t,n,r,i,a),o)}},H=class extends V{trackingFilePaths=new Set;trackingInactiveCount=new Map;lastSeenMtimeMs=new Map;unsubscribePolled;constructor(e,t){super(e,t)}clearTrackingState(e){this.trackingFilePaths.delete(e),this.trackingInactiveCount.delete(e),this.lastSeenMtimeMs.delete(e)}async persistImportedStatus(e){let{session:t}=await s.request(u.getByLogFilePath,{logFilePath:e});return!t||t.importStatus!==`tracking`||(await s.request(u.updateImportStatus,{sessionId:t.sessionId,importStatus:`imported`})).success?!0:(console.warn(`${this.logPrefix} Failed to persist imported status for ${e}`),!1)}async start(){!this.isEnabled()||this.isRunning()||(await super.start(),this.unsubscribePolled=this.watcher.onPolled(e=>{this.onPollCycle(e).catch(e=>{console.error(`${this.logPrefix} Error handling poll cycle:`,e instanceof Error?e.message:String(e))})}),await this.restorePersistedTrackingState())}async stop(){this.unsubscribePolled?.(),this.unsubscribePolled=void 0,await super.stop()}async dispose(){this.trackingFilePaths.clear(),this.trackingInactiveCount.clear(),this.lastSeenMtimeMs.clear(),await super.dispose()}async handleFileChange(e){let{filePath:t,changeType:n,stat:i}=e;if(this.shouldSkipFile(t))return;let{cursor:a}=await s.request(r.get,{filePath:t});if(!a){await this.discoverNewFile(e);return}n===`modified`&&await this.handleModifiedImportedFile(t,e,i.mtime)}async restorePersistedTrackingState(){this.trackingFilePaths.clear(),this.trackingInactiveCount.clear(),this.lastSeenMtimeMs.clear();try{let{sessions:e}=await s.request(u.listImported,{source:this.config.adapterName,importStatus:`tracking`});for(let t of e){if(t.source!==this.config.adapterName)continue;if(!t.logFilePath){(await s.request(u.updateImportStatus,{sessionId:t.sessionId,importStatus:`imported`})).success||console.warn(`${this.logPrefix} Failed to reset tracking status for session ${t.sessionId}`);continue}let e=this.watcher.getTrackedFileMtimeMs(t.logFilePath);if(e===void 0){(await s.request(u.updateImportStatus,{sessionId:t.sessionId,importStatus:`imported`})).success||console.warn(`${this.logPrefix} Failed to reset tracking status for ${t.logFilePath}`);continue}this.trackingFilePaths.add(t.logFilePath),this.trackingInactiveCount.set(t.logFilePath,0),this.lastSeenMtimeMs.set(t.logFilePath,e)}}catch(e){console.warn(`[DiscoveryOrchestrator] Failed to restore persisted tracking state:`,e instanceof Error?e.message:String(e))}}async discoverNewFile(e){let{filePath:t,stat:n}=e,r=await this.importer.extractDiscoveryMetadata(t);if(!(r.hasMessages??!1)){await this.updateCursor(t,0,n.mtime);return}if(await this.isSessionSkipped(r.adapterSessionId)){await this.updateCursor(t,0,n.mtime);return}let i=this.queueEvent({subject:c.session.discovered,payload:{adapterId:this.config.adapterId,adapterName:this.config.adapterName,adapterSessionId:r.adapterSessionId,model:r.model??null,cwd:r.cwd??null,title:r.title,parentAdapterSessionId:r.parentAdapterSessionId??null,forkPointMessageId:r.forkPointMessageId??null,kind:r.kind??`root`,startedAt:r.startedAt,logFilePath:t}});await this.eventQueue.queueAfterEvents(()=>this.updateCursor(t,0,n.mtime),[i])}async handleModifiedImportedFile(e,t,n){let{session:r}=await s.request(u.getByLogFilePath,{logFilePath:e});if(!r){await this.discoverNewFile(t);return}if(r.source===this.config.adapterName&&!(r.importStatus!==`imported`&&r.importStatus!==`tracking`)){if(await super.handleFileChange(t),r.importStatus===`imported`&&!(await s.request(u.updateImportStatus,{sessionId:r.sessionId,importStatus:`tracking`})).success){console.warn(`${this.logPrefix} Failed to persist tracking status for ${e}`);return}this.trackingFilePaths.add(e),this.lastSeenMtimeMs.set(e,n.getTime()),this.trackingInactiveCount.delete(e),this.watcher.triggerImmediatePoll(e)}}async onPollCycle(e){for(let t of[...this.trackingFilePaths]){if(!e.has(t)){await this.persistImportedStatus(t)&&this.clearTrackingState(t);continue}let n=this.watcher.getTrackedFileMtimeMs(t),r=this.lastSeenMtimeMs.get(t);if(!(n===void 0||r===void 0))try{if(n===r){let e=(this.trackingInactiveCount.get(t)??0)+1;e>=3?await this.persistImportedStatus(t)&&this.clearTrackingState(t):this.trackingInactiveCount.set(t,e)}else this.lastSeenMtimeMs.set(t,n),this.trackingInactiveCount.delete(t)}catch(e){console.warn(`${this.logPrefix} Failed to process tracked file ${t}:`,e instanceof Error?e.message:String(e))}}}};export{V as BaseLogOrchestrator,H as DiscoveryOrchestrator,p as parseJsonlFile,m as readFirstJsonlRecords,h as someJsonlRecord};
|