agentix-cli 0.146.0 → 0.148.0
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/{App-EU2AJWW5.js → App-2O2UUZGG.js} +2 -2
- package/dist/{ChatApp-ORR3U3AN.js → ChatApp-YU4NF63L.js} +2 -2
- package/dist/{absorb-eval-3VGPDRWS.js → absorb-eval-WHWOJYDX.js} +2 -2
- package/dist/{agent-NVJNOK5L.js → agent-NLCR6VBE.js} +2 -2
- package/dist/{board-dashboard-JV2JNRWD.js → board-dashboard-KXSZIMWV.js} +216 -216
- package/dist/board-dashboard-KXSZIMWV.js.map +1 -0
- package/dist/{chunk-UFX6INNI.js → chunk-2MW32M2D.js} +2 -2
- package/dist/{chunk-5YAUENDI.js → chunk-3HVRWULP.js} +2 -2
- package/dist/{chunk-7O7VDA3J.js → chunk-5IHUZVPU.js} +2 -2
- package/dist/{chunk-USTNT7P7.js → chunk-5QXRPYOY.js} +2 -2
- package/dist/{chunk-3BMIZY6X.js → chunk-6QFDFYI7.js} +2 -2
- package/dist/{chunk-5TFXFLMN.js → chunk-6TJNWUMA.js} +3 -3
- package/dist/{chunk-MOCKFVYE.js → chunk-6YNRLI6I.js} +2 -2
- package/dist/{chunk-OEB6RTRA.js → chunk-AONY6U45.js} +2 -2
- package/dist/{chunk-WCOT35YG.js → chunk-ATCIRFH6.js} +2 -2
- package/dist/{chunk-O7ZJS33Z.js → chunk-BZ6Y264Z.js} +2 -2
- package/dist/{chunk-TYONASHA.js → chunk-CHBZHUIF.js} +41 -41
- package/dist/chunk-CHBZHUIF.js.map +1 -0
- package/dist/{chunk-NBDYBTI6.js → chunk-CJVAIAD7.js} +259 -259
- package/dist/chunk-CJVAIAD7.js.map +1 -0
- package/dist/{chunk-UVJLIHLL.js → chunk-DWOERPBG.js} +2 -2
- package/dist/chunk-E7LPZAXP.js +7 -0
- package/dist/chunk-E7LPZAXP.js.map +1 -0
- package/dist/{chunk-UTYNYG7M.js → chunk-EIY2HRAS.js} +2 -2
- package/dist/{chunk-OT5KLHUT.js → chunk-GMMRBTLQ.js} +2 -2
- package/dist/{chunk-GECGRCYC.js → chunk-GRI5HOPC.js} +2 -2
- package/dist/{chunk-UYLVSS6I.js → chunk-IGA3T3ZT.js} +2 -2
- package/dist/chunk-INT5PIF3.js +533 -0
- package/dist/chunk-INT5PIF3.js.map +1 -0
- package/dist/{chunk-WBG6NA7R.js → chunk-KP7KDLZ2.js} +2 -2
- package/dist/{chunk-QNS3WHGU.js → chunk-NMYC5RW7.js} +2 -2
- package/dist/{chunk-DTWBB7B7.js → chunk-NW4N67TU.js} +2 -2
- package/dist/chunk-OIMJLAWD.js +7 -0
- package/dist/chunk-OIMJLAWD.js.map +1 -0
- package/dist/{chunk-TZVJP4H3.js → chunk-OWMKQ4HZ.js} +2 -2
- package/dist/chunk-PXKIPU27.js +64 -0
- package/dist/chunk-PXKIPU27.js.map +1 -0
- package/dist/{chunk-DG2DC43E.js → chunk-PYHR4HXO.js} +2 -2
- package/dist/{chunk-SK24JFEK.js → chunk-S22IBRY6.js} +2 -2
- package/dist/chunk-S5NGIJDI.js +35 -0
- package/dist/chunk-S5NGIJDI.js.map +1 -0
- package/dist/chunk-X7UQY7CH.js +5 -0
- package/dist/chunk-X7UQY7CH.js.map +1 -0
- package/dist/{chunk-SNCRLEH3.js → chunk-Z7GEW2SR.js} +5 -5
- package/dist/cli.js +1 -1
- package/dist/{client-6KZZKCN2.js → client-A2N6ETK2.js} +2 -2
- package/dist/config-2QM2WTI2.js +2 -0
- package/dist/{config-mutate-57YT7BNB.js → config-mutate-UJS4F7BT.js} +2 -2
- package/dist/config-mutator-VWR3SMD3.js +2 -0
- package/dist/{contributions-Y6B6LG7X.js → contributions-43FWZOGF.js} +2 -2
- package/dist/doctor-5R6X7JH6.js +2 -0
- package/dist/{follow-up-tool-5AMZKVI4.js → follow-up-tool-VB7K6HCL.js} +2 -2
- package/dist/{hub-BZF3ZYQ5.js → hub-JNNNUAZM.js} +2 -2
- package/dist/index.d.ts +119 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/note-tool-EZWSB3J3.js +2 -0
- package/dist/note-tool-EZWSB3J3.js.map +1 -0
- package/dist/{program-MO7HLAP5.js → program-VS6QDZNX.js} +209 -209
- package/dist/program-VS6QDZNX.js.map +1 -0
- package/dist/{promote-IJANZNQK.js → promote-VFYVWVTL.js} +2 -2
- package/dist/{query-DC74NB3R.js → query-RB2MU2HV.js} +2 -2
- package/dist/{query-settings-RXFOATOZ.js → query-settings-5B54WHCS.js} +2 -2
- package/dist/{registry-24IXRDWX.js → registry-6OX7U6FV.js} +2 -2
- package/dist/{request-planner-33CWWCJU.js → request-planner-TUHVEYSF.js} +2 -2
- package/dist/{review-candidates-ENWB6LHD.js → review-candidates-FDYTGG2N.js} +2 -2
- package/dist/{routing-AUFJ4MNP.js → routing-U35SFPEI.js} +2 -2
- package/dist/schedule-tool-EPQKUYJX.js +2 -0
- package/dist/{scheduler-KWSBBZKW.js → scheduler-H2QHWNQ2.js} +2 -2
- package/dist/{seat-YGMLJ6KS.js → seat-EB3KJMIE.js} +2 -2
- package/dist/{select-JJGBM6ZT.js → select-IU4IOVSO.js} +2 -2
- package/dist/{set-enabled-THE7QIGQ.js → set-enabled-64BSJ7LR.js} +2 -2
- package/dist/{tool-4ACTSFKC.js → tool-PLM6Z42O.js} +2 -2
- package/dist/{tool-6LR6VORJ.js → tool-W3CIQZJ7.js} +2 -2
- package/dist/{wiki-YAW7UEOQ.js → wiki-4KMRUD5C.js} +2 -2
- package/dist/wiki-enrich-N4GLW2JX.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-JV2JNRWD.js.map +0 -1
- package/dist/chunk-IBK7AG4S.js +0 -62
- package/dist/chunk-IBK7AG4S.js.map +0 -1
- package/dist/chunk-J723FL3J.js +0 -7
- package/dist/chunk-J723FL3J.js.map +0 -1
- package/dist/chunk-K3QDK4BX.js +0 -5
- package/dist/chunk-K3QDK4BX.js.map +0 -1
- package/dist/chunk-MO7DH5L6.js +0 -535
- package/dist/chunk-MO7DH5L6.js.map +0 -1
- package/dist/chunk-NBDYBTI6.js.map +0 -1
- package/dist/chunk-S2GAEH2F.js +0 -13
- package/dist/chunk-S2GAEH2F.js.map +0 -1
- package/dist/chunk-TYONASHA.js.map +0 -1
- package/dist/config-W6JNVPBY.js +0 -2
- package/dist/config-mutator-6NWQPE7K.js +0 -2
- package/dist/doctor-ZP4KADAD.js +0 -2
- package/dist/program-MO7HLAP5.js.map +0 -1
- package/dist/schedule-tool-NAMOBMZE.js +0 -2
- package/dist/wiki-enrich-6ANFA2VB.js +0 -2
- /package/dist/{App-EU2AJWW5.js.map → App-2O2UUZGG.js.map} +0 -0
- /package/dist/{ChatApp-ORR3U3AN.js.map → ChatApp-YU4NF63L.js.map} +0 -0
- /package/dist/{absorb-eval-3VGPDRWS.js.map → absorb-eval-WHWOJYDX.js.map} +0 -0
- /package/dist/{agent-NVJNOK5L.js.map → agent-NLCR6VBE.js.map} +0 -0
- /package/dist/{chunk-UFX6INNI.js.map → chunk-2MW32M2D.js.map} +0 -0
- /package/dist/{chunk-5YAUENDI.js.map → chunk-3HVRWULP.js.map} +0 -0
- /package/dist/{chunk-7O7VDA3J.js.map → chunk-5IHUZVPU.js.map} +0 -0
- /package/dist/{chunk-USTNT7P7.js.map → chunk-5QXRPYOY.js.map} +0 -0
- /package/dist/{chunk-3BMIZY6X.js.map → chunk-6QFDFYI7.js.map} +0 -0
- /package/dist/{chunk-5TFXFLMN.js.map → chunk-6TJNWUMA.js.map} +0 -0
- /package/dist/{chunk-MOCKFVYE.js.map → chunk-6YNRLI6I.js.map} +0 -0
- /package/dist/{chunk-OEB6RTRA.js.map → chunk-AONY6U45.js.map} +0 -0
- /package/dist/{chunk-WCOT35YG.js.map → chunk-ATCIRFH6.js.map} +0 -0
- /package/dist/{chunk-O7ZJS33Z.js.map → chunk-BZ6Y264Z.js.map} +0 -0
- /package/dist/{chunk-UVJLIHLL.js.map → chunk-DWOERPBG.js.map} +0 -0
- /package/dist/{chunk-UTYNYG7M.js.map → chunk-EIY2HRAS.js.map} +0 -0
- /package/dist/{chunk-OT5KLHUT.js.map → chunk-GMMRBTLQ.js.map} +0 -0
- /package/dist/{chunk-GECGRCYC.js.map → chunk-GRI5HOPC.js.map} +0 -0
- /package/dist/{chunk-UYLVSS6I.js.map → chunk-IGA3T3ZT.js.map} +0 -0
- /package/dist/{chunk-WBG6NA7R.js.map → chunk-KP7KDLZ2.js.map} +0 -0
- /package/dist/{chunk-QNS3WHGU.js.map → chunk-NMYC5RW7.js.map} +0 -0
- /package/dist/{chunk-DTWBB7B7.js.map → chunk-NW4N67TU.js.map} +0 -0
- /package/dist/{chunk-TZVJP4H3.js.map → chunk-OWMKQ4HZ.js.map} +0 -0
- /package/dist/{chunk-DG2DC43E.js.map → chunk-PYHR4HXO.js.map} +0 -0
- /package/dist/{chunk-SK24JFEK.js.map → chunk-S22IBRY6.js.map} +0 -0
- /package/dist/{chunk-SNCRLEH3.js.map → chunk-Z7GEW2SR.js.map} +0 -0
- /package/dist/{client-6KZZKCN2.js.map → client-A2N6ETK2.js.map} +0 -0
- /package/dist/{config-W6JNVPBY.js.map → config-2QM2WTI2.js.map} +0 -0
- /package/dist/{config-mutate-57YT7BNB.js.map → config-mutate-UJS4F7BT.js.map} +0 -0
- /package/dist/{config-mutator-6NWQPE7K.js.map → config-mutator-VWR3SMD3.js.map} +0 -0
- /package/dist/{contributions-Y6B6LG7X.js.map → contributions-43FWZOGF.js.map} +0 -0
- /package/dist/{doctor-ZP4KADAD.js.map → doctor-5R6X7JH6.js.map} +0 -0
- /package/dist/{follow-up-tool-5AMZKVI4.js.map → follow-up-tool-VB7K6HCL.js.map} +0 -0
- /package/dist/{hub-BZF3ZYQ5.js.map → hub-JNNNUAZM.js.map} +0 -0
- /package/dist/{promote-IJANZNQK.js.map → promote-VFYVWVTL.js.map} +0 -0
- /package/dist/{query-DC74NB3R.js.map → query-RB2MU2HV.js.map} +0 -0
- /package/dist/{query-settings-RXFOATOZ.js.map → query-settings-5B54WHCS.js.map} +0 -0
- /package/dist/{registry-24IXRDWX.js.map → registry-6OX7U6FV.js.map} +0 -0
- /package/dist/{request-planner-33CWWCJU.js.map → request-planner-TUHVEYSF.js.map} +0 -0
- /package/dist/{review-candidates-ENWB6LHD.js.map → review-candidates-FDYTGG2N.js.map} +0 -0
- /package/dist/{routing-AUFJ4MNP.js.map → routing-U35SFPEI.js.map} +0 -0
- /package/dist/{schedule-tool-NAMOBMZE.js.map → schedule-tool-EPQKUYJX.js.map} +0 -0
- /package/dist/{scheduler-KWSBBZKW.js.map → scheduler-H2QHWNQ2.js.map} +0 -0
- /package/dist/{seat-YGMLJ6KS.js.map → seat-EB3KJMIE.js.map} +0 -0
- /package/dist/{select-JJGBM6ZT.js.map → select-IU4IOVSO.js.map} +0 -0
- /package/dist/{set-enabled-THE7QIGQ.js.map → set-enabled-64BSJ7LR.js.map} +0 -0
- /package/dist/{tool-4ACTSFKC.js.map → tool-PLM6Z42O.js.map} +0 -0
- /package/dist/{tool-6LR6VORJ.js.map → tool-W3CIQZJ7.js.map} +0 -0
- /package/dist/{wiki-YAW7UEOQ.js.map → wiki-4KMRUD5C.js.map} +0 -0
- /package/dist/{wiki-enrich-6ANFA2VB.js.map → wiki-enrich-N4GLW2JX.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as w,
|
|
1
|
+
import{a as w,c as f}from"./chunk-KP7KDLZ2.js";import{randomUUID as _}from"crypto";function p(r){return r.status&&r.status!=="ringing"?", waiting_since=NULL, told_at=NULL":""}var E=["ringing","answered","later"],A=`id, agent_id AS agentId, kind, reason, urgency, status, created_at AS createdAt,
|
|
2
2
|
ringing_since AS ringingSince, answered_at AS answeredAt, ended_at AS endedAt,
|
|
3
3
|
ring_again_at AS ringAgainAt, note, summary, channel, chat_id AS chatId`,y=class{constructor(t){this.db=t;t.exec(`CREATE TABLE IF NOT EXISTS calls (
|
|
4
4
|
id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, reason TEXT NOT NULL,
|
|
@@ -8,4 +8,4 @@ import{a as w,b as f}from"./chunk-WBG6NA7R.js";import{randomUUID as _}from"crypt
|
|
|
8
8
|
CREATE INDEX IF NOT EXISTS calls_recent ON calls(created_at DESC);`);let e=new Set(t.prepare("PRAGMA table_info(calls)").all().map(n=>n.name));e.has("kind")||t.exec("ALTER TABLE calls ADD COLUMN kind TEXT NOT NULL DEFAULT 'voice'"),e.has("channel")||t.exec("ALTER TABLE calls ADD COLUMN channel TEXT"),e.has("chat_id")||t.exec("ALTER TABLE calls ADD COLUMN chat_id TEXT"),e.has("waiting_since")||t.exec("ALTER TABLE calls ADD COLUMN waiting_since INTEGER"),e.has("told_at")||t.exec("ALTER TABLE calls ADD COLUMN told_at INTEGER")}waiting(){let t=this.db.prepare("SELECT id, waiting_since AS since, told_at AS toldAt FROM calls WHERE waiting_since IS NOT NULL AND status='ringing'").all();return new Map(t.map(({id:e,since:n,toldAt:i})=>[e,{since:n,toldAt:i??n}]))}setWaiting(t,e){this.db.prepare("UPDATE calls SET waiting_since=?, told_at=? WHERE id=?").run(e?.since??null,e?.toldAt??null,t)}insert(t){this.db.prepare(`INSERT INTO calls (id, agent_id, kind, reason, urgency, status, created_at, ringing_since,
|
|
9
9
|
answered_at, ended_at, ring_again_at, note, summary, channel, chat_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(t.id,t.agentId,t.kind,t.reason,t.urgency,t.status,t.createdAt,t.ringingSince,t.answeredAt,t.endedAt,t.ringAgainAt,t.note,t.summary,t.channel,t.chatId)}get(t){return this.db.prepare(`SELECT ${A} FROM calls WHERE id=?`).get(t)}update(t,e){let n={reason:"reason",urgency:"urgency",status:"status",ringingSince:"ringing_since",answeredAt:"answered_at",endedAt:"ended_at",ringAgainAt:"ring_again_at",note:"note",summary:"summary"},i=Object.keys(e).filter(a=>a in n);if(i.length){let a=i.map(s=>`${n[s]}=?`).join(", ")+p(e);this.db.prepare(`UPDATE calls SET ${a} WHERE id=?`).run(...i.map(s=>e[s]??null),t)}return this.get(t)}transition(t,e,n){let i=Array.isArray(e)?e:[e],a={status:"status",ringingSince:"ringing_since",answeredAt:"answered_at",endedAt:"ended_at",ringAgainAt:"ring_again_at",note:"note",summary:"summary"},s=Object.keys(n).filter(l=>l in a),o=s.map(l=>`${a[l]}=?`).join(", ")+p(n),u=i.map(()=>"?").join(",");return this.db.prepare(`UPDATE calls SET ${o} WHERE id=? AND status IN (${u})`).run(...s.map(l=>n[l]??null),t,...i).changes?this.get(t):void 0}list(t={}){let e=Math.min(Math.max(t.limit??50,1),200),n=[],i=[];t.status?.length&&(n.push(`status IN (${t.status.map(()=>"?").join(",")})`),i.push(...t.status)),t.kind&&(n.push("kind=?"),i.push(t.kind));let a=n.length?`WHERE ${n.join(" AND ")}`:"";return this.db.prepare(`SELECT ${A} FROM calls ${a} ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(...i,e)}countSince(t,e){return this.db.prepare("SELECT COUNT(*) AS n FROM calls WHERE agent_id=? AND created_at>?").get(t,e).n}};var C=200,k=1e4,I=2*36e5,$=10,T=240;function D(r=process.env){return r.AGENTX_TASK_ID?{"X-AgentX-Task":r.AGENTX_TASK_ID}:r.AGENTX_CHANNEL&&r.AGENTX_CHAT_ID?{"X-AgentX-Channel":r.AGENTX_CHANNEL,"X-AgentX-Chat":r.AGENTX_CHAT_ID}:{}}function N(r){return`[Call answered] The owner just picked up the voice call you asked for. You called because: "${r.reason}". Speak first: greet them in a few words and say why you called, then let them answer.`}var M="[Call ended] The owner hung up. In two or three plain sentences, summarise what was said and decided on this call, for your records. Reply with the summary only.",S=class{constructor(t){this.deps=t;this.waiting=t.store.waiting()}widgetSeenAt=0;widget={};waiting;setWaiting(t,e){if(e)this.waiting.set(t,e);else if(!this.waiting.delete(t))return;this.deps.store.setWaiting(t,e)}now(){return this.deps.now?.()??Date.now()}name(t){return this.deps.agentName(t)??t}async request(t,e={}){let n=String(t.agentId??"").trim(),i=String(t.reason??"").replace(/\s+/g," ").trim(),a=t.urgency==="urgent"?"urgent":"normal",s=t.kind==="camera"?"camera":"voice";if(t.kind!==void 0&&t.kind!=="voice"&&t.kind!=="camera")return{ok:!1,status:400,error:"kind must be voice or camera"};if(!n||!i)return{ok:!1,status:400,error:"Required: agentId and reason"};if(i.length>C)return{ok:!1,status:413,error:`reason is over ${C} characters; keep it to one line`};if(this.deps.agentName(n)===null)return{ok:!1,status:404,error:`Unknown agent: ${n}`};if(!this.deps.isRunningTurn(n,e))return{ok:!1,status:403,error:`No running turn of ${n} placed this call. An agent calls from inside its own run.`};let o=this.deps.config();if(!o.allow.includes("*")&&!o.allow.includes(n))return{ok:!1,status:403,error:`${n} ${s==="camera"?"may not ask to see through the owner's camera":"may not call the owner"}. Add it to calls.allow in agentx.json (or: agentx call allow ${n}).`};if(await this.sweep(),this.deps.store.list({status:E,limit:200}).some(m=>m.agentId===n))return{ok:!1,status:409,error:`${n} already has a call in progress`};let u=this.now();if(this.deps.store.countSince(n,u-36e5)>=o.maxPerHour)return{ok:!1,status:429,error:`${n} has placed ${o.maxPerHour} calls in the last hour (calls.maxPerHour)`};let g=s==="camera"?this.deps.turnSession?.(n,e)??e:{},l={id:`call-${_().slice(0,8)}`,agentId:n,kind:s,reason:i,urgency:a,status:"ringing",createdAt:u,ringingSince:u,answeredAt:null,endedAt:null,ringAgainAt:null,note:null,summary:null,channel:g.channel&&g.chatId?g.channel:null,chatId:g.channel&&g.chatId?g.chatId:null};this.deps.store.insert(l),this.deps.log?.(`[calls] ${n} asks ${s==="camera"?"to see":"for a call"} (${a}): ${i}`);let d=await this.ring(l),h=this.deps.store.get(l.id);return d!=="waiting"?{ok:!0,call:h,rang:d}:this.waiting.has(l.id)?{ok:!0,call:h,rang:d,busy:this.busyInfo(l)}:{ok:!0,call:h,rang:"widget"}}async cancel(t,e={}){let n=String(t.agentId??"").trim();if(!n)return{ok:!1,status:400,error:"Required: agentId"};if(!this.deps.isRunningTurn(n,e))return{ok:!1,status:403,error:`No running turn of ${n} asked for this. An agent withdraws its own call from inside its run.`};let i=this.deps.store.list({status:["ringing","later"],kind:"voice",limit:200}).find(s=>s.agentId===n);if(!i)return{ok:!1,status:404,error:`${n} has no call waiting or ringing`};let a=this.deps.store.transition(i.id,["ringing","later"],{status:"ended",endedAt:this.now(),ringingSince:null,ringAgainAt:null,note:b});return a?(this.setWaiting(i.id,null),this.deps.log?.(`[calls] ${i.id} withdrawn by ${n}`),{ok:!0,call:a}):{ok:!1,status:409,error:`call is ${this.deps.store.get(i.id)?.status}`}}async ring(t){let e=(this.deps.focus??w)();return e.active&&t.urgency!=="urgent"?(this.deps.store.transition(t.id,"ringing",{status:"missed",ringingSince:null,note:f(e)})&&await this.notice(t,this.missedTitle(t)),!1):t.kind==="camera"?(await this.notice(t,`${this.name(t.agentId)} wants to see through your camera`,`Open the phone app and tap Show within ${this.deps.config().ringSeconds} s.`),"notify"):this.widgetAlive()?!this.widget.busy&&!this.otherCalls(t).length?"widget":(this.startWaiting(t),await this.callWaiting(t),"waiting"):(await this.notice(t,`${this.name(t.agentId)} is calling`,`Open AgentX Voice to answer within ${this.deps.config().ringSeconds} s.`),"notify")}async notice(t,e,n){try{await this.deps.alert({title:e,message:n?`${t.reason}
|
|
10
10
|
${n}`:t.reason,urgent:t.urgency==="urgent",from:t.agentId})}catch(i){this.deps.log?.(`[calls] notice for ${t.id} failed: ${i?.message??i}`)}}startWaiting(t){let e=this.now();this.setWaiting(t.id,{since:e,toldAt:e}),this.deps.log?.(`[calls] ${t.id} from ${t.agentId} waits: the widget is busy`)}otherCalls(t){return this.deps.store.list({status:["ringing","answered"],kind:"voice",limit:200}).filter(e=>e.id!==t.id).reverse()}async callWaiting(t){let e=this.deps.config().busy;await this.notice(t,e.title.replaceAll("{agent}",this.name(t.agentId)),e.notice)}busyInfo(t){let e=this.deps.config().busy,{since:n,toldAt:i}=this.waiting.get(t.id)??{since:this.now(),toldAt:this.now()},a=this.otherCalls(t),s=a.find(d=>d.status==="answered"),o=a.find(d=>d.id===this.widget.showing)??a.find(d=>!this.waiting.has(d.id)),u=n+e.maxWaitMinutes*6e4+this.deps.config().ringSeconds*1e3,g=i+e.retryMinutes*6e4,l=n+e.maxWaitMinutes*6e4;return{why:s?"call":o?"ringing":"voice",with:s?this.name(s.agentId):o?this.name(o.agentId):null,remindAt:g<l?g:null,waitsUntil:u}}missedTitle(t){return t.kind==="camera"?`${this.name(t.agentId)} asked to see through your camera`:`Missed call from ${this.name(t.agentId)}`}inCall(){if(this.widgetAlive()&&this.widget.busy)return"the widget is busy";let t=this.now()-I,e=this.deps.store.list({status:["answered"],limit:5}).find(n=>(n.answeredAt??0)>=t);return e?`on a call with ${this.name(e.agentId)}`:null}widgetAlive(){return this.now()-this.widgetSeenAt<k}async ringing(t={}){return this.widgetSeenAt=this.now(),this.widget=t,await this.hold(t),await this.sweep(),this.deps.store.list({status:["ringing"],kind:"voice",limit:20}).reverse()}async hold(t){let e=this.now(),n=this.deps.config().busy,i=[],a=this.deps.store.list({status:["ringing"],kind:"voice",limit:20});for(let s of[...this.waiting.keys()])a.some(o=>o.id===s)||this.setWaiting(s,null);for(let s of a){if(s.id===t.showing){this.waiting.has(s.id)&&(this.setWaiting(s.id,null),this.deps.store.transition(s.id,"ringing",{ringingSince:e}));continue}if(!t.busy)continue;let o=this.waiting.get(s.id);if(!(o&&e-o.since>=n.maxWaitMinutes*6e4)&&this.deps.store.transition(s.id,"ringing",{ringingSince:e})){if(!o)this.startWaiting(s);else if(e-o.toldAt>=n.retryMinutes*6e4)this.setWaiting(s.id,{since:o.since,toldAt:e});else continue;i.push(s)}}for(let s of i)await this.callWaiting(s)}async asking(){return await this.sweep(),this.deps.store.list({status:["ringing"],kind:"camera",limit:20}).reverse()}async sweep(){let t=this.now(),e=this.deps.config().ringSeconds*1e3,n=this.deps.config().maxCallMinutes*6e4;for(let i of this.deps.store.list({status:["ringing","later","answered"],limit:200}))if(i.status==="ringing"&&i.ringingSince!==null&&t-i.ringingSince>=e){if(!this.deps.store.transition(i.id,"ringing",{status:"missed",ringingSince:null,note:this.waiting.has(i.id)?"widget busy":"not answered"}))continue;this.deps.log?.(`[calls] ${i.id} from ${i.agentId} missed`),await this.notice(i,this.missedTitle(i))}else if(i.status==="answered"&&i.answeredAt!==null&&t-i.answeredAt>=n){if(!this.deps.store.transition(i.id,"answered",{status:"ended",endedAt:t,note:"no hang-up"}))continue;this.deps.log?.(`[calls] ${i.id} from ${i.agentId} ended: no hang-up in ${this.deps.config().maxCallMinutes} min`)}else if(i.status==="later"&&i.ringAgainAt!==null&&t>=i.ringAgainAt){let a=this.deps.store.transition(i.id,"later",{status:"ringing",ringingSince:t,ringAgainAt:null});if(!a)continue;this.setWaiting(i.id,null),await this.ring(a)}}answer(t){let e=this.deps.store.get(t);if(!e)return c(t);let n=this.deps.store.transition(t,"ringing",{status:"answered",answeredAt:this.now(),ringingSince:null});return n?(this.deps.log?.(`[calls] ${t} answered (${e.agentId})`),n.kind==="camera"?{ok:!0,call:n}:{ok:!0,call:n,opener:N(n)}):{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}, not ringing`}}decline(t){if(!this.deps.store.get(t))return c(t);let n=this.deps.store.transition(t,["ringing","later"],{status:"declined",endedAt:this.now(),ringingSince:null,ringAgainAt:null});return n?{ok:!0,call:n}:{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}`}}later(t,e){if(!this.deps.store.get(t))return c(t);let i=e===void 0?$:Number(e);if(!Number.isInteger(i)||i<1||i>T)return{ok:!1,status:400,error:`minutes must be a whole number from 1 to ${T}`};let a=this.deps.store.transition(t,"ringing",{status:"later",ringingSince:null,ringAgainAt:this.now()+i*6e4});return a?{ok:!0,call:a}:{ok:!1,status:409,error:`call is ${this.deps.store.get(t)?.status}, not ringing`}}hangup(t){let e=this.deps.store.get(t);if(!e)return c(t);let n=this.deps.store.transition(t,"answered",{status:"ended",endedAt:this.now()});if(!n)return{ok:!1,status:409,error:`call is ${e.status}, not answered`};this.deps.log?.(`[calls] ${t} ended (${e.agentId})`);let i=this.deps.summarize;if(n.kind==="camera"||!this.deps.config().summary||!i)return{ok:!0,call:n};let a=(async()=>{try{let s=(await i(n))?.trim();if(!s)return;let o=this.deps.store.update(t,{summary:s});this.deps.file?.(o,s)}catch(s){this.deps.log?.(`[calls] summary for ${t} failed: ${s?.message??s}`)}})();return{ok:!0,call:n,summarized:a}}endCamera(t,e){let n=this.deps.store.get(t);if(!n||n.kind!=="camera")return!1;let i=this.deps.store.transition(t,"answered",{status:"ended",endedAt:this.now(),note:e??null});return i&&this.deps.log?.(`[calls] ${t} ended (${n.agentId}): ${e??"share over"}`),!!i}get(t){return this.deps.store.get(t)}list(t={}){return this.deps.store.list(t)}},b="withdrawn by the caller";function W(r,t=Date.now(),e){let n=a=>`${new Date(a).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short",timeZone:e})} (in ${Math.max(1,Math.round((a-t)/6e4))} min)`;return`${r.why==="call"?`The owner is busy in another call${r.with?` (with ${r.with})`:""}.`:r.why==="ringing"?`The owner is busy: another call${r.with?` (from ${r.with})`:""} is ringing.`:"The owner is busy on the voice widget."} They were told you are calling, and why. Your call waits and rings by itself as soon as they are free: do not call again. `+(r.remindAt!==null?`Still busy at ${n(r.remindAt)}, they are told again that you are waiting. `:"")+`It waits until ${n(r.waitsUntil)} at most, then counts as a missed call.`}var c=r=>({ok:!1,status:404,error:`No such call: ${r}`});export{y as a,D as b,M as c,S as d,W as e};
|
|
11
|
-
//# sourceMappingURL=chunk-
|
|
11
|
+
//# sourceMappingURL=chunk-PYHR4HXO.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{d as h}from"./chunk-
|
|
1
|
+
import{d as h}from"./chunk-5IHUZVPU.js";var d=["main contact","primary contact","point of contact","billing contact","technical contact","decision maker"],f=/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g,w=/\b(role|title|position|job)\s*\**\s*[::]\s*\**\s*([^\n;|]+)/gi;function L(t,c,e=[]){let l=[c,...e].join(`
|
|
2
2
|
`),a=l.toLowerCase(),i=h(t,l);for(let s of p(t.match(f)??[]))a.includes(s.toLowerCase())||i.push(`email ${s}`);let m=t.toLowerCase();for(let s of d)m.includes(s)&&!a.includes(s)&&i.push(`marker "${s}"`);for(let s of t.matchAll(w)){let n=s[2].replace(/\*+/g,"").trim();n&&!a.includes(n.toLowerCase())&&i.push(`${s[1].toLowerCase()} "${n}"`)}return p(i)}function p(t){return[...new Set(t)]}var $=.9,g=/^\s*(?:wait\b|here(?:'s| is) the (?:updated|modified|patched|revised)|i (?:must|need to|will|should) (?:output|return|write)|(?:okay|ok|sure)[,.!]\s|let me\b|as requested\b)/im;function k(t,c){let e=[],l=t.split(`
|
|
3
3
|
`).filter(o=>o.trim()).length,a=c.split(`
|
|
4
4
|
`).filter(o=>o.trim()).length;l>=5&&a<Math.floor(l*$)&&e.push(`the article shrinks from ${l} to ${a} lines`);let i=c.match(g);i&&!t.match(g)&&e.push(`it contains the model's own commentary ("${i[0].trim().slice(0,40)}")`);let m=o=>{let r=new Map;for(let u of o.split(`
|
|
5
5
|
`))/^#{1,6} /.test(u)&&r.set(u.trim(),(r.get(u.trim())??0)+1);return r},s=m(t);for(let[o,r]of m(c))r>1&&r>(s.get(o)??0)&&e.push(`the heading "${o}" appears ${r} times`);let n=L(t,c);return n.length&&e.push(`it drops ${n.length} fact(s): ${n.slice(0,6).join(", ")}${n.length>6?", \u2026":""}`),e}export{L as a,k as b};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-S22IBRY6.js.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import{a as k}from"./chunk-IMLAPB7G.js";import{i as y}from"./chunk-TJZGAKIB.js";import{b as X}from"./chunk-KP7KDLZ2.js";import{I as W,J as B,K as G,L as J,P as A,T as xe}from"./chunk-PXKIPU27.js";import{existsSync as K,readFileSync as ve}from"node:fs";import{dirname as b,join as h}from"node:path";import{fileURLToPath as Ae}from"node:url";import{homedir as ke}from"node:os";var M="tn.acme.agentx.voice",st="AgentX Desktop.app",V="AgentX Helper.app";function at(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function lt(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function L(e){return`'${e.replace(/'/g,"'\\''")}'`}var z="/usr/bin:/bin:/usr/sbin:/sbin";function ut(e,t){return t||[...new Set([...e?[b(e)]:[],...z.split(":")])].join(":")}function N(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function ct(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?N(t[1]):z}var pt=e=>/agentx\.voice.*\.plist$/.test(e);function dt(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,c)=>s.file<c.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],c=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!c||!N(c).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:N(s)}):n={file:o,label:N(s)})}return{keep:n??{file:h(e,`${M}.plist`),label:M},remove:r}}function Z(e,t,n){for(let r of t.split(":"))if(r&&n(h(r,e)))return h(r,e);return null}function mt(e){let t=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${L(e.cwd)} && ${L(e.node)} ${L(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
3
|
+
<plist version="1.0"><dict>
|
|
4
|
+
<key>Label</key><string>${t(e.label??M)}</string>
|
|
5
|
+
<key>ProgramArguments</key><array><string>${t(e.executable)}</string></array>
|
|
6
|
+
<key>WorkingDirectory</key><string>${t(e.cwd)}</string>
|
|
7
|
+
<key>EnvironmentVariables</key><dict>${Object.entries(n).map(([r,o])=>`<key>${r}</key><string>${t(o)}</string>`).join("")}</dict>
|
|
8
|
+
<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
|
|
9
|
+
<key>ProcessType</key><string>Interactive</string>
|
|
10
|
+
<key>StandardErrorPath</key><string>${t(e.log)}</string>
|
|
11
|
+
</dict></plist>
|
|
12
|
+
`}function ft(e){return e?["--icon",e]:[]}function be(e){return h(e,"Applications",V,"Contents/MacOS/agentx-mac-helper")}function Ne(e=b(Ae(import.meta.url))){for(let t=e;;t=b(t)){try{if(JSON.parse(ve(h(t,"package.json"),"utf8")).name==="agentix-cli")return t}catch{}if(b(t)===t)return null}}function Re(e,t,n){if(n)return n;let r=be(t);return K(r)||!e?r:h(e,"apps/mac-helper/build",V,"Contents/MacOS/agentx-mac-helper")}function T(){let e=Re(Ne(),ke(),process.env.AGENTX_MAC_HELPER);return K(e)?e:null}import{accessSync as Ce,constants as Le}from"fs";import{execFile as _}from"child_process";var Y=5e3,R=(e,t)=>new Promise(n=>{try{_(e,t,{timeout:Y},r=>n(!r))}catch{n(!1)}}),Q=(e,t)=>new Promise(n=>{try{_(e,t,{timeout:Y},(r,o)=>n(r?null:String(o)))}catch{n(null)}}),P=(e,t)=>new Promise((n,r)=>{_(e,t,{timeout:3e4,maxBuffer:8*1024*1024},(o,i,s)=>{o?r(new Error(`${e} ${t[0]}: ${(s||o.message).trim()}`)):n(i)})});var ee=e=>e.helper===void 0?T():e.helper;async function Pe(e,t=Q){if(!e)return"missing";let n=await t(e,["notify-status"]),r=null;try{r=n?JSON.parse(n):null}catch{r=null}return r?r.authorization==="notDetermined"?"not-asked":r.authorization==="denied"?"not-allowed":r.alertStyle==="none"?"hidden":"ready":"outdated"}function te(e={}){let t=e.run??R;return{async post({title:n,message:r}){let o=ee(e);return o&&await t(o,["notify","--title",n,"--message",r])||await t("/usr/bin/osascript",["-e","on run argv","-e","display notification (item 2 of argv) with title (item 1 of argv)","-e","end run",n,r])?"posted":"failed"},status:()=>Pe(ee(e),e.capture)}}var $e=`
|
|
13
|
+
function run(argv) {
|
|
14
|
+
var folderName = argv[0], title = argv[1], body = argv[2]
|
|
15
|
+
var Notes = Application("Notes")
|
|
16
|
+
var esc = function (s) { return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") }
|
|
17
|
+
var folder = Notes.folders.whose({ name: folderName })()[0]
|
|
18
|
+
if (!folder) {
|
|
19
|
+
folder = Notes.Folder({ name: folderName })
|
|
20
|
+
Notes.folders.push(folder)
|
|
21
|
+
folder = Notes.folders.whose({ name: folderName })()[0]
|
|
22
|
+
}
|
|
23
|
+
var lines = body.split("\\n").map(function (l) { return "<div>" + (l ? esc(l) : "<br>") + "</div>" })
|
|
24
|
+
// Notes takes the title from the first line: a name as well would show it twice.
|
|
25
|
+
var note = Notes.Note({ body: "<div><h1>" + esc(title) + "</h1></div>" + lines.join("") })
|
|
26
|
+
folder.notes.push(note)
|
|
27
|
+
return note.id()
|
|
28
|
+
}
|
|
29
|
+
`;function ne(e=P){return{async add({folder:t,title:n,body:r}){let i=(await e("/usr/bin/osascript",["-l","JavaScript","-e",$e,t,n,r])).trim();if(!i)throw new Error("Notes did not return the new note's id");return{id:i}}}}import{existsSync as Oe,readdirSync as Ee}from"fs";var ie="/System/Library/Sounds";function re(e){if(!/^[\w -]+$/.test(e))return null;let t=`${ie}/${e}.aiff`;return Oe(t)?t:null}function oe(e={}){let t=e.run??R;return{async play(n,r){let o=re(n);o&&await t("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,r))),o])},has:n=>re(n)!==null,async names(){try{return Ee(ie).filter(n=>n.endsWith(".aiff")).map(n=>n.slice(0,-5)).sort()}catch{return[]}}}}var le="\u200B";function $(e){return e.startsWith("-")?le+e:e}var se=e=>e?.startsWith(le+"-")?e.slice(1):e;function I(e){if(!e.trim()||e.startsWith("-"))throw new Error(`Reminders list name "${e}" is not usable: it must not be empty or start with "-"`);return e}var ae=e=>new Date(Math.floor(e.getTime()/6e4)*6e4).toISOString().replace(/\.\d{3}Z$/,"Z");function ue(e="remindctl",t=P){return{async ensureList(n){let r=await t(e,["list","--json","--no-input"]),o=JSON.parse(r.trim()||"[]");if(!Array.isArray(o))throw new Error(`${e} list: expected a JSON array`);o.some(i=>i?.title===n)||await t(e,["list",I(n),"--create","--json","--no-input"])},async listOpen(n){let r=await t(e,["show","all","--list",I(n),"--json","--no-input"]),o=JSON.parse(r.trim()||"[]");if(!Array.isArray(o))throw new Error(`${e} show: expected a JSON array`);return o.filter(i=>i&&typeof i.id=="string"&&!i.isCompleted).map(i=>({...i,title:se(i.title)??"",...i.notes!==void 0?{notes:se(i.notes)}:{}}))},async add({list:n,title:r,notes:o,due:i,priority:s}){let c=["add","--title",$(r),"--list",I(n),"--notes",$(o)];i&&c.push("--due",ae(i)),s&&s!=="none"&&c.push("--priority",s);let l=await t(e,[...c,"--json","--no-input"]),d;try{d=JSON.parse(l.trim())?.id}catch{d=void 0}if(typeof d!="string"||!d)throw new Error(`${e} add: no reminder id in its answer`);return{id:d}},async update(n,r){let o=["edit",n];r.title!==void 0&&o.push("--title",$(r.title)),r.notes!==void 0&&o.push("--notes",$(r.notes)),r.due===null?o.push("--clear-due"):r.due&&o.push("--due",ae(r.due)),o.length!==2&&await t(e,[...o,"--json","--no-input"])},async complete(n){await t(e,["complete",n,"--json","--no-input"])},async remove(n){await t(e,["delete",n,"--force","--json","--no-input"])}}}var Me=e=>{try{return Ce(e,Le.X_OK),!0}catch{return!1}},Te={async active(){let e=X();return e.active?!0:e.reason==="no active Focus assertion"?!1:null}};function ce(e={},t={}){let n=e.reminders?.command||"remindctl";return{os:"macos",tasks:ue(n,t.output),notes:ne(t.output),banner:te(t),sound:oe(t),focus:Te,async describe(){let r=[],o=t.isExecutable??Me;return(n.includes("/")?o(n):!!Z(n,process.env.PATH||"",o))||r.push(`Reminders: ${n} not found (brew install steipete/tap/remindctl, or set reminders.command).`),{os:"macos",tasks:!0,notes:!0,banner:!0,sound:!0,focus:!0,problems:r}}}}function O(e){return{os:"none",async describe(){return{os:"none",tasks:!1,notes:!1,banner:!1,sound:!1,focus:!1,problems:[e]}}}}var _e={darwin:ce};function D(e={},t={}){if(e.native?.adapter==="none")return O('Turned off: native.adapter is "none".');let n=t.platform??process.platform,r=(t.factories??_e)[n];return r?r(e,t.io??{}):O(`AgentX has no native adapter for ${n} yet.`)}import{existsSync as Ie}from"fs";import{homedir as De}from"os";import{isAbsolute as qe}from"path";var Fe={banner:!0,sound:!0,soundName:"Glass",volume:.4};function Jt(e){return{...Fe,...e??{}}}function Xt(e,t={}){let n=D({native:t.native},{platform:t.platform,io:{run:t.run,helper:t.helper}});return async(r,o)=>{let i=[];e.banner&&n.banner&&i.push(n.banner.post({title:r,message:o})),e.sound&&n.sound&&i.push(n.sound.play(e.soundName,e.volume)),await Promise.all(i)}}function Kt(e,t,n=process.platform){let r={...e??{}},o=D({},{platform:n});if("banner"in t&&(r.banner=!!t.banner),"sound"in t&&(r.sound=!!t.sound),"soundName"in t){let i=String(t.soundName).trim();if(!(o.sound?o.sound.has(i):/^[\w -]+$/.test(i)))throw new Error(`no system sound named "${i}" on this machine`);r.soundName=i}if("icon"in t){let i=String(t.icon??"").trim().replace(/^~(?=\/)/,De());if(!i)delete r.icon;else{if(!qe(i)||!/\.(png|jpe?g|icns)$/i.test(i))throw new Error("icon must be the full path to a .png, .jpg or .icns file");if(o.banner&&!Ie(i))throw new Error(`no icon file at ${i}`);r.icon=i}}if("volume"in t){let i=Number(t.volume);if(!Number.isFinite(i)||i<0||i>1)throw new Error("volume must be between 0 and 1");r.volume=i}return r}import{existsSync as Je,mkdirSync as Xe,readFileSync as Ke,renameSync as Ve,writeFileSync as ze}from"fs";import{dirname as me,resolve as Ze}from"path";G();xe();G();var Qt=["owner","agent","person"],He=36e5,je=e=>J.includes(e.state);function pe(e){return t=>!e||e.get(t)?.state!=="active"?null:e.steps(t).find(n=>n.state==="active")?.agentId??null}function q(e,t){return e.state==="waiting_owner"?{group:"owner",who:A}:e.promise&&e.owedTo&&e.owedTo!==A&&!t.isAgent(e.owedTo)?{group:"person",who:e.owedTo}:e.state==="needs_attention"?{group:"owner",who:A}:{group:"agent",who:t.activeStepAgent?.(e.id)??e.agentId}}function F(e,t,n){return je(e)?e.state==="needs_attention"?e.attentionReason??"needs attention":e.dueAt!==null?n>e.dueAt?`past its due time (${Ue(e.dueAt)})`:null:n-e.updatedAt>t*He?`no activity for ${t} h or more`:null:null}function en(e,t,n,r){let o={owner:[],agent:[],person:[]};for(let i of e){let s=F(i,t,n);if(!s)continue;let{group:c,who:l}=q(i,r);o[c].push({request:i,group:c,who:l,why:s})}return o}function tn(e,t){return e==="owner"?"you":e==="agent"?`agent ${t}`:`${t} (outside person)`}var Ue=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function nn(e){if(e==null||e==="")return;let t=typeof e=="number"?e:typeof e=="string"?Date.parse(e.trim()):NaN;return!Number.isFinite(t)||t<=0?"due must be an ISO date (2030-01-31T17:00:00Z) or epoch milliseconds":t}function rn(e){return t=>W(t,e())}var We=10;async function on(e,t,n){let r=e.dueForCheck(n.now-n.everyMinutes*6e4,We),o=0;return await Promise.all(r.map(async i=>{e.markChecked(i.id,i.verifyState,i.verifyDetail??"",n.now);let s=await t(i.closeWhen,i).catch(c=>({verdict:"unverifiable",detail:String(c?.message??c)}));if(s.verdict==="met"){e.closeVerified(i.id,s.detail,n.now)&&(o++,n.log(`[requests] ${i.id} closed by its check: ${s.detail}`));return}e.markChecked(i.id,s.verdict==="unverifiable"?"unverified":i.verifyState==="failed"?"failed":null,s.detail,n.now)})),{checked:r.length,closed:o}}var Be=200,de=4e3;function Ge(e){return e.replace(/```[\s\S]*?```/g," ").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+[.)])\s+/gm,"").replace(/[*_~`]+/g,"").replace(/\s+/g," ").trim()}function f(e,t=Be){let n=Ge(e);if(n.length<=t)return n;let r=n.slice(0,t),o=Math.max(r.lastIndexOf(". "),r.lastIndexOf("? "),r.lastIndexOf("! "));return o>t/2?r.slice(0,o+1):`${r.slice(0,t-1).trimEnd()}\u2026`}function cn(e,t,n,r){let o=n?.get(e.id),i=r?F(e,r.staleAfterHours,r.now):null,s=t.lastAnswer(e.id),c=s&&s.text.length>de?`${s.text.slice(0,de)}
|
|
30
|
+
|
|
31
|
+
\u2026`:s?.text;return{...e,summary:f(e.text),textHtml:k(e.text),why:e.state==="waiting_owner"?e.question:e.state==="needs_attention"?e.attentionReason:null,ownerNoteHtml:e.ownerNote?k(e.ownerNote):null,lastAnswer:s?{agentId:s.agentId,at:s.at,html:k(c)}:null,loop:e.promise||e.dueAt!==null||e.closeWhen?{owedTo:e.owedTo,promise:e.promise,dueAt:e.dueAt,check:e.closeWhen?B(e.closeWhen):null,verifyState:e.verifyState,verifyDetail:e.verifyDetail}:null,stall:r&&i?{...q(e,{isAgent:r.isAgent,activeStepAgent:pe(n)}),why:i}:null,plan:o?{state:o.state,steps:n.steps(e.id).map(l=>({idx:l.idx,name:l.name,kind:l.kind,agentId:l.agentId,state:l.state,approval:l.needsApproval?l.approval:null,evidence:l.evidence,note:l.note,nudges:l.nudges}))}:null}}var H=3,Ye=30*24*36e5;function ge(e){return Ze(e,".agentx","native-mirror.json")}function ye(e){try{let t=JSON.parse(Ke(ge(e),"utf-8"));return{...t,items:t?.items&&typeof t.items=="object"?t.items:{}}}catch{return{items:{}}}}function fe(e,t){let n=ge(e);Je(me(n))||Xe(me(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;ze(r,JSON.stringify(t,null,2)+`
|
|
32
|
+
`),Ve(r,n)}var Qe=5*6e4;function yn(e,t,n=Date.now()){let r=ye(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=Qe)?!1:r.items[`card:${t}`]?.state!=="failed"}var j=24*36e5;function he(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function et(e,t,n,r){let o=Date.parse(e.expires),i=[f(e.ask,y.ask)];return e.choices?.length&&i.push(...e.choices.map((s,c)=>`${c+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${f(e.recommend,y.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:f(e.title,y.title),notes:i.join(`
|
|
33
|
+
`),due:he(r,t,o),priority:Number.isFinite(o)&&o-r<=j?"high":"none"}}function tt(e,t,n,r){let o=[f(e.question||e.text,y.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:f(e.text,y.title),notes:o.join(`
|
|
34
|
+
`),due:he(r,t,i),priority:i!==void 0&&i-r<=j?"high":"none"}}async function hn(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),c={created:0,completed:0,dismissed:0,failed:0},l=ye(t);delete l.lastError;let d=a=>{l.lastError={at:s,message:a}},w=new Map;try{if(n.include.includes("card"))for(let a of e.cards())a.status==="pending"&&Date.parse(a.expires)>i&&w.set(`card:${a.id}`,et(a,n,e.answerUrl,i));if(n.include.includes("request"))for(let a of e.requests())a.state==="waiting_owner"&&w.set(`request:${a.id}`,tt(a,n,e.answerUrl,i))}catch(a){return o(`[mirror] could not read what is waiting: ${a?.message??a}`),d(String(a?.message??a)),fe(t,l),c}let U=!0,x=new Map,we=async a=>{if(!x.has(a))try{x.set(a,new Set((await r.listOpen(a)).map(u=>u.id)))}catch(u){o(`[mirror] could not read list "${a}": ${u?.message??u}`),d(String(u?.message??u)),x.set(a,null),U=!1}return x.get(a)};for(let[a,u]of Object.entries(l.items)){if(u.state!=="open"||!u.id)continue;let p=await we(u.list);if(p)if(w.has(a))p.has(u.id)||(l.items[a]={...u,state:"dismissed",at:s},c.dismissed++,o(`[mirror] ${a}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(p.has(u.id))try{await r.complete(u.id)}catch(g){o(`[mirror] ${a}: could not complete its task: ${g?.message??g}`),d(String(g?.message??g));continue}l.items[a]={...u,state:"completed",at:s},c.completed++}}let E=null,S=[];for(let[a,u]of w){let p=l.items[a];if(p&&(p.state==="open"||p.state==="dismissed")||p?.state==="failed"&&p.failures>=H)continue;if(E===null)try{await r.ensureList(n.list),E=!0}catch(m){o(`[mirror] could not make list "${n.list}": ${m?.message??m}`),d(String(m?.message??m)),E=!1}let g=p?.state==="failed"?p.failures:0;try{let{id:m}=await r.add({list:n.list,title:u.title,notes:u.notes,due:u.due,priority:u.priority});l.items[a]={id:m,list:n.list,state:"open",at:s,failures:0},c.created++}catch(m){let v=String(m?.message??m),C=g+1;l.items[a]={list:n.list,state:"failed",at:s,failures:C,lastError:v},d(v),c.failed++,o(`[mirror] ${a}: could not add to Reminders (${C}/${H}): ${v}`),C===H&&S.push({title:u.title,message:v})}}let Se=l.failureToldAt?Date.parse(l.failureToldAt):NaN;if(S.length&&!(i-Se<j)){let a=S[0],u=S.length>1?` (and ${S.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${a.title}${u}: ${f(a.message,200)}. Still on the Desk.`),l.failureToldAt=s}catch(p){o(`[mirror] could not tell the owner: ${p?.message??p}`)}}U&&(l.checkedAt=s,l.cards=n.include.includes("card"));for(let[a,u]of Object.entries(l.items))u.state!=="open"&&!w.has(a)&&i-Date.parse(u.at)>Ye&&delete l.items[a];return fe(t,l),c}export{st as a,V as b,at as c,lt as d,ut as e,ct as f,pt as g,dt as h,Z as i,mt as j,ft as k,be as l,Ne as m,Re as n,T as o,re as p,D as q,Fe as r,Jt as s,Xt as t,Kt as u,Qt as v,pe as w,q as x,en as y,tn as z,Ue as A,nn as B,rn as C,on as D,f as E,cn as F,ye as G,yn as H,hn as I};
|
|
35
|
+
//# sourceMappingURL=chunk-S5NGIJDI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/desktop/install.ts","../src/native/macos/index.ts","../src/native/macos/run.ts","../src/native/macos/banner.ts","../src/native/macos/notes.ts","../src/native/macos/sound.ts","../src/native/macos/tasks.ts","../src/native/none.ts","../src/native/index.ts","../src/notify/local.ts","../src/approvals/mirror.ts","../src/requests/card-view.ts","../src/requests/loops.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { homedir } from 'node:os'\n\nexport const DESKTOP_LABEL = 'tn.acme.agentx.voice'\nexport const DESKTOP_APP = 'AgentX Desktop.app'\nexport const HELPER_APP = 'AgentX Helper.app'\nexport function desktopPlatformError(platform: string, arch: string, release: string): string | null {\n if (platform !== 'darwin' || arch !== 'arm64' || Number(release.split('.')[0]) < 23)\n return 'AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.'\n return null\n}\nexport function selectDesktopAgent(agents: Record<string, unknown>, requested?: string): string {\n if (requested && !Object.hasOwn(agents, requested)) throw new Error(`Unknown agent: ${requested}. Run agentx agent list.`)\n const id = requested || Object.keys(agents)[0]\n if (!id) throw new Error('No agents configured. Run agentx setup first.')\n return id\n}\nexport function shellQuote(value: string): string { return `'${value.replace(/'/g, \"'\\\\''\")}'` }\n/** launchd's default PATH, which is all a login item gets unless the plist sets one. */\nexport const LAUNCHD_PATH = '/usr/bin:/bin:/usr/sbin:/sbin'\n/** PATH for the login item: AGENTX_VOICE_PATH when set, else the folder of\n * the ffmpeg found at install time (mlx_whisper needs it) ahead of launchd's default. */\nexport function desktopPath(ffmpeg: string | null, override?: string): string {\n if (override) return override\n return [...new Set([...(ffmpeg ? [dirname(ffmpeg)] : []), ...LAUNCHD_PATH.split(':')])].join(':')\n}\nfunction unxml(s: string): string {\n const ents: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" }\n return s.replace(/&(amp|lt|gt|quot|apos);/g, (_, e) => ents[e])\n}\n/** The PATH a login item plist sets, or launchd's default when it sets none. */\nexport function plistPathEnv(plist: string): string {\n const m = plist.match(/<key>PATH<\\/key>\\s*<string>([^<]*)<\\/string>/)\n return m ? unxml(m[1]) : LAUNCHD_PATH\n}\n/** Login item files the voice app may have been installed under. */\nexport const isVoiceLoginItemFile = (name: string) => /agentx\\.voice.*\\.plist$/.test(name)\nexport type LoginItem = { file: string; label: string }\n/** One login item per Mac. The label was renamed once and\n * apps/mac-voice/install.sh writes its own, so adopt the first existing\n * `*agentx.voice*` item that runs the voice app (any bundle name) and\n * retire the others; with none, use DESKTOP_LABEL. Plists are XML text. */\nexport function adoptLoginItem(dir: string, items: { file: string; plist: string }[]): { keep: LoginItem; remove: LoginItem[] } {\n let keep: LoginItem | null = null\n const remove: LoginItem[] = []\n for (const { file, plist } of [...items].sort((a, b) => (a.file < b.file ? -1 : 1))) {\n const label = plist.match(/<key>Label<\\/key>\\s*<string>([^<]*)<\\/string>/)?.[1]\n const program = plist.match(/<key>ProgramArguments<\\/key>\\s*<array>\\s*<string>([^<]*)<\\/string>/)?.[1]\n if (!label || !program || !unxml(program).endsWith('/Contents/MacOS/AgentXVoice')) continue\n if (keep) remove.push({ file, label: unxml(label) })\n else keep = { file, label: unxml(label) }\n }\n return { keep: keep ?? { file: join(dir, `${DESKTOP_LABEL}.plist`), label: DESKTOP_LABEL }, remove }\n}\n/** The file that a process with this PATH would run, or null. */\nexport function findOnPath(bin: string, path: string, isExecutable: (file: string) => boolean): string | null {\n for (const dir of path.split(':')) if (dir && isExecutable(join(dir, bin))) return join(dir, bin)\n return null\n}\n/** Without `agent` the app talks to the agent picked in its menu-bar\n * icon; with it, that agent is pinned and the menu cannot switch. */\nexport function desktopPlist(opts: { label?: string; executable: string; cwd: string; agent?: string; url: string; helper: string; cli: string; node: string; log: string; path: string }): string {\n const xml = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"').replace(/'/g, ''')\n const env = {\n PATH: opts.path,\n ...(opts.agent ? { AGENTX_VOICE_AGENT: opts.agent } : {}),\n AGENTX_DAEMON_URL: opts.url,\n AGENTX_MAC_HELPER: opts.helper,\n AGENTX_PASTE_COMMAND: `cd ${shellQuote(opts.cwd)} && ${shellQuote(opts.node)} ${shellQuote(opts.cli)} paste`,\n }\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>${xml(opts.label ?? DESKTOP_LABEL)}</string>\n<key>ProgramArguments</key><array><string>${xml(opts.executable)}</string></array>\n<key>WorkingDirectory</key><string>${xml(opts.cwd)}</string>\n<key>EnvironmentVariables</key><dict>${Object.entries(env).map(([k,v]) => `<key>${k}</key><string>${xml(v)}</string>`).join('')}</dict>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>\n<key>ProcessType</key><string>Interactive</string>\n<key>StandardErrorPath</key><string>${xml(opts.log)}</string>\n</dict></plist>\\n`\n}\n/** build.sh arguments for the helper: the banner icon from\n * notifications.local.icon, or none for the bundled AgentX logo. */\nexport function helperBuildArgs(icon?: string): string[] {\n return icon ? ['--icon', icon] : []\n}\nexport function installedHelper(home: string): string {\n return join(home, 'Applications', HELPER_APP, 'Contents/MacOS/agentx-mac-helper')\n}\n/** The AgentX package folder, found by walking up from this file (dist/\n * when installed, src/ in a checkout) — never from the caller's cwd, so\n * `agentx notify` finds a repo-built helper from any folder. */\nexport function packageRoot(from = dirname(fileURLToPath(import.meta.url))): string | null {\n for (let dir = from; ; dir = dirname(dir)) {\n try {\n if (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).name === 'agentix-cli') return dir\n } catch { /* no package.json here — keep walking up */ }\n if (dirname(dir) === dir) return null\n }\n}\n/** The helper to run: an explicit path, else the one `agentx desktop\n * install` put in ~/Applications, else one built in the package. */\nexport function resolveHelper(root: string | null, home: string, override?: string): string {\n if (override) return override\n const installed = installedHelper(home)\n if (existsSync(installed) || !root) return installed\n return join(root, 'apps/mac-helper/build', HELPER_APP, 'Contents/MacOS/agentx-mac-helper')\n}\n/** The AgentX Helper binary when one is built or installed, else null.\n * AGENTX_MAC_HELPER points at a helper somewhere else. */\nexport function findHelper(): string | null {\n const path = resolveHelper(packageRoot(), homedir(), process.env.AGENTX_MAC_HELPER)\n return existsSync(path) ? path : null\n}\n","import { accessSync, constants } from \"fs\"\nimport { findOnPath } from \"@/desktop/install\"\nimport { readSystemFocus } from \"@/notify/focus\"\nimport type { NativeAdapter, NativeFocus } from \"../types\"\nimport { macosBanner } from \"./banner\"\nimport { macosNotes } from \"./notes\"\nimport type { Capture, Output, Run } from \"./run\"\nimport { macosSound } from \"./sound\"\nimport { macosTasks } from \"./tasks\"\n\n/** Programs the adapter runs, so tests can stand in for them. */\nexport interface MacosIo {\n run?: Run\n capture?: Capture\n output?: Output\n /** The AgentX Helper binary; null means none. Unset: looked up on use. */\n helper?: string | null\n /** Is this file an executable? Used to find remindctl. */\n isExecutable?: (file: string) => boolean\n}\n\nconst executable = (file: string): boolean => {\n try { accessSync(file, constants.X_OK); return true } catch { return false }\n}\n\n/** System Focus from the private Focus database (notify/focus.ts). That\n * reader answers \"not in Focus\" when it can't read the file, so here\n * anything but a clean answer is null: the OS could not tell. */\nconst focus: NativeFocus = {\n async active() {\n const s = readSystemFocus()\n if (s.active) return true\n return s.reason === \"no active Focus assertion\" ? false : null\n },\n}\n\nexport function macosAdapter(cfg: { reminders?: { command?: string } } = {}, io: MacosIo = {}): NativeAdapter {\n const command = cfg.reminders?.command || \"remindctl\"\n return {\n os: \"macos\",\n tasks: macosTasks(command, io.output),\n notes: macosNotes(io.output),\n banner: macosBanner(io),\n sound: macosSound(io),\n focus,\n async describe() {\n const problems: string[] = []\n const isExec = io.isExecutable ?? executable\n const found = command.includes(\"/\") ? isExec(command) : !!findOnPath(command, process.env.PATH || \"\", isExec)\n if (!found) problems.push(`Reminders: ${command} not found (brew install steipete/tap/remindctl, or set reminders.command).`)\n return { os: \"macos\", tasks: true, notes: true, banner: true, sound: true, focus: true, problems }\n },\n }\n}\n","import { execFile } from \"child_process\"\n\n/** Runs a program; resolves true when it exited 0. Never rejects. */\nexport type Run = (file: string, args: string[]) => Promise<boolean>\n\n/** Runs a program; resolves its stdout, or rejects with its stderr. */\nexport type Output = (file: string, args: string[]) => Promise<string>\n\n/** Runs a program; resolves its stdout, or null when it failed. */\nexport type Capture = (file: string, args: string[]) => Promise<string | null>\n\n/** A banner or a sound may not hold a caller hostage: afplay on a long\n * custom sound, or osascript stuck on a permission prompt, is cut off. */\nconst STEP_TIMEOUT_MS = 5_000\n\nexport const run: Run = (file, args) =>\n new Promise((done) => {\n try {\n execFile(file, args, { timeout: STEP_TIMEOUT_MS }, (err) => done(!err))\n } catch {\n done(false) // the program is not on this machine: not worth reporting\n }\n })\n\nexport const capture: Capture = (file, args) =>\n new Promise((done) => {\n try {\n execFile(file, args, { timeout: STEP_TIMEOUT_MS }, (err, stdout) => done(err ? null : String(stdout)))\n } catch {\n done(null)\n }\n })\n\nexport const output: Output = (file, args) =>\n new Promise((resolve, reject) => {\n execFile(file, args, { timeout: 30_000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {\n if (err) reject(new Error(`${file} ${args[0]}: ${(stderr || err.message).trim()}`))\n else resolve(stdout)\n })\n })\n","import { findHelper } from \"@/desktop/install\"\nimport type { BannerStatus, NativeBanner } from \"../types\"\nimport { capture as defaultCapture, run as defaultRun, type Capture, type Run } from \"./run\"\n\n// The banner is posted by the AgentX Helper app when it is installed, so it\n// carries the helper's icon (the AgentX logo by default). Without the\n// helper, or before macOS has allowed it to notify, osascript posts it, and\n// macOS shows it as coming from Script Editor.\n\nexport interface BannerIo {\n run?: Run\n capture?: Capture\n /** The helper binary; null means none. Unset: looked up on each use. */\n helper?: string | null\n}\n\nconst helperOf = (io: BannerIo): string | null => (io.helper === undefined ? findHelper() : io.helper)\n\n/** What the helper reports about its notification permission. Never shows\n * the macOS \"allow notifications\" prompt and never posts a banner. */\nexport async function helperBannerStatus(path: string | null, capture: Capture = defaultCapture): Promise<BannerStatus> {\n if (!path) return \"missing\"\n const out = await capture(path, [\"notify-status\"])\n let status: { authorization?: string; alertStyle?: string } | null = null\n try { status = out ? JSON.parse(out) : null } catch { status = null }\n if (!status) return \"outdated\"\n if (status.authorization === \"notDetermined\") return \"not-asked\"\n if (status.authorization === \"denied\") return \"not-allowed\"\n if (status.alertStyle === \"none\") return \"hidden\"\n return \"ready\"\n}\n\nexport function macosBanner(io: BannerIo = {}): NativeBanner {\n const exec = io.run ?? defaultRun\n return {\n async post({ title, message }) {\n const helper = helperOf(io)\n // A non-zero exit is usually \"not allowed to notify yet\" (the first\n // banner asks), so this one goes through osascript instead.\n if (helper && await exec(helper, [\"notify\", \"--title\", title, \"--message\", message])) return \"posted\"\n // Title and message travel as argv, never spliced into the script,\n // so a quote in either cannot turn into AppleScript.\n const ok = await exec(\"/usr/bin/osascript\", [\n \"-e\", \"on run argv\",\n \"-e\", \"display notification (item 2 of argv) with title (item 1 of argv)\",\n \"-e\", \"end run\",\n title, message,\n ])\n return ok ? \"posted\" : \"failed\"\n },\n status: () => helperBannerStatus(helperOf(io), io.capture),\n }\n}\n","import type { NativeNotes } from \"../types\"\nimport { output as defaultOutput, type Output } from \"./run\"\n\n// Apple Notes through JXA (osascript -l JavaScript). The folder, title\n// and body travel as argv and are read by the script, never spliced into\n// it, so nothing in them can run as code. Notes stores a body as HTML:\n// the script escapes the text and keeps its line breaks. The first call\n// from the daemon's process asks for the macOS Automation permission\n// (System Settings › Privacy & Security › Automation › Notes).\n\nexport const NOTES_SCRIPT = `\nfunction run(argv) {\n var folderName = argv[0], title = argv[1], body = argv[2]\n var Notes = Application(\"Notes\")\n var esc = function (s) { return s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\") }\n var folder = Notes.folders.whose({ name: folderName })()[0]\n if (!folder) {\n folder = Notes.Folder({ name: folderName })\n Notes.folders.push(folder)\n folder = Notes.folders.whose({ name: folderName })()[0]\n }\n var lines = body.split(\"\\\\n\").map(function (l) { return \"<div>\" + (l ? esc(l) : \"<br>\") + \"</div>\" })\n // Notes takes the title from the first line: a name as well would show it twice.\n var note = Notes.Note({ body: \"<div><h1>\" + esc(title) + \"</h1></div>\" + lines.join(\"\") })\n folder.notes.push(note)\n return note.id()\n}\n`\n\nexport function macosNotes(exec: Output = defaultOutput): NativeNotes {\n return {\n async add({ folder, title, body }) {\n const raw = await exec(\"/usr/bin/osascript\", [\"-l\", \"JavaScript\", \"-e\", NOTES_SCRIPT, folder, title, body])\n const id = raw.trim()\n if (!id) throw new Error(\"Notes did not return the new note's id\")\n return { id }\n },\n }\n}\n","import { existsSync, readdirSync } from \"fs\"\nimport type { NativeSound } from \"../types\"\nimport { run as defaultRun, type Run } from \"./run\"\n\nconst SOUNDS = \"/System/Library/Sounds\"\n\n/** The system sound file for a name, or null when there is none. Names\n * only: a path in the config must not reach afplay. */\nexport function soundPath(name: string): string | null {\n if (!/^[\\w -]+$/.test(name)) return null\n const path = `${SOUNDS}/${name}.aiff`\n return existsSync(path) ? path : null\n}\n\nexport function macosSound(io: { run?: Run } = {}): NativeSound {\n const exec = io.run ?? defaultRun\n return {\n async play(name, volume) {\n const path = soundPath(name)\n if (!path) return\n await exec(\"/usr/bin/afplay\", [\"-v\", String(Math.min(1, Math.max(0, volume))), path])\n },\n has: (name) => soundPath(name) !== null,\n async names() {\n try {\n return readdirSync(SOUNDS).filter((f) => f.endsWith(\".aiff\")).map((f) => f.slice(0, -5)).sort()\n } catch {\n return []\n }\n },\n }\n}\n","import type { NativeTask, NativeTasks } from \"../types\"\nimport { output as defaultOutput, type Output } from \"./run\"\n\n// Apple Reminders through remindctl (Homebrew). It is the same tool the\n// mac-pim skill uses, so the daemon and the skill see the same lists. The\n// first call from the daemon's process triggers the macOS Reminders\n// permission prompt.\n//\n// Every value travels as its own argv entry, never through a shell, so\n// quotes and newlines arrive as typed. remindctl 0.1.1 reads any value\n// that starts with \"-\" as an option (and a value equal to --help or\n// --version runs that), and has no \"--opt=value\" form, so such a value\n// gets an invisible zero-width space in front. Reminders keeps that\n// character; listOpen takes it off again. A list name is a lookup key and\n// cannot carry it, so a list name that starts with \"-\" is refused.\n//\n// Reminders keeps a due time to the minute, in this Mac's time zone:\n// seconds are dropped.\n\nconst ZWSP = \"\\u200b\"\n\n/** A value remindctl takes literally. */\nexport function argValue(v: string): string {\n return v.startsWith(\"-\") ? ZWSP + v : v\n}\n\nconst unArg = (v: string | undefined): string | undefined => (v?.startsWith(ZWSP + \"-\") ? v.slice(1) : v)\n\nfunction listName(list: string): string {\n if (!list.trim() || list.startsWith(\"-\")) throw new Error(`Reminders list name \"${list}\" is not usable: it must not be empty or start with \"-\"`)\n return list\n}\n\n/** ISO to the minute, which is all Reminders keeps. */\nconst isoDue = (d: Date): string => new Date(Math.floor(d.getTime() / 60_000) * 60_000).toISOString().replace(/\\.\\d{3}Z$/, \"Z\")\n\nexport function macosTasks(command = \"remindctl\", exec: Output = defaultOutput): NativeTasks {\n return {\n async ensureList(list) {\n const raw = await exec(command, [\"list\", \"--json\", \"--no-input\"])\n const lists = JSON.parse(raw.trim() || \"[]\")\n if (!Array.isArray(lists)) throw new Error(`${command} list: expected a JSON array`)\n if (lists.some((l: { title?: string }) => l?.title === list)) return\n await exec(command, [\"list\", listName(list), \"--create\", \"--json\", \"--no-input\"])\n },\n async listOpen(list) {\n const raw = await exec(command, [\"show\", \"all\", \"--list\", listName(list), \"--json\", \"--no-input\"])\n const items = JSON.parse(raw.trim() || \"[]\")\n if (!Array.isArray(items)) throw new Error(`${command} show: expected a JSON array`)\n return items\n .filter((r: NativeTask) => r && typeof r.id === \"string\" && !r.isCompleted)\n .map((r: NativeTask) => ({ ...r, title: unArg(r.title) ?? \"\", ...(r.notes !== undefined ? { notes: unArg(r.notes) } : {}) }))\n },\n async add({ list, title, notes, due, priority }) {\n const args = [\"add\", \"--title\", argValue(title), \"--list\", listName(list), \"--notes\", argValue(notes)]\n if (due) args.push(\"--due\", isoDue(due))\n if (priority && priority !== \"none\") args.push(\"--priority\", priority)\n const raw = await exec(command, [...args, \"--json\", \"--no-input\"])\n let id: unknown\n try { id = JSON.parse(raw.trim())?.id } catch { id = undefined }\n if (typeof id !== \"string\" || !id) throw new Error(`${command} add: no reminder id in its answer`)\n return { id }\n },\n async update(id, patch) {\n const args = [\"edit\", id]\n if (patch.title !== undefined) args.push(\"--title\", argValue(patch.title))\n if (patch.notes !== undefined) args.push(\"--notes\", argValue(patch.notes))\n if (patch.due === null) args.push(\"--clear-due\")\n else if (patch.due) args.push(\"--due\", isoDue(patch.due))\n // remindctl refuses an edit that changes nothing; so does this.\n if (args.length === 2) return\n await exec(command, [...args, \"--json\", \"--no-input\"])\n },\n async complete(id) {\n await exec(command, [\"complete\", id, \"--json\", \"--no-input\"])\n },\n async remove(id) {\n await exec(command, [\"delete\", id, \"--force\", \"--json\", \"--no-input\"])\n },\n }\n}\n","import type { NativeAdapter } from \"./types\"\n\n/** The adapter for a machine AgentX has no OS layer for, or where the owner\n * turned it off. Every capability is absent; describe() says why. */\nexport function noneAdapter(reason: string): NativeAdapter {\n return {\n os: \"none\",\n async describe() {\n return { os: \"none\", tasks: false, notes: false, banner: false, sound: false, focus: false, problems: [reason] }\n },\n }\n}\n","import { macosAdapter, type MacosIo } from \"./macos\"\nimport { noneAdapter } from \"./none\"\nimport type { NativeAdapter } from \"./types\"\n\nexport * from \"./types\"\nexport { noneAdapter } from \"./none\"\n\nexport type NativeAdapterChoice = \"auto\" | \"none\"\n\nexport type NativeConfig = { native?: { adapter?: NativeAdapterChoice }; reminders?: { command?: string } }\n\n/** Programs an adapter runs, so tests can stand in for them. */\nexport type NativeIo = MacosIo\n\n/** Builds the adapter for one OS. Each OS adapter registers here. */\nexport type NativeAdapterFactory = (cfg: NativeConfig, io: NativeIo) => NativeAdapter\n\nconst FACTORIES: Partial<Record<NodeJS.Platform, NativeAdapterFactory>> = {\n darwin: macosAdapter,\n}\n\n/** The adapter for this machine. `native.adapter: \"none\"` forces none on\n * any OS; \"auto\" (the default) picks by platform. */\nexport function loadNativeAdapter(\n cfg: NativeConfig = {},\n opts: { platform?: NodeJS.Platform; factories?: Partial<Record<NodeJS.Platform, NativeAdapterFactory>>; io?: NativeIo } = {},\n): NativeAdapter {\n if (cfg.native?.adapter === \"none\") return noneAdapter(\"Turned off: native.adapter is \\\"none\\\".\")\n const platform = opts.platform ?? process.platform\n const make = (opts.factories ?? FACTORIES)[platform]\n return make ? make(cfg, opts.io ?? {}) : noneAdapter(`AgentX has no native adapter for ${platform} yet.`)\n}\n","import { existsSync } from \"fs\"\nimport { homedir } from \"os\"\nimport { isAbsolute } from \"path\"\nimport { loadNativeAdapter, type NativeConfig, type NativeIo } from \"@/native\"\n\nexport { findHelper } from \"@/desktop/install\"\n\n// What happens on THIS machine when a notification is delivered: a banner\n// on screen and a short sound. The push goes to the phone; these are for\n// the person sitting at the computer that raised the event. Both go\n// through the native adapter (src/native); a machine without one skips\n// them.\n//\n// Both are awaited rather than fired and forgotten. A caller that exits\n// straight after notifying — a `launchctl submit` job that removes itself,\n// a cron one-liner — used to take the sound down with it before it\n// played. Waiting costs about a second and makes the step reliable.\n//\n// Never fatal: a notification whose banner failed still arrived, and no\n// caller should have to handle an audio error to say a build finished.\n\nexport interface LocalSettings {\n /** Show a desktop banner (macOS only; other platforms skip it). */\n banner: boolean\n /** Play a sound (macOS only). */\n sound: boolean\n /** A system sound, by name (on a Mac, one of the sounds in System Settings › Sound). */\n soundName: string\n /** 0 (silent) … 1 (full). */\n volume: number\n /** Image for the helper's app icon, which macOS puts on its banners.\n * Unset: the AgentX logo. Applied when `agentx desktop install` builds\n * the helper, since macOS reads the icon from the app, not the banner. */\n icon?: string\n}\n\n/** Glass is the gentlest system sound that is still audible over a\n * keyboard — Basso and Sosumi are alerts, Funk and Frog are jokes, and\n * Ping is the one every other app already uses. */\nexport const DEFAULT_LOCAL: LocalSettings = { banner: true, sound: true, soundName: \"Glass\", volume: 0.4 }\n\n/** Shows the banner and plays the sound for one delivered notification. */\nexport type LocalAlert = (title: string, message: string) => Promise<void>\n\n/** Fill gaps in a partial `notifications.local` block with the defaults. */\nexport function localSettings(cfg: Partial<LocalSettings> | undefined): LocalSettings {\n return { ...DEFAULT_LOCAL, ...(cfg ?? {}) }\n}\n\nexport function localAlert(\n settings: LocalSettings,\n deps: { run?: NativeIo[\"run\"]; platform?: NodeJS.Platform; helper?: string | null; native?: NativeConfig[\"native\"] } = {},\n): LocalAlert {\n const native = loadNativeAdapter({ native: deps.native }, { platform: deps.platform, io: { run: deps.run, helper: deps.helper } })\n return async (title, message) => {\n const steps: Promise<unknown>[] = []\n if (settings.banner && native.banner) steps.push(native.banner.post({ title, message }))\n if (settings.sound && native.sound) steps.push(native.sound.play(settings.soundName, settings.volume))\n await Promise.all(steps)\n }\n}\n\n/**\n * Apply a change to a stored `notifications.local` block, the one rule\n * both the CLI and the dashboard write through. Returns the new block;\n * throws on a value that would not load. Only a machine with a native\n * adapter has sounds to check a name against; elsewhere the setting is\n * inert, so it need only be well-formed.\n */\nexport function patchLocal(\n current: Partial<LocalSettings> | undefined,\n patch: Record<string, unknown>,\n platform: NodeJS.Platform = process.platform,\n): Partial<LocalSettings> {\n const next = { ...(current ?? {}) }\n const native = loadNativeAdapter({}, { platform })\n if (\"banner\" in patch) next.banner = Boolean(patch.banner)\n if (\"sound\" in patch) next.sound = Boolean(patch.sound)\n if (\"soundName\" in patch) {\n const name = String(patch.soundName).trim()\n const ok = native.sound ? native.sound.has(name) : /^[\\w -]+$/.test(name)\n if (!ok) throw new Error(`no system sound named \"${name}\" on this machine`)\n next.soundName = name\n }\n if (\"icon\" in patch) {\n const icon = String(patch.icon ?? \"\").trim().replace(/^~(?=\\/)/, homedir())\n if (!icon) delete next.icon\n else {\n if (!isAbsolute(icon) || !/\\.(png|jpe?g|icns)$/i.test(icon)) throw new Error(\"icon must be the full path to a .png, .jpg or .icns file\")\n if (native.banner && !existsSync(icon)) throw new Error(`no icon file at ${icon}`)\n next.icon = icon\n }\n }\n if (\"volume\" in patch) {\n const v = Number(patch.volume)\n if (!Number.isFinite(v) || v < 0 || v > 1) throw new Error(\"volume must be between 0 and 1\")\n next.volume = v\n }\n return next\n}\n","import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport type { NativePriority, NativeTasks } from \"@/native\"\nimport { summarize } from \"@/requests/card-view\"\nimport type { RequestRecord } from \"@/requests/store\"\nimport { CARD_LIMITS, type DecisionCard } from \"./cards\"\n\n// --- The Reminders mirror (#1062 step 5) ---\n//\n// Each pending decision card, and each request waiting on the owner,\n// becomes one task in the OS task app (Apple Reminders on a Mac) with a due\n// time. Calendar shows it, and the system alert comes back when it falls\n// due. Answering stays on the Desk, the Approvals page or the CLI: a task\n// cannot carry choices or a draft.\n//\n// Runs once a minute beside the approvals sweep, on the node that holds the\n// cards (forwarded cards live on the owner's node, so that is where they\n// are mirrored). Off by default.\n//\n// Rules:\n// - one task per card or request, created once;\n// - the card is answered, expires or is closed, or the request stops\n// waiting on the owner: the task is completed;\n// - the owner ticks the task off or deletes it while the item still\n// waits: the item stays on the Desk and is never mirrored again.\n// Ticking a task is not an answer;\n// - three failed adds for one item: the owner is told once and that\n// item is not tried again;\n// - every task ends with `agentx: card=<id>` or `agentx: request=<id>`,\n// which check-ins and the reminders hand-back skip, so a mirrored\n// task never turns back into a card or an agent's job.\n//\n// State lives in its own file, written only by the daemon, not in the card\n// files that the CLI and the dashboard also write.\n\nexport interface MirrorSettings {\n enabled: boolean\n list: string\n dueAfterMinutes: number\n include: (\"card\" | \"request\")[]\n /** Where the owner answers. Unset: the local dashboard's Approvals page. */\n answerUrl?: string\n}\n\nexport type MirrorState = \"open\" | \"completed\" | \"dismissed\" | \"failed\"\n\nexport interface MirrorEntry {\n /** The task's id in the OS task app, once added. */\n id?: string\n list: string\n state: MirrorState\n /** ISO time of the last change. */\n at: string\n failures: number\n lastError?: string\n}\n\nexport interface MirrorFile {\n /** Keyed `card:<id>` or `request:<id>`, the inbox's keys. */\n items: Record<string, MirrorEntry>\n /** ISO time of the last pass that read every list it needed. Stale\n * (the mirror was turned off, or the list can't be read) means the\n * mirror no longer covers anything, and the Mac popup is back. */\n checkedAt?: string\n /** That pass mirrored cards (include has \"card\"). */\n cards?: boolean\n /** ISO time the owner was last told adds are failing: once a day. */\n failureToldAt?: string\n /** The latest pass's last error, for doctor. */\n lastError?: { at: string; message: string }\n}\n\nexport const MAX_ADD_FAILURES = 3\n/** Closed entries are kept this long, then forgotten. */\nconst KEEP_CLOSED_MS = 30 * 24 * 3_600_000\n\nexport function mirrorPath(root: string): string {\n return resolve(root, \".agentx\", \"native-mirror.json\")\n}\n\nexport function readMirror(root: string): MirrorFile {\n try {\n const parsed = JSON.parse(readFileSync(mirrorPath(root), \"utf-8\"))\n return { ...parsed, items: parsed?.items && typeof parsed.items === \"object\" ? parsed.items : {} }\n } catch {\n return { items: {} }\n }\n}\n\nfunction writeMirror(root: string, file: MirrorFile): void {\n const path = mirrorPath(root)\n if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true })\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(file, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\n/** A pass older than this means the mirror is not running. */\nexport const MIRROR_FRESH_MS = 5 * 60_000\n\n/** True when the mirror is running and covers this card: it has a task,\n * or gets one on the next pass, or the owner ticked its task off. The Mac\n * popup then leaves it alone, so the owner is not alerted twice. A card\n * whose task could not be added is not covered. */\nexport function mirrorCovers(root: string, cardId: string, now = Date.now()): boolean {\n const file = readMirror(root)\n const checked = file.checkedAt ? Date.parse(file.checkedAt) : NaN\n if (!file.cards || !(now - checked <= MIRROR_FRESH_MS)) return false\n return file.items[`card:${cardId}`]?.state !== \"failed\"\n}\n\n/** What one task says. */\nexport interface MirrorItem {\n key: string\n title: string\n notes: string\n due: Date\n priority: NativePriority\n}\n\nconst DAY_MS = 24 * 3_600_000\n\nfunction dueFor(now: number, settings: MirrorSettings, limit?: number): Date {\n const due = now + settings.dueAfterMinutes * 60_000\n return new Date(limit !== undefined && Number.isFinite(limit) ? Math.max(now, Math.min(due, limit)) : due)\n}\n\nexport function cardItem(card: DecisionCard, settings: MirrorSettings, answerUrl: string, now: number): MirrorItem {\n const expires = Date.parse(card.expires)\n const lines = [summarize(card.ask, CARD_LIMITS.ask)]\n if (card.choices?.length) lines.push(...card.choices.map((c, i) => `${i + 1}. ${c}`))\n if (card.recommend) lines.push(`Recommended: ${summarize(card.recommend, CARD_LIMITS.recommend)}`)\n lines.push(`Answer: ${answerUrl}`, `agentx: card=${card.id}`)\n return {\n key: `card:${card.id}`,\n title: summarize(card.title, CARD_LIMITS.title),\n notes: lines.join(\"\\n\"),\n due: dueFor(now, settings, expires),\n priority: Number.isFinite(expires) && expires - now <= DAY_MS ? \"high\" : \"none\",\n }\n}\n\nexport function requestItem(r: RequestRecord, settings: MirrorSettings, answerUrl: string, now: number): MirrorItem {\n const lines = [summarize(r.question || r.text, CARD_LIMITS.ask), `Asked of ${r.agentId}.`, `Answer: ${answerUrl}`, `agentx: request=${r.id}`]\n const dueAt = r.dueAt ?? undefined\n return {\n key: `request:${r.id}`,\n title: summarize(r.text, CARD_LIMITS.title),\n notes: lines.join(\"\\n\"),\n due: dueFor(now, settings, dueAt),\n priority: dueAt !== undefined && dueAt - now <= DAY_MS ? \"high\" : \"none\",\n }\n}\n\nexport interface MirrorDeps {\n root: string\n settings: MirrorSettings\n tasks: NativeTasks\n /** Pending cards on this node. */\n cards: () => DecisionCard[]\n /** Requests in waiting_owner. */\n requests: () => RequestRecord[]\n answerUrl: string\n /** Tell the owner, through the usual notification. */\n notify: (title: string, message: string) => Promise<void>\n log: (msg: string) => void\n now?: number\n}\n\nexport interface MirrorResult {\n created: number\n completed: number\n dismissed: number\n failed: number\n}\n\n/** One pass of the mirror. Never throws. */\nexport async function runMirror(deps: MirrorDeps): Promise<MirrorResult> {\n const { root, settings, tasks, log } = deps\n const now = deps.now ?? Date.now()\n const at = new Date(now).toISOString()\n const result: MirrorResult = { created: 0, completed: 0, dismissed: 0, failed: 0 }\n const file = readMirror(root)\n // lastError says how the latest pass went: a clean pass clears it.\n delete file.lastError\n const fail = (message: string) => { file.lastError = { at, message } }\n\n const waiting = new Map<string, MirrorItem>()\n try {\n if (settings.include.includes(\"card\")) {\n for (const c of deps.cards()) if (c.status === \"pending\" && Date.parse(c.expires) > now) waiting.set(`card:${c.id}`, cardItem(c, settings, deps.answerUrl, now))\n }\n if (settings.include.includes(\"request\")) {\n for (const r of deps.requests()) if (r.state === \"waiting_owner\") waiting.set(`request:${r.id}`, requestItem(r, settings, deps.answerUrl, now))\n }\n } catch (e: any) {\n log(`[mirror] could not read what is waiting: ${e?.message ?? e}`)\n fail(String(e?.message ?? e))\n writeMirror(root, file)\n return result\n }\n\n // Close or notice dismissal for what is already mirrored. The open list\n // is read once per list; when it can't be read, nothing is closed or\n // dismissed this pass, so a hiccup never loses a task.\n let allRead = true\n const openIds = new Map<string, Set<string> | null>()\n const openIn = async (list: string): Promise<Set<string> | null> => {\n if (!openIds.has(list)) {\n try {\n openIds.set(list, new Set((await tasks.listOpen(list)).map((t) => t.id)))\n } catch (e: any) {\n log(`[mirror] could not read list \"${list}\": ${e?.message ?? e}`)\n fail(String(e?.message ?? e))\n openIds.set(list, null)\n allRead = false\n }\n }\n return openIds.get(list)!\n }\n\n for (const [key, entry] of Object.entries(file.items)) {\n if (entry.state !== \"open\" || !entry.id) continue\n const open = await openIn(entry.list)\n if (!open) continue\n if (!waiting.has(key)) {\n if (open.has(entry.id)) {\n try {\n await tasks.complete(entry.id)\n } catch (e: any) {\n log(`[mirror] ${key}: could not complete its task: ${e?.message ?? e}`)\n fail(String(e?.message ?? e))\n continue\n }\n }\n file.items[key] = { ...entry, state: \"completed\", at }\n result.completed++\n } else if (!open.has(entry.id)) {\n file.items[key] = { ...entry, state: \"dismissed\", at }\n result.dismissed++\n log(`[mirror] ${key}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`)\n }\n }\n\n let listReady: boolean | null = null\n const gaveUp: { title: string; message: string }[] = []\n for (const [key, item] of waiting) {\n const entry = file.items[key]\n if (entry && (entry.state === \"open\" || entry.state === \"dismissed\")) continue\n if (entry?.state === \"failed\" && entry.failures >= MAX_ADD_FAILURES) continue\n // The list is made on the first add of a pass, when it is missing.\n if (listReady === null) {\n try {\n await tasks.ensureList(settings.list)\n listReady = true\n } catch (e: any) {\n log(`[mirror] could not make list \"${settings.list}\": ${e?.message ?? e}`)\n fail(String(e?.message ?? e))\n listReady = false\n }\n }\n const failures = entry?.state === \"failed\" ? entry.failures : 0\n try {\n const { id } = await tasks.add({ list: settings.list, title: item.title, notes: item.notes, due: item.due, priority: item.priority })\n file.items[key] = { id, list: settings.list, state: \"open\", at, failures: 0 }\n result.created++\n } catch (e: any) {\n const message = String(e?.message ?? e)\n const n = failures + 1\n file.items[key] = { list: settings.list, state: \"failed\", at, failures: n, lastError: message }\n fail(message)\n result.failed++\n log(`[mirror] ${key}: could not add to Reminders (${n}/${MAX_ADD_FAILURES}): ${message}`)\n if (n === MAX_ADD_FAILURES) gaveUp.push({ title: item.title, message })\n }\n }\n\n // One notification a day at most, however many items gave up: a missing\n // permission fails every card the same way.\n const told = file.failureToldAt ? Date.parse(file.failureToldAt) : NaN\n if (gaveUp.length && !(now - told < DAY_MS)) {\n const first = gaveUp[0]\n const more = gaveUp.length > 1 ? ` (and ${gaveUp.length - 1} more)` : \"\"\n try {\n await deps.notify(\"Could not add to Reminders\", `${first.title}${more}: ${summarize(first.message, 200)}. Still on the Desk.`)\n file.failureToldAt = at\n } catch (err: any) {\n log(`[mirror] could not tell the owner: ${err?.message ?? err}`)\n }\n }\n\n if (allRead) {\n file.checkedAt = at\n file.cards = settings.include.includes(\"card\")\n }\n\n for (const [key, entry] of Object.entries(file.items)) {\n if (entry.state !== \"open\" && !waiting.has(key) && now - Date.parse(entry.at) > KEEP_CLOSED_MS) delete file.items[key]\n }\n writeMirror(root, file)\n return result\n}\n","import { markdownToHtml } from \"@/utils/markdown-html\"\nimport type { RequestRecord, RequestStore } from \"./store\"\nimport type { PlanState, PlanStore, StepState } from \"./plan-store\"\nimport { describeCloseWhen } from \"./checkers\"\nimport { activeStepAgentOf, stalledWhy, waitsOn, type StallGroup } from \"./loops\"\n\n// --- One open request as a card the owner can read in seconds (#459) ---\n//\n// The Approvals page shows each open request as a card: a short plain\n// summary, where it stands and why it is not finished, then the words the\n// owner used and the agent's last answer, both rendered. markdownToHtml\n// escapes before it marks up, so nothing an agent or a channel wrote\n// reaches the page as HTML. No model call: the summary is the start of the\n// request's own words, without the markdown marks.\n\nexport const SUMMARY_MAX = 200\n/** An answer of pages is cut: the card is for reading quickly. */\nexport const ANSWER_MAX = 4000\n\nexport interface RequestCard extends RequestRecord {\n summary: string\n /** The request in the owner's words (the transcript, when spoken). */\n textHtml: string\n /** Why it is not finished, or what is being asked. Null: work is under way. */\n why: string | null\n ownerNoteHtml: string | null\n lastAnswer: { agentId: string; at: number; html: string } | null\n /** The open loop (#1039): who it is owed to, when it is due, what\n * closes it. Null on a request with none of it. */\n loop: {\n owedTo: string | null\n promise: boolean\n dueAt: number | null\n /** What its check waits for, in words. */\n check: string | null\n verifyState: string | null\n verifyDetail: string | null\n } | null\n /** Stalled, and what it waits on. Null: not stalled, or not asked. */\n stall: { group: StallGroup; who: string; why: string } | null\n /** Its tracked plan (#788), step by step. Null: no plan. */\n plan: {\n state: PlanState\n steps: Array<{ idx: number; name: string; kind: string; agentId: string; state: StepState; approval: string | null; evidence: string | null; note: string | null; nudges: number }>\n } | null\n}\n\n/** Markdown to the words alone, on one line. */\nexport function plain(md: string): string {\n return md\n .replace(/```[\\s\\S]*?```/g, \" \")\n .replace(/!?\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\")\n .replace(/^\\s{0,3}(#{1,6}|>|[-*+]|\\d+[.)])\\s+/gm, \"\")\n .replace(/[*_~`]+/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n}\n\n/** The start of the request, cut at a sentence when one ends in reach. */\nexport function summarize(md: string, max = SUMMARY_MAX): string {\n const text = plain(md)\n if (text.length <= max) return text\n const cut = text.slice(0, max)\n const end = Math.max(cut.lastIndexOf(\". \"), cut.lastIndexOf(\"? \"), cut.lastIndexOf(\"! \"))\n return end > max / 2 ? cut.slice(0, end + 1) : `${cut.slice(0, max - 1).trimEnd()}…`\n}\n\n/** What the stall view needs: the quiet time, the clock, and which ids are agents. */\nexport interface StallLookup { staleAfterHours: number; now: number; isAgent: (id: string) => boolean }\n\nexport function requestCard(\n r: RequestRecord,\n store: Pick<RequestStore, \"lastAnswer\">,\n plans?: Pick<PlanStore, \"get\" | \"steps\"> | null,\n stall?: StallLookup,\n): RequestCard {\n const plan = plans?.get(r.id)\n const why = stall ? stalledWhy(r, stall.staleAfterHours, stall.now) : null\n const answer = store.lastAnswer(r.id)\n const cutAnswer = answer && answer.text.length > ANSWER_MAX ? `${answer.text.slice(0, ANSWER_MAX)}\\n\\n…` : answer?.text\n return {\n ...r,\n summary: summarize(r.text),\n textHtml: markdownToHtml(r.text),\n why: r.state === \"waiting_owner\" ? r.question : r.state === \"needs_attention\" ? r.attentionReason : null,\n ownerNoteHtml: r.ownerNote ? markdownToHtml(r.ownerNote) : null,\n lastAnswer: answer ? { agentId: answer.agentId, at: answer.at, html: markdownToHtml(cutAnswer!) } : null,\n loop: r.promise || r.dueAt !== null || r.closeWhen ? {\n owedTo: r.owedTo, promise: r.promise, dueAt: r.dueAt, check: r.closeWhen ? describeCloseWhen(r.closeWhen) : null,\n verifyState: r.verifyState, verifyDetail: r.verifyDetail,\n } : null,\n stall: stall && why ? { ...waitsOn(r, { isAgent: stall.isAgent, activeStepAgent: activeStepAgentOf(plans) }), why } : null,\n plan: plan ? {\n state: plan.state,\n steps: plans!.steps(r.id).map((s) => ({\n idx: s.idx, name: s.name, kind: s.kind, agentId: s.agentId, state: s.state,\n approval: s.needsApproval ? s.approval : null, evidence: s.evidence, note: s.note, nudges: s.nudges,\n })),\n } : null,\n }\n}\n","import { OPEN_STATES, OWED_TO_OWNER, type RequestRecord, type RequestStore } from \"./store\"\nimport { runCheck, type CheckContext, type CheckResult, type CloseWhen } from \"./checkers\"\n\n// --- Open loops: who each one waits on, and when it is stalled (#1039) ---\n//\n// A loop is an open request: one the owner asked for, or one an agent\n// promised (action promise). It is stalled when it is past its due time,\n// or, without one, when nothing has happened for staleAfterHours. A loop\n// that needs attention is stalled too: nothing is retrying it.\n//\n// Stalled loops are grouped by what they wait on:\n// owner the owner's answer (waiting_owner), or the owner's decision\n// on one that needs attention\n// agent an agent: the one that has it, a plan step's agent, or the\n// agent it is owed to\n// person an outside person: a promise owed to a known person\n// The requests panel, `agentx requests --stalled` and the sweep's notice\n// all use this one grouping.\n\nexport const STALL_GROUPS = [\"owner\", \"agent\", \"person\"] as const\nexport type StallGroup = (typeof STALL_GROUPS)[number]\n\nexport interface StalledLoop {\n request: RequestRecord\n group: StallGroup\n /** Who it waits on: \"owner\", an agent id or a person id. */\n who: string\n /** Why it counts as stalled, in words. */\n why: string\n}\n\nexport interface LoopLookups {\n isAgent: (id: string) => boolean\n /** The agent of the active step of the request's plan, if it has one. */\n activeStepAgent?: (requestId: string) => string | null\n}\n\nconst HOUR = 3_600_000\nconst isOpen = (r: RequestRecord) => (OPEN_STATES as readonly string[]).includes(r.state)\n\n/** The agent of each request's active plan step, from the plan store. */\nexport function activeStepAgentOf(plans: { get(id: string): { state: string } | null; steps(id: string): Array<{ state: string; agentId: string }> } | null | undefined) {\n return (requestId: string): string | null => {\n if (!plans || plans.get(requestId)?.state !== \"active\") return null\n return plans.steps(requestId).find((s) => s.state === \"active\")?.agentId ?? null\n }\n}\n\n/** What an open loop waits on. */\nexport function waitsOn(r: RequestRecord, look: LoopLookups): { group: StallGroup; who: string } {\n if (r.state === \"waiting_owner\") return { group: \"owner\", who: OWED_TO_OWNER }\n if (r.promise && r.owedTo && r.owedTo !== OWED_TO_OWNER && !look.isAgent(r.owedTo)) return { group: \"person\", who: r.owedTo }\n if (r.state === \"needs_attention\") return { group: \"owner\", who: OWED_TO_OWNER }\n const step = look.activeStepAgent?.(r.id)\n return { group: \"agent\", who: step ?? r.agentId }\n}\n\n/** Why an open loop is stalled, or null when it is not. */\nexport function stalledWhy(r: RequestRecord, staleAfterHours: number, now: number): string | null {\n if (!isOpen(r)) return null\n if (r.state === \"needs_attention\") return r.attentionReason ?? \"needs attention\"\n if (r.dueAt !== null) return now > r.dueAt ? `past its due time (${when(r.dueAt)})` : null\n return now - r.updatedAt > staleAfterHours * HOUR ? `no activity for ${staleAfterHours} h or more` : null\n}\n\n/** Stalled loops among `items`, oldest first, grouped. */\nexport function stalledLoops(items: RequestRecord[], staleAfterHours: number, now: number, look: LoopLookups): Record<StallGroup, StalledLoop[]> {\n const out: Record<StallGroup, StalledLoop[]> = { owner: [], agent: [], person: [] }\n for (const r of items) {\n const why = stalledWhy(r, staleAfterHours, now)\n if (!why) continue\n const { group, who } = waitsOn(r, look)\n out[group].push({ request: r, group, who, why })\n }\n return out\n}\n\n/** The group, in words, for people. */\nexport function waitsOnWords(group: StallGroup, who: string): string {\n return group === \"owner\" ? \"you\" : group === \"agent\" ? `agent ${who}` : `${who} (outside person)`\n}\n\nexport const when = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace(\"T\", \" \") + \" UTC\"\n\n/** A due time an agent or the owner gave: epoch ms, or an ISO date.\n * Undefined when absent, a string when it is not a time. */\nexport function parseDue(v: unknown): number | undefined | string {\n if (v === undefined || v === null || v === \"\") return undefined\n const at = typeof v === \"number\" ? v : typeof v === \"string\" ? Date.parse(v.trim()) : NaN\n if (!Number.isFinite(at) || at <= 0) return \"due must be an ISO date (2030-01-31T17:00:00Z) or epoch milliseconds\"\n return at\n}\n\n// ── Running the checkers from the requests check ─────────────────────────\n\n/** Runs a loop's checker. The daemon's own; tests give their own. */\nexport type LoopChecker = (spec: CloseWhen, request: RequestRecord) => Promise<CheckResult>\n\nexport function loopChecker(ctx: () => CheckContext): LoopChecker {\n return (spec) => runCheck(spec, ctx())\n}\n\n/** How many checkers run at once, and how many loops one check takes on. */\nconst CHECK_BATCH = 10\n\n/** Run the checker of every open loop whose last check is older than\n * `everyMinutes`. Met closes it as done with the checker's evidence;\n * unverifiable marks it unverified; not met leaves it as it is. */\nexport async function checkLoops(\n store: RequestStore,\n check: LoopChecker,\n opts: { everyMinutes: number; now: number; log: (msg: string) => void },\n): Promise<{ checked: number; closed: number }> {\n const due = store.dueForCheck(opts.now - opts.everyMinutes * 60_000, CHECK_BATCH)\n let closed = 0\n await Promise.all(due.map(async (r) => {\n // Marked before the call: a check that hangs is not started again\n // at the next minute.\n store.markChecked(r.id, r.verifyState, r.verifyDetail ?? \"\", opts.now)\n const res = await check(r.closeWhen!, r).catch((e: any): CheckResult => ({ verdict: \"unverifiable\", detail: String(e?.message ?? e) }))\n if (res.verdict === \"met\") {\n if (store.closeVerified(r.id, res.detail, opts.now)) {\n closed++\n opts.log(`[requests] ${r.id} closed by its check: ${res.detail}`)\n }\n return\n }\n // A refused done stays \"failed\" until the check says otherwise.\n store.markChecked(r.id, res.verdict === \"unverifiable\" ? \"unverified\" : r.verifyState === \"failed\" ? \"failed\" : null, res.detail, opts.now)\n }))\n return { checked: due.length, closed }\n}\n"],"mappings":"oMAAA,OAAS,cAAAA,EAAY,gBA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,CAAG,GAAKlC,EAAM,KAAK,MAAMmC,EAAM,EAAE,EAAItD,IAAgB,OAAOQ,EAAK,MAAM6C,CAAG,EAEvH,OAAA9C,GAAYL,EAAMM,CAAI,EACfmC,CACT","names":["existsSync","readFileSync","dirname","join","fileURLToPath","homedir","DESKTOP_LABEL","DESKTOP_APP","HELPER_APP","desktopPlatformError","platform","arch","release","selectDesktopAgent","agents","requested","id","shellQuote","value","LAUNCHD_PATH","desktopPath","ffmpeg","override","unxml","s","ents","_","e","plistPathEnv","plist","m","isVoiceLoginItemFile","name","adoptLoginItem","dir","items","keep","remove","file","a","b","label","program","findOnPath","bin","path","isExecutable","desktopPlist","opts","xml","env","k","v","helperBuildArgs","icon","installedHelper","home","packageRoot","from","resolveHelper","root","installed","findHelper","accessSync","constants","execFile","STEP_TIMEOUT_MS","run","file","args","done","err","capture","stdout","output","resolve","reject","stderr","helperOf","io","findHelper","helperBannerStatus","path","capture","out","status","macosBanner","exec","run","title","message","helper","NOTES_SCRIPT","macosNotes","exec","output","folder","title","body","id","existsSync","readdirSync","SOUNDS","soundPath","name","path","existsSync","macosSound","io","exec","run","volume","readdirSync","f","ZWSP","argValue","v","unArg","listName","list","isoDue","d","macosTasks","command","exec","output","raw","lists","l","items","r","title","notes","due","priority","args","id","patch","executable","file","accessSync","constants","focus","s","readSystemFocus","macosAdapter","cfg","io","command","macosTasks","macosNotes","macosBanner","macosSound","problems","isExec","findOnPath","noneAdapter","reason","FACTORIES","macosAdapter","loadNativeAdapter","cfg","opts","noneAdapter","platform","make","existsSync","homedir","isAbsolute","DEFAULT_LOCAL","localSettings","cfg","localAlert","settings","deps","native","loadNativeAdapter","title","message","steps","patchLocal","current","patch","platform","next","name","icon","homedir","isAbsolute","existsSync","v","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","dirname","resolve","init_checkers","init_store","init_checkers","STALL_GROUPS","HOUR","isOpen","r","OPEN_STATES","activeStepAgentOf","plans","requestId","s","waitsOn","look","OWED_TO_OWNER","stalledWhy","staleAfterHours","now","when","stalledLoops","items","out","why","group","who","waitsOnWords","ms","parseDue","v","at","loopChecker","ctx","spec","runCheck","CHECK_BATCH","checkLoops","store","check","opts","due","closed","res","e","SUMMARY_MAX","ANSWER_MAX","plain","md","summarize","max","text","cut","end","requestCard","r","store","plans","stall","plan","why","stalledWhy","answer","cutAnswer","markdownToHtml","describeCloseWhen","waitsOn","activeStepAgentOf","s","MAX_ADD_FAILURES","KEEP_CLOSED_MS","mirrorPath","root","resolve","readMirror","parsed","readFileSync","writeMirror","file","path","existsSync","dirname","mkdirSync","tmp","writeFileSync","renameSync","MIRROR_FRESH_MS","mirrorCovers","cardId","now","checked","DAY_MS","dueFor","settings","limit","due","cardItem","card","answerUrl","expires","lines","summarize","CARD_LIMITS","c","i","requestItem","r","dueAt","runMirror","deps","tasks","log","at","result","fail","message","waiting","e","allRead","openIds","openIn","list","t","key","entry","open","listReady","gaveUp","item","failures","id","n","told","first","more","err"]}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{mkdirSync as b,readFileSync as p,renameSync as w,writeFileSync as N}from"fs";import{dirname as h,resolve as $}from"path";var u={title:120,body:4e3};function R(t){return!!t.node&&t.node!==t.selfNode&&t.tokenPeer===t.node?t.claimed&&t.isLocalAgent(t.claimed)?{error:`"${t.claimed}" is an agent on this node; a peer may only write for its own agents`}:{agentId:t.claimed||null,node:t.node}:{agentId:t.proven(),node:""}}var d=new Map;function f(t){return $(t,".agentx","native-notes.json")}function y(t,e){try{let n=JSON.parse(p(f(t),"utf-8"));return n?.date===e&&n.counts&&typeof n.counts=="object"?n.counts:{}}catch{return{}}}function I(t,e,n){let r=f(t);b(h(r),{recursive:!0});let s=`${r}.${process.pid}.tmp`;N(s,JSON.stringify({date:e,counts:n},null,2)+`
|
|
2
|
+
`),w(s,r)}function S(t){let e=new Date(t);return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}async function k(t,e){let{settings:n,root:r}=e,s=e.now??Date.now();if(!n.enabled)return{status:409,body:{error:"notes are off on this node (native.notes.enabled is false)"}};if(!e.agentId)return{status:403,body:{error:"only an agent's running turn can add a note"}};let a=typeof t?.title=="string"?t.title.replace(/\s+/g," ").trim():"",g=typeof t?.body=="string"?t.body.trim():"";if(!a||a.length>u.title)return{status:400,body:{error:`title is required, at most ${u.title} characters`}};if(!g||g.length>u.body)return{status:400,body:{error:`body is required, at most ${u.body} characters`}};let i=S(s),m=y(r,i),o=e.node?`${e.agentId}@${e.node}`:e.agentId;if((m[o]??0)+(d.get(o)??0)>=n.perAgentPerDay)return{status:429,body:{error:`${e.agentId} already added ${n.perAgentPerDay} notes today; the limit is native.notes.perAgentPerDay`}};d.set(o,(d.get(o)??0)+1);try{let l=await v(a,g,e,s);if(l.status===201){let c=y(r,i);c[o]=(c[o]??0)+1,I(r,i,c)}return l}finally{let l=(d.get(o)??1)-1;l>0?d.set(o,l):d.delete(o)}}async function v(t,e,n,r){let{settings:s}=n,a;if(n.notes){let g=`${e}
|
|
3
|
+
|
|
4
|
+
\u2014 ${n.agentId}${n.node?` on ${n.node}`:""}, ${new Date(r).toISOString()}`;try{let{id:i}=await n.notes.add({folder:s.folder,title:t,body:g});a={status:201,body:{ok:!0,id:i,folder:s.folder}}}catch(i){return{status:502,body:{error:`could not add the note: ${i?.message??i}`}}}}else if(n.forward)a=await n.forward({title:t,body:e,agentId:n.agentId,node:n.node});else return{status:501,body:{error:"this machine has no notes app, and native.forwardTo (or approvals.forwardTo) names no peer to send it to"}};return a}export{u as a,R as b,k as c};
|
|
5
|
+
//# sourceMappingURL=chunk-X7UQY7CH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/native/notes-api.ts"],"sourcesContent":["import { mkdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport type { NativeNotes } from \"./types\"\n\n// --- Ideas to the owner's notes app: POST /native/notes (#1062 step 9) ---\n//\n// An agent with an idea for the owner writes it as a note (Apple Notes on\n// a Mac) through the agentx_note tool, instead of a message. Write-only:\n// reading notes back is a separate question (#850). Off by default.\n//\n// 409 native.notes.enabled is off on this node\n// 403 the caller is not an agent's running turn (or a peer naming one)\n// 400 title or body missing or too long\n// 429 this agent already wrote perAgentPerDay notes today\n// 201 written here, or on the peer native.forwardTo names\n// 501 no notes app here and nowhere to forward\n//\n// A node without a notes app (a Linux server) forwards to the owner's\n// machine over the mesh; that node applies its own switch and limit too.\n\nexport const NOTE_LIMITS = { title: 120, body: 4000 } as const\n\nexport interface NoteSettings {\n enabled: boolean\n folder: string\n perAgentPerDay: number\n}\n\nexport interface NoteReply {\n status: number\n body: Record<string, unknown>\n}\n\nexport interface NoteDeps {\n root: string\n settings: NoteSettings\n /** This node's notes app; undefined when it has none. */\n notes?: NativeNotes\n /** Sends the note to the owner's machine; undefined when no peer is set. */\n forward?: (payload: { title: string; body: string; agentId: string; node: string }) => Promise<NoteReply>\n /** The agent the call proves, or null. */\n agentId: string | null\n /** Where the agent runs, for the signature: this node, or the peer that forwarded it. */\n node: string\n now?: number\n}\n\n/** Who a note is from. A peer is believed only when the call's token is\n * that peer's own token (not this node's MESH_TOKEN, which local agents\n * hold) and the agent it names is not one of this node's; otherwise the\n * agent is the one the running turn proves. */\nexport function noteCaller(c: {\n node: string\n selfNode: string\n /** The peer whose own token the call carries, or null. */\n tokenPeer: string | null\n claimed?: string\n isLocalAgent: (id: string) => boolean\n /** The agent the call's running turn proves, or null. */\n proven: () => string | null\n}): { agentId: string | null; node: string } | { error: string } {\n const fromPeer = !!c.node && c.node !== c.selfNode && c.tokenPeer === c.node\n if (!fromPeer) return { agentId: c.proven(), node: \"\" }\n if (c.claimed && c.isLocalAgent(c.claimed)) return { error: `\"${c.claimed}\" is an agent on this node; a peer may only write for its own agents` }\n return { agentId: c.claimed || null, node: c.node }\n}\n\n/** Notes being written now, per agent: counted against the limit, so two\n * at once cannot both pass it. */\nconst inFlight = new Map<string, number>()\n\nfunction countsPath(root: string): string {\n return resolve(root, \".agentx\", \"native-notes.json\")\n}\n\n/** Notes written per agent on one local day: { date, counts }. */\nfunction readCounts(root: string, date: string): Record<string, number> {\n try {\n const parsed = JSON.parse(readFileSync(countsPath(root), \"utf-8\"))\n return parsed?.date === date && parsed.counts && typeof parsed.counts === \"object\" ? parsed.counts : {}\n } catch {\n return {}\n }\n}\n\nfunction writeCounts(root: string, date: string, counts: Record<string, number>): void {\n const path = countsPath(root)\n mkdirSync(dirname(path), { recursive: true })\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify({ date, counts }, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\nfunction localDate(now: number): string {\n const d = new Date(now)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, \"0\")}-${String(d.getDate()).padStart(2, \"0\")}`\n}\n\nexport async function handleNoteRequest(input: Record<string, unknown> | undefined, deps: NoteDeps): Promise<NoteReply> {\n const { settings, root } = deps\n const now = deps.now ?? Date.now()\n if (!settings.enabled) return { status: 409, body: { error: \"notes are off on this node (native.notes.enabled is false)\" } }\n if (!deps.agentId) return { status: 403, body: { error: \"only an agent's running turn can add a note\" } }\n const title = typeof input?.title === \"string\" ? input.title.replace(/\\s+/g, \" \").trim() : \"\"\n const body = typeof input?.body === \"string\" ? input.body.trim() : \"\"\n if (!title || title.length > NOTE_LIMITS.title) return { status: 400, body: { error: `title is required, at most ${NOTE_LIMITS.title} characters` } }\n if (!body || body.length > NOTE_LIMITS.body) return { status: 400, body: { error: `body is required, at most ${NOTE_LIMITS.body} characters` } }\n\n const date = localDate(now)\n const counts = readCounts(root, date)\n const key = deps.node ? `${deps.agentId}@${deps.node}` : deps.agentId\n if ((counts[key] ?? 0) + (inFlight.get(key) ?? 0) >= settings.perAgentPerDay) {\n return { status: 429, body: { error: `${deps.agentId} already added ${settings.perAgentPerDay} notes today; the limit is native.notes.perAgentPerDay` } }\n }\n inFlight.set(key, (inFlight.get(key) ?? 0) + 1)\n try {\n const reply = await write(title, body, deps, now)\n if (reply.status === 201) {\n const fresh = readCounts(root, date)\n fresh[key] = (fresh[key] ?? 0) + 1\n writeCounts(root, date, fresh)\n }\n return reply\n } finally {\n const n = (inFlight.get(key) ?? 1) - 1\n if (n > 0) inFlight.set(key, n)\n else inFlight.delete(key)\n }\n}\n\nasync function write(title: string, body: string, deps: NoteDeps, now: number): Promise<NoteReply> {\n const { settings } = deps\n let reply: NoteReply\n if (deps.notes) {\n const signed = `${body}\\n\\n— ${deps.agentId}${deps.node ? ` on ${deps.node}` : \"\"}, ${new Date(now).toISOString()}`\n try {\n const { id } = await deps.notes.add({ folder: settings.folder, title, body: signed })\n reply = { status: 201, body: { ok: true, id, folder: settings.folder } }\n } catch (e: any) {\n return { status: 502, body: { error: `could not add the note: ${e?.message ?? e}` } }\n }\n } else if (deps.forward) {\n reply = await deps.forward({ title, body, agentId: deps.agentId!, node: deps.node })\n } else {\n return { status: 501, body: { error: \"this machine has no notes app, and native.forwardTo (or approvals.forwardTo) names no peer to send it to\" } }\n }\n return reply\n}\n"],"mappings":"AAAA,OAAS,aAAAA,EAAW,gBAAAC,EAAc,cAAAC,EAAY,iBAAAC,MAAqB,KACnE,OAAS,WAAAC,EAAS,WAAAC,MAAe,OAmB1B,IAAMC,EAAc,CAAE,MAAO,IAAK,KAAM,GAAK,EA+B7C,SAASC,EAAWC,EASsC,CAE/D,MADiB,CAAC,CAACA,EAAE,MAAQA,EAAE,OAASA,EAAE,UAAYA,EAAE,YAAcA,EAAE,KAEpEA,EAAE,SAAWA,EAAE,aAAaA,EAAE,OAAO,EAAU,CAAE,MAAO,IAAIA,EAAE,6EAA8E,EACzI,CAAE,QAASA,EAAE,SAAW,KAAM,KAAMA,EAAE,IAAK,EAF5B,CAAE,QAASA,EAAE,OAAO,EAAG,KAAM,EAAG,CAGxD,CAIA,IAAMC,EAAW,IAAI,IAErB,SAASC,EAAWC,EAAsB,CACxC,OAAON,EAAQM,EAAM,UA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H,EAAK,UAAUA,EAAK,KAAO,OAAOA,EAAK,OAAS,OAAO,IAAI,KAAKJ,CAAG,EAAE,YAAY,IAChH,GAAI,CACF,GAAM,CAAE,GAAAc,CAAG,EAAI,MAAMV,EAAK,MAAM,IAAI,CAAE,OAAQC,EAAS,OAAQ,MAAAC,EAAO,KAAMO,CAAO,CAAC,EACpFJ,EAAQ,CAAE,OAAQ,IAAK,KAAM,CAAE,GAAI,GAAM,GAAAK,EAAI,OAAQT,EAAS,MAAO,CAAE,CACzE,OAASU,EAAP,CACA,MAAO,CAAE,OAAQ,IAAK,KAAM,CAAE,MAAO,2BAA2BA,GAAG,SAAWA,GAAI,CAAE,CACtF,UACSX,EAAK,QACdK,EAAQ,MAAML,EAAK,QAAQ,CAAE,MAAAE,EAAO,KAAAC,EAAM,QAASH,EAAK,QAAU,KAAMA,EAAK,IAAK,CAAC,MAEnF,OAAO,CAAE,OAAQ,IAAK,KAAM,CAAE,MAAO,0GAA2G,CAAE,EAEpJ,OAAOK,CACT","names":["mkdirSync","readFileSync","renameSync","writeFileSync","dirname","resolve","NOTE_LIMITS","noteCaller","c","inFlight","countsPath","root","readCounts","date","parsed","writeCounts","counts","path","tmp","localDate","now","d","handleNoteRequest","input","deps","settings","title","body","key","reply","write","fresh","n","signed","id","e"]}
|